简体   繁体   English

Python 是否有 function 减少分数?

[英]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 ?例如,当我计算98/42时,我想得到7/3而不是2.3333333 ,是否有 function 用于使用 Python 或Numpy

The fractions module can do that fractions模块可以做到这一点

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

There's a recipe overhere for a numpy gcd. 这里有一个 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)

Addition to John's answer:除了约翰的回答:

To get simplified fraction from a decimal number (say 2.0372856077554062)从十进制数中得到简化分数(比如 2.0372856077554062)

Using Fraction gives the following output:使用 Fraction 给出以下输出:

Fraction(2.0372856077554062)
#> Fraction(4587559351967261, 2251799813685248)

To get simplified answer :要获得简化的答案

Fraction(2.0372856077554062).limit_denominator()
#> Fraction(2732, 1341)

This python code uses only the math module """此 python 代码仅使用数学模块“””

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))

""" """

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM