![](/img/trans.png)
[英]Python automatically converts the numerator and denominator of some fractions into big numbers. Why?
[英]Fractions in python returning ridiculously big numbers
我有Python代碼來解決一些遞歸問題,我希望它返回一些分數。
問題是我的代碼返回了荒謬的分數(是正確的),但它們不是最小的分數,我知道這是因為我可以手動求解公式。
這是我的代碼:
from __future__ import division
import sys
from fractions import Fraction
def t(n):
if n==0:
return 0
else:
return 1/(4-t(n-1))
print(Fraction(t(int(sys.argv[1]))))
如果您使用python fraction.py 2
運行此代碼,則應該為4/15,但這是我得到的:
4803839602528529/18014398509481984
我認為這在數字上是正確的,當我進行計算時,我得到0.26666666666666666(也許兩個分數在從0開始的x位數處都不同)。
這里有什么問題?
在進行數學運算之前 ,而不是之后,轉換為Fraction
對象:
def t(n):
n = Fraction(n)
if n==0:
return n
else:
return 1/(4-t(n-1))
如果在轉換為Fraction
之前先進行數學運算,則該數學將作為浮點數學完成,給您不精確的結果,然后您將其轉換為不精確的Fraction
。
如果先進行轉換,則數學將作為分數數學完成,並且事情將保持精確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.