Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrating Discrete point in Python

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) enter image description here 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- enter image description here

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- enter image description here

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

like image 416
Zeeshan Avatar asked Dec 01 '25 05:12

Zeeshan


1 Answers

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
like image 160
Warren Weckesser Avatar answered Dec 03 '25 18:12

Warren Weckesser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!