我使用python 2.7,和我的代碼是:Python的浮動輪錯誤117.285輪117.28 117.29不
a = 10.5 * 22.34/2.0
print "%.2f" % a
,我希望結果是117.29,但它顯示117.28。如何解決問題?
我使用python 2.7,和我的代碼是:Python的浮動輪錯誤117.285輪117.28 117.29不
a = 10.5 * 22.34/2.0
print "%.2f" % a
,我希望結果是117.29,但它顯示117.28。如何解決問題?
如果Python是使用64位IEEE-754二進制浮點類型,那麼它的使用確切值將是
117.284999999999996589394868351519107818603515625
...這顯然比117.28之間的中點低117.29。有可能這就是發生了什麼事。
另一種選擇是Python正在使用Banker's Rounding。
如果確切的小數值對您有影響,您可以考慮使用decimal
來代替。
飛碟雙向先生the correct answer,下面是如何使用decimal
模塊,他指的是一個例子:如果你想有一個簡單的解決方案,並且不關心性能
import decimal
a = decimal.Decimal('117.285')
rounded = a.quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_HALF_UP)
print rounded
# 117.29
repr(rounded)
# "Decimal('117.29')"
,你可以使用這樣的功能轉換爲整數,圓形,轉換回飄:
def round_exact(number, decimal_places=0):
"""Round the number to the given number of decimal places by converting to
and from integers to avoid floating point error."""
factor = 10**(decimal_places + 1)
rounded_int = int(number * factor)
if rounded_int % 10 >= 5:
# Round up
return (int(rounded_int//10) + 1)/float(factor//10)
# Round down
return int(rounded_int//10)/float(factor//10)
很好奇......在嘗試上述(v2.6.4),'打印了'收益率「117.285」。更奇怪的是,'print'%.4f「%117.285'產生」117.2850「。 – 2012-02-15 21:44:27
@NathanErnst:沒有任何東西,它可能使用了一些默認的精度 - 當你指定4 SF時,它*是* 117.2850 ... – 2012-02-15 21:48:11
Python使用平臺'double'作爲它的浮點類型,而'117.285'的確切值確實就在它下面。 (請參閱'%.18f'%117.285'。)Python也使用Banker的舍入,正如您通過比較'%.0f'%0.5'和''%.0f'%1.5'所看到的。 – 2012-02-15 22:15:15