Problem: Numerical Integration Using the Trapezoidal Rule
Numerical integration is a key topic in computational mathematics.
In this example, we will approximate the integral of a given function using the trapezoidal rule and compare the result to the exact value.
Objective
- Integrate $ f(x) = \sin(x) $ over the interval $([0, \pi])$ numerically using the trapezoidal rule.
- Visualize the approximation and compare it with the actual curve of the function.
Mathematical Background
The integral of $ f(x) = \sin(x) $ over $([0, \pi])$ is:
$$
\int_0^\pi \sin(x) , dx = 2
$$
The trapezoidal rule approximates the integral by dividing the interval into $( n ) $subintervals and approximating $ f(x) $ as a straight line over each subinterval.
The formula is:
$$
\int_a^b f(x) , dx \approx \frac{h}{2} \left[ f(x_0) + 2 \sum_{i=1}^{n-1} f(x_i) + f(x_n) \right]
$$
where $( h = \frac{b-a}{n} )$ is the width of each subinterval.
Python Code
1 | import numpy as np |
Explanation of the Code
- Function and Interval:
- The function $( f(x) = \sin(x) )$ is defined along with the integration interval $([0, \pi])$.
- Trapezoidal Rule:
- The interval is divided into $( n )$ subintervals, and the trapezoidal rule is applied to approximate the integral.
- Exact Solution:
- The exact integral is $( 2 )$, used here for error comparison.
- Visualization:
- The function is plotted alongside the trapezoids used for approximation.
- The filled area under $ f(x) $ represents the exact integral.
Results and Insights

- Numerical Approximation:
- The trapezoidal rule provides an approximate integral value close to the exact solution.
For $( n = 10 )$, the numerical result is accurate within a small error margin.
- The trapezoidal rule provides an approximate integral value close to the exact solution.
- Graph:
- The blue curve shows $ f(x) = \sin(x) $.
- Red points indicate the nodes where the function is evaluated.
- Orange lines represent the trapezoids approximating the area under the curve.
- Error Analysis:
- Increasing the number of subintervals $( n )$ reduces the approximation error, demonstrating the method’s convergence.
Applications in Computational Mathematics
- Integration of Complex Functions:
- Useful when analytical integration is impossible.
- Engineering and Physics:
- Applied to problems involving areas, volumes, and physical quantities.
- Data Analysis:
- Approximation of cumulative distributions or areas under discrete data points.
This example highlights how numerical integration works and provides a visual understanding of the trapezoidal rule.








