Menu Close

Simpson 1/3rd Rule | Python

The Simpson’s 1/3 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) + 4*f((a+b)/2) + f(b)]/6

 

Simpson 1/3rd Rule in Python

				
					def simpsons_1_3_rule(f, a, b, n):

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


a = 0  # LOWER LIMIT
b = 1  # UPPER LIMIT
n = 100 # NUMBER OF SUBINTERVALS

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

# OUTPUT - 0.3333
				
			

More Related Stuff