简体   繁体   English

与scipy.integrate.simps集成,但覆盖一个子集

[英]Integrate with scipy.integrate.simps but over a subset

I have a domain X discretized at X_0, ... X_n . 我有一个域X离散X_0, ... X_n I would like to integrate a function f(x) = x^0.5 using scipy.integrate.simps . 我想使用scipy.integrate.simps集成功能f(x) = x^0.5 However, I don't want to integrate over the whole X , but rather [a, b] \\in X . 但是,我不想在整个X进行积分,而是在[a, b] \\in X进行积分。

Now, the total integration \\int_X f(x) dx would be done using 现在,总积分\\int_X f(x) dx将使用

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? 但是,如果我只想在1.5和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 ? 当我无法确保离散化网格实际上具有点X_i = 1.5时,是否有任何方法无需手动插值f(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. 通常,当一个人可以随意评估一个函数时,应该使用quad方法进行积分。 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. 与实际值0.660873 ...相比,上面的返回0.660880 ...相反,在整个间隔(1、2)中, simps在小数点后产生6个正确的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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