Generating equally-spaced floats with least rounding error

Mark Dickinson dickinsm at gmail.com
Sat Sep 24 14:23:21 EDT 2011


On Sep 24, 6:01 pm, Steven D'Aprano <steve
+comp.lang.pyt... at pearwood.info> wrote:
> Ah, I knew it was too easy!
>
> >>> from fractions import Fraction as F
> >>> start, stop, n = 1, 3.1, 7
> >>> [float(F(start) + i*(F(stop)-F(start))/n) for i in range(n+1)]
>
> [1.0, 1.3, 1.6, 1.9000000000000001, 2.2, 2.5, 2.8000000000000003, 3.1]

I believe that's still giving correctly-rounded results.  Note that
the stop value of 3.1 isn't exactly 3.1 here:  it's

    3.100000000000000088817841970012523233890533447265625

So the 4th value above is the closest float to 4/7 * 1.0 + 3/7 *
3.100000000000000088817841970012523233890533447265625.

--
Mark




More information about the Python-list mailing list