这是我在这个论坛的第一篇文章,所以如果不是应该的方式,请原谅我。
我的问题是关于在 python 中实现“布尔规则”。我已经成功实现了梯形和辛普森,但是当我计算积分时,前 2 和布尔规则之间的结果存在差异。结果在 1 和 10 之间有所不同。这是我的代码:
# implementation of 3 different integration techniques
from math import *
from scipy import *
1.:梯形规则
# the trapezodial rule approximates the area under the function as a trapezoid. Mostly it averages the left and right
# sums of 2 sums given by the Riemann-Integral.
# the approximation is as follows:
f= lambda x: e**(-x**2)
g= lambda x: x**6-3*x**5+10*x**4-20*x**3
h= lambda x:1/(x**2-3*x+5)
def trapezoidal (f,a,b,n):
dx= ((b-a)/2)/n
x=a
sum = 0
while x<b:
sum += f(x)*dx
x += dx
return sum
print("trapezoidal f1:",trapezoidal(f,0,1,10000))
print("trapezoidal f2:",trapezoidal(g,0,4,10000))
print("trapezoidal f3:",trapezoidal(h,0,10,10000))
#2. : Simpson´s rule
def simpson(f, a, b, n):
if n % 2: raise ValueError("n must be even (received n=%d)" % n)
dx = (b - a) / n
sum = f(a) + f(b)
for i in range(1, n, 2):
sum += 4 * f(a + i * dx)
for i in range(2, n-1, 2):
sum += 2 * f(a + i * dx)
return sum * dx / 3
print("simpson f1:",simpson(f,0,1,10000))
print("simpson f2:",simpson(g,0,4,10000))
print("simpson f3:",simpson(h,0,10,10000))
# 3. : Boole´s rule:
def boole (f,a,b,n):
dx = (b - a) / (n-1)
sum = 7*(f(a) + f(b))
sum += 32*(f(a+dx)+f(b-dx))
sum += 12*(f(a+2*dx))
return 2*sum * dx / 45
print("boole f1:",boole(f,0,1,5))
print("boole f2:",boole(g,0,4,5))
print("boole f3:",boole(h,0,10,5))
我使用了维基百科上给出的公式,但没有错误术语。