5.4.22 · D4 · HinglishScientific Computing (Python)

ExercisesFloating point gotchas — catastrophic cancellation, associativity failure

3,325 words15 min read↑ Read in English

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


Level 1 — Recognition

Goal: bina koi mushkil calculation kiye spot karo ki precision kahan marti hai.

Exercise 1.1 — Villain ka naam batao

Har expression ke liye, danger kya hai — (A) catastrophic cancellation, (B) absorption / associativity failure, ya (C) kuch nahi?

  1. for
  2. running sum se shuru karke
  3. for
Recall Solution 1.1

1 → (A). Dono square roots hain aur almost equal hain; near-twins subtract karne se hidden relative error expose ho jaati hai. Amplifier bahut bada hai. 2 → (B) absorption. Har term running sum ke comparison mein astronomically chota hai. ke paas representable doubles ke beech ka gap approximately hai, aur us gap se bahut neeche hai → har add kuch nahi deta. Dekho Catastrophic cancellation ka cousin, absorption. 3 → (C). Multiplication relative error amplify nahi karta; product relative error ke saath store hota hai. Safe hai. 4 → (A). ; ise store karne par interesting part almost round ho jaata hai, phir subtract karne se ek toot-phoot result milta hai. Fix: math.expm1 use karo.


Exercise 1.2 — True ya false

  1. Float addition commutative hai: hamesha.
  2. Float addition associative hai: hamesha.
  3. Do nearly-equal floats ko subtract karna apne aap mein ek inaccurate operation hai.
Recall Solution 1.2

1 → True. aur ek hi real number round karte hain, toh dono exactly agree karte hain. 2 → False. Har + partial sum ki magnitude ke hisaab se ek jagah round karta hai; regrouping alag tarike se round karta hai. 3 → False. Sterbenz lemma ke according (is page ke upar define kiya gaya hai), jab factor of ke andar hain toh subtraction exact hota hai. Yeh sirf woh error expose karta hai jo stored operands mein already baki thi.


Level 2 — Application

Goal: machine model ko real numbers par run karo.

Exercise 2.1 — Amplifier factor

Maan lo aur (exact reals ki tarah treat karo). Is bound ko use karte hue: amplification factor compute karo aur ki worst-case relative error nikalo.

Recall Solution 2.1

WHAT: numbers ko derived amplifier mein dalo. , aur . Worst-case relative error . WHY iska matlab kya hai: humne relative error se shuru kiya aur use tak blow up kar diya — humne almost 7 decimal digits kho diye, exactly amplifier ka .


Exercise 2.2 — Absorption predict karo

Haath se compute karo ki Python (1.0 + 1e16) - 1e16 aur 1.0 + (1e16 - 1e16) ke liye kya print karega. ke paas representable doubles ke beech ka gap exactly hai.

Recall Solution 2.2

Pehla expression: . Sach mein sum hai. Do candidate representable results hain: (neeche) aur (upar, ek pura gap). Sach mein value par hai, jo dono ke exactly beech mein hai. IEEE-754 round-to-nearest, ties-to-even use karta hai: woh us neighbour ko pick karta hai jiski last mantissa bit (even) ho. Yahan ki last bit hai, toh tie neeche ki taraf round hoti hai. Phir . Prints 0.0. Doosra expression: exactly, phir . Prints 1.0. Same teen numbers, sirf brackets alag — answers 100% se different hain. Yeh absorption ke through associativity failure hai. (Tie-to-even detail isliye hai ki kyun gayab hota hai; even tie se alag, koi bhi addend se chota waise bhi round down ho jaata.)


Exercise 2.3 — Stable quadratic root

solve karo jahan , , . Dono roots stably compute karo. identity use karke full precision mein report karo.

Recall Solution 2.3

WHAT/WHY: hai, toh ; + branch same-sign numbers add karta hai → safe root pehle. , matlab se thoda kam. Ab bina subtraction ke dangerous root: Check: ✓ aur ✓. Naive do numbers subtract karta hai → catastrophic. Dekho Quadratic formula numerical issues.


Level 3 — Analysis

Goal: cancellation khatam karne ke liye reformulate karo, aur faayda quantify karo.

Exercise 3.1 — Square-root difference ko rationalise karo

ko par evaluate karo. Naive value ki problem batao, stable rewrite do, aur stable numeric answer bhi do.

