Worked examples — Implementing numerical integration from scratch — trapezoidal, Simpson's
5.4.24 · D3· Coding › Scientific Computing (Python) › Implementing numerical integration from scratch — trapezoida
Shuru karne se pehle, hum un dono machines ko yaad karte hain jinmein hum inputs daal rahe hain. Dono ek function , ek interval , aur equal slices ki sankhya lete hain. Slice ki width node spacing hai, aur jahan hum curve ko sample karte hain woh points nodes hain.
Error terms — signs kahan se aate hain
Examples se pehle hum dono error formulas ek baar settle karte hain, taaki neeche har "Verify:" inhi pe lean kar sake bina hand-waving ke. Hum error ko rule minus truth define karte hain, . Positive ka matlab hai rule ne overshoot kiya.
actually kahan se aata hai (ek Taylor sketch)
Hum chahte hain ki aap local error pe blindly trust na karein; yahan plain steps mein argument hai. Ek slice pe rakhein (width , symmetry ke liye pe centred), aur midpoint value ho.
Step A — curve expand karo. Ek Taylor series kehta hai ki midpoint ke paas, Kyun? Taylor woh ek tool hai jo unknown curve ko "value + tilt + bend + …" likhta hai, exactly woh pieces jo ek straight chord match kar sakta hai aur nahi kar sakta.
Step B — true area integrate karo. Symmetric slice ke upar odd term integrate hokar deta hai, baaki bachta hai Kyun? , aur .
Step C — chord integrate karo (trapezoid actually kya compute karta hai). Trapezoid dono endpoint heights use karta hai, jinka average hai Width se multiply karne par trapezoid area milta hai Kyun? Chord value aur tilt match karta hai lekin bend ko over-account karta hai, kyunki woh curve ko sirf un dono far ends pe sample karta hai jahan convex curve highest hoti hai.
Step D — subtract karo. Local error = chord − truth: Plus kyun? , toh chord ka bend-term jeet jaata hai → positive local error, jo convex-overshoot picture se match karta hai.
Ab slices sum karo: har ek contribute karta hai, aur slices hone se ka ek factor ban jaata hai:
Scenario matrix
Neeche har cell ek class of situation hai jo yeh topic aap pe throw kar sakta hai. Aane wale examples mein har ek us cell ke saath tagged hai jo use cover karta hai.
| # | Case class | Isme kya special hai | Example |
|---|---|---|---|
| C1 | Exact case — rule ki degree ke andar polynomial | Error bilkul exactly zero hona chahiye (rounding tak) | Ex 1 |
| C2 | Convex curve, overshoot sign | Trapezoid over-estimate karta hai; error ka sign kya hai? | Ex 2 |
| C3 | Concave curve, undershoot sign | Trapezoid under-estimate karta hai — opposite sign | Ex 3 |
| C4 | Rule silently fail karta hai — degree jo usse capture hoti hai se upar | Simpson exact nahi hai; ek residual error bacha rehta hai | Ex 4 |
| C5 | Degenerate / reversed input — , , , ya | Zero-width, flat, single slice, reversed limits | Ex 5 |
| C6 | Simpson ke liye odd trap | Parity bug: jab odd ho toh kya karein | Ex 6 |
| C7 | Convergence / limiting behaviour — halving | Error (trap) aur (Simpson) drop honi chahiye | Ex 7 |
| C8 | Real-world word problem — sirf data, koi formula nahi | Aapke paas measurements hain, nahi | Ex 8 |
| C9 | Exam twist — sign change / axis ke neeche negative area | Integral negative ho sakta hai; "area" intuition mislead karta hai | Ex 9 |
Example 1 — exact case (C1)
Recall
kyun kaafi tha? Zyada slices phir bhi exactly 8 denge — ek line ko refine karna kuch nahi badalta ::: kyunki kisi bhi apne do points ko join karne wali straight line us line par hi hoti hai, toh har trapezoid exact hota hai chahe kitne bhi use karein.
Example 2 — convex curve, trapezoid overshoots (C2)
Figure s01 dekho. Horizontal axis hai pe, vertical axis hai. Lavender curve hai; green line woh dono chords hain jo trapezoids use karte hain. Takeaway: ek convex curve pe chord curve ke upar hoti hai, aur coral shaded slivers woh extra area hain jo trapezoid galti se count karta hai — yeh overshoot visible ho gaya.

