如何在没有 scipy 的情况下在 python 中使用辛普森规则进行集成



我需要使用 python 中的辛普森规则将函数 g(t(=2e^(-t^2( 从 0 集成到 3,而不使用 scipy 中内置的辛普森规则。 任何帮助不胜感激

以下是如何在不使用 scipy 的情况下实现辛普森规则。 我已经给了你代码的骨架,你所要做的就是正确填写它。

我假设你知道辛普森法则是什么。 我们要做的第一件事是为积分构造一个 python 函数。

import numpy as np
g = lambda t:

接下来,让我们设置一组均匀分布的点,我们可以在这些点上执行正交。

#Sample the function
h = 0.01
a = 0
b = 3
x = np.arange(a,b+h,h)

接下来,我们将为辛普森规则的系数构造一个数组。

#Coefficients for simpons rule
coefs = np.zeros(x.size)
coefs[0] = #What is the first coefficient or simpson's rule
coefs[1::2] =  #What should the coefficient of the odd xs be
coefs[2::2] =  #What should the coefficient of the even xs be
coefs[-1] = #What is the last coefficient of simpson's rule

辛普森法则只是一个总和,可以使用内积快速计算出来。

#Perform the integration
area = h/3* #Can you express simpson's rule as a dot product?  Look up np.dot or the @ operator
print(area)

#Absolute Error.  Should be O(10^-16) meaning it is very close to scipy's area
from scipy.integrate import simps
print(simps(g(x),x) - area)

最新更新