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

Jack Diederich jack at performancedrivers.com
Wed Jan 12 20:40:35 MST 2005


On Wed, Jan 12, 2005 at 01:50:48PM -0700, Scott Durkin wrote:
> Hi,
> 
> My apologies for posing a VERY low-level user question . . .
> 
> I use (well, try to anyway) Python in a junior high class I teach.  
> I have a simple script and very dumb question . . . 
> 
> 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?!?!?!

Like in C, floats aren't exact so rounding error makes equality inexact.

if ((1.0 + 1.0) == 2.0): # might compare 2.00000000001 to 1.99999999999
  print "This might never be true!"

In real programs you work around this by adding a delta that is smaller than
the smallest difference you care about

delta = 0.001
while ((change + delta) >= 0.01):
  print change

In your example you could switch to using ints
change = 5
while change >= 1
  print change
  change -= 1

Ints don't have rounding error so this will always work.
You could double back to the floating point example later for a more
advanced lesson.


-Jack



More information about the FRPythoneers mailing list