GCD in Fractions
Wolfgang Maier
wolfgang.maier at biologie.uni-freiburg.de
Tue Sep 23 07:53:49 EDT 2014
On 09/23/2014 10:16 AM, blindanagram wrote:
> What is the rationale for gcd(x, y) in Fractions returning a negative
> value when y is negtive?
>
I guess it is implemented this way because its main use is in the
Fraction constructor.
> For example gcd(3, -7) returns -1, which means that a co-prime test that
> would work in many other languages 'if gcd(x, y) == 1' will fail in
> Python for negative y.
>
On the other hand, it allows:
>>> Fraction(3, -7)
Fraction(-3, 7)
and:
>>> Fraction(3, -7) == Fraction(-3, 7)
True
Given that the implementation is particularly useful for Fraction() it
is debatable whether the function shouldn't be called _gcd instead of
gcd, but otherwise it makes sense.
> And, of course, since -|x| is less than |x|, returning -|x| rather than
> |x| is not returning the greatest common divisor of x and y when y is
> negative.
>
however, you can always use abs on y before passing it to gcd.
Wolfgang
More information about the Python-list
mailing list