The Algorithms logoThe Algorithms
About

The Simpson’s Method

Simpson's Rule is a numerical method that approximates the value of a definite integral by using quadratic functions. This method is named after the English mathematician Thomas Simpson (1710−1761).

Let's check this method for the next function: $$f(x) = ({e^x / 2})*(cos(x)-sin(x))$$ with $\varepsilon = 0.001$

import math 
import numpy as np

def simpsone(a, b, n, func):
    h = float((b-a)/n)
    s = (func(a) + func(b)) * 0.5
    for i in np.arange(0, n-1):
        xk = a + h*i
        xk1 = a + h*(i-1)
        s = s + func(xk) + 2*func((xk1+xk)/2)
    x = a + h*n
    x1 = a + h*(n-1)
    s += 2 *func((x1 + x)/2)
    return s*h/3.0

Some input data

f = lambda x: (math.e**x / 2)*(math.cos(x)-math.sin(x))

n = 10000  
a = 2.0
b = 3.0

print("Result: ", simpsone(a, b, n, f))
Result:  -8.404153016168566