I have two numpy array (x,y)-
import numpy as np
import scipy
from scipy.integrate import simps
y=np.array([1,1,2,1,-2])
x=np.array([0,1,2,3,4])
Which when plotted look like this - (in Blue line)
The black lines highlight the actual points. I wish to integrate between two points (marked red line) on x axis which are not in the original dataset. The goal is to find the area shaded in gray (between the two red lines) in the figure above.
How do I do it in python? Using python SciPy library I can integrate like this
scipy.integrate.trapz(y,x)
That gives me the area shaded in the gray region- 
But if I integrate between the points say 1.5 and 2.2 on x axis, the trapz gives the area shaded in gray below- 
How do I get this correct.
PS- The line graph cannot be expressed as a function as there are many random points in the original array.
Any insight in the right direction would be helpful
The scipy interpolators (such as InterpolatedUnivariateSpline) have an integral method. For example,
In [23]: from scipy.interpolate import InterpolatedUnivariateSpline
In [24]: x = np.array([0, 1, 2, 3, 4])
In [25]: y = np.array([1, 1, 2, 1, -2])
In [26]: f = InterpolatedUnivariateSpline(x, y, k=1) # k=1 gives linear interpolation
In [27]: f.integral(1.5, 2.2)
Out[27]: 1.2550000000000003
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