[Tutor] generators?

Kirby Urner urnerk@qwest.net
Thu, 29 Nov 2001 22:10:50 -0800


>
>  >>> for i in range(0,1,.1): print i,
>
>  0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0

OK, I get it now.

yield, like print, is not returning the full floating
point representation as stored internally, and adding .1
successively is introducing slight variances from the
decimal answer, because of the binary thing.

If I force yield to dump a more explicit floating point,
I can see what's happening:

 >>> def lazyrange(start,stop,inc):
         if (start<stop and inc<0) or \
            (start>stop and inc>0):
            raise ValueError,"Illegal"
         while start<stop:
            yield "%r" % start  # <------- note change
            start += inc
         return

 >>> for i in lazyrange(0,1,0.1): print i

0
0.10000000000000001
0.20000000000000001
0.30000000000000004
0.40000000000000002
0.5
0.59999999999999998
0.69999999999999996
0.79999999999999993
0.89999999999999991
0.99999999999999989

start didn't quite reach 1, and so actually yields 1.0
(in the original version) before quitting.

Moral:  floating point can be tricky!  Take care.

Kirby