5.4.22 · D3 · HinglishScientific Computing (Python)

Worked examplesFloating point gotchas — catastrophic cancellation, associativity failure

3,134 words14 min read↑ Read in English

5.4.22 · D3 · Coding › Scientific Computing (Python) › Floating point gotchas — catastrophic cancellation, associat

Kuch bhi shuru karne se pehle: teen words jo hum baar baar use karenge.


The scenario matrix

Is topic par har trouble in cells mein se ek mein aati hai. Har row neeche ek worked example hai.

# Case class Trigger What breaks Fix family
A Near-equal positives subtract karo , dono catastrophic cancellation algebraic reformulation
B Quadratic, same-sign root , safe sign lo theek hai (koi fix nahi chahiye)
C Quadratic, opposite-sign root doosra root cancellation in
D Degenerate: term rounds to zero , total loss (answer = 0) trig identity
E Absorption — small + huge chota wala gayab ho jaata hai reorder / Kahan
F Associativity flip grouping se answer badal jaata hai pehle large terms cancel karo
G Summation order over a list many tiny + one huge error ke saath badhti hai sort ascending / Kahan
H Equality comparison 0.1+0.2 == 0.3 unexpectedly False tolerance compare
I Real-world word problem GPS / distance difference cancellation disguise mein chhupta hai physics reformulate karo
J Exam twist "higher precision fixes it?" conditioning ≠ precision reformulate karo, upgrade mat karo

Example A — near-equal positives subtract karo

Steps.

  1. True value. . Ye step kyun? Hume honest target chahiye taaki hum uske against error measure kar sakein. Approximation se aati hai.

  2. Naive compute. Doubles mein, exactly hai, aur — lekin rounds to (gap near hai, isliye add karna edge se gir jaata hai, cell E in disguise). Toh dono square roots ke barabar hain, aur subtraction deti hai. Ye step kyun? Double failure dikhata hai: pehle absorption, phir do identical numbers subtract karo toh exactly milta hai.

  3. Damage measure karo. Relative error — 100% galat. Ye step kyun? Confirm karta hai "catastrophic": answer completely lost ho gaya.

  4. Reformulate. Top aur bottom ko conjugate se multiply karo: Ab compute karo. Near-equals ki koi subtraction nahi — hum sirf same-sign roots add karte hain aur divide karte hain. Ye step kyun? Division aur same-sign addition kabhi relative error amplify nahi karte (parent note, §2), toh hum villain ke around route le lete hain.

Verify: reformulated value true se full precision tak match karta hai. Sanity: large ke liye consecutive roots ke beech gap ki tarah shrink hona chahiye — karta hai. ✓


Examples B & C — do quadratic roots

Hum ek quadratic lete hain aur dono roots nikalte hain, kyunki dono roots alag matrix cells mein rehte hain: ek safe hai (B), ek cancel hota hai (C).

Steps.

  1. Discriminant. , toh . Ye step kyun? Dono roots ye square root share karte hain; ek baar compute karo.

  2. Same-sign root (Cell B — safe). Kyunki hai, term positive hai; safe root do positives add karta hai: Ye step kyun? Do same-sign near-equal numbers add karna cancel nahi karta — koi amplification nahi. Ye root trustworthy hai.

  3. Opposite-sign root, naive (Cell C — catastrophic). Yahan cancellation do operands aur ke beech hoti hai. Parent note ka amplifier, generic subtraction ke liye likha, hai (parent ke §2 mein letters sirf placeholder operands hain — ye quadratic coefficients nahi hain). Plug in karo: — precision annihilated. Ye step kyun? Cancellation aur uski size expose karta hai, operands ko coefficients se confuse nahi karte.

  4. Stable second root. (product of roots) use karo, toh Ye step kyun? Hamare paas pehle se safe root hai; product identity sirf division use karke deta hai — near-equals ki koi subtraction nahi. Dekho Quadratic formula numerical issues.

Verify: back plug karo: . Product check: . Sum check: . ✓


Example D — ek term zero round ho jaata hai (degenerate)

Steps.

  1. True value. Taylor: , toh aur . Ye step kyun? Target establish karta hai.

  2. Machine kya store karta hai. . Lekin , toh exactly round ho jaata hai. Ye step kyun? Woh information jo ko nonzero banati thi machine epsilon ke neeche rehti hai — subtraction se pehle hi gone ho jaati hai.

  3. Naive result. , toh . Relative error (total loss). Ye step kyun? Degeneracy confirm karta hai: answer zero collapse ho jaata hai.

  4. Trig identity se reformulate karo. , hence Chhote argument ka accurately compute hota hai (woh argument hai, koi cancellation nahi), aur , toh . Ye step kyun? Humne "subtract near-equals" ko " of a small number" se replace kiya, jise library faithfully evaluate karti hai.

