How about adding rational fraction to Python?

Carl Banks pavlovevidence at gmail.com
Sun Feb 17 03:21:40 CET 2008


On Feb 16, 7:54 pm, Jeff Schwab <j... at schwabcenter.com> wrote:
> Carl Banks wrote:
> > On Feb 16, 5:51 pm, Jeff Schwab <j... at schwabcenter.com> wrote:
> >> Carl Banks wrote:
> >>> On Feb 16, 3:03 pm, Lie <Lie.1... at gmail.com> wrote:
> >>>> Although rationals have its limitations too, it is a much
> >>>> better choice compared to floats/Decimals for most cases.
> >>> Maybe that's true for your use cases, but it's not true for most cases
> >>> in general.
> >>> Rationals are pretty useless for almost any extended calculations,
> >>> since the denominator tends to grow in size till it's practically
> >>> unusbale,
> >> What do you mean by "practically unusable?"
>
> > So big that a fraction takes 10 minutes to reduce to simplest form and/
> > or your hard disk starts thrashing.
>
> > It can easily happen with seemingly innocuous calculations.
>
> >> I heard similar arguments
> >> made against big integers at one point ("Primitive types are usually big
> >> enough, why risk performance?") but I fell in love with them when I
> >> first saw them in Smalltalk, and I'm glad Python supports them natively.
>
> > It's not the same argument, though.
>
> > Repeated calculations don't make bignums too large to manage unless
> > they're growing it exponentially.
>
> > With rationals, the accumulating calculations usually makes the
> > denominator grow out of control (unless there's some mitigating
> > factor, like in Paul Rubin's example where there were only a ever few
> > denominators.)
>
> OK, thanks for explaining.  It doesn't seem to me intuitively like
> something that would be a problem, but I'm willing to take your word for it.

Consider what happens when you add two fractions:

1/2 + 1/5

To do that, you have to take the LCD of the denomintor, in this case
10, so you get

5/10 + 2/10 = 7/10

Now imagine that you're adding a lot of different numbers with a lot
of different bases.  That LCD's going to be pretty big.  To make
matters worse, imagine taking this number as the divisor in a later
calculation: a new denominator would appear (7).  So you get
denominators that you didn't even input, which can make LCDs go
higher.

Any iteration with repeated divisions and additions can thus run the
denominators up.  This sort of calculation is pretty common (examples:
compound interest, numerical integration).

The thing I don't like about rationals is that they give a false sense
of security.  They are performing reasonably, and then you make a
slight change or some circumstance changes slightly and suddenly they
blow up.


Carl Banks



More information about the Python-list mailing list