0
0
SciPydata~5 mins

Simpson's rule (simpson) in SciPy

Choose your learning style9 modes available
Introduction

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.

You want to estimate the total distance traveled from speed data over time.
You have measurements of temperature at different times and want to find the average heat over a period.
You want to calculate the area under a sales curve to find total sales over days.
You have experimental data points and want to estimate the integral without a formula.
Syntax
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.

Examples
Integrates y assuming points are 1 unit apart.
SciPy
from scipy.integrate import simpson

# Simple data points with equal spacing
y = [1, 4, 9, 16]
area = simpson(y)
print(area)
Integrates y with specific x values for spacing.
SciPy
from scipy.integrate import simpson

x = [0, 1, 2, 3]
y = [1, 4, 9, 16]
area = simpson(y, x)
print(area)
Integrates y = x² over 0 to 2 using Simpson's rule.
SciPy
from scipy.integrate import simpson

import numpy as np
x = np.linspace(0, 2, 5)
y = x**2
area = simpson(y, x)
print(area)
Sample Program

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.

SciPy
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}")
OutputSuccess
Important Notes

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.

Summary

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.