Figure — Floating point gotchas — catastrophic cancellation, associativity failure
Figure s01 — Left (danger): do chalk bars, pink aur yellow , itne nearly equal ki unke tops indistinguishable hain; blue double-arrow us razor-thin sach waale difference ko mark karta hai jahan significant digits mar jaate hain. Right (stable): ek single blue bar seedha se compute kiya gaya — koi subtraction nahi, toh koi cancellation nahi. Dono ke beech pink arrow woh conjugate rewrite hai jo danger ko route around karta hai.

Recall Solution 3.1

Naive: aur . Unka difference hai, lekin har root mein relative error hai har ek mein absolute error ; near-twins subtract karne par amplifier se sab kuch barbaad ho jaata hai. Rewrite (WHY): conjugate se multiply karo — yeh near-equals ki subtraction ko denominator mein ek addition se replace kar deta hai: Stable value: . Figure dekho: red "near-twin" bars subtract hokar ek sliver bante hain; blue rewrite us sliver ko bina cancellation ke directly compute karta hai.


Exercise 3.2 — limit

par naive returns (sach wali limit hai). Gap argument se kyun return hota hai yeh dikhao, phir se stable value compute karo.

Recall Solution 3.2

Kyun : . Lekin ke paas sabse chota step hai, aur half a step se bhi chota hai exactly par round ho jaata hai. Phir , aur . Total loss. Stable: ke saath, (tiny arguments ke liye accurately compute hota hai), toh Relative error — perfect.


Exercise 3.3 — Khone wale digits count karo

Aap subtract karte ho amplifier ke saath. Double ke digits se shuru karte hue result mein roughly kitne significant decimal digits bachte hain?

Recall Solution 3.3

Rule: digits lost . digits lost. Survivors significant decimal digits. Yahi amplifier ka practical matlab hai: uska base-10 log digit death toll hai. Dekho Round-off error propagation.


Level 4 — Synthesis

Goal: ek poora stable algorithm assemble karo.

Exercise 4.1 — Kahan summation ko haath se trace karo

Kahan compensated summation ko data par (isi order mein) run karo. Sach wala sum hai. Har step ke baad s aur c dikhao, aur naive left-to-right sum se compare karo.

Recall Solution 4.1

Loop yaad karo: y = x - c; t = s + y; c = (t - s) - y; s = t. Jo facts use honge: ke paas gap hai, toh wahan integers sirf tab representable hain jab even hon; aur representable hain, nahi hai.

Naive left-to-right: . ( absorb ho gaya), (phir absorb), phir . Naive result ka error hai.

Kahan trace (start ). Har line mein: WHAT operation hai, phir rounded value:

  • : y = 1 - 0 = 1 (exact). t = fl(0 + 1) = 1 (exact). c = fl((1 - 0) - 1) = 0. s = 1. → .
  • : y = fl(1e16 - 0) = 1e16 (exact). t = fl(1 + 1e16) = 1e16 half gap se neeche hai, absorb ho gaya. Ab recover karo: t - s = fl(1e16 - 1) = 1e16 (phir absorb, exact difference round up hokar ban gaya), phir c = fl((t - s) - y) = fl(1e16 - 1e16) = 0. Hmm — toh is simple integer data par Kahan c = 0 store karta hai. → . (WHY khoya hua abhi capture nahi hua: t-s aur recovery dono exact grid points par land kiye, toh is step mein koi residual surface nahi hua — loss implicitly is fact mein carry ho raha hai ki s kam hai.)
  • : y = fl(1 - 0) = 1 (exact). t = fl(1e16 + 1) = 1e16 — absorb phir. t - s = fl(1e16 - 1e16) = 0, toh c = fl(0 - 1) = -1. Ab dropp hua capture ho gaya: . s = 1e16. → .
  • : y = fl(-1e16 - (-1)) = fl(-1e16 + 1) = -1e16 ( absorb ho gaya, lekin woh y ki intent mein held hai). t = fl(1e16 + (-1e16)) = 0 (exact cancellation). t - s = fl(0 - 1e16) = -1e16, c = fl((-1e16) - (-1e16)) = 0. s = 0. → .

Final s = 0.0 is exact IEEE trace ke saath. ka akele 's ke aas-paas yeh single interleaving Kahan ko bhi yahan defeat kar deta hai, kyunki compensation khud mein re-add hone par absorb ho jaata hai. Lesson: Kahan us subnormal-relative addend ki pure absorption ke khilaf magic nahi hai jo baad mein cancel ho jaati hai — cure hai reorder karna (giants pehle cancel karo). Yahi Exercise 5.3 hai.

Contrast — ek order jahan Kahan kaam karta hai. par, naive deta hai, lekin left-to-right sum deta hai ; kyunki representable hai, yeh hai . Exact. Moral yehi hai: order beats absorption; Kahan tab help karta hai jab losses residuals hote hain, total absorptions nahi jinke terms baad mein cancel ho jaate hain.


Exercise 4.2 — Robust float comparison design karo

Woh predicate likhao jise Python ka math.isclose use karta hai "kya aur close hain?" ke liye, aur har term explain karo. Phir decide karo: kya 0.1 + 0.2, 0.3 ke close hai defaults rtol=1e-9, atol=0.0 ke saath?

Recall Solution 4.2

Predicate:

  • rtol (relative tolerance) operands ki magnitude ke saath scale hota hai — zaruri hai kyunki float error relative hoti hai.
  • atol (absolute tolerance) us case ko rescue karta hai jab dono ke paas hain (wahan relative test degenerate ho jaata hai). case: computed sum hai, se differ karta hai. Threshold . Kyunki , woh close HAIN → predicate True return karta hai, bhaley hi == False return kare.

Level 5 — Mastery

Goal: prove aur generalise karo.

Exercise 5.1 — Amplifier bound prove karo

Stored operands , se shuru karo jahan , aur assume karo ki subtraction exact hai (Sterbenz, kyunki — is page ke top par definition dekho), aur prove karo:

Recall Solution 5.1

Step 1 (WHAT): computed result expand karo. Step 2: sach wala subtract karo: Step 3 (numerator bound karo): triangle inequality aur se, Step 4 ( se divide karo): WHY "exact subtraction" assumption fair hai: Sterbenz lemma guarantee karta hai ki hone par koi nayi rounding nahi hoti; saara damage mein rehta hai, jo precisely wahi hai jo proof isolate karta hai.


Exercise 5.2 — Absorption threshold, exactly

Ek chota ek bade mein add karo: kin values of ke liye (total absorption) hoga? Threshold ko gap use karke express karo, phir par apply karo.

Recall Solution 5.2

Step 1 (WHAT gap hai): ke paas representable doubles ke beech ki spacing hai: Yeh ke exponent par least-significant mantissa bit ki weight hai. Step 2 (round-to-nearest rule): sach wali value do neighbours aur ke beech hai. Round-to-nearest tab par snap karta hai jab woh se at most half a gap upar ho: Exactly half gap par, ties-to-even decide karta hai: agar ki last mantissa bit (even) hai toh tie bhi ki taraf round hoti hai, toh strict absorption region hai even- ke liye (aur otherwise ). Step 3 ( apply karo): , toh Isliye koi bhi fully absorb ho jaata hai: . Wakai pehla positive integer hai jo double represent nahi kar sakta — ek famous landmark: doubles tak har integer represent karte hain, phir skip karna shuru kar dete hain.


Exercise 5.3 — Sum ko minimize error ke liye order karo

Aapko plain left-to-right addition se (no Kahan) sum karna hai. Sach wala sum hai. Ek aisa ordering dhoondho jo exact answer deta hai, aur principle explain karo.

Recall Solution 5.3

Bura order : absorb, absorb, phir cancel → . Achha order : giants ko pehle cancel karo ( exactly), phir . Exact. Principle: bade opposite-sign terms ko ek doosre ke saath kill karo pehle, taaki woh chote survivors ko nigal na sakein. Jab aap reorder nahi kar sakte (streaming data), residual losses ke liye Kahan use karo — lekin jaise Exercise 4.1 ne dikhaya, Kahan ek total absorption ko bhi rescue nahi kar sakta jo baad mein cancel ho, isliye reordering primary weapon hai. Yahi associativity-failure lesson ek strategy mein badal gaya hai.


Recall

Recall Rapid self-test — answers chhupa lo
  • ke amplifier se kitne digits jaate hain? ::: lagbhag (yaani uska ), bachte hain.
  • ka stable rewrite? ::: .
  • Pehla integer jo double represent nahi kar sakta? ::: .
  • math.isclose predicate? ::: .
  • ka exact sum left-to-right? ::: (giants pehle cancel karo).
  • Quadratic root kaunsa directly compute karte ho, sign-wise? ::: woh jiska , ke sign se match kare (same-sign addition).

Parent: Floating point gotchas · Dekho bhi IEEE-754 floating point representation, Catastrophic cancellation, Kahan compensated summation.