Python 3.x 在Python 3.4.2中将小数转换为分数
我只是想在Python中将十进制转换成分数。我在stackoverflow上找到了一些答案 我尝试了这两种方法,但它们在1.4输入下不起作用,尽管它们在0.25输入下起作用Python 3.x 在Python 3.4.2中将小数转换为分数,python-3.x,fractions,python,Python 3.x,Fractions,Python,我只是想在Python中将十进制转换成分数。我在stackoverflow上找到了一些答案 我尝试了这两种方法,但它们在1.4输入下不起作用,尽管它们在0.25输入下起作用 使用标准库:分数 相反 将整数更改为字符串。让我们称之为alpha 查找alpha 创建两个空字符串:beta和gamma 循环的初始a从0到长度 将alpha中的所有元素添加到beta中,直到找到为止 If a decimal is not found or only 0 (or any amounts of z
- 使用标准库:分数
- 相反
alpha
beta
和gamma
从0到长度
alpha
中的所有元素添加到beta
中,直到找到
为止
If a decimal is not found or only 0 (or any amounts of zeros), then your number is over `alpha` over 1.
If a decimal is found, start adding the elements to `gamma`
gamma
转换回int
并使用之前找到的函数beta
转换回int
并乘以gamma
def findFraction(string):
from math import pow
length = len(string)
c = '{a}/{b}'.format(a=string, b=int(pow(10,length)))
print(c)
return c
def finishFraction(addToNumerator, currentFraction):
temp = ''
temp2 = ''
slashFlag = False
for i in range(0,len(currentFraction)):
if currentFraction[i]=='/':
slashFlag = True
elif slashFlag==True:
temp2 =temp2+currentFraction[i]
else:
temp = temp+currentFraction[i]
numerator = int(temp)+(int(addToNumerator)*int(temp2))
fraction = str(numerator)+'/'+str(temp2)
return fraction
def fractionForm(number):
alpha = str(number)
length = len(alpha)
beta = ''
gamma = ''
dotFlag = False
for i in range(0, length):
if alpha[i]=='.':
if dotFlag==True:
print("SHOULD NOT HAVE TWO DECIMALS IN NUMBER")
assert(False)
dotFlag=True
elif dotFlag==False:
beta=beta+alpha[i]
else:
gamma=gamma+alpha[i]
if gamma=='':
print('{a}/{b}'.format(a=int(beta),b=1))
return (int(beta),1)
else:
fraction = findFraction(gamma)
fraction = finishFraction(beta,fraction)
print(fraction)
return fraction
def test():
woooo = fractionForm(1.25)
woohoo= fractionForm(99.999)
dtest()
并非所有实数值都可以用浮点表示。计算
(1.4)。as_integer_fraction()
将为您提供(3152519739159347,2251799813685248)
,即。如果你想要100%的精度,那么你必须完全避免浮点数,并且从一开始就使用小数。