Step 1. ; nodes ; . Kyun yeh step? Plug karne se pehle standard node table.
Step 2. . Kyun yeh step? Endpoints ka weight 1 hai, single interior node ka weight 2 hai.
Step 3. Compare karo: → overshoot by . Kyun yeh step? Error ka sign is case ka poora point hai.
Verify: Kisi bhi convex ke liye () chord curve ke upar hoti hai, toh . Hamare fixed convention mein ke saath, plus coefficient banata hai — rule truth ke upar. Yeh overshoot sign mein exactly match karta hai.
Example 3 — concave curve, trapezoid undershoots (C3)
Figure s02 dekho. Axes same hain ( horizontal pe, vertical). Lavender curve hai; green line trapezoid chords hain. Takeaway: chord ab arch ke neeche sag karti hai, aur coral slivers woh area hai jo trapezoid miss karta hai — s01 ka exact mirror image, isliye error ka sign flip hota hai.

Step 1. ; nodes ; . Kyun yeh step? Arch ko uski base, peak, base pe sample karo.
Step 2. . Kyun yeh step? Sirf peak node contribute karta hai; endpoints zero hain.
Step 3. → undershoot by . Kyun yeh step? Concavity C2 se compare karke sign flip karta hai.
Verify: pe, toh mein plus coefficient times negative deta hai — rule truth ke neeche. Undershoot confirmed. C2 aur C3 milke prove karte hain ki trapezoid error ka sign ke sign ke barabar hota hai: convex overshoots, concave undershoots.
Example 4 — Simpson exact nahi hai (C4)
Figure s05 dekho. Lavender curve hai; mint dashed curve woh parabola hai jo Simpson teen nodes se fit karta hai. Takeaway: parabola ke sharp late upturn ko follow nahi kar sakti, aur unke beech ka coral gap woh degree-4 error hai jo Simpson absorb nahi kar sakta — isliye answer exact nahi hai.

Step 1. ; nodes ; . Kyun yeh step? pe hai — se confuse mat karo.
Step 2. Kyun yeh step? 1-4-1 stencil, peak node ka weight 4.
Step 3. True value hai, toh estimate overshoots: . Kyun yeh step? Yeh woh case hai jahan rule almost jeet jaata hai lekin fourth-degree error leak karta hai.
Verify — kaunsa error form, aur kyun. Hamaara poora interval ek single Simpson pair hai (sirf slices), toh natural tool per-pair error hai, composite wala nahi — yahan composite use karna pair structure ko double-count kar deta. Per-pair form se, width aur : Yeh truth-minus-rule grouping ke tahat deta hai jo classic sign derive karne ke liye use hoti hai. Hamare page convention ke tahat, yeh flip hokar banta hai — computed overshoot se match karta hai. Magnitude unambiguous hai; sirf printed sign convention pe depend karta hai — exactly woh sign trap jo pehle flag kiya gaya tha. Kisi bhi taraf se, "Simpson is exact" sirf degree 3 tak hold karta hai.
Example 5 — degenerate aur reversed inputs (C5)
Step 1 — zero-width interval. ⇒ . Har term se multiply hota hai, toh . Kyun yeh step? Zero width ka interval koi area enclose nahi karta — formula return karna chahiye, aur karta hai kyunki poori sum ko zero kar deta hai. Koi crash nahi.
Step 2 — flat function. on . Har , toh weighted sum hai; . True integral . Exact. Kyun yeh step? Zero ek degree-0 polynomial hai — dono rules ki exactness ke andar, toh koi error possible nahi.
Step 3 — single slice () aur Simpson kyun nahi kar sakta. ke saath Trapezoid ke koi interior nodes nahi hote; sum empty hai aur — ek valid single trapezoid. Simpson with mathematically impossible hai: Simpson's rule exactly teen nodes ke through parabola ka integral hai, lekin sirf do nodes deta hai (). Do points ek line determine karte hain, kabhi unique parabola nahi, toh integrate karne ke liye koi parabola hi nahi hai — rule undefined hai, aur code ka
ValueErroriska honest report hai. Kyun yeh step? Yeh jaanna ki yeh geometric reason se fail hota hai (too few points), coding whim se nahi, off-by-one panics rokta hai.Step 4 — reversed limits. : yahan , toh . Example 2 ka trapezoid arithmetic negative ke saath redo karo: nodes , , . Kyun yeh step? Negative sign tumhare liye carry karta hai, toh estimate exactly forward answer hai.
Verify: (a) , (b) , (c) pe ka Example 1 mein diya tha, (d) , se match karta hai. Sab consistent. Ek genuine crash sirf hai (tab blow up karta hai), isliye production code mein
n >= 1guard hona zaroori hai.
Example 6 — odd- Simpson trap (C6)
Step 1. odd hai. 1-4-1 stencil slices ek saath do khaata hai; 3 slices ke saath ek bina partner parabola ke reh jaati hai. Kyun yeh step? Yeh structural reason hai ki parity kyun matter karti hai, coding whim nahi.
Step 2. Parent ka code check karta hai
if n % 2 == 1: raise ValueError. Toh call loudly refuse karta hai — best outcome, silent lie se behtar. Kyun yeh step? Raised error ek feature hai: yeh #1 silent bug ko track mein rok deta hai.Step 3 — fix. Do clean options hain: (i) next even tak bump karo (yahan ), ya (ii) pehle even number of slices pe Simpson apply karo aur final dangling slice ko trapezoid se handle karo. Exam ke liye simplest: even choose karo pehle se. Kyun yeh step? Tum case ko sirf detect nahi, repair bhi kar sako, yeh zaroori hai.
Verify: Fixed se redo karo: , nodes , . — exact, jaise ek parabola ke liye expected. Even flawlessly kaam karta hai.
Example 7 — convergence / limiting behaviour (C7)
Figure s03 dekho. Horizontal axis number of subintervals hai (values ); vertical axis trapezoid error hai logarithmic scale pe (toh equal drops equal ratios mean karte hain). Takeaway: teen lavender dots log axis pe straight line mein girte hain, aur har coral "÷4" label mark karta hai ki doubling se error exactly se divide hoti hai — yeh factor ka visual fingerprint hai.

