我需要使用python中的辛普森规则将函数g(t)= 2e ^(-t ^ 2)从0集成到3,而无需在scipy中使用内置的simpsons规则。任何帮助表示赞赏
答案 0 :(得分:0)
这是无需使用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)