2014-02-10 131 views
2

當我分2/3我得到0.66666666,當我做2 // 3我得到0.在Python中使用整數除法時,我可以保持小數精度嗎?

是否有任何方法來計算整數除法,同時仍保留小數點?

編輯:看起來像我可能會困惑你很多,我的壞。因此,我的教授告訴我,由於標準分區(2/3)只會返回0.666666666666至203位數字,因此當我要計算小數點後需要203位以上的數字時,它才無用。我想知道如果有一種方法可以做到2 // 3(這將返回0),但不知何故仍然獲得0.6666到底

+0

爲什麼第一種方法不起作用? – Christian

+0

你確實說'Integer division _with decimals_'? – 2014-02-10 05:18:02

+0

似乎因爲所有的答案都以不同的方式解釋你的問題,所以你需要讓你的問題更清楚一些。 – SethMMorton

回答

5

對於某些有限小數,您可以使用Python的浮動.as_integer_ratio()方法:

>>> 0.5.as_integer_ratio() 
(1, 2) 

2/3,這是不是在小數精確表示,這開始讓不太理想的結果:

>>> (2/3).as_integer_ratio() 
(6004799503160661, 9007199254740992)  # approximation of 2/3 

對於任意精度的有理數,請在Python庫中使用fractions

>>> import fractions 
>>> fractions.Fraction('2/3') 
Fraction(2, 3) 
>>> Frac=fractions.Fraction 
>>> Frac('2/3') + Frac('1/3') + Frac('1/10') 
Fraction(11, 10) 
>>> Frac('2/3') + Frac('1/6') + Frac('1/10') 
Fraction(14, 15) 

然後,如果你想要的是十進制的更精確表示,使用Decimal庫到整數分子和分母轉換爲任意精度的小數:

>>> f=Frac('2/3') + Frac('1/6') + Frac('1/10') 
>>> f 
Fraction(14, 15) 
>>> f.numerator 
14 
>>> f.denominator 
15 
>>> import decimal 
>>> decimal.Decimal(f.numerator)/decimal.Decimal(f.denominator) 
Decimal('0.9333333333333333333333333333') 
0

也許看一看decimal.Decimal()

>>> import decimal 
>>> x = decimal.Decimal(2/3) 
>>> x 
Decimal('0.66666666666666662965923251249478198587894439697265625') 
+5

這難道不會在一開始就打敗小數?也許更好的是'十進制(2)/十進制(3)' – mgilson

1

你可以在劃分之前也將一個整數投射到一個浮點數。

In [1]: float(2)/3 
Out[1]: 0.6666666666666666 

這將防止整數截斷,給你一個結果作爲float

0

//是一個地板分區,它會給你結果的整數地板。不管你使用2//3還是float(2)//3。使用//時無法保持精確度。

在我的環境(python2.7.6)2//3返回0float(2)//3返回0.0,都不能保持精度。

A similar question也許對你有幫助。

0

這不是直接回答你的問題但它會幫助你udnerstand。

我張貼兩個連接這也解釋了有關實現的非常多的細節:

這是我們需要的東西知道:

>>> 2/3 
0 
>>> 2/3.0 
0.6666666666666666 
>>> 2//3 
0 
>>> -2//3 
-1 
>>> 

from the PEP-0238

當前劃分(/)操作員具有用於 數值參數不明確的含義:它返回除法的數學 結果的地板如果參數是整數或多頭,但它 返回一個合理的近似如果 參數是浮點或複數,則除法結果的結果。這使得表達式期望 漂浮或複雜結果容易出錯,當整數不是 預期但可能作爲輸入。

我們建議由 不同的操作引入不同的運營商來解決這個問題:X/Y來劃分(「真師」)中,x // y的數學結果返回 一個合理的近似 返回地面(「地板劃分」)。我們稱目前,x/y「經典部門」的含義是混合的 。 - 在Python 2.x 系列中,Classic Division將保持默認;真正的劃分將在Python 3.0中成爲標準。

- The // operator will be available to request floor division 
    unambiguously. 

- The future division statement, spelled "from __future__ import 
    division", will change the/operator to mean true division 
    throughout the module. 

- A command line option will enable run-time warnings for classic 
    division applied to int or long arguments; another command line 
    option will make true division the default. 

- The standard library will use the future division statement and 
    the // operator when appropriate, so as to completely avoid 
    classic division. 
相關問題