41

Duplicates:
How is floating point stored? When does it matter?

Is floating point math broken?

Why does the following occur in the Python Interpreter?

>>> 0.1+0.1+0.1-0.3
5.551115123125783e-17
>>> 0.1+0.1
0.2
>>> 0.2+0.1
0.30000000000000004
>>> 0.3-0.3
0.0
>>> 0.2+0.1
0.30000000000000004
>>> 

Why doesn't 0.2 + 0.1 = 0.3?

martineau
  • 119,623
  • 25
  • 170
  • 301
Musaab
  • 1,574
  • 3
  • 18
  • 37

2 Answers2

34

That's because .1 cannot be represented exactly in a binary floating point representation. If you try

>>> .1

Python will respond with .1 because it only prints up to a certain precision, but there's already a small round-off error. The same happens with .3, but when you issue

>>> .2 + .1
0.30000000000000004

then the round-off errors in .2 and .1 accumulate. Also note:

>>> .2 + .1 == .3
False
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • @MarkByers: good point, expanded my answer. – Fred Foo Sep 25 '11 at 10:50
  • 3
    and 0.2 ;-) neither of the 3 can be represented as (-1)^sign * 1.fraction * 2^(exp-127) see http://en.wikipedia.org/wiki/IEEE_754-1985 referenced from accepted answer http://stackoverflow.com/questions/56947/how-is-floating-point-stored-when-does-it-matter/57031#57031 from the duplicate source http://stackoverflow.com/questions/56947/how-is-floating-point-stored-when-does-it-matter – Jeroen Wiert Pluimers Sep 25 '11 at 10:52
  • 1
    so computers can't add `.1` and `.3`? That seems pretty useless then – CodyBugstein Jun 21 '15 at 06:41
  • 11
    http://0.30000000000000004.com/ – tk120404 Nov 13 '15 at 16:32
17

Not all floating point numbers are exactly representable on a finite machine. Neither 0.1 nor 0.2 are exactly representable in binary floating point. And nor is 0.3.

A number is exactly representable if it is of the form a/b where a and b are an integers and b is a power of 2. Obviously, the data type needs to have a large enough significand to store the number also.

I recommend Rob Kennedy's useful webpage as a nice tool to explore representability.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490