Worked examples — Implementing ODE solvers from scratch — Euler, RK4
5.4.23 · D3· Coding › Scientific Computing (Python) › Implementing ODE solvers from scratch — Euler, RK4
Tumne Euler aur RK4 parent note mein already dekha hai. Is page ka ek hi kaam hai: in dono update rules ko har tarah ki situation se guzaarna jo ek step-marching solver face kar sakta hai — growth, decay, oscillation, ek curve jo "galat" direction mein bend karti hai, itna bada step ki method blow up ho jaaye, ek real-world cooling problem, aur ek exam trap. Agar tum in sab ko follow kar sako, toh koi bhi ODE-solver question tumhe surprise nahi kar sakta.
Shuru karne se pehle, do tools ko plain words mein re-anchor karte hain taaki neeche koi bhi symbol aisa na ho jo tumhe diya na gaya ho.
"Slope" har example ka hero hai. Yeh picture apne dimaag mein rakho: ek hiker fog mein apne paon ke paas compass padh raha hai (Euler), versus ek hiker jo commit karne se pehle teen baar aage jhankta hai (RK4).
The scenario matrix
Har case class jo ek ODE-stepper se puchhi ja sakti hai, aur woh example jo use hit karta hai:
| Cell | Kya ise distinct banata hai | Example |
|---|---|---|
| A. Growth | slope badhti hai, curve upar bend karti hai → Euler undershoot karta hai | Ex 1 |
| B. Decay | slope shrink hoti hai, curve zero ki taraf bend karti hai → error ka sign flip hota hai | Ex 2 |
| C. Non-autonomous | slope par depend karti hai — ke andar -shifts matter karte hain | Ex 3 |
| D. Oscillation | curve dono taraf turn karti hai; slope zero se guzarti hai | Ex 4 |
| E. Degenerate / zero slope | flat line; dono methods ko constant return karna chahiye | Ex 5 |
| F. Big-step instability large on decay | ek critical ke baad dono methods blow up ho jaate hain | Ex 6 |
| G. Real-world word problem | Newton cooling, set up karna aur units padhna zaroori hai | Ex 7 |
| H. Exam twist | reuse- trap + error-scaling reasoning | Ex 8 |
Hum neeche aathon ko work out karte hain. Har ek mein pehle Forecast karo — steps padhne se pehle actually guess karo.
Example 1 — Cell A: exponential growth ,
Forecast: curve upar bend karti hai (slope badhti rehti hai). Euler slope sirf low-left start par padhta hai, isliye woh bahut-chhoti slope use karta hai → undershoot karna chahiye. Kaun sa method closer landega? Abhi guess karo.
- Euler. . Yeh step kyun? Euler assume karta hai ki starting slope poore half-step tak hold karti hai. Kyunki real slope step ke dauran badhti hai, ka value se kam padh jaata hai.
- RK4 . . Kyun? Bilkul wahan slope jahan hum khade hain — wohi reading jo Euler ne use ki.
- RK4 . . Kyun? Midpoint par peek karo, ko se aage nudge karke. Wahan slope badi hai — yeh undershoot ko already correct kar raha hai.
- RK4 . . Kyun? Midpoint dobara karo lekin ko better slope se nudge karo. Har stage pichle ko refine karta hai.
- RK4 . . Kyun? End-of-step slope, use karke wahan pahuncha.
- RK4 combine. . kyun? Weighted mean slope; midpoints double count karti hain kyunki woh step ke average ko best represent karti hain. Inner sum note karo: … ruko — dhyan se count karo: .
Arithmetic clearly bataate hain taaki kuch bhi fudge na ho: weighted sum hai isliye
Verify: true . Euler error ; RK4 error — RK4 ek single step mein ~530× closer hai. Euler ke liye undershoot forecast confirmed. ✓
Figure padho: Figure s01 mein white curve true hai. Amber line follow karo — yeh Euler ka straight hop hai, aur yeh white curve ke neeche end hota hai: woh gap woh undershoot hai jo tumne forecast ki thi. Cyan square RK4 ka endpoint hai, practically white curve par baith raha hai. Visual takeaway: ek straight Euler segment ek bending curve ko hug nahi kar sakta, lekin RK4 ka four-slope average kar sakta hai.

