[Python-Dev] range objects in 3.x

Terry Reedy tjreedy at udel.edu
Sat Sep 24 23:12:30 CEST 2011


On 9/23/2011 10:40 PM, Guido van Rossum wrote:
> On Fri, Sep 23, 2011 at 7:13 PM, Steven D'Aprano<steve at pearwood.info>  wrote:

>> 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.

To avoid inclusion/exclusion errors, you should be testing values 
against a stop value that is (except for rounding errors) half a step 
above the last value you want to yield. In other words, subtract or add 
step/2.0 to the stop value according to whether or not you want it 
excluded or included.

> 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.

I completely agree. For range(n), n is both the stop value and number of 
ints generated. It is otherwise stop-start, which is to say, stop = 
start + n, which is why there is no need for an n-based api (all this is 
by design).

> 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]. Or maybe it would even be better to use
> inclusive end points? OTOH if you consider extending the API to
> complex numbers, it might be better to specify an initial value, a
> step, and a count. So frange(0.0, 0.7, 3) to generate [0.0, 0.7, 1.4].
> Probably it shouldn't be called frange then.

In float use cases I can think of, one wants either both or neither end 
point. If neither, one probably wants points at .5*step, 1.5*step, etc., 
where step calculated as (right-left)/n.

-- 
Terry Jan Reedy



More information about the Python-Dev mailing list