Search code examples
pythonpython-3.xfractions

Replacement for deprecated `fractions.gcd()` function?


I'd like to compute the Greatest Common Divisor of two rational numbers implemented as fractions.Fraction instances. It works as expected although deprecation warning is printed:

In [1]: gcd(Fraction(2, 3), Fraction(2, 3))
/usr/local/bin/ipython:1: DeprecationWarning: fractions.gcd() is deprecated. Use math.gcd() instead.
  #!/usr/local/opt/python3/bin/python3.6
Out[1]: Fraction(1, 6)

Looking at the documentation I can see that fractions.gcd() is indeed deprecated and that users are invited to use math.gcd() instead. The problem is that the latter does not support rational numbers:

In [2]: gcd(Fraction(2, 3), Fraction(2, 3))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-c3ad2389f290> in <module>()
----> 1 gcd(Fraction(2, 3), Fraction(2, 3))

TypeError: 'Fraction' object cannot be interpreted as an integer

Which function can I use in replacement of fractions.gcd()? I'm not looking for the actual algorithm used here, but the replacement for the deprecated function.


Solution

  • You might have to write one. gcd(a/b, c/d) = gcd(a, c)/lcm(b, d), so this isn't too bad. math doesn't provide a lcm, so I'm using the one written here.

    from fractions import Fraction
    from math import gcd
    
    def lcm(a, b):
        """Return lowest common multiple."""
        return a * b // gcd(a, b)
    
    def fraction_gcd(x, y):
        a = x.numerator
        b = x.denominator
        c = y.numerator
        d = y.denominator
        return Fraction(gcd(a, c), lcm(b, d))
    
    print(fraction_gcd(Fraction(2, 3), Fraction(2, 3)))
    # 2/3