Wolfgang Maier added the comment:

Wouldn't it make more sense to change gcd() in the fractions module to return 
only positive integers?

The current gcd could become _gcd for private use by fractions, and the new 
wrapper gcd could just be implemented as:

def gcd(a,b):
    return abs(_gcd(a, b))


An aspect that hasn't really been discussed so far on the mailing list is that 
this is *not* only about whether the gcd of negative integers should be 
negative or positive, but also about the fact that in the current 
implementation the result of gcd is dependent on the order of the arguments:

>>> gcd(-3,6) == gcd(6,-3)
False

which I think is clearly unexpected.


@Steven:
I share your fear of generating backwards incompatibility only partially. Of 
course, there may be code out there that is relying on the current documented 
behavior for negative integer input, but probably not in too many places since 
after all it's a pretty special need and it's easy enough to implement that 
most people will not even come across the stdlib function before writing their 
own. Even if your code's affected it is really easily fixed.

I do admit though that the proposed change of behavior *could* cause 
hard-to-track bugs in pieces of code that *do* use fractions.gcd right now. So 
I do favor your scheme of raising a warning with negative numbers in Python 
3.5, then changing the behavior in 3.6.

@Steven again:
I was playing around with the idea of having a gcd that accepts more than two 
arguments (and the same for a potential lcm function), then realized that its 
easily written right now as:

>>>reduce(gcd, (3,6,9))
3

Ironically, though, the proposed new gcd would make this slower than it has to 
be since it would do the abs() repeatedly, when

abs(reduce(_gcd, (3,6,9))) would suffice.

So, I guess that's the tradeoff coming with the proposed change:

- a more concise implementation of gcd

against

- broken backwards compatibility and
- reduced flexibility by calling abs implicitly instead of just when the user 
needs it

I guess with that I am 
+0.5 for the change though maybe an extra sentence in the docs about the 
consequences of the already documented behavior of gcd and that you really 
*should* call abs() on the result in most situations may be enough.

----------
nosy: +wolma

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue22477>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to