【发布时间】:2018-06-10 15:24:58
【问题描述】:
我想使用 scipy 在 python 中用 sin(x)/x 的积分计算定积分。 n = 256。它似乎效果不佳:
from scipy import integrate
exact = integrate.quad(lambda x : (np.sin(x))/x, 0, 2*np.pi)[0]
print("Exact value of integral:", exact)
# Approx of sin(x)/x by Trapezoidal rule
x = np.linspace(0, 2*np.pi, 257)
f = lambda x : (np.sin(x))/x
approximation = np.trapz(f(x), x)
print ("Estimated value of trapezoidal O(h^2):", round(approximation, 5),
'+', round((2/256)**2, 5))
print ("real error:", exact - approximation)
# Approx of sin(x)/x by Simpsons 1/3 rule
approximation = integrate.simps(f(x), x)
print("Estimated value of simpsons O(h^4):", round(approximation, 9),
'+', round((2/256)**4, 9))
print ("real error:", exact - approximation)
plt.figure()
plt.plot(x, f(x))
plt.show()
精确的积分计算得很好,但我得到一个求积错误...怎么了?
Exact value of integral: 1.4181515761326284
Estimated value of trapezoidal O(h^2): nan + 6e-05
real error: nan
Estimated value of simpsons O(h^4): nan + 4e-09
real error: nan
提前致谢!
【问题讨论】:
标签: python python-3.x numpy scipy integral