对于给定的函数,我尝试使用辛普森的 1/3和辛普森的 3/8规则找到它的数值积分。
然后,我将数值积分的解与解析积分进行比较以计算误差。我发现 3/8 规则的误差是 1/3 规则的两倍,而预期的相反。我哪里做错了?
1/3 规则的 Python3 函数:
def simpsons13(a, b, N):
"""
Calculates the numerical integral of a function f(x) using the Simpson's 1/3rd rule:
F(x) = Σ(0 to (N-2)/2) Δx/3 * (f(x(2i)) + 4f(x(2i + 1)) + f(x(2i + 2)))
Parameters:
a: The lower limit of the definite integral (real)
b: The upper limit of the definite integral (real)
N: A positive, even integer to denote the number of intervals of the function for the integral
Returns I, the numerical integral calculated through Simpson's 1/3rd rule
"""
if N%2 != 0:
return "N must be even"
dx = (b - a)/N
narr = np.linspace(a, b, N+1) # N intervals corresponds to N + 1 points
I = 0
for i in range(int((N - 2) / 2) + 1):
I = I + dx/3*(f(narr[2*i]) + 4*f(narr[2*i + 1]) + f(narr[2*i + 2]))
return I
3/8 规则的 Python3 函数:
def simpsons38(a, b, N):
"""
Calculates the numerical integral of a function f(x) using the Simpson's 3/8 rule:
F(x) = Σ(0 to (N-3)/3) 3Δx/8 * (f(x(3i)) + 3f(x(3i + 1)) + 3f(x(3i + 2)) + f(x(3i + 3)))
Parameters:
a: The lower limit of the definite integral (real)
b: The upper limit of the definite integral (real)
N: A positive, even integer to denote the number of intervals of the function for the integral
Returns I, the numerical integral calculated through Simpson's 3/8 rule
"""
if N%3 != 0:
return "N must be divisible by 3"
dx = (b - a)/N
narr = np.linspace(a, b, N+1)
I = 0
for i in range(int((N-3)/3) + 1):
I = I + 3*dx/8 * (f(narr[3*i]) + 3*f(narr[3*i + 1]) + 3*f(narr[3*i + 2]) + f(narr[3*i + 3]))
return I
我考虑简单的功能并从中找到其数值积分通过考虑间隔。我将数值解和解析解之间的误差计算为:
error = np.abs(ans - approx)
我通过 1/3 方法得到的错误是并通过 3/8 方法得到. 3/8 规则的误差是 1/3 规则的两倍多。为什么会这样?