Step 1. : Example 2 se, , error . Kyun yeh step? Jaani hui value ko baseline ke taur pe reuse karo.
Step 2. : , nodes , . . Error . Kyun yeh step? Ratio test karne ke liye ka ek doubling.
Step 3. : eight-node sum compute karne se , error milta hai. Kyun yeh step? Doosra doubling confirm karta hai ki pattern fluke nahi hai.
Step 4 — conclude. Error ratios: aur . Exactly per doubling. Kyun yeh step? Yeh demonstration close karta hai: ki halving ko numeric verdict tak carry kiya gaya.
Verify: drop exactly mein factor hai: halving ko se multiply karta hai. (Isliye Richardson extrapolation aur combine karke term cancel kar sakta hai aur Simpson manufacture kar sakta hai.)
Example 8 — real-world word problem, sirf data (C8)
Step 1. Integral identify karo. Distance speed-time curve ke neeche area hai, , aur hamaara data spacing uniform hai: s. Kyun yeh step? Numerical integration woh ek tool hai jab samples hain, symbolic nahi.
Step 2. Slices count karo: 5 points ⇒ subintervals. even hai, toh Simpson allowed hai — zyada accuracy ke liye use karo. Kyun yeh step? Points ; Simpson choose karne se pehle parity check karo.
Step 3 — Simpson. m. Kyun yeh step? Odd-index nodes (10, 30) weight 4 lete hain; even interior node (22) weight 2 leta hai.
Step 4 — trapezoid cross-check. m. Kyun yeh step? Ek doosra method pehle ke bilkul paas hona ek strong evidence hai ki hum blunder nahi kiya.
Verify: Dono m dete hain; woh agree karte hain, 8 s ke liye accelerate karne wali car ke liye sensible. Units: ✓ — time ke saath speed ka integral distance deta hai, dimensionally correct.
Example 9 — exam twist: signed area (C9)
Figure s04 dekho. Horizontal axis hai pe, vertical axis , -axis drawn hai. Mint region pe positive hill hai (area ); coral region pe negative valley hai (area ). Takeaway: numerical rules signed area compute karte hain — axis ke neeche heights negative hain aur subtract hoti hain — toh dono regions cancel hokar deta hai.

Step 1. True value: . Kyun yeh step? Truth trap expose karta hai: answer zero hai, koi bada area nahi.
Step 2. ; nodes ; . Kyun yeh step? pe negative sample note karo — yahan intuition newcomers ko fail karti hai.
Step 3. . Kyun yeh step? Weight-4 peaks aur cancel ho jaate hain; answer exactly hai.
Verify: true value. Agar exam geometric area maangta (sign se regardless total shaded region), toh aap integrate karte ya pe split karte aur aur add karke paate. Hamesha poochho: signed integral ya geometric area? — yeh differ karte hain jab bhi curve axis cross karti hai.
Connections
- Parent topic — woh derivations jo yeh examples exercise karti hain.
- Riemann sums — woh limit jisme exact cases (C1) reduce hote hain.
- Newton-Cotes formulas — kyun trapezoid degree 1 pe cap karta hai aur Simpson degree 3 pe (C4).
- Polynomial interpolation — Simpson Ex 4 ke figure ka interpolating parabola integrate karta hai.
- Taylor series — yahan derive aur verify kiye gaye aur error terms ki origin.
- Richardson extrapolation — Ex 7 mein error drop wohi hai jo ise kaam karne deta hai.
- scipy.integrate.quad — production code data/word-problem case (Ex 8) ko adaptively kaise handle karta hai.