123.3 + 0.1 is 123.3999999999 ?

Anton Vredegoor anton at vredegoor.doge.nl
Thu May 15 13:38:25 EDT 2003


A Puzzled User <kendear_nospam at nospam.com> wrote:

>In Python 2.2.2
>
> >>> float("123.4")+0.1
>123.5
>
> >>> float("123.3")+0.1
>123.39999999999999
>
> >>> float("123.1") + 1
>124.09999999999999
>
>how come there are these inaccuracies?

Computers work with bits internally. A bit can be either switched on
or off. If one wants to express something like the number 1 divided by
3 there's no way to perfectly represent the outcome using something
built out of 2-valued  bits. If there were 3-valued bits this would be
possible, but then there would be problems representing 1 divided by
2. In fact choosing *any* integer-valued bits, there will always be
fractional numbers that can not be exactly represented. So until
there's some smarter way of representing numbers (Qbits, variable
primenumber-valued bits?) we're going to keep having imprecise floats.

>
>
>--------------------------------
>P.S.
>I just tried in Perl
>
>   print eval("123.3") + 0.1;
>
>and it gives
>123.4

Typing in "float("123.3")+0.1" in the interactive interpreter prints
more decimals (printing all *bits* would tell even more), but the same
command as above, but now used in Python gives this:

$ python
Python 2.3b1 (#2, Apr 26 2003, 15:09:25) 
[GCC 2.95.3-5 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print eval("123.3") + 0.1
123.4
>>> 

Now the question is: Can Perl give the value it *really* uses
internally? :->

Anton





More information about the Python-list mailing list