[Tutor] Floating Confusion

Chris Calloway cbc at unc.edu
Thu Aug 23 03:07:28 CEST 2007


wormwood_3 wrote:
> The second case is, of course, what is throwing me. By having a decimal point, "1.1" is a float type, and apparently it cannot be represented by binary floating point numbers accurately. I must admit that I do not understand why this is the case. Would anyone be able to enlighten me?

This is fairly standard computer science, not just Python. If you take 
freshman Fortran for scientists, you will eat, sleep, and breath this stuff.

Is one tenth any power of 2?

Like how 2**-1 is 0.5? Or how 2**-2 is 0.25? Or 2**-3 is 0.125? Or 2**-4 
is 0.0625. Oops, we went right by 0.1.

Any binary representation of one tenth will have a round-off error in 
the mantissa.

See http://docs.python.org/tut/node16.html for a Pythonic explanation.

See http://en.wikipedia.org/wiki/IEEE_floating-point_standard for how it 
is implemented on most platforms.

This problem was solved in Python 2.4 with the introduction of the 
Decimal module into the standard library:

http://docs.python.org/lib/module-decimal.html
http://www.python.org/dev/peps/pep-0327/

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599





More information about the Tutor mailing list