简体   繁体   中英

Integrate with scipy.integrate.simps but over a subset

I have a domain X discretized at X_0, ... X_n . I would like to integrate a function f(x) = x^0.5 using scipy.integrate.simps . However, I don't want to integrate over the whole X , but rather [a, b] \\in X .

Now, the total integration \\int_X f(x) dx would be done using

X = np.linspace(1, 2) # generate discretized space
simps(X**0.5, X)

But what if I only wanted to integrate this between 1.5 and 2? Is there any way of doing this without manually interpolating f(1.5) when I can't ensure that my discretized grid actually has a point X_i = 1.5 ?

The situation you describe is pretty unusual; normally, when one is able to evaluate a function at will, the quad method should be used for integration. It's much more efficient to let the integration routine decide where to evaluate the function than blindly evaluate at equally spaced points and then try to get an integral out of that.

But if you are stuck with already-discretized function and don't want to interpolate, a quick and dirty approach is to replace the values outside of the range of integration by zeros:

simps(np.where(X >= 1.5, Y, 0), X)

Since this truncation creates a discontinuous function, the accuracy of integration will not be as good as one normally gets from Simpson. The above returns 0.660880... compared to the actual value 0.660873... In contrast, for the entire interval (1, 2) simps yields 6 correct digits after the decimal dot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM