[Tutor] Loop over floating point values

Steven D'Aprano steve at pearwood.info
Sun Dec 1 10:26:18 CET 2013


On Sun, Dec 01, 2013 at 07:03:15PM +1000, Amit Saha wrote:
> Hello,
> 
> Much to my disbelief, I realized I hadn't written a program in Python
> as far as I can recall which required me to do something like this, in
> psuedocode:
> 
> x = 0.1
> 
> for i = 0 to x step 0.01
> # do something with i
> end i


Such floating point loops are tricky to get right, thanks to rounding of 
floats. Observe:

py> x = 0.0
py> while x < 1.0:
...     x += 0.1
...
py> x == 1.0
False
py> x
1.0999999999999999

We expect that after the loop is done, x should equal 1, but it doesn't. 
That means that it actually loops one time too many.

One way to fix this is to iterate over integers, and then divide just 
before doing the work:

for x in range(0, 10):
    print x/10.0


Another way is to use the recipes I have here:

http://code.activestate.com/recipes/577878-generate-equally-spaced-floats/

http://code.activestate.com/recipes/577881-equally-spaced-floats-part-2/

http://code.activestate.com/recipes/577068-floating-point-range/

I encourage you to read all three. If you have any questions, please 
feel free to ask.




More information about the Tutor mailing list