123.3 + 0.1 is 123.3999999999 ?

Tim Roberts timr at probo.com
Sat May 17 20:21:43 EDT 2003


A Puzzled User <kendear_nospam at nospam.com> wrote:
>
>I think people won't like it if  12.95 becomes  12.94999999999
>and some comparison fails such as checking if an item is more than
>or equal to $12.95 and the   12.94999999999  doesn't satisfy
>the  >= 12.95   check.

And that's why you have to be very careful when comparing floating point
numbers, a situation that is true in ALL languages on ALL digital
computers.

>I suppose there is no situation that the inaccuracy
>can cause such obvious bugs?

Of course there are!  Floating point is a very dangerous tool when used
improperly or naïvely.  It tends to lull you into thinking that all numbers
are exact, when in fact that is not the case.  As long as you are careful,
things work fine.

>I just wonder why the
>interactive command line gives us 12.949999999 while
>print 12.5    will give us 12.95.... why doesn't the
>command line lie also?

Because the "print" command uses str() which ROUNDS the number to 12
decimal places, whereas the command line uses repr() gives you the "exact"
value, even if the exact value is not what you expected.
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.




More information about the Python-list mailing list