-
-
Notifications
You must be signed in to change notification settings - Fork 31.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add math.gcd() #66676
Comments
fractions.gcd() is required for normalising numerator and denominator of the Fraction data type. Some speed improvements were applied to Fraction in bpo-22464, now the gcd() function takes up about half of the instantiation time in the benchmark in bpo-22458, which makes it quite a heavy part of the overall Fraction computation time. The current implementation is def gcd(a, b):
while b:
a, b = b, a%b
return a Reimplementing it in C would provide for much faster calculations. Here is a Cython version that simply drops the calculation loop into C as soon as the numbers are small enough to fit into a C long long int: def _gcd(a, b):
# Try doing all computation in C space. If the numbers are too large
# at the beginning, retry until they are small enough.
cdef long long ai, bi
while b:
try:
ai, bi = a, b
except OverflowError:
pass
else:
# switch to C loop
while bi:
ai, bi = bi, ai%bi
return ai
a, b = b, a%b
return a It's substantially faster already because the values will either be small enough right from the start or quickly become so after a few iterations with Python objects. Further improvements should be possible with a dedicated PyLong implementation based on Lehmer's GCD algorithm: |
In case it's useful, see issue bpo-1682 for my earlier Lehmer gcd implementation. At the time, that approach was dropped as being premature optimisation. |
If Python grows an optimized implementation, how about exposing it in the math module? |
+1. |
That's what the patch does anyway. +1 |
Hmm... which patch? |
Here is updated Mark's patch from bpo-1682. It is ported to 3.5, slightly simplified and optimized (I did not touched the main algorithm still), utilized in the fractions module, added tests and documentation. It speeds up Stefan's fractions benchmark about 20%. |
The problem is that this changes the behaviour of fractions.gcd() w.r.t. negative numbers. It's a public function, so we should keep it for backwards compatibility reasons, *especially* when adding a new function in the math module. |
Oh, and thanks for working on it, Serhiy! :) |
see bpo-22477 for a discussion of whether the behavior of fractions.gcd should be changed or not |
sorry, forgot to format the link: |
The thing is, if we add something new in a substantially more exposed place (the math module), then why break legacy code *in addition*? Just leaving it the way it is won't harm anyone, really. |
I wasn't arguing for or against anything, just providing a link to the relevant discussion. |
Well, here is a patch which keeps the same weird behavior of fractions.gcd(). |
I am inclined to think that a maths.gcd() makes sense as this would be where I would go first to find this function. And the prospect of better performance is attractive since the gcd is an important operation in work with number theory algorithms. Would it co-exist with fractions.gcd(), with identical semantics? Or would it co-exist with fractions.gcd(), with the 'less surprising' semantics that are under discussion in the 'GCD in Fractions' thread? Would it take on the suggestion of operating on one or more input parameters? |
Yes, exactly. math.gcd will always give a nonnegative result. The output of fractions.gcd remains unchanged for integer inputs, for backwards compatibility. |
Serhiy: thank you! I've been meaning to update that patch for a long time, but hadn't found the courage or time to face the inevitable bitrot. |
Now I spent more time on the patch. Changes in updated patch:
|
Thanks, Serhiy. However, something is wrong with the implementation. The benchmark runs into an infinite loop (it seems). And so do the previous patches. Does it work for you? |
I compiled it with 30 bit digits, in case that's relevant. (It might be.) |
It works to me (compiled with 15-bit digits). Cold you please add debugging |
This is what hangs for me: math.gcd(1216342683557601535506311712, 436522681849110124616458784) "a" and "b" keep switching between both values, but otherwise, the loop just keeps running. The old fractions.gcd() gives 32 for them. |
I can confirm that it works with 15 bit digits. |
To avoid regressions, please can we leave the old For example, the current I'd also worry about breaking existing uses involving integer-like objects (instances of numpy.int64, for example) in place of instances of ints. [1] By "works", I mean that if a and b are Fractions then gcd(a, b) returns a Fraction such that (1) a and b are integer multiples of gcd(a, b), and (2) gcd(a, b) is an integer multiple of any other number with this property. |
Uh-oh. Sounds like I screwed up somewhere. I'll take a look this weekend, unless Serhiy beats me too it. |
Bah. "to it". Stupid fingers. |
Thank you Stefan. I confirm that it hangs with 30-bit digits. One existing bug is in the use of PyLong_AsLong() before simple Euclidean |
Here is fixed patch. There was integer overflow. In C short*short is extended to int, but int*int |
And for comparison here is simpler patch with Euclidean algorithm. |
Patch 7 works for me. Why are the two Py_ABS() calls at the end needed when we start off the algorithm with long_abs()? The Lehmer code is complex (I guess that's why you added the pure Euclidean implementation), but it's the right algorithm to use here, so I'd say we should. It's 4% faster than the Euclidean code for the fractions benchmark when using 30 bit digits, but (surprisingly enough) about the same speed with 15 bit digits. There is no major difference to expect here as the numbers are perpetually normalised in Fractions and thus kept small (usually small enough to fit into a 64bit integer), i.e. Euclid should do quite well on them. The difference for big numbers is substantial though: Euclid: $ ./python -m timeit -s 'from math import gcd; a = 2**123 + 3**653 + 5**23 + 7**49; b = 2**653 + 2**123 + 5**23 + 11**34' 'gcd(a,b)'
10000 loops, best of 3: 71 usec per loop Lehmer: $ ./python -m timeit -s 'from math import gcd; a = 2**123 + 3**653 + 5**23 + 7**49; b = 2**653 + 2**123 + 5**23 + 11**34' 'gcd(a,b)'
100000 loops, best of 3: 11.6 usec per loop |
Because long_abs()'s are omitted for small enough numbers (common case). So we
Euclidean algorithm is required step at the end of Lehmer algorithm.
May be because Lehmer code uses 64-bit computation for 30-bit digits, and
1000-bit integers are big, but can be encountered in real word (e.g. in |
My personal take is: if there is an implementation in the stdlib, it should be the one that's most widely applicable. And that includes large numbers. We have a working implementation that is algorithmically faster for large numbers, so I can't see why we should drop it unused. I'm for merging patch 7. |
Any objections to merging the last patch? |
Yes! Please don't make these changes to |
There are not such changes in patch 7. The fractions.gcd() function is unchanged but no longer used by the Fraction type, which now uses math.gcd() internally instead. |
Ah, I misread; thanks. What happens with this patch if a Fraction has been created with Integrals that aren't of type int? (E.g., with NumPy int32 instances, for example?) |
Why patching fraction.Fraction constructor instead of fractions.gcd()? I don't like the idea of having two functions, math.gcd and fractions.gcd, which do almost the same, but one is slow, whereas the other is fast. It's harder to write efficient code working on Python < 3.5 (use fractions) and Python >= 3.5 (use math or fractions?). I suggest to modify fractions.gcd() to use math.gcd() if the two parameters are int. We just have to adjust the sign: if the second parameter is negative, return -math.gcd(a, b). (I guess that we have unit tests for fractions.gcd checking the 4 cases for signed parameters.) |
Sounds fine to me, so long as the code (both fractions.gcd and the fractions.Fraction implementation) continues to function as before for objects that don't have exact type int. |
+1 I mean, there is already such a type check in Fraction.__init__(), but I can see a case for also optimising fraction.gcd() for exact ints. |
One other suggestion: I think math.gcd should work with arbitrary Python objects implementing __index__, and not just with instances of int. |
That type-check doesn't protect us from non-int Integrals, though, as far as I can tell. It looks to me as though doing |
I suggest just add deprecation warning in fractions.gcd(). Or at least add
Agree. |
What's the status of this issue? See also the issue bpo-22477. |
Here is a patch which addresses both Mark's suggestions.
But before committing I want to experiment with simpler implementation and compare it with current complex implementation. If the difference will be not too large, we could use simpler implementation. |
Any more comments on this? The deadlines for new features in Py3.5 are getting closer. It seems we're just discussing details here, but pretty much everyone wants this feature. So, what are the things that still need to be done? Serhiy submitted working patches months ago. |
New changeset 34648ce02bd4 by Serhiy Storchaka in branch 'default': |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: