Menu Close

Simpson 3/8 Rule | Python

The Simpson’s 3/8 rule is a numerical integration method that approximates the definite integral of a function between two limits.

It states that given a function f(x) defined on the interval [a,b], the definite integral of f(x) from a to b can be approximated by:

integral of f(x) from a to b is approximately

(b – a) * [f(a) + 3f(a + (b-a)/3) + 3f(a + 2*(b-a)/3) + f(b)]/8

Simpson 3/8 Rule in Python

				
					def simpsons_3_8_rule(f, a, b, n):
    
  # Simpson 3/8 Rule [By Bottom Science]
  h = (b - a) / n
  s = f(a) + f(b)
  for i in range(1, n, 3):
    s += 3 * f(a + i * h)
  for i in range(3, n-1, 3):
    s += 3 * f(a + i * h)
  for i in range(2, n-2, 3):
    s += 2 * f(a + i * h)
  return s * 3 * h / 8
 
def f(x):
  return x**2

a = 0
b = 1
n = 100

result = simpsons_3_8_rule(f, a, b, n)
print(result)

#OUTPUT - 0.3138
				
			

More Related Stuff