Open Python or a JavaScript console and try 0.1 + 0.2. It prints 0.30000000000000004. Not 0.3. Is the computer bad at arithmetic? No. It is doing exactly what it was designed to do, and the design is a trade. A computer stores every number in a fixed row of bits. A row of 32 or 64 bits can't hold every number between 0 and 1; it can hold only a limited collection, and it picks the nearest one. At the same time, the very same row of 32 bits can hold the speed of light, 3 × 10⁸ metres a second, and the mass of an electron, 9 × 10⁻³¹ kilograms. How can one format cover numbers that different, and be a little wrong about 0.1?
The answer is the format every processor uses, called IEEE 754. The idea is the one you know from physics: scientific notation. You don't write the speed of light with eight digits before the decimal point; you write 3 × 10⁸, a short number and a power. A computer does the same in binary: it stores a sign, a short list of significant bits, and a power of two.
By the end of this chapter you will be able to turn a number like −6.75 or 118.625 into the 32 bits of a single-precision float, and read such a pattern back into a number. You will know what the exponent bias is for, what the special patterns for zero, infinity and NaN mean, and what a denormal number is. And you will explain machine epsilon and why 0.1 + 0.2 is not exactly 0.3, in the way a written paper wants it.
We go in four parts: numbers with a point and binary scientific notation; encoding and decoding by hand; the special values; and precision, machine epsilon and rounding.