[FRPythoneers] I must be sitting too close to the monitor.

Keith Hellman khellman at mcprogramming.com
Wed Jan 12 19:38:45 MST 2005


On Wed, Jan 12, 2005 at 01:50:48PM -0700, Scott Durkin wrote:
> SCRIPT:
> 
> change = 0.05
> while change >= 0.01:
>     print change
>     change = change - 0.01 
> 
> OUTPUT:
> 
> 0.05
> 0.04
> 0.03
> 0.02
> 
> QUESTION:
> 
> Why doesn't "0.01" appear in the output?!?!?!
> 

I don't think this is a trivial question at all, things like this always
used to hang me up till I learned to beware the floating point!

You are experiencing round-off error.

I replaced your print statement with 'print "%.18f" % (change,)' and the
output became:
0.050000000000000003
0.040000000000000001
0.029999999999999999
0.019999999999999997

When 0.01 is subtracted from the last number it becomes
0.009999999999999997 (or there abouts...) which is decidely < 0.01

I try to always remember to use something like round(change,2) >= 0.01
when using floating points in comparison.

HTH.


-- 
Keith Hellman                             #include <disclaimer.h>
khellman at mcprogramming.com                from disclaimer import standard
public key @ www.mcprogramming.com

It's a small world. So you gotta use your elbows a lot.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
URL: <http://lists.community.tummy.com/pipermail/frpythoneers/attachments/20050112/56ff7109/attachment.pgp>


More information about the FRPythoneers mailing list