5.4.9 · HinglishScientific Computing (Python)

scipy.integrate — odeint, solve_ivp (RK45, DOP853), quad

1,873 words9 min readRead in English

5.4.9 · Coding › Scientific Computing (Python)


1. quad — numerical definite integral

Simplest rule ko scratch se derive karna (trapezoid → Simpson)

Hum chahte hain sirf use karke, jahan . In 3 points se ek parabola fit karo aur use exactly integrate karo. Shift karo taaki . Phir:

Odd term vanish ho jaata hai (Why? symmetry se). Ab ko samples ke through express karo: , aur . Substitute karo:

Yahi hai Simpson's rule. quad yahi idea hai, lekin adaptive aur 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-09
  • val = estimate, err = estimated absolute error.
  • Extra params args=(...) se pass karo; kinks flag karne ke liye points=[...] use karo.

2. solve_ivp — modern ODE solver

Ek single step derive karna (forward Euler, phir RK)

Exact statement (calculus ka fundamental theorem) se shuru karo:

WHY yeh seed hai: agar hum us integral ko exactly jaante toh kaam ho jaata; har method bas us chhote integral ke liye ek quadrature rule hai.

  • Euler (left-rectangle): integral ko se approximate karo:

  • RK4 / RK45 (Runge–Kutta): step ke andar kuch trial points pe slope sample karo, jaise Simpson ne ek interval ke andar kiya, aur blend karo: jahan , , wagera.

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] (ek list)? solve_ivp hamesha state ko ek vector maanta hai; scalar bhi 1-element hona chahiye.
  • Why sol.y[0]? rows state components hain, columns time points hain.

Worked example — ek system (SHM / 2nd-order → 1st-order)

. Why convert karte hain? Solvers sirf first-order systems lete hain. rakh lo:

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 conserved

3. odeint — legacy classic

from scipy.integrate import odeint
y = odeint(lambda y, t: -2*y, 3.0, np.linspace(0,5,100))  # note (y, t)!
  • Shape (len(t), n_states) ka array return karta hai — yeh bhi solve_ivp se transposed hai.
  • Modern advice: solve_ivp prefer karo (events, dense output, method choice). odeint ki knowledge purana code padhne ke liye rakhho.

Recall Feynman: 12-saal ke bacche ko samjhao

Socho tumhe pata hai ki ek toy car har pal kitni tez chal rahi hai, lekin yeh nahi ki woh kahan hai. Yeh pata karne ke liye ki woh kahan pahunchi, ek tiny moment lo, uski current speed se thoda aage badhao, speed phir check karo, aur repeat karo — yahi hai solve_ivp jo ODE solve karta hai. Smart solvers har tiny step ke andar kuch baar peek karte hain (RK45) taaki zyada accurately aage badh sakein, aur bade steps lete hain smooth seedhi sadak pe aur chhote steps curvy jagah pe. quad alag hai: wahan tumhe pehle se ek hill ki shape pata hai aur bas uske neeche ka area chahiye, toh clever jagahon pe height sample karte ho aur add karte ho.


Flashcards

quad kya return karta hai?
Ek tuple (value, estimated_absolute_error).
solve_ivp ke RHS ka argument order?
f(t, y) — time pehle.
odeint ke RHS ka argument order?
f(y, t) — state pehle (solve_ivp se ulta).
RK45 ka default kya hai aur yeh step size kaise choose karta hai?
Dormand–Prince 5(4): ek embedded 4th-order estimate ko 5th-order se compare karta hai; difference local error hai jo adapt karne ke liye use hota hai. :::
Stiff problem pe RK45/DOP853 se BDF/Radau pe kab switch karna chahiye?
Jab ODE stiff ho (bahut alag time-scales) aur explicit methods ko impractically chhote steps chahiye hon. :::
t_eval kya control karta hai (aur kya NAHI karta)?
Kahan solution report ho; yeh solver ke internal adaptive step size ko set NAHI karta. :::
pe Simpson's rule formula?
, cubics ke liye exact. :::
2nd-order ODE ko solve karne se pehle kyun rewrite karna padta hai?
Solvers sirf first-order systems accept karte hain; introduce karo taaki ho. :::
solve_ivp solution array sol.y ki shape?
(n_states, n_time_points) — components rows hain. :::
DOP853 apni cost ke liye kyun worth hai?
8th order: smooth problems pe bade accurate steps → tight tolerances ke liye kam evaluations. :::
odeint aur solve_ivp dono ka output shape kya hai?
odeint: (len(t), n_states); solve_ivp: (n_states, n_time_points) — dono transposed hain ek doosre se. :::
Simpson's rule mein odd term kyun vanish hota hai?
Kyunki symmetry se — odd functions ka symmetric interval pe integral zero hota hai. :::
Gauss quadrature points ke saath kitne degree tak exact hai?
Degree tak ke polynomials ke liye exact. :::
solve_ivp mein y0 ko list kyun banana padta hai scalar ke liye bhi?
solve_ivp state ko hamesha vector maanta hai; isliye scalar bhi 1-element list/array hona chahiye. :::
Simpson's rule ka error term kis derivative pe depend karta hai aur kyun?
pe — kyunki humne degree-2 polynomial match ki, toh pehla uncaptured term 4th derivative (next even derivative) se aata hai. :::
Stiff system ka matlab kya hai?
Woh system jisme bahut fast aur bahut slow time-scales saath hoon, jisse explicit methods stability ke liye absurdly tiny use karne ko majboor hoon. :::
solve_ivp mein t_eval set karne se accuracy kyun nahi badh'ti?
Kyunki internal adaptive steps solver khud choose karta hai tolerances ke basis pe; t_eval sirf reporting points set karta hai. :::

Connections

Concept Map

solves

solves

unifies

method

special case

derived from

error term

legacy API

modern API

methods

built from

derived from

approximated by

scipy.integrate module

Definite integral quad

ODE solvers

Integration in calculus

Adaptive Gauss-Kronrod

Simpson rule

Fit parabola thru 3 pts

E ~ f 4th deriv

odeint

solve_ivp

RK45 and DOP853

Forward Euler step

FTC integral of slope