About Rational Number (PEP 239/PEP 240)
Mel
mwilson at the-wire.com
Sun Dec 16 13:17:22 EST 2007
Steven D'Aprano wrote:
> Yes, but my point (badly put, I admit) was that people find fractions far
> easier to work with than they find floating point numbers.
I'm not so sure. I got caught by the comic XKCD's
infinite-resistor-grid thing, and simplified it to a ladder network --
call it L -- made up of 2 1-ohm resistors in series with a 1-ohm
resistor paralleled by L. Simulating this -- assuming an arbitrary
endpoint with resistance 3 -- well, it takes a little thought to
decide that 11/15 < 3/4, and a lot more to decide the same thing for
153/209 and thus decide whether the series is coming or going.
Then when you work out the right answer from
L = 2 + (L / (L+1))
that answer depends on sqrt(12), which Rationals handle just as badly
as floats, and at far greater expense.
I wrote a Rational class back when I was learning to do these things
in Python, and it was actually pretty easy: a dash of GCD, a pinch of
partial fractions, and a lot of following the Python Reference Manual.
It eventually worked as advertised, but I haven't used it since.
It could stand to be updated to use the __new__ method and produce
genuinely immutable instances, if I could find the source.
Mel.
And with any
> rational data type worth the name, you simply should never get anything
> as unintuitive as this:
>
>>>> from __future__ import division
>>>> 4/10 + 2/10 == 6/10
> False
>
>
>
More information about the Python-list
mailing list