5.4.23 · D4 · HinglishScientific Computing (Python)

ExercisesImplementing ODE solvers from scratch — Euler, RK4

3,257 words15 min read↑ Read in English

5.4.23 · D4 · Coding › Scientific Computing (Python) › Implementing ODE solvers from scratch — Euler, RK4


Level 1 — Recognition

(Kya tum pieces ko naam de sakte ho aur formulas mein plug kar sakte ho?)

Exercise L1.1

Euler's method jo single slope use karta hai — words mein aur symbols mein batao woh kahan se aata hai, aur Euler update likho.

Recall Solution

Euler slope ko sirf step ke left endpoint par evaluate karta hai, point par, aur phir maan leta hai ki woh ek slope poore interval mein constant rehta hai. Socho ek straight line se us slope ke saath nikal rahi hai; tum us par horizontal distance slide karte ho aur nayi height padhte ho.

Exercise L1.2

IVP , ke liye ke saath, ek Euler step lo aur do.

Recall Solution

Start par slope: . Yahan sirf par depend karta hai, aur par slope genuinely hai, toh Euler pehle step mein koi rise predict nahi karta (true solution bhi origin par flat hai). .

Exercise L1.3

RK4 ke chaar stages aur final update list karo, label karte hue ki interval mein kahan har slope sample kiya gaya hai.

Recall Solution k_1 &= f(t_n,\ y_n) && \text{slope at the start}\\ k_2 &= f\!\left(t_n+\tfrac h2,\ y_n+\tfrac h2 k_1\right) && \text{slope at the midpoint, using }k_1\\ k_3 &= f\!\left(t_n+\tfrac h2,\ y_n+\tfrac h2 k_2\right) && \text{midpoint again, using }k_2\\ k_4 &= f\!\left(t_n+h,\ y_n+h\,k_3\right) && \text{slope at the end, using }k_3\\ y_{n+1} &= y_n + \tfrac h6\big(k_1 + 2k_2 + 2k_3 + k_4\big) \end{aligned}$$ Weights $1,2,2,1$ ka sum $6$ hai, toh $\tfrac h6(\dots)$ ek sachcha **weighted average slope** hai.

Level 2 — Application

(Real numbers par machinery chalao.)

Exercise L2.1

IVP , (true solution ). use karte hue, estimate karne ke liye do Euler steps lo. Dono intermediate values aur se final error do.

Recall Solution

Step 1 ( se): slope . Step 2 ( se): slope . Error . Curve upar ki taraf bend karta hai, toh Euler — har baar lower left-endpoint slope use karke — undershoot karta hai.

Exercise L2.2

Same IVP , . ke saath estimate karne ke liye ek RK4 step lo. Har dikhao.

Recall Solution k_1 &= f(0,1) = 1\\ k_2 &= f(0.5,\ 1 + 0.5\cdot 1) = f(0.5,\,1.5) = 1.5\\ k_3 &= f(0.5,\ 1 + 0.5\cdot 1.5) = f(0.5,\,1.75) = 1.75\\ k_4 &= f(1,\ 1 + 1\cdot 1.75) = f(1,\,2.75) = 2.75 \end{aligned}$$ $$y_1 = 1 + \tfrac16\big(1 + 2(1.5) + 2(1.75) + 2.75\big) = 1 + \tfrac{10.25}{6} \approx 2.70833$$ Error $\approx 2.71828 - 2.70833 = 0.00995$ — upar ke two-step Euler se lagbhag **47× chhota**, aur RK4 ne *poora step ek hi shot mein* use kiya.

Exercise L2.3

Non-autonomous IVP , . ke saath ek RK4 step lo. (True answer: .) Kyunki par depend nahi karta, sirf -shifts matter karte hain — unhe dikhao.

Recall Solution

Yahan hai, toh har sirf shifted time ka hai:

k_1 &= \sin(0) = 0\\ k_2 &= \sin(0+\tfrac{\pi}{2}) = 1\\ k_3 &= \sin(\tfrac{\pi}{2}) = 1\\ k_4 &= \sin(\pi) = 0 \end{aligned}$$ $$y_1 = 0 + \tfrac{\pi}{6}\big(0 + 2 + 2 + 0\big) = \tfrac{4\pi}{6} = \tfrac{2\pi}{3} \approx 2.0944$$ Error $\approx 0.0944$. Notice karo ki yeh **exactly** Simpson's $1/3$ rule hai $\int_0^\pi \sin t\,dt$ par apply kiya gaya: integrand ko dono ends aur middle par weights $1,4,1$ ke saath sample karo (RK4 ke middle mein $2+2=4$). Dekho [[Simpson's Rule]].

Level 3 — Analysis

(Behaviour explain aur predict karo, sirf compute mat karo.)

