Published On Sep 18, 2024
The trapezoidal rule is a numerical method used to approximate the definite integral of a function. It works by dividing the area under a curve into trapezoids, rather than rectangles (as in Riemann sums), and summing their areas to estimate the integral.
import numpy as np
import matplotlib.pyplot as plt
Define the function
def f(x):
return 4*x + 2
Trapezoidal Rule Implementation
def trapezoidal_rule(f, a, b, n):
h = (b - a) / n # Step size
x = np.linspace(a, b, n+1)
y = f(x)
area = (h / 2) * (y[0] + 2 * np.sum(y[1:-1]) + y[-1])
return area
Parameters
a = 1 # Lower limit
b = 4 # Upper limit
n = 6 # Number of strips
Calculate the area using Trapezoidal Rule
area = trapezoidal_rule(f, a, b, n)
print(f"Approximate area under the curve using trapezoidal rule: {area}")
Generate the curve for the function
x_vals = np.linspace(a, b, 1000)
y_vals = f(x_vals)
Plot the function
plt.plot(x_vals, y_vals, label='f(x) = 4x + 2', color='blue')
Highlight the trapezoidal areas
x_trapezoid = np.linspace(a, b, n+1)
y_trapezoid = f(x_trapezoid)
plt.fill_between(x_trapezoid, y_trapezoid, color='lightgray', label='Trapezoidal approximation')
Add labels and title
plt.title('Trapezoidal Rule Approximation')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.grid(True)
Show the plot
plt.show()