[Tutor] Floating Confusion
Alan Gauld
alan.gauld at btinternet.com
Thu Aug 23 09:52:17 CEST 2007
"wormwood_3" <wormwood_3 at yahoo.com> wrote
>>>> 1.1
> 1.1000000000000001
> "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.
This isn't just a problem in binary. Consider using normal
decimal the cases of 1/7 or 1/3. There cannot be represented
by any fixed number of decimal digits. 1/3 is 0.3333333.... to
infinity and 1/7 is 0.142857142857..... repeating.
In binary the denominator of the fraction must be a power
of 2 (2,4,8,16 etc) for it to be accurately represented, otherwise
you will get an approximation. Thus 1/10 could be approximated
by 102/1024 = 0.09961 with a fairly small error (4/1024 = 0.00039).
We can reduce the error still further by using bigger numbers,
thus 6554/65536 = 0.100006 The best we can do in Python is
use 2**64 as the denominator and the best approximation of
2**64/10 as the numerator, which gives the result above:
>>> n= (2**64)/10
>>> n
1844674407370955161L
>>> float(n)/(2**64)
0.10000000000000001
But we can never eliminate the error entirely because no power
of two is also a power of 10.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list