for with decimal values?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun May 3 20:05:33 EDT 2009


En Sun, 03 May 2009 17:41:49 -0300, Zentrader <zentraders at gmail.com>  
escribió:

> There is no need for a function or a generator.  A for() loop is a
> unique case of a while loop
> ## for i in range(-10.5, 10.5, 0.1):
> ctr = -10.5
> while ctr < 10.5:
>    print ctr
>    ctr += 0.1

Isn't so easy. You have representation errors and rounding errors here,  
and they accumulate. The last number printed should be 10.4 but I get 10.5:
...
10.3
10.4
10.5
(or more precisely, 10.499999999999959)

Also, after exiting a for loop, the *last* value used is retained. In your  
while loop, the ctr variable contains the *next* value.

-- 
Gabriel Genellina




More information about the Python-list mailing list