gladman added the comment:
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 :-)
----------
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue22477>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com