Neeche di gayi figure is poore level ke liye geometry setup karti hai. Exercises try karne se pehle ise padho.

Figure — Implementing ODE solvers from scratch — Euler, RK4

Exercise L3.1

, par Euler tak apply karne par par error aur par milta hai. par error kya predict karte ho, aur kyun? Ratio kaun sa order confirm karta hai?

Recall Solution

Euler ka global error hai — ko adha karne se error lagbhag adha ho jaata hai (ratio yeh confirm karta hai). se tak dobara adha karte hue: kyun? Har step ek size ka Taylor term phek deta hai (local truncation error). steps mein yeh accumulate hote hain: . Dekho Taylor Series Expansion.

Exercise L3.2

Same problem par RK4 par error deta hai. aur par error predict karo. Woh order batao jo tumhara factor justify karta hai.

Recall Solution

RK4 ka global error hai, toh adha karne par error se ghatta hai: Yahi wajah hai ki RK4 dominate karta hai: per step same effort seize karne par accuracy sixteen-fold badhti hai har halving mein, jabki Euler ka sirf doubling hota hai.

Exercise L3.3

Figure (s01) dekho. jaisi upward-bending curve par, forward Euler over- ya under-shoot karta hai? Ek aisi curve par jo downward-bending hai jaise region jahan solution concave hai? "One left slope" ki geometry se explain karo.

Recall Solution

Euler left endpoint par khinchi tangent line follow karta hai. Aisi curve ke liye jo concave up hai (upar ki taraf bend karti hai, jaise ), tangent curve ke neeche rehti hai, toh Euler undershoot karta hai (jaise L2.1 mein: ). Aisi curve ke liye jo concave down hai, tangent curve ke upar rehti hai, toh Euler overshoot karta hai. Error ka sign ke sign se set hota hai — precisely woh Taylor term jo Euler discard karta hai. RK4 ise largely cancel karta hai kyunki woh commit karne se pehle midpoint aur end par peek karta hai.


Level 4 — Synthesis

(Ideas combine karo, trade-offs weigho, chhote facts prove karo.)

Exercise L4.1

Ek student ko par mein ka global error chahiye. Scaling laws use karte hue (Euler , RK4 ), roughly har method ko kitne steps chahiye? Practical verdict par comment karo.

Recall Solution

Steps ki sankhya , aur error , toh tak pahunchne ke liye chahiye, yani (constant ignore karte hue).

  • Euler : steps — ek sau million.
  • RK4 : steps. Bhalecha RK4 4 function calls per step cost karta hai, uska total work evaluations Euler ke ko crush karta hai. Verdict: kisi bhi demanding accuracy par, RK4 orders of magnitude se jeetta hai — yahi poori wajah hai ki yeh default workhorse hai.

Exercise L4.2

Prove karo ki autonomous linear test problem ke liye, ek RK4 step ko ek fixed factor se multiply karta hai Phir ke liye evaluate karo aur se compare karo.

Recall Solution

ke saath ( likho):

k_1 &= \lambda y_n\\ k_2 &= \lambda\!\left(y_n + \tfrac h2 k_1\right) = \lambda y_n\left(1+\tfrac z2\right)\\ k_3 &= \lambda\!\left(y_n + \tfrac h2 k_2\right) = \lambda y_n\left(1+\tfrac z2+\tfrac{z^2}{4}\right)\\ k_4 &= \lambda\!\left(y_n + h k_3\right) = \lambda y_n\left(1+z+\tfrac{z^2}{2}+\tfrac{z^3}{4}\right) \end{aligned}$$ $y_{n+1}=y_n+\tfrac h6(k_1+2k_2+2k_3+k_4)$ mein insert karo aur $y_n$ factor karo. $z$ ki powers collect karne par exactly milta hai $$y_{n+1} = y_n\Big(1 + z + \tfrac{z^2}{2} + \tfrac{z^3}{6} + \tfrac{z^4}{24}\Big) = y_n\,R(z).$$ Yeh $e^{z}$ ki Taylor series hai $z^4$ term ke baad truncate ki gayi — RK4 ki order-4 accuracy ka algebraic fingerprint. $z=1$ par: $$R(1) = 1 + 1 + 0.5 + 0.1\overline{6} + 0.041\overline{6} = 2.708\overline{3}$$ jabki $e^1 = 2.71828\dots$ — L2.2 ke $y_1\approx 2.70833$ se exactly match karta hai.

Exercise L4.3

L4.1/L4.2 se use karte hue, par RK4 ki stability condition explain karo jab ho (decaying solution). ko kya satisfy karna chahiye, aur bahut negative ke liye ke baare mein yeh kya imply karta hai?

Recall Solution

