scipy.integrate — odeint, solve_ivp (RK45, DOP853), quad
1. quad — numerical definite integral
Deriving the simplest rule from scratch (trapezoid → Simpson)
We want using only with . Fit a parabola through these 3 points and integrate it exactly. Shift so . Then:
The odd term vanishes (Why? by symmetry). Now express via the samples: , and . Substitute:
That is Simpson's rule. quad is this idea, but adaptive and higher order.
from scipy.integrate import quad
import numpy as np
val, err = quad(lambda x: np.exp(-x**2), 0, np.inf)
# val ≈ 0.8862269 (= sqrt(pi)/2), err ≈ 7.1e-09val= estimate,err= estimated absolute error.- Pass extra params with
args=(...); usepoints=[...]to flag kinks.
2. solve_ivp — the modern ODE solver
Deriving a single step (forward Euler, then RK)
Start from the exact statement (fundamental theorem of calculus):
WHY this is the seed: if we knew that integral exactly we'd be done; every method is just a quadrature rule for that little integral.
-
Euler (left-rectangle): approximate the integral by :
-
RK4 / RK45 (Runge–Kutta): sample the slope at several trial points inside the step, like Simpson did inside an interval, and blend: with , , etc.
Worked example — exponential decay
Exact solution: .
from scipy.integrate import solve_ivp
import numpy as np
sol = solve_ivp(lambda t, y: -2*y, [0, 5], [3.0],
method='RK45', t_eval=np.linspace(0, 5, 100),
rtol=1e-8, atol=1e-10)
sol.t # times
sol.y[0] # y values, shape (n_states, n_times)- Why
y0=[3.0](a list)?solve_ivpalways treats the state as a vector; even a scalar must be 1-element. - Why
sol.y[0]? rows are state components, columns are time points.
Worked example — a system (SHM / 2nd-order → 1st-order)
. Why convert? Solvers only take first-order systems. Let :
w = 2.0
def rhs(t, y):
return [y[1], -w**2 * y[0]]
sol = solve_ivp(rhs, [0, 10], [1, 0], method='DOP853', rtol=1e-10)
# x(t) = sol.y[0] should match cos(2t); energy conserved3. odeint — the legacy classic
from scipy.integrate import odeint
y = odeint(lambda y, t: -2*y, 3.0, np.linspace(0,5,100)) # note (y, t)!- Returns an array of shape
(len(t), n_states)— also transposed vssolve_ivp. - Modern advice: prefer
solve_ivp(events, dense output, method choice). Keepodeintknowledge for reading old code.
Recall Feynman: explain to a 12-year-old
Imagine you only know how fast a toy car is moving at every instant, but not where it is. To find where it ends up, you take a tiny moment, move it forward a little using its current speed, check the speed again, and repeat — that's solve_ivp solving an ODE. Smart solvers peek a few times inside each tiny step (RK45) to move more accurately, and they take bigger steps on a smooth straight road and smaller steps on a curvy one. quad is different: there you already know the shape of a hill and just want the area under it, so you sample the height at clever spots and add them up.
Flashcards
What does quad return?
(value, estimated_absolute_error).Argument order of the RHS for solve_ivp?
f(t, y) — time first.Argument order of the RHS for odeint?
f(y, t) — state first (reversed from solve_ivp).What is RK45's default and how does it choose step size?
When should you switch from RK45/DOP853 to BDF/Radau?
What does t_eval control (and NOT control)?
Simpson's rule formula on ?
Why must a 2nd-order ODE be rewritten before solving?
Shape of solve_ivp solution array sol.y?
(n_states, n_time_points) — components are rows. :::What makes DOP853 worth its cost?
Connections
- Riemann sums and Fundamental Theorem of Calculus — the seed of all integration here.
- Runge-Kutta methods · Stiff differential equations · Numerical stability
- Gaussian quadrature — the math behind
quad. - numpy.trapz and simpson — fixed-grid integration when you only have samples.
- Harmonic oscillator — canonical
solve_ivptest system.
Concept Map
Hinglish (regional understanding)
Intuition Hinglish mein samjho
Dekho, scipy.integrate ke andar do bilkul alag kaam hote hain. Pehla hai quad — yahan tumhare paas pura function already hai aur tumhe sirf ek number chahiye: us curve ke neeche ka area, yaani . quad smart tareeke se kuch points pe function ki value leta hai (Simpson/Gauss-Kronrod rule) aur weighted sum bana ke area de deta hai. Yeh tumhe (value, error) ka tuple deta hai — error woh khud estimate karta hai.
Dusra kaam hai ODE solve karna — solve_ivp aur purana odeint. Yahan tumhe function nahi pata, sirf uska slope pata hai: , aur ek starting point . Solver chhote-chhote steps leke aage badhta hai. Forward Euler simplest hai (current speed se thoda aage badho), aur RK45 thoda smart hai — ek step ke andar 4-5 jagah slope check karta hai taaki accuracy zyada ho. RK45 default hai, DOP853 high-accuracy ke liye, aur agar problem stiff ho (bahut fast aur bahut slow scale saath me) to BDF/Radau use karo.
Sabse common galti: argument order ulta likh dena. solve_ivp me function f(t, y) hota hai — time pehle. Lekin odeint (purana hai) me f(y, t) hota hai — ulta. Yaad rakho: "old = reversed". Aur t_eval se step size control nahi hota, woh sirf decide karta hai ki answer kahan-kahan report karna hai; accuracy badhani ho to rtol/atol change karo ya method badlo.
Yeh isliye important hai kyunki science aur engineering ki har simulation — planet ki orbit, chemical reaction, circuit, population model — yahi tools use karti hai. Ek baar intuition clear ho jaaye to tum koi bhi physical system code me simulate kar sakte ho.