Verify: par, , toh . Limit se match karta hai. ✓

Figure neeche dono naive aur reformulated versions ko kaafi values par plot karta hai. Aise padho: dashed gray line true limit hai; green curve (reformulated) seedha usse hug karta rehta hai neeche tak; red curve (naive) pe ride karta hai jab tak , phir cliff se gir ke par aa jaata hai jis waqt round ho jaata hai. Woh cliff hi catastrophic cancellation hai — picture exactly woh dikhati hai jahan naive formula marr jaata hai.

Figure — Floating point gotchas — catastrophic cancellation, associativity failure

Example E — absorption (small + huge)

Steps.

  1. par gap. magnitude ke paas, consecutive doubles se differ karte hain (mantissa ka last bit ab nahi, weight karta hai). Toh ke neighbours apart hain. Ye step kyun? Us magnitude par resolution jaanna zaroori hai — precision relative hoti hai, isliye bade numbers coarse spacing rakhte hain (dekho IEEE-754 floating point representation).

  2. add karo. (odd) — lekin woh representable nahi; nearest doubles aur hain. Rounding-to-nearest rakhta hai. Ye step kyun? gap ke aadhe se chhhota hai, isliye absorbed ho jaata hai — completely vanish ho jaata hai.

  3. Consequence. . ne koi trace nahi chhoda. Ye step kyun? Ye Example F mein associativity break ka mechanism hai.

Verify: Python mein, 1e16 + 1 == 1e16 is True; 1e16 + 2 == 1e16 is False. Gap exactly hai. ✓


Example F — associativity flip

Example se pehle, ek chhhota sa lemma jis par hum lean karenge.

Steps.

  1. Left grouping . (absorption, Example E). Phir . Ye step kyun? Dikhata hai ki pehle add mein mar jaata hai, isliye result hai.

  2. Right grouping . exactly — ye Sterbenz lemma upar hai: aur magnitude mein equal hain, isliye subtraction koi rounding introduce nahi karta. Phir . Ye step kyun? Yahan huge numbers pehle cancel ho jaate hain (exactly), tiny ko protect karte hain.

  3. Compare. Left , right . differ karte hain. Ye step kyun? Demonstrate karta hai ki floating addition associative nahi hai — grouping decide karta hai kaun se bits survive karte hain.

  4. Rule of thumb. Large opposite-sign terms ko pehle cancel karo, chote ones add karne se pehle. Ye step kyun? Chote term ko absorb hone se bachata hai.

Verify: (1.0 + 1e16) + (-1e16) == 0.0 aur 1.0 + (1e16 + (-1e16)) == 1.0. ✓

Bar chart neeche flip ko vivid banata hai. Aise padho: left red bar grouping hai — woh tak collapse ho jaata hai kyunki ko ne absorb kar liya ke cancel karne se pehle; right green bar hai — woh tak pahunchta hai kyunki do huge terms pehle annihilate ho jaate hain (Sterbenz-exact) aur survive karta hai. Numbers ke do identical sets, do alag heights: woh height gap hi associativity failure hai.

Figure — Floating point gotchas — catastrophic cancellation, associativity failure

Example G — list par summation order

Steps.

  1. Naive left-to-right. Start . Pehla add karo: (absorbed). Har subsequent similarly absorbed ho jaata hai. Final — saare ones lost. Ye step kyun? Running partial sum pehle step se hi huge hai, isliye har tiny addend uske gap ke neeche gir jaata hai.

  2. Ascending order. Sort karo taaki huge number last aaye: pehle million ones sum karo, milega (har add comparable numbers ke beech hai — safe), phir add karo. Ab : gap at hai, aur , isliye survive karta hai: . Ye step kyun? Pehle smallest add karne se woh itne bade number mein accumulate ho jaate hain ki absorb na ho sakein. Dekho Round-off error propagation.

  3. Kahan option. Kahan compensated summation lost low bits ko ek compensator c mein carry karta hai, jo error deta hai order aur se independent. Ye step kyun? Jab sort nahi kar sakte (streaming data), Kahan waise bhi accuracy recover karta hai.

Verify: naive deta hai; ascending deta hai; dono true se compare karo. ✓


