So I am seeing really strange behavior from my python code and couldn't find any other examples of my problem. From what I've read of python, a function can only access variables that are either global or inside it. However, I've discovered in the following snippet that the two print statements return different results even though the variable 'density' is never returned by the function and isn't declared globally.
def findHeight(density):
print density
height = integrateHeight(density, cutOff)
print density
return height
This is a real pain in the a** because it is messing up code later on in the script.
I am using python 2.7.6 and my function definition is as follows:
def integrateHeight(data, cutOff):
# accumulate data values and rescale to fit interval [0,1]
# Calculate bin widths (first one is a different size from the others)
data[0,1] = -2*data[0,0]*data[0,1]
data[1:,1] = (data[2,0] - data[1,0])*data[1:,1]
# accumulate distribution and divide by the total
data[:,1] = np.cumsum(data[:,1]) / data[:,1].sum()
# Assign a default height value
height = data[0,0]
# store the first height,fraction pair
prev = data[0]
# loop through remaining height,fraction pairs
for row in data[1:]:
# check that the cut-off is between two values
if row[1] > cutOff >= prev[1]:
# Interpolate between height values
height = interpolate(cutOff, prev[::-1], row[::-1])
# exit the loop when the height is found
break
# store the current height,fraction value
prev = row
return height
This particular script is supposed to take a distribution, accumulate it, and find the height corresponding to a certain fraction of the cumulative distribution.
densityobject? Maybe you can make a deep copy of it and pass that instead.data[0,1] = ...is a much different operation fromdata = .... The former invokesdata.__setitem__, the latter changes what the namedatapoints to.densityis anumpy.ndarrayobject. I used thenumpy.copymethod when I passed it to integrateHeight and it now works as intended.