Integration into numpy array with positive scope only

I want to calculate the following integral using the numpys trapz function

numpy.trapz([-1, 1]) # returns 0 

But I do not want to allow negative areas. Is there an efficient way to do this, or do I need to look for the minimum point and convert the array manually?

Does numpy.trapz(numpy.abs([-1, 1])) make sense?

+6
source share
1 answer

If you want to drop negative contributions to the integrated area, we can simply take the source code np.trapz 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 

Quick test:

 np.trapz([-1,0,1]) 0.0 abstrapz([-1,0,1]) 0.5 

If you just want to avoid areas where y less than zero, just mask the values โ€‹โ€‹of "y" less than 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 is not the best way to do this, but it is a good approximation. If this is what you mean, I can update this.

I had to slightly modify your example, since trapz([-1,1]) will always return 0 by definition. We remove some functions this way, if you need to do this on multidimensional arrays, it is easy to add it back.

+2
source

Source: https://habr.com/ru/post/956886/


All Articles