簡體   English   中英

在Python中使用整數除法時,我可以保持小數精度嗎?

[英]Can I keep decimal precision while using integer division in Python?

當我除2/3時我得到0.66666666,當我做2 // 3時我得到0。

有沒有辦法在保持小數點的同時計算整數除法?

編輯:看起來我可能很困惑你,我的壞。 所以我的教授告訴我,由於標准除法(2/3)只返回0.666666666666到203位數,所以當我想進行小數點后需要超過203位數的計算時它沒有用。 我想知道是否有辦法做2 // 3(將返回0)但不知何故仍然得到.6666到底

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

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

對於2/3,這在十進制中不能完全表示,這開始給出不太理想的結果:

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

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

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

您還可以在分割之前將一個整數強制轉換為浮點數。

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

這將阻止整數截斷並以float給出結果。

也許看看decimal.Decimal()

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

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

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

類似的問題可能對您有所幫助。

這不是您問題的直接答案,但它可以幫助您完成任務。

我發布了兩個鏈接,它解釋了有關實現的非常詳細信息:

以下是我們需要注意的事項:

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

來自PEP-0238

當前的除法運算符(/)對於數值參數有一個模糊的含義:如果參數是int或long,它返回除法的數學結果的底限,但如果參數是浮點數或復數,則返回除法結果的合理近似值。 這使得表達式期望浮點或復雜結果在不期望整數但可能作為輸入時容易出錯。

我們建議通過為不同的操作引入不同的運算符來解決這個問題:x / y返回分區的數學結果的合理近似值(“真正的除法”),x // y返回分層(“底層分割”)。 我們稱之為x / y“經典分裂”的當前混合含義。 - Classic Division仍將是Python 2.x系列中的默認值。 真正的除法將成為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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM