[Python-Dev] range objects in 3.x

Guido van Rossum guido at python.org
Sat Sep 24 17:13:11 CEST 2011


On Fri, Sep 23, 2011 at 11:55 PM, Georg Brandl <g.brandl at gmx.net> wrote:
> Am 24.09.2011 04:40, schrieb Guido van Rossum:
>> On Fri, Sep 23, 2011 at 7:13 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>>>>> http://code.activestate.com/recipes/577068-floating-point-range/
>>>>
>>>> I notice that your examples carefully skirt around the rounding issues.
>>>
>>> I also carefully *didn't* claim that it made rounding issues disappear
>>> completely. I'll add a note clarifying that rounding still occurs and as a
>>> consequence results can be unexpected.
>>
>> I believe this API is fundamentally wrong for float ranges, even if
>> it's great for int ranges, and I will fight against adding it to the
>> stdlib in that form.
>>
>> Maybe we can come up with a better API, and e.g. specify begin and end
>> points and the number of subdivisions? E.g. frange(0.0, 2.1, 3) would
>> generate [0.0, 0.7, 1.4].
>
> This is what numpy calls linspace:
> http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html
>
> numpy also has an "arange" that works with floats, but:
> """When using a non-integer step, such as 0.1, the results will often not be
> consistent. It is better to use linspace for these cases."""

Aha, I like linspace(). I started a G+ thread
(https://plus.google.com/u/0/115212051037621986145/posts/ZnrWDiHHiaW)
but it mostly served to demonstrate that few people understand
floating point, and that those that do don't understand how hard it is
for the others. Jeffrey Yaskin's analysis (starting with "To anyone
who thinks they can recover inside frange():") is the best of the
bunch. But I still believe that it's best *not* to have frange(), and
to warn about the flaws in the existing implementations floating
around (like Steven's), referring them to linspace() instead.

It looks easy enough to implement a basic linspace() that doesn't have
the problems of frange(), and having a recipe handy (for those who
don't want or need NumPy) would be a great start.

I expect that to implement a version worthy of the stdlib math module,
i.e. that computes values that are correct within 0.5ULP under all
circumstances (e.g. lots of steps, or an end point close to the end of
the floating point range) we'd need a numerical wizard like Mark
Dickinson or Tim Peters (retired). Or maybe we could just borrow
numpy's code.

-- 
--Guido van Rossum (python.org/~guido)


More information about the Python-Dev mailing list