Generating equally-spaced floats with least rounding error

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Sep 24 18:46:39 CEST 2011


Mark Dickinson wrote:

> On Sep 24, 2:53 pm, Steven D'Aprano <steve
> +comp.lang.pyt... at pearwood.info> wrote:
>> I'm trying to generate a sequence of equally-spaced numbers between a
>> lower and upper limit. Given arbitrary limits, what is the best way to
>> generate a list of equally spaced floats with the least rounding error
>> for each point?
>>
>> For example, suppose I want to divide the range 0 to 2.1 into 7 equal
>> intervals, then the end-points of each interval are:
>>
>> (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1)
>>
>> and I'd like to return the values in the brackets. Using Decimal or
>> Fraction is not an option, I must use floats. If the exact value isn't
>> representable as a float, I'm okay with returning the nearest possible
>> float.
> 
> Can you explain why you're constrained not to use Fraction?  Speed?

Speed is important, but secondary to correctness. To be honest, I never even
thought of using fractions as an intermediate result -- I was thinking of
generating lists of Fractions. I think I can use this approach.

But out of curiosity, how would you do it using nothing but floats? Is there
a way?



-- 
Steven




More information about the Python-list mailing list