Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Modelling the Trapezoidal Rule for Numerical Integration in Python
The purpose of definite integration is to calculate the area under a curve of a function between two limits, a and b. Numerical integration (also called quadrature) approximates this area by dividing it into simple geometric shapes.
Numerical integration becomes essential when ?
No explicit formula exists for the integral of the function
Integration must be performed on empirical data
The accuracy depends on the number of subdivisions more strips give better approximation.
Trapezoidal Rule
The Trapezoidal Rule approximates the area under a curve by dividing it into vertical trapezoids of equal width h. Each trapezoid's top edge follows the curve.
Mathematical Formula
For n trapezoids with width h = (b-a)/n, the area of each trapezoid is ?
Area? = h/2 × [f(x?) + f(x?)]
The total integral becomes ?
I = h × [½(f(a) + f(b)) + ?f(x?)] for i = 1 to n-1
Notice that intermediate points f(x?) through f(x???) appear twice, so they get full coefficient h, while endpoints get h/2.
Implementation in Python
Let's solve the integral ??^(?/2) x·cos(x) dx using the Trapezoidal Rule ?
import numpy as np
def f(x):
"""Function to integrate: x * cos(x)"""
return x * np.cos(x)
# Define integration limits
a = 0 # Lower limit
b = np.pi / 2 # Upper limit
n = 5 # Number of trapezoids
# Calculate trapezoid width
h = (b - a) / n
# Create array of x values
x = np.linspace(a, b, n + 1)
print(f"x values: {x}")
# Initialize with endpoint terms
I = 0.5 * (f(a) + f(b))
# Add intermediate terms
for j in range(1, n):
I += f(x[j])
# Multiply by width
I = h * I
print(f"Approximate integral with n={n}: {I:.6f}")
x values: [0. 0.31415927 0.62831853 0.9424778 1.25663706 1.57079633] Approximate integral with n=5: 0.549590
Improving Accuracy
Increasing the number of trapezoids improves accuracy ?
import numpy as np
def trapezoidal_rule(f, a, b, n):
"""Apply trapezoidal rule for numerical integration"""
h = (b - a) / n
x = np.linspace(a, b, n + 1)
# Start with endpoints
integral = 0.5 * (f(a) + f(b))
# Add intermediate points
for j in range(1, n):
integral += f(x[j])
return h * integral
def f(x):
return x * np.cos(x)
# Test with different numbers of trapezoids
a, b = 0, np.pi / 2
test_values = [5, 10, 20, 50]
print("n\tApproximate Integral")
print("-" * 30)
for n in test_values:
result = trapezoidal_rule(f, a, b, n)
print(f"{n}\t{result:.6f}")
# Analytical solution for comparison
analytical = (np.pi/2) * np.sin(np.pi/2) - (-np.cos(np.pi/2) + np.cos(0))
print(f"\nAnalytical solution: {analytical:.6f}")
n Approximate Integral ------------------------------ 5 0.549590 10 0.570585 20 0.575838 50 0.577462 Analytical solution: 0.570796
Complete Function Implementation
Here's a reusable function for any integration problem ?
import numpy as np
import matplotlib.pyplot as plt
def trapezoidal_integration(func, a, b, n=10):
"""
Numerical integration using Trapezoidal Rule
Parameters:
func: Function to integrate
a: Lower limit
b: Upper limit
n: Number of trapezoids
Returns:
Approximate integral value
"""
h = (b - a) / n
x = np.linspace(a, b, n + 1)
# Trapezoidal rule formula
integral = 0.5 * (func(a) + func(b))
integral += sum(func(x[i]) for i in range(1, n))
return h * integral
# Example: Different functions
def example1(x):
return x**2
def example2(x):
return np.sin(x)
# Test the function
print("??² x² dx:")
result1 = trapezoidal_integration(example1, 0, 2, 20)
analytical1 = (2**3) / 3 # x³/3 from 0 to 2
print(f"Numerical: {result1:.6f}")
print(f"Analytical: {analytical1:.6f}")
print("\n??? sin(x) dx:")
result2 = trapezoidal_integration(example2, 0, np.pi, 20)
analytical2 = 2 # [-cos(x)] from 0 to ?
print(f"Numerical: {result2:.6f}")
print(f"Analytical: {analytical2:.6f}")
??² x² dx: Numerical: 2.668000 Analytical: 2.666667 ??? sin(x) dx: Numerical: 2.000455 Analytical: 2.000000
Key Points
More trapezoids (larger
n) give better accuracyThe method works well for smooth, continuous functions
Width
h = (b-a)/nmust be calculated correctlyEndpoint values get coefficient ½, intermediate values get coefficient 1
Conclusion
The Trapezoidal Rule provides an effective method for numerical integration by approximating curved areas with trapezoids. Accuracy improves with more subdivisions, making it practical for engineering and scientific applications where analytical solutions are difficult.
---