Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Floating Point Math  ›  Lesson

Why 0.1 + 0.2 Is Not 0.3

Floating Point Math 12 minA binary fraction can only store sums of halves, quarters, eighths and so on exactly, so a decimal like 0.1 is rounded when stored and small errors appear in arithmetic.

Why 0.1 + 0.2 Is Not 0.3

Open almost any programming language and type 0.1 + 0.2. Python, JavaScript, Java and C all agree on the answer: 0.30000000000000004. It is not a bug in the language. It is what happens when you write decimal fractions with binary digits, and every programmer who works with measurements or money needs to understand it.

The rule

Binary fractions are sums of halves; 0.1 is not, so it is rounded.

After the binary point, the places are worth ½, ¼, ⅛, 1/16 and so on, each half of the one before:

binary 0.1    = 1/2          = decimal 0.5
binary 0.011  = 1/4 + 1/8    = decimal 0.375
decimal 0.1   = binary 0.0001100110011…   (repeats forever)

A number is exact in binary only if it can be built from a finite sum of these halves. In other words, written as a fraction in lowest terms, its denominator must be a power of two: ½, ¾, ⅝ and 3/16 are fine.

A tenth has denominator 10 = 2 × 5. That factor of 5 makes the binary pattern repeat forever, just as 1/3 = 0.3333… repeats forever in decimal. A computer keeps only a fixed number of bits, so it stores the nearest value it can. The stored "0.1" is a tiny bit more than 0.1, the stored "0.2" is too, and their sum lands just above the value stored for 0.3.

The error is tiny, around the 17th significant digit. It becomes a problem when you test for exact equality, or when millions of small errors pile up.

The shortcut

To know whether a decimal is stored exactly, write it as a fraction in lowest terms and look at the denominator. Only 2s in it: exact. Any other factor: rounded.

Which of 0.75, 0.3 and 0.625 are exact?Step 1 of 4
  1. 0.75

    0.75 = 3/4. Denominator 4 = 2 × 2: exact.

The trap: thinking "short decimal" means "exact". 0.1 is short in decimal but infinite in binary.

Drills

Answer fast — trust the rule.

quick drill

Which value is stored exactly as a binary floating-point number?

quick drill

Why is 0.1 not stored exactly?

quick drill

What does 0.1 + 0.2 == 0.3 give in Python?

quick drill

Which is the best decimal analogy for 0.1 in binary?

Remember

  • Binary fractions are sums of halves; 0.1 is not, so it is rounded.
  • Lowest-terms denominator a power of two: exact. Anything else: rounded.
  • The trap: a short decimal can be an endless binary fraction.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainThe bug report

A user reports a bug: the program says 0.1 + 0.2 is 0.30000000000000004. Write a short, friendly explanation of why this happens, using an analogy with writing 1/3 in decimal, and name one number that would have added exactly.