I want to be able to compute following integral using numpys trapz function
numpy.trapz([-1, 1]) # returns 0
But I don't want to allow negative areas. Is there an efficient way to do this or do I have to look for the minimum point and transform the array by hand?
Does numpy.trapz(numpy.abs([-1, 1]))
make sense?
If you want to discard negative contributions to the integrated area we can simply grab the np.trapz
source code and rewrite it:
def abstrapz(y, x=None, dx=1.0):
y = np.asanyarray(y)
if x is None:
d = dx
else:
x = np.asanyarray(x)
d = np.diff(x)
ret = (d * (y[1:] +y[:-1]) / 2.0)
return ret[ret>0].sum() #The important line
A quick test:
np.trapz([-1,0,1])
0.0
abstrapz([-1,0,1])
0.5
If you just want to avoid areas where y
is less then zero simply mask 'y' values less then zero to zero:
arr = np.array([-2,-1,0.5,1,2,1,0,5,3,0])
np.trapz(arr)
10.5
arr[arr<0] = 0
np.trapz(arr)
12.5
This isn't the best way to do it, but it is a good approximation. If this is what you mean I can update this.
I had to change your example slightly as trapz([-1,1])
will always return 0 by definition. We do remove some functionality this way, if you need to do this on multidimensional arrays it is easy to add it back in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With