3

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

3
  • The line graph cannot be expressed as a function as there are many random points in the original array - How is that a problem? You can just interpolate the values between two points. Commented Aug 12, 2015 at 12:15
  • ok fine. But how do I integrate. Which function to use? Commented Aug 12, 2015 at 12:17
  • 1
    Use numpy.interp to get your new data points between which you want to integrate. Here's the official documentation: link Commented Aug 12, 2015 at 12:18

1 Answer 1

9

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
Sign up to request clarification or add additional context in comments.

1 Comment

Note on integral: 'A caveat is that this routine assumes the spline to be zero outside of the data limits', docs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.