2015-02-23 17 views
1

例子來說明我的用例:最好的方式來打印十進制數最高的精度,而不在Python尾隨零

from __future__ import division 
a = 215/4 
print a # Case 1. Should print 53.75 

a = 215/3 
print a # Case 2. Should print 71.6666666666666714 i.e. decimal to 16 precision. 

可能的解決方案,不起作用:

print str(a) # Case 2 gets printed with only 12 precision (needed 16) 

print repr(a) # Case 2 gets printed as 71.66666666666667 (precision 14, needed 16) 

print '{0:.16f}'.format(a) # Case 1 gets printed with trailing zeroes 

print '{0:.16g}'.format(a) # Decimal precision is 14, needed 16. 

什麼是最好的pythonic解決這個問題?

編輯:如果16的精度是float除法的限制,那麼用什麼樣的pythonic方法可以得到8位小數的精度。有更好的soln嗎?比'{0:.8f}'.format(a).rstrip('0')

+0

精度實際上不是16位,因爲,你可以看到,它在'714'結束,這是不正確的。 – MattDMo 2015-02-23 04:30:43

+1

爲什麼浮點數實際上沒有16位精度時,要顯示16位數字? – user2357112 2015-02-23 04:36:51

+0

這是否意味着無法通過浮點除法得到18位有效數字(包括16位精度)? – prat0318 2015-02-23 04:52:05

回答

1

我相信getcontext()將會在這裏成爲你的朋友,在小數庫中。

這使您可以設置精度和操縱重要的數字結果。

https://docs.python.org/2/library/decimal.html

+0

這隻適用於使用'decimal.Decimal'進行的計算,並且對於顯示精度並沒有做任何事情。 – user2357112 2015-02-23 04:38:28