Exercise 2: Why 0.5 Is Exact but 0.1 and 0.2 Are Not — Possible Solution ==================================================================== WHAT DETERMINES WHETHER A BINARY EXPANSION TERMINATES ------------------------------ A fraction's binary expansion terminates (has a finite number of digits) exactly when the fraction, written in lowest terms, has a denominator that is a pure power of 2 (1, 2, 4, 8, 16, ...). This is the binary equivalent of the decimal rule that a fraction terminates in decimal exactly when its denominator (in lowest terms) is only made of the prime factors of 10, namely 2 and 5. WHY 0.5 IS EXACT ------------------------------ 0.5 = 1/2. The denominator, 2, is exactly 2^1 - a pure power of two. In binary this is simply 0.1 (one binary digit after the point, representing 2^-1). There is no repeating pattern - the expansion terminates after a single digit, so it fits perfectly into a floating-point mantissa with room to spare and stores with zero error. WHY 0.1 AND 0.2 ARE NOT EXACT ------------------------------ 0.1 = 1/10, and 10 = 2 * 5. Because the denominator has a factor of 5 in it - a prime factor that is not 2 - the fraction cannot be written as an exact power-of-two denominator no matter how it's simplified. The same is true of 0.2 = 1/5, whose denominator is purely 5, again not a power of 2. This chapter verified directly that both 0.1 and 0.2 expand into the infinitely repeating binary pattern 0011 rather than terminating. Since only a finite number of mantissa bits (52 for a double) are available, that infinite pattern must be cut off and rounded, which is exactly why 0.1 and 0.2 are each stored as a close approximation rather than their true value. THE GENERAL RULE ------------------------------ A decimal fraction stores exactly in binary floating point if and only if it can be written as (some integer) / 2^n for a non-negative integer n - in other words, only sums of exact negative powers of 2 (1/2, 1/4, 1/8, 1/16, ...) are guaranteed exact. Any fraction whose reduced denominator contains a prime factor other than 2 - which includes the overwhelming majority of ordinary decimal fractions like 0.1, 0.2, 0.3, and 0.7 - will repeat forever in binary and therefore be stored only approximately. WHY THIS WORKS AS AN ANSWER ------------------------------ The explanation identifies the actual mathematical condition (prime factors of the reduced denominator) rather than just restating that "0.1 doesn't work and 0.5 does," applies that condition correctly to both numbers, and generalizes it into a rule the reader could apply to a new fraction without having to expand it by hand.