Why 0.1 + 0.2 is not 0.3

· 2 min read

#how-it-works#data

Add 0.1 and 0.2 with ordinary floating-point numbers and the result prints as 0.30000000000000004, not 0.3. The idea to keep: the computer never stored exactly 0.1 in the first place.

The short version

A double (IEEE 754 binary64) keeps a number as a binary fraction with 53 bits of precision. Most decimal fractions, 0.1 among them, have no exact binary form, so the computer stores the nearest one it can. The stored 0.1 sits a hair above 0.1, as the table shows. Addition then works on those stored values, and their small errors end up in the sum.

How 0.1 + 0.2 becomes 0.30000000000000004 The numbers 0.1 and 0.2 are each rounded to the nearest double. The two doubles are added, and the result prints as 0.30000000000000004. you write 1 stored 2 add 3 printed 0.1 0.2 double for 0.1 double for 0.2 add 0.30000000000000004 the stored values are slightly off, so the sum is too
Simplified: each number is rounded when stored, then the rounded values are added.

Step by step

  1. You write 0.1 and 0.2.
  2. Each one is rounded to the nearest double the computer can hold.
  3. The two stored values are added.
  4. The sum prints as 0.30000000000000004.
Value
You write 0.1
The double stores 3602879701896397 / 2**55
In decimal, exactly 0.1000000000000000055511151231257827021181583404541015625

Why it matters

The upside is that 53 bits give about 15 to 17 significant decimal digits, plenty for most work. The downside is that decimal fractions are only approximate, so even 0.1 + 0.1 + 0.1 == 0.3 is false in Python. For money, use a decimal type, or whole numbers such as cents when there is none, and round only for display.

Sources