Why 0.1 + 0.2 is not 0.3
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.
Step by step
- You write 0.1 and 0.2.
- Each one is rounded to the nearest double the computer can hold.
- The two stored values are added.
- 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
- Floating-Point Arithmetic: Issues and Limitations (Python docs): most decimal fractions have no exact binary form, 0.1 stored as 3602879701896397 / 2**55 and slightly larger than 0.1, 53 bits of precision, 0.1 + 0.1 + 0.1 == 0.3 is False
- The Floating-Point Guide: Basic Answers: 0.1 and 0.2 are rounded to the nearest representable value, the small errors add up to 0.30000000000000004, decimal types, cents as integers and rounding for display
- Number (MDN): 64-bit double precision, about 15 to 17 significant decimal digits