This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author gladman
Recipients akira, brg@gladman.plus.com, gladman, mark.dickinson, scoder, steven.daprano, terry.reedy, vstinner, wolma
Date 2014-09-24.19:55:18
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <542321A6.4070002@gladman.plus.com>
In-reply-to <1411575855.15.0.535929588438.issue22477@psf.upfronthosting.co.za>
Content
On 24/09/2014 17:24, Wolfgang Maier wrote:
> 
> Wolfgang Maier added the comment:
[snip]

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

Yes, that's another interesting surprise.

> 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:

I must admit to being more than a little hazy about what is fast and
what isn't in the Python interpreter but wouldn't the use of reduce to
repeatedly call _gcd be slower than an alternative that avoids this?

Taking on board one of Steven D'Aprano's thoughts about multiple inputs,
I had envisaged something like this:

def mgcd(a, *r):  # multiple gcd
  for b in r:
    while b:
      a, b = b, a % b
  return abs(a)

which gives:

>>> mgcd(0)
0
>>> mgcd(7, 0)
7
>>> mgcd(0, 7)
7
>>> mgcd(-3, -7)
1
>>> mgcd(-3, 7)
1
>>> mgcd(7, -3)
1
mgcd(-21, -91, 707)
7

So it has the properties that I believe it should have (yes, I know we
don't agree on this). I am not sure I would extend it to rationals,
although I don't feel strongly about this.

This could be introduced elsewhere without changing what is done in
fractions.  Having two 'gcd's that return different results in some
circumstances might be a source of confusion for some - but not more
than already exists about what values the gcd should return :-)

PS I just know that I am going to regret posting code 'on the hoof' -
it's almost certain to be wrong :-)
History
Date User Action Args
2014-09-24 19:55:18gladmansetrecipients: + gladman, terry.reedy, mark.dickinson, scoder, vstinner, steven.daprano, akira, wolma, brg@gladman.plus.com
2014-09-24 19:55:18gladmanlinkissue22477 messages
2014-09-24 19:55:18gladmancreate