Does Python have a function to reduce fractions? Does Python have a function to reduce fractions? numpy numpy

Does Python have a function to reduce fractions?


The fractions module can do that

>>> from fractions import Fraction>>> Fraction(98, 42)Fraction(7, 3)

There's a recipe over here for a numpy gcd. Which you could then use to divide your fraction

>>> def numpy_gcd(a, b):...     a, b = np.broadcast_arrays(a, b)...     a = a.copy()...     b = b.copy()...     pos = np.nonzero(b)[0]...     while len(pos) > 0:...         b2 = b[pos]...         a[pos], b[pos] = b2, a[pos] % b2...         pos = pos[b[pos]!=0]...     return a... >>> numpy_gcd(np.array([98]), np.array([42]))array([14])>>> 98/14, 42/14(7, 3)


Addition to John's answer:

To get simplified fraction from a decimal number (say 2.0372856077554062)

Using Fraction gives the following output:

Fraction(2.0372856077554062)#> Fraction(4587559351967261, 2251799813685248)

To get simplified answer :

Fraction(2.0372856077554062).limit_denominator()#> Fraction(2732, 1341)