Generating equally-spaced floats with least rounding error

Chris Angelico rosuav at gmail.com
Sun Sep 25 02:02:47 EDT 2011


On Sun, Sep 25, 2011 at 3:31 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:>> If you look again at
the code I used, I did. I just did it inside the list> comp.
You did, but you created a Fraction from a float; my version used
Fraction(21,10) instead of (effectively) Fraction(2.1). My description
was a little sloppy, but what I meant was to use Fraction for the
actual arguments to the "function" that this is implementing.
> Something looks a tad suspicious here... the two list comps are identical,
> but give completely different results, even though you don't re-assign
> start and stop between calls. You're not editing your results are you?
> <wink>

Whooops! I had a whole lot of other commands in the scrollback
(displaying intermediate results and such), and elided the rather
crucial reassignment of parameters along with them!

Fortunately, thanks to my reiplophobia, I still have the original
session up in IDLE. This is even the most recent thing in it.

>>> sys.version
'3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)]'
>>> 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]
>>> start, stop, n = F(-1), F(11,10), 7
>>> [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]

There, now it's honest. Sorry about that!!

ChrisA



More information about the Python-list mailing list