Generating equally-spaced floats with least rounding error

Chris Angelico rosuav at gmail.com
Sat Sep 24 13:19:34 EDT 2011


On Sun, Sep 25, 2011 at 3:01 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Mark Dickinson wrote:
>
>> Using Fraction for intermediate calculations actually works perfectly
>> for this, since conversions from float to Fraction are exact, while
>> conversions from Fraction to float are correctly rounded.  So if
>> you're using Python, you're not too bothered about efficiency, and you
>> want provably correctly-rounded results, why not use Fraction?
>>
> Ah, I knew it was too easy!

Try using Fraction for the start and stop too:
>>> from fractions import Fraction as F
>>> start,stop,n = F(0),F(21,10),7
>>> [float(start+i*(stop-start)/n) for i in range(n+1)]
[0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1]
>>> [float(start+i*(stop-start)/n) for i in range(n+1)]
[-1.0, -0.7, -0.4, -0.1, 0.2, 0.5, 0.8, 1.1]

(Tested in Py 3.2 for Win)

ChrisA



More information about the Python-list mailing list