Example H — equality trap

Steps.

  1. Kyun woh exact nahi hain. finite binary fractions nahi hain (jaise decimal mein ). Har ek nearest double ke roop mein store hota hai, pehle se off. Ye step kyun? Premise "math mein equal ⇒ floats mein equal" galat hai kyunki inputs khud rounded hain.

  2. Sum. , jabki . Dono se differ karte hain. Ye step kyun? Dikhata hai ki dono sides alag doubles par land karte hain, isliye == False return karta hai.

  3. Fix: tolerance compare. math.isclose(x, y) use karo, yaani default rtol=1e-9 ke saath. Ye step kyun? Hum poochhte hain "kya woh round-off ke andar equal hain?" bajaaye "bit-identical?".

Verify: 0.1 + 0.2 == 0.3 is False; difference lagbhag hai; abs((0.1+0.2)-0.3) < 1e-9 is True. ✓


Example I — real-world word problem

Steps.

  1. True difference. . Ye step kyun? Target set karta hai: ek 25 cm difference.

  2. Digit accounting. Har altitude significant digits (double) ke liye good hai. Har ek ka absolute error lagbhag hai. Subtraction exact hai (Sterbenz — do values factor of 2 ke andar hain), toh woh do absolute errors seedha mein carry ho jaate hain: worst case . ka relative error tab hai. Ye step kyun? Relative-error amplifier batata hai ki hum lagbhag digits lose karte hain. good digits se start karke, roughly bachte hain — toh yahan bhi theek hai. Lekin agar do altitudes 25 nanometres apart hote, amplifier hota aur kuch bhi survive na karta. Ye kyun matter karta hai: danger scale karta hai ki do bade numbers kitne close hain.

  3. Engineering fix. Difference ko ek common reference se store karo: har reading se ek base altitude (maano ) rounding se pehle subtract karo, ya ek local coordinate frame mein kaam karo jahan chhhoti quantity seedha represent ki jaati hai na ki do bade numbers ke difference ke roop mein. Tab tum 25 cm quantity par full precision rakhte ho, kyunki woh kabhi big-minus-big se paida nahi hoti. Ye step kyun? Interesting chhhoti number ko kabhi do nearly-equal large numbers ke difference ke roop mein paida mat hone do — seedha represent karo. Dekho Numerical stability and conditioning.

Verify: ; amplifier ; digits lost . ✓


Example J — exam twist

Steps.

  1. float128 kya deta hai. `np.float128` (x86 80-bit extended) mein significant digits hain, . Ye step kyun? Claim karne se pehle naya resolution jaano ki woh help karta hai ya nahi.

  2. Kya cancellation vanish ho jaati hai? ; ab , toh term is particular par survive karti hai, aur tumhe milta hai. Lagta hai fixed ho gaya. Ye step kyun? Dikhata hai ki higher precision sirf cliff ko postpone karta hai.

  3. chhhota karo. par, , toh float128 bhi round kar deta hai. Catastrophe wapas aata hai — tumne sirf threshold move ki. Ye step kyun? Prove karta hai ki problem formula ki conditioning hai, machine ki precision nahi.

  4. Correct fix. ke roop mein reformulate karo (Example D). Ye plain float64 mein sabhi small ke liye kaam karta hai. Ye step kyun? Expression fix karna hardware upgrade karne se better hai — parent note ka mistake "more precision always fixes accuracy", cell J.

Verify: par, float64 naive lekin reformulated ; reformulation ko koi extra precision nahi chahiye. ✓


Recall

Recall Answers cover karo — kaun sa fix kaun se cell ke liye?

Kaun sa cell hai "do bade same-sign numbers subtract karo"? ::: A / C — catastrophic cancellation, fix by reformulation. Safe quadratic root kaun sa sign of use karta hai? ::: Woh sign jo ko add karta hai (same sign as ), toh koi cancellation nahi. Dangerous quadratic root safely kaise nikaalte hain? ::: product of roots se. Kyun float64 mein exactly 0 deta hai? ::: correction ke neeche hai, toh round ho jaata hai. One-huge-many-tiny ke liye best summation order? ::: Ascending (smallest first) — ya Kahan. Kya float128 ek cancelling formula fix karta hai? ::: Nahi, ye sirf threshold move karta hai; bajaaye reformulate karo. Sterbenz lemma kya guarantee karta hai? ::: Agar do same-sign floats factor of 2 ke andar hain, unki subtraction exactly compute hoti hai (koi rounding nahi).