Decimals -> Fraction strings, my solution

David C. Ullrich ullrich at math.okstate.edu
Tue May 23 21:11:11 CEST 2000


On Mon, 22 May 2000 12:18:26 +0200, Peter Schneider-Kamp
<petersc at stud.ntnu.no> wrote:

>"David C. Ullrich" wrote:
>> 
>>         Why does Python's implementation of modulo make
>> this a good idea? Is there a problem with the "original"
>> 
>> def gcd(a, b):
>>     while a:
>>         a, b = b % a, a
>>     return b
>> 
>> that I've just never found?
>
>Hei David!
>
>Actually the only problem I see is that the outcome is
>negative. return abs(b) would of course also solve that.

	Well, I personally don't see why that
would be a problem, unless you're assuming it
can't happen - anything unexpected can be bad.

>Additionally I wrote "while a > 0:" which of course
>makes problems for negative numbers... :-7

	I suppose that _could_ be a problem. (I don't
see any "while a > 0" above this point in the thread -
maybe I'm being blind again or maybe you're referring
to unposted code?)

	I guess generally speaking testing the sign
of something is safer than testing whether it equals
zero, lest the thing slip from positive to negative
without hitting 0 in between. But here a is guaranteed
to become 0 sooner or later.

	A year ago my personal gcd function did both
the a = abs(a) and the "if a > b swap" thing. Then
a little later I wanted to deal with rational functions,
ie quotients of polynomials. Imagine how tickled I
was to find that the same gcd routine worked fine if
I just omitted those lines.

DU




More information about the Python-list mailing list