PEP 260: simplify xrange()
Tim Peters
tim.one at home.com
Wed Jun 27 13:25:33 EDT 2001
[Dinu Gherman, on extend range/xrange to floats]
> No, I haven't followed the discussion... but you asked
> about an implementation; I'm using the one below.
>
> Dinu
>
>
> def frange(start, end=None, inc=None):
> "A range function, that does accept float increments..."
>
> if end == None:
> end = start + 0.0
> start = 0.0
>
> if inc == None:
> inc = 1.0
>
> L = [start]
> while L[-1] + inc < end:
> L.append(L[-1] + inc)
>
> return L
>>> print len(frange(0.0, 1.0, 0.1))
11
>>>
That's the kind of "inexplicable" crap we don't want to have to try to
explain <wink>: repeated addition is a Bad Idea for floats.
You can improve the numeric quality of the results by generating via
L = []
while 1:
next = start + len(L) * inc
if next >= end:
break
L.append(next)
instead (repeated addition accumulates rounding errors without bound; the
alternative suffers no more than 2 rounding errors (total) for each element
produced). Then it returns 10 elements in the example above.
More information about the Python-list
mailing list