SciPy Tutorial menu

SciPy Integration

Integration calculates the total area under a curve, which often means adding up a changing quantity.

Why Integration Matters

If you know a car's speed at every moment, integration gives the total distance. If you know the power used each hour, it gives the total energy. You do not need to do the calculus by hand: scipy.integrate does it numerically.

FunctionUse it when
quad(f, a, b)You have a formula f(x) and limits a to b
trapezoid(y, x)You only have measured data points
solve_ivp(f, t_span, y0)You have a differential equation (a rate of change)

Integrating a Function With quad

Find the area under y = x² from 0 to 3. The exact answer is 9.

Example

python
from scipy.integrate import quad

area, error = quad(lambda x: x ** 2, 0, 3)
print(round(area, 6))
print(error < 1e-10)
Output
9.0
True

quad returns two values: the result and an estimate of the error, which is tiny here.

A Practical Example

A water tank fills at a rate of r(t) = 20 + 4t litres per minute. How much water flows in during the first 10 minutes?

Example

python
from scipy.integrate import quad

def rate(t):
    return 20 + 4 * t

litres, _ = quad(rate, 0, 10)
print(litres)
Output
400.0

Infinite Limits

quad also works with infinity, using np.inf. The area under the standard bell curve is exactly 1:

Example

python
import numpy as np
from scipy.integrate import quad

bell = lambda x: np.exp(-x ** 2 / 2) / np.sqrt(2 * np.pi)
total, _ = quad(bell, -np.inf, np.inf)
print(round(total, 6))
Output
1.0

Integrating Measured Data

Often you have readings, not a formula. A motorbike's speed (metres per second) was recorded every 10 seconds:

Example

python
import numpy as np
from scipy.integrate import trapezoid

time = np.array([0, 10, 20, 30, 40])
speed = np.array([0, 8, 12, 12, 6])
distance = trapezoid(speed, time)
print(distance, "metres")
Output
350.0 metres

The trapezoid rule joins the points with straight lines and adds up the areas of the shapes under them.

The more often you take readings, the more accurate trapezoid becomes. With only a few points, the result is a rough estimate.

Solving a Differential Equation

A differential equation describes how something changes. Your savings grow by 10% per year, continuously: dy/dt = 0.1·y. Starting with Rs 100,000, how much after 5 years?

Example

python
from scipy.integrate import solve_ivp

def growth(t, y):
    return 0.1 * y

sol = solve_ivp(growth, t_span=(0, 5), y0=[100000], t_eval=[5], rtol=1e-8)
print(round(sol.y[0][-1]))
Output
164872

The exact answer is 100000 × e^0.5 = 164,872, so SciPy matches it.

Exercise

Exercise

Which function should you use to integrate a list of measured data points?

Learn SciPy with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp