Exercise 2: Fixing the "while x != 1.0" Loop — Possible Solution ==================================================================== WHAT GOES WRONG ------------------------------ The loop's stopping condition, x != 1.0, assumes that repeatedly adding 0.1 to x will, at some exact iteration, produce a value that is bit-for-bit identical to the floating-point number 1.0. That assumption is false. Each addition of 0.1 introduces its own tiny rounding error (per this chapter's own verified finding that even ten additions of 0.1 produce 0.9999999999999999, not 1.0). Those small errors accumulate differently than exact decimal arithmetic would suggest, and verified directly, x overshoots past 1.0 without ever landing on it exactly - by the 20th iteration it has already reached 2.0000000000000004 and keeps climbing. Since x can now never equal 1.0 exactly, the != 1.0 condition is true forever, and the loop never terminates. THE ACTUAL BUG, NAMED PRECISELY ------------------------------ The bug is not "adding decimals is unreliable" in some vague sense. It is specifically that the loop's termination condition depends on exact equality (!=) between two floating-point values that were never guaranteed to coincide bit-for-bit in the first place. Exact equality is the wrong tool for comparing floating-point results of any accumulated arithmetic. A ONE-LINE FIX ------------------------------ while x < 1.0: x += 0.1 Replacing the exact-equality check with an ordering comparison (< 1.0) fixes the infinite loop, because the loop no longer requires x to land on a specific exact bit pattern - it only requires x to eventually exceed a threshold, which accumulating positive additions is guaranteed to do. (A comparison against a small tolerance, e.g. abs(x - 1.0) < 1e-9, is the more general fix used later in this course for checking "close enough" equality, but for a simple incrementing loop like this one, switching to < is the minimal, correct one-line change.) WHY THIS WORKS AS AN ANSWER ------------------------------ The explanation identifies the precise mechanism of failure (exact equality against an accumulated floating-point sum that was never guaranteed to hit that exact value), ties it directly back to this chapter's own verified ten-addition and twenty-iteration findings, and proposes a minimal, genuinely correct fix rather than a vague suggestion like "use a different data type."