Does Python have a function to reduce fractions?

爱⌒轻易说出口 提交于 2019-12-22 01:33:21

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/17537613/does-python-have-a-function-to-reduce-fractions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!