How about adding rational fraction to Python?

Steve Holden steve at holdenweb.com
Sun Feb 17 15:05:40 EST 2008


Lie wrote:
>> 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.

Surely this assumes that the denominators are being reduced after each 
operation, which would certainly add to the time the operations take.

The simplest and fasted implementation of rational addition and 
subtraction uses a common denominator which is the product of both. To 
avoid denominator growth at each operation you have to start extracting 
common factors, which is bound to slow you down.

So, presuming your "certain limit" is the product of all mutually prime 
denominators that have been involved, you are slowing things down to 
maintain that limitation.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list