Simpson's rule helps us find the area under a curve using simple math. It gives a good estimate when we have data points or a function.
Simpson's rule (simpson) in SciPy
scipy.integrate.simpson(y, x=None, dx=1, axis=-1, even='avg')
y is the data points you want to integrate.
x is optional and gives the sample points corresponding to y. If not given, equal spacing dx is assumed.
from scipy.integrate import simpson # Simple data points with equal spacing y = [1, 4, 9, 16] area = simpson(y) print(area)
from scipy.integrate import simpson x = [0, 1, 2, 3] y = [1, 4, 9, 16] area = simpson(y, x) print(area)
from scipy.integrate import simpson import numpy as np x = np.linspace(0, 2, 5) y = x**2 area = simpson(y, x) print(area)
This program calculates the area under the curve y = x² between 0 and 4 using Simpson's rule. It uses numpy arrays for x and y values and prints the estimated area.
from scipy.integrate import simpson import numpy as np # Define x values from 0 to 4 x = np.array([0, 1, 2, 3, 4]) # Define y values as squares of x y = x**2 # Calculate area under curve y = x^2 from 0 to 4 area = simpson(y, x) print(f"Estimated area under y=x^2 from 0 to 4: {area}")
Simpson's rule works best when you have an odd number of points (even number of intervals).
If you have an even number of intervals, the even parameter controls how the last interval is handled.
Use simpson for better accuracy than simple trapezoid rule when data is smooth.
Simpson's rule estimates the area under a curve using parabolas between points.
It requires data points and optionally their positions.
It is useful for numerical integration when you don't have a formula or want a quick estimate.