This is my first post in this forum so please forgive me if it is not the way it should be.
My problem is about implementing "Boole's rule" into python. I have succesfully implementet trapezoidal and simpsons, but there is a difference in the results between the first 2 and Boole's rule when I calculate an integral. The results differ between 1 and 10. Here it's my code:
# implementation of 3 different integration techniques
from math import *
from scipy import *
1. : Trapezoidal rule
# 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))
I used the formula given on Wikipedia but without the error term.
$$\int_{x_1}^{x_5} f(x)\,dx = \frac{2 h}{45}\left( 7f(x_1) + 32 f(x_2) + 12 f(x_3) + 32 f(x_4) + 7f(x_5) \right) + \text{error term}\, .$$