python中的布尔规则

计算科学 Python 计算物理学
2021-12-22 08:49:46

这是我在这个论坛的第一篇文章,所以如果不是应该的方式,请原谅我。

我的问题是关于在 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))

我使用了维基百科上给出的公式,但没有错误术语。

x1x5f(x)dx=2h45(7f(x1)+32f(x2)+12f(x3)+32f(x4)+7f(x5))+error term.

1个回答

我认为您的实施是正确的。但是,如果您在较大的时间间隔内集成,您实现它的方式会产生很大的错误。

如果您查看实施梯形规则和辛普森规则的方式,您可以n步数。所以即使梯形规则是两点积分而辛普森规则是三点积分,它们也会给出更好的结果,因为你应用它们n次数。

为了您实施布尔规则,n只能等于五。在这个实现中,您可以一次性整合整个间隔,而不是拆分它(就像您使用其他两种方法一样)。即使布尔规则是五点积分,它也不能胜过其他两种方法,因为它们被应用n给定积分的时间,其中布尔规则仅应用一次。