Python是否具有减少分数的功能? [英] Does Python have a function to reduce fractions?

查看:73
本文介绍了Python是否具有减少分数的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,当我计算98/42时,我想获取7/3而不是2.3333333,是否有使用Python或Numpy的函数?

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?

推荐答案

fractions模块可以做到这一点

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

此处上有一个用于numpy gcd的食谱.然后可以用来分割分数

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)

这篇关于Python是否具有减少分数的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