Example 2 — Cell B: exponential decay ,
Forecast: ab curve zero ki taraf upar se bend karti hai — yeh convex hai, girte girte flat hoti jaati hai. Euler steep starting slope ko poore step ke liye use karta hai. Kya yeh true value ke upar ya neeche land karega?
- Euler. . Yeh step kyun? Starting slope woh sabse steep descent hai jo curve yahan kabhi karti hai; use poore step ke liye use karne se hum bahut zyada neeche chale jaate hain.
- Compare. True , isliye Euler par undershoot karta hai (neeche land karta hai). Yeh note kyun karte hain? Cell A (growth) mein Euler curve ke neeche land kiya tha, lekin wahan "neeche" matlab tha "bahut kam rise". Yahan "neeche" matlab hai "bahut tezi se gira". Lesson: Euler hamesha starting slope ki taraf error karta hai, aur woh high hai ya low yeh curvature par depend karta hai — lekin growth aur is decay dono ke liye yeh true curve ke neeche land karta hai kyunki dono convex hain.
Verify: actual error. Leading-order Taylor estimate hai — sahi order of magnitude; expansion mein higher-order terms true tak ke gap ka hisaab lagate hain. ✓
Example 3 — Cell C: non-autonomous ,
Forecast: yahan bilkul ko ignore karta hai — slope purely time se set hoti hai. Yeh exactly woh case hai jahan ke andar -shifts bhoolna tumhe silently barbad kar deta hai. Guess karo: kya RK4 ek parabola ke liye exact ya approximate hoga?
Is poore example mein step size hai, isliye jahan bhi dikhe iska matlab hai aur ka matlab hai — main formulas mein rakhta hoon aur end mein substitute karta hoon taaki general shape visible rahe.
- . . Kyun? Bilkul start par slope, , zero hai.
- . . Kyun? Hume zaroor par evaluate karna hai, par nahi. -nudge irrelevant hai kyunki nahi padhta, lekin -shift sab kuch hai.
- . . Kyun? Same → same slope . Confirm karta hai ki jab -independent ho toh do midpoint slopes agree karti hain.
- . . Kyun? End-of-step slope par.
- Combine. factor ko explicit rakhte hue: Kyun? Chaar slopes ka weighted average, se scale kiya kyunki , exactly land karta hai.
Verify: true at is → RK4 error . Exact kyun? RK4 Taylor series ko tak match karta hai; ek quadratic mein ke baad koi terms nahi hain, isliye RK4 uske liye exact hai. ✓
Example 4 — Cell D: oscillation ,
Forecast: slope se shuru hoti hai (tezi se badhti) lekin is quarter-period ke end tak tak ghatti hai. Euler interval ki sabse badi slope ko lock in kar leta hai. Overshoot ya undershoot?
- Euler. . Yeh step kyun? Euler poore quarter-turn mein start slope par trust karta hai. Lekin real slope ghatti rehti hai zero tak, isliye constant slope badly overshoot karta hai.
- Interpret. True value , Euler deta hai → overshoot of . Ex 1 se flip kyun? Growth mein missed slope baad mein badi thi (undershoot). Yahan missed slope baad mein chhhoti hai, isliye same "trust-the-start" rule ab overshoot karta hai. Isliye curvature sign, method nahi, error ki direction decide karta hai.
Verify: . Overshoot confirmed. ✓
Figure padho: Figure s02 mein white curve hai jo tak badhti hai phir flat hoti hai. Amber straight line Euler ka step hai — yeh constant steep slope par chadhti hai aur white curve ke upar shoot karti hai, par end hoti hai jabki true endpoint (cyan square) par baitha hai. s01 se contrast karo: same "trust the start slope" rule, lekin yahan curve flat hoti hai isliye error opposite direction mein jaata hai. Woh sign-flip hi poora lesson hai.

Example 5 — Cell E: degenerate zero slope ,
Forecast: slope har jagah zero hai. Ek correct solver ko unchanged return karna chahiye. Agar tumhara drift kare, toh bug hai.
- Euler. . Kyun? Zero slope × koi bhi step = koi movement nahi.
- RK4. , isliye . Kyun? Har peek zero padhta hai; zeros ka weighted average zero hai.
Verify: dono kisi bhi ke liye exactly return karte hain. ✓ Yeh sabse sasta lekin sabse important unit test hai — koi bhi solver jo tum likhte ho usp pehle run karo.
Example 6 — Cell F: big-step instability ,
Pehle, ek symbol ki zaroorat hai. Jab ek ODE ki form ho, toh number (Greek "lambda") sirf growth/decay coefficient hai — wahi role jo matrix ki rows mein play karta hai "" aur "". Hamare problem ke liye hum simply padh lete hain (ek decay, kyunki negative hai). Neeche sab kuch ke saath likha hai taaki rule reusable rahe, lekin hamare liye .
Forecast: true solution monotonically zero ki taraf decay karti hai. Lekin dekho bada step kya karta hai. Guess karo: kya Euler ke numbers chhhote aur positive rahenge?
- Step 1. . Disaster kyun? Euler step ko slope se multiply karta hai. ke saath correction zero se past negative territory mein overshoot kar jaata hai — ek decay ke liye physically impossible.
- Step 2. . Kyun? Overshoot sign flip karta hai, slope bhi flip hoti hai, aur error har step badhta hai.
- Step 3. . Kyun? Har step magnitude se multiply hoti hai. Yeh hamesha double hota rehta hai — unstable.
Euler ki stability rule: forward Euler par bounded tabhi rehta hai jab . Yahan , isliye hume chahiye . Hamara ise violate karta hai.
Kya RK4 bach jaata hai? Nahi — higher order ka matlab unconditionally stable nahi hota. ke liye har RK4 step ko polynomial se multiply karta hai ( ki Taylor series par truncated — exactly chaar stages). RK4 bounded tabhi hai jab . ke saath milta hai aur jiska magnitude hai, isliye RK4 bhi ke saath is problem par blow up hoga. RK4 ki stability limit yahan roughly hai (jahan ) — Euler ke se bada, lekin phir bhi finite. Lesson: stiff decay ke liye dono methods ke liye chhota karna padega; Numerical Stability and Stiff ODEs dekho.
Verify: safe ke saath: Euler — phir bhi negative lekin , isliye magnitudes ab shrink karti hain, badhti nahi. Sequence . Bounded. RK4 ke liye , deta hai , , isliye RK4 bhi bounded hai. ✓
Figure padho: Figure s03 mein white curve true decay hai jo zero se chipki hui hai. Amber zig-zag Euler hai ke saath: yeh white dashed zero-line ke upar aur neeche fling hota hai, har swing pichle se bada — woh doubling jo tumne compute ki. Cyan markers Euler hain safe ke saath: same alternating signs lekin har swing chhhoti, zero mein spiral hoti. Picture "unstable vs bounded" ko zig-zag ke badhne ya ghattne ka matter bana deta hai.