Har step se multiply karta hai, toh steps baad . Numerical solution ke liye true solution ki tarah decay karne ke liye ( jab ), hamen chahiye Real ke liye yeh tab tak hold karta hai jab (RK4 ki real stability boundary, sabse negative jahan ). Toh strongly negative ke liye tumhe rakhna padega — ek bahut chhota step — ya phir numbers blow up ho jaate hain bhalecha true answer shrink kar raha ho. Yeh Numerical Stability and Stiff ODEs ka darwaza hai: stiff problems mein huge hota hai, jo tiny force karta hai aur implicit solvers ko motivate karta hai.


Level 5 — Mastery

(Design karo, generalise karo, edge cases ke against defend karo.)

Exercise L5.1

Apne solvers ko ek system (vector-valued) ke liye generalise karo. Scalar rk4 ki kaun si line(s) change hoti hain, aur formula unchanged kyun rehta hai?

Recall Solution

aur har ko vectors ki tarah treat karo; ek vector return karta hai. Python mein NumPy arrays ke saath code identical hai — arithmetic y + h/2 * k1, weighted sum, sab componentwise broadcast hota hai:

def rk4_system(f, t0, y0, h, n):   # y0 is a numpy array
    t, y = t0, y0.copy()
    ts, ys = [t], [y.copy()]
    for _ in range(n):
        k1 = f(t,       y)
        k2 = f(t + h/2, y + h/2 * k1)
        k3 = f(t + h/2, y + h/2 * k2)
        k4 = f(t + h,   y + h   * k3)
        y = y + (h/6) * (k1 + 2*k2 + 2*k3 + k4)
        t = t + h
        ts.append(t); ys.append(y.copy())
    return ts, ys

Update mein linear hai, toh yeh har component par independently apply hota hai — wahi weighted average of slopes, ab ek slope per dimension. Isi tarah 2nd-order ODE solve hota hai: system , ke roop mein rewrite karo.

Exercise L5.2

Harmonic oscillator ki samajh test karo. , , (true: ) ko first-order system ke roop mein rewrite karo, aur position component ke liye ke saath ek RK4 step lo. (True: .)

Recall Solution

lo jahan . Toh , start , . Har stage ek vector hai; hum dono components track karte hain aur end mein position padhte hain.

k_1 &= (v,\,-y)\big|_{(1,0)} = (0,\,-1)\\ \mathbf y + \tfrac h2 k_1 &= \big(1 + \tfrac h2\cdot 0,\ 0 + \tfrac h2(-1)\big) = (1,\,-0.7854)\\ k_2 &= (-0.7854,\,-1)\\ \mathbf y + \tfrac h2 k_2 &= \big(1 + \tfrac h2(-0.7854),\ 0 + \tfrac h2(-1)\big) = (0.3831,\,-0.7854)\\ k_3 &= (-0.7854,\,-0.3831)\\ \mathbf y + h\,k_3 &= \big(1 + h(-0.7854),\ 0 + h(-0.3831)\big) = (-0.2337,\,-0.6017)\\ k_4 &= (-0.6017,\,0.2337) \end{aligned}$$ Ab **position** component par RK4 update apply karo (har $k_i$ ki pehli entry): $$y_1 = 1 + \tfrac h6\big(0 + 2(-0.7854) + 2(-0.7854) + (-0.6017)\big) = 1 + \tfrac{1.5708}{6}(-3.7433) \approx 0.0198$$ True value $\cos(\tfrac\pi2)=0$ hai, toh ek bade step ke baad error sirf $\approx 0.02$ hai — remarkable ek step ke liye jo quarter period span karta hai. (`===VERIFY===` mein numerically verify kiya gaya.)

Exercise L5.3

Degenerate/edge cases. Har ek ke liye, batao tumhara solver kya return karta hai aur kya yeh correct hai: (a) ; (b) steps; (c) (constant solution); (d) ek discontinuous jo ek step ke andar jump karta hai.

Recall Solution
  • (a) : har update hoga aur kabhi advance nahi karta. Loop chalta hai lekin par constant list produce karta hai — mathematically vacuous (koi time pass nahi hota). Code mein iske against guard lagao.
  • (b) : for loop body kabhi execute nahi hoti; tum sirf initial point return karte ho. Correct — zero steps maangne par.
  • (c) : saare , toh hamesha — exactly true constant solution. Euler aur RK4 dono yahan exact hain (zero error), kyunki ek constant degree-0 polynomial hai jo RK4 ki order-4 exactness ke andar aata hai.
  • (d) discontinuous : RK4 ki order-4 accuracy assume karti hai ki smooth hai (yeh ki Taylor expansion par rely karti hai). ke andar ek jump us assumption ko todta hai; tum silently accuracy kho dete ho. Fix: grid point ko exactly discontinuity par rakho taaki koi step ise straddle na kare — wahi event-handling jo scipy.integrate.solve_ivp provide karta hai.


Connections