在以下代码中,我已经在Python中实现了Simpsons Rule。我已尝试将整数范围n的适当范围内的绝对误差绘制为n的函数。我知道确切的结果应该是1-cos(pi / 2)。但是我的图似乎不正确。如何修复代码以获得正确的输出?有两个循环,我认为我没有正确实现图形编码
def simpson(f, a, b, n):
"""Approximates the definite integral of f from a to b by the composite Simpson's rule, using n subintervals (with n even)"""
h = (b - a) / (n)
s = f(a) + f(b)
diffs = {}
for i in range(1, n, 2):
s += 4 * f(a + i * h)
for i in range(2, n-1, 2):
s += 2 * f(a + i * h)
r = s
exact = 1 - cos(pi/2)
diff = abs(r - exact)
diffs[n] = diff
ordered = sorted(diffs.items())
x,y = zip(*ordered)
plt.autoscale()
plt.loglog(x,y)
plt.xlabel("Intervals")
plt.ylabel("Error")
plt.show()
return s * h / 3
simpson(lambda x: sin(x), 0.0, pi/2, 100)
答案 0 :(得分:1)
您的ng new FirstDataApp
? Would you like to add Angular routing? (y/N) events.js:167
throw er; // Unhandled 'error' event
^
方法应该只为simpson
的单个值计算积分(确实如此),但是为n
的多个值创建图应该在该方法之外。为:
n