Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have a function to reduce fractions?

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?

like image 981
LWZ Avatar asked Jul 08 '13 23:07

LWZ


People also ask

Can Python handle fractions?

In Python the Fraction module supports rational number arithmetic. Using this module, we can create fractions from integers, floats, decimal and from some other numeric values and strings. There is a concept of Fraction Instance. It is formed by a pair of integers as numerator and denominator.

Are fractions floats in Python?

Changed in version 3.2: The Fraction constructor now accepts float and decimal. Decimal instances. Changed in version 3.9: The math. gcd() function is now used to normalize the numerator and denominator.

How do you find the quotient of a Fraction in Python?

Get quotient and remainder with divmod() in Python In Python, you can calculate the quotient with // and the remainder with % . The built-in function divmod() is useful when you want both the quotient and remainder. divmod(a, b) returns a tuple (a // b, a % b) .


1 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) 
like image 162
John La Rooy Avatar answered Oct 02 '22 11:10

John La Rooy