How about adding rational fraction to Python?

Lie Lie.1296 at gmail.com
Sun Feb 17 13:45:57 EST 2008


> 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).

Wrong. Addition and subtraction would only grow the denominator up to
a certain limit

> > 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.
>
> Or, to put it another way, rationals and floats both are dangerous, but
> in different ways. The performance of rationals can fall drastically, and
> floating point calculations can suddenly become inaccurate. You make your
> choice and take your chances.

When I mean safety, fraction is safe in calculation integrity safety,
it is always safe to do calculations in fraction (although at one time
the huge calculation might stall the system, the calculation will
always be correct all the time). But actually there is a way to ensure
performance safety in Fraction class, fraction might grow
uncontrollably only if the data is multiplied or divided. If you're
just doing addition and subtraction, the denominator growth is limited
to a certain range given a limited range of data.



More information about the Python-list mailing list