Example 7 — Cell G: real-world word problem (Newton's cooling)
Forecast: cup pehle tezi se cool hoti hai (bada gap → steep slope), phir slowly. Poore 10-minute step mein Euler sirf initial steep slope use karega. Kya woh true temperature ko overshoot ya undershoot karega?
Setup: . Units: . Start .
- Euler. slope . . Suspicious kyun? Euler predict karta hai ki coffee room temperature par exactly pahunch jaati hai, initial fast cooling ko poore 10 minutes ke liye use karke. Real cooling slow ho jaati hai, isliye itna cool nahi ho sakta.
- RK4 . .
- RK4 . -nudge: ; . Kyun? midpoint slope gentler hai kyunki cup already cool ho gayi.
- RK4 . ; . Kyun? midpoint ko se refine karo.
- RK4 . ; . Kyun? end slope, sab mein sabse gentle.
- Combine. Slopes ka weighted sum hai . Isliye .
Verify: exact solution , isliye . Euler ka ek gross overshoot in cooling hai ( off); RK4 ka sirf off hai ek giant 10-minute step ke bawajood. ✓ Units sab mein. Forecast (Euler bahut zyada cool karta hai) confirmed.
Example 8 — Cell H: exam twist (the reuse- trap + scaling)
Forecast (a): reuse karne se aur identical ho jaate hain — method ek independent slope kho deta hai. Kya correct se bada hoga ya chhota?
Part (a):
- Correct stages (parent se): , correct deta hai.
- Buggy . ( ke same). Damage kyun? ab ko refine nahi karta; do midpoint peeks ab identical information carry karte hain, isliye averaging kamzor hai.
- Buggy . . Kyun changed? galat par build karta hai.
- Combine. . Kyun worse? True ; correct RK4 ne diya (error ), buggy deta hai (error ) — bug ~ worse hai, Euler-jaisi quality ki taraf collapse karta hai.
Part (b):
- Scaling law. RK4 error . se jaana factor reduction hai step mein. kyun? Global error order hai (parent), isliye error se shrink hota hai.
- Predict. .
Verify: (a) buggy inner sum , isliye ; correct RK4 value se iska gap hai. ✓ (b) . ✓
Recall Kaun se cell ne kaun sa lesson sikhaya?
Growth vs decay :::: curvature sign, method nahi, over/undershoot direction decide karta hai (Ex 1, 2, 4). Non-autonomous :::: ke andar -shift kabhi skip mat karo (Ex 3). Zero slope :::: dono methods ko kisi bhi ke liye constant return karna chahiye — tumhara pehla unit test (Ex 5). Big step :::: Euler bounded tabhi hai jab ; RK4 bounded tabhi hai jab — dono ki finite limit hoti hai (Ex 6). Reuse- :::: har stage ko next ko feed karna chahiye warna tum first order ki taraf wapas aa jaate ho (Ex 8a).
Connections
- Taylor Series Expansion — RK4 Ex 3 mein quadratic par exact kyun hai, aur Ex 2 mein error ka source.
- Simpson's Rule — averaging philosophy jo Ex 1 ke RK4 step ke peeche hai.
- Finite Difference Approximation of Derivatives — woh forward difference jo hai Euler.
- Numerical Stability and Stiff ODEs — Ex 6 mein blow-up puri tarah explain kiya gaya hai.
- Adaptive Step Size (RK45 / Dormand–Prince) — solvers kaise choose karte hain taaki Ex 6 kabhi na ho.
- scipy.integrate.solve_ivp — woh production tool jo yeh sab wrap karta hai.