Does Python have a function to reduce fractions?

Question:

For example, when I calculate 98/42 I want to get 7/3, not 2.3333333, is there a function for that using Python or Numpy?

Asked By: LWZ

||

Answers:

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)
Answered By: John La Rooy

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)
Answered By: rahul-ahuja

This python code uses only the math module
"""

import math
def _fractions_(numerator, denominator):
    if math.gcd(numerator, denominator) == denominator:
        return int(numerator/denominator)
    elif math.gcd(numerator, denominator) == 1:
        return str(numerator) + "/" + str(denominator)
    else:
        top = numerator / math.gcd(numerator, denominator)
        bottom = denominator / math.gcd(numerator, denominator)
        return str(top) + "/" + str(bottom)
print(_fractions_(46,23))
print(_fractions_(34,25))
print(_fractions_(24, 28))

"""

Answered By: Jadon Jung

Does Python have a function to reduce fractions?

No there is no built-in or external function, still you have two solutions.

1. Using fractions module

You can use Fraction objects from fractions module. From the documentation:

from fractions import Fraction
Fraction(16, -10)

>>> Fraction(-8, 5)

In this module a fraction is implicitly reduced, you can get the numerator and the denominator:

a = 16
b = -10
q = Fraction(a, b)
a = q.numerator
b = q.denominator
print (f'{q} == {a}/{b}')

>>> -8/5 == -8/5

2. Reduction using the GCD

Any fraction can be reduced using the GCD, greatest common factor, of numerator and denominator: a/b == (a/gcd)/(b/gcd).

GCD function is available both from numpy and math modules:

import numpy as np
a = 98
b = 42
gcd = np.gcd(a, b)
print(f'{a}/{b} == {int(a/gcd)}/{int(b/gcd)}')

`>>> 98/42 == 7/3


There is an alternative, but I do not consider it as valid for common needs: Use symbolic math with module sympy.

This allows to work with exact numbers at the cost of a loss of efficiency. sympy is it’s own world and some learning time is required.

Answered By: mins