Python有减少分数的函数吗?

问题描述 投票:0回答:4

例如,当我计算

98/42
时,我想要得到
7/3
,而不是
2.3333333
,是否有使用Python或
Numpy
的函数?

python python-2.7 numpy numerical fractions
4个回答
65
投票

fractions
模块可以做到这一点

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

这里有一个 numpy gcd 的配方。然后你可以用它来除你的分数

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

8
投票
约翰的回答的补充:

从小数中得到简化分数(比如 2.0372856077554062)

使用分数给出以下输出:

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

获得简化答案

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

2
投票
使用数学模块中的数学 gcd

import math def simplify_fraction(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)
    

1
投票
Python有减少分数的函数吗?

不,没有内置或外部功能,但您仍然有两种解决方案。

1。使用 fractions

 模块

您可以使用

Fraction

 模块中的 
fractions
 对象。来自文档:

from fractions import Fraction Fraction(16, -10)

>>> Fraction(-8, 5)


在这个模块中,分数被隐式约简,你可以得到分子和分母:

a = 16 b = -10 q = Fraction(a, b) a = q.numerator b = q.denominator print (f'{q} == {a}/{b}')

>>> -8/5 == -8/5


2。使用 GCD 减少

任何分数都可以使用分子和分母的 GCD(最大公因数)进行约简:

a/b == (a/gcd)/(b/gcd)

GCD 功能可从

numpy

math
 模块使用:

import numpy as np a = 98 b = 42 gcd = np.gcd(a, b) print(f'{a}/{b} == {int(a/gcd)}/{int(b/gcd)}')
`>>> 98/42 == 7/3


还有一种替代方案,但我认为它不适用于常见需求:使用带有模块

sympy 的符号数学。

这允许使用精确的数字,但代价是效率损失。

sympy

是自己的世界,需要一些学习时间。

© www.soinside.com 2019 - 2024. All rights reserved.