PYTHON
Numerical integration using trapezoidal rule | Python
Introduction
Numerical integration is a method used to approximate the definite integral of a function within a given interval. One of the simplest numerical integration methods is the trapezoidal rule. In this blog post, we'll delve into the implementation of the trapezoidal rule in Python and explore its application for approximating integrals.
Understanding the Trapezoidal Rule
The trapezoidal rule approximates the integral of a function f(x) over the interval [a,b] by dividing the area under the curve into trapezoids. It replaces the curve with straight line segments connecting the function values at the interval endpoints.
Code
def f(x):
return 1 / (1 + x ** 2)
def trapezoidal_rule(f, a, b, n):
h = (b - a) / n
integral = 0.5 * (f(a) + f(b))
for i in range(1, n):
integral += f(a + i * h)
integral *= h
return integral
# Define the interval [a, b] and the number of subdivisions n
a = 0
b = 6
n = 1000 # Number of subdivisions (adjust for desired accuracy)
# Calculate the integral using the trapezoidal rule
integral = trapezoidal_rule(f, a, b, n)
print("Approximate value of the integral:", integral)
Output
Approximate value of the integral: 1.2490457723982545
Explanation
1. We define the function f(x) that we want to integrate.
2. Define the trapezoidal_rule function that implements the trapezoidal rule for numerical integration.
3. Specify the interval [a,b] and the number of subdivisions
4. Calculate the integral using the trapezoidal_rule function.
5. Print the approximate value of the integral.
Conclusion
The trapezoidal rule is a straightforward method for numerical integration, providing reasonably accurate results with a relatively simple implementation. In this blog post, we've discussed the theory behind the trapezoidal rule and provided a Python implementation to approximate definite integrals. This method is useful for a wide range of applications, including physics, engineering, and finance, where numerical integration is required to solve various problems.
Post a Comment
0 Comments