Menu Close

Trapezoidal Rule | Python

The trapezoidal 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) + f(b)]/2

Trapezoidal Rule in Python

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

a = 0
b = 1
n = 100

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

#OUTPUT - 0.333
				
			

More Related Stuff