Korva
Tech

Your computer cannot quite write 0.1, so 0.1 plus 0.2 is not 0.3

In binary there is no exact tenth, only halves, quarters, and eighths, so 0.1 repeats forever and has to be cut short.

AI image
Computerphile · Floating Point Numbers - Computerphile

Type 0.1 + 0.2 into most programming languages and the computer answers with something like 0.30000000000000004, not 0.3. It looks like a bug, but it is how the machine does arithmetic.

Computers rarely store decimals the way we write them, because a format that could stretch from the size of the universe to the size of an atom with all the zeros written out would be hugely inefficient. Instead they use floating point, which is scientific notation in base 2: a lengthy string of binary digits multiplied by a power of two, plus a record of where the point goes.

The trouble starts with place value. After the decimal point, we count in tenths, hundredths, and thousandths, so writing one tenth as 0.1 is natural. After the binary point, a computer counts in halves, quarters, eighths, and sixteenths. There is no exact tenth in that system.

To write 0.1 in binary, the machine has to build it out of those ever smaller halves. It comes out as 0.0001100110011, with the 0011 repeating forever. A 32-bit machine keeps only 23 significant digits of that endless string, and a 64-bit machine keeps more but still cuts it off, because it has no way to store “repeating forever.”

It is the same problem as writing one third in decimal. Without a symbol for recurrence, one third becomes 0.333 and stops, so one third plus one third plus one third comes to 0.999, not 1. In binary, both one tenth and two tenths are repeating fractions, so when the computer adds the chopped versions of 0.1 and 0.2, it honestly concludes that they do not quite equal 0.3.

Questions people ask

Does using a more powerful 64-bit computer fix the problem?

No. A 64-bit number, called a double, stores about 15 to 16 decimal digits of precision, compared with about 7 for a 32-bit float. The error gets much smaller, so 0.1 + 0.2 looks like 0.30000000000000004, but the endless binary fraction still has to be cut somewhere.

If computers are always slightly wrong, why does anything work?

Usually it does not matter, because the error is tiny. A video game does not care about a hundredthousandth of a pixel, and most science and engineering already work with measurements that are approximate. It matters when tiny errors add up over millions of calculations or when an exact answer is required.

How do banks avoid charging me $0.3000000001?

They avoid floating point for money. Many programs store prices as whole cents or pence, so $1.10 becomes 110, add with ordinary integer math, and divide by 100 only at the end. Some languages also offer a decimal type designed to represent tenths exactly.