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?

Was it helpful?

Solution

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)

OTHER TIPS

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top