在Python中以最大精度打印十进制数而不带尾随零的最佳方法
显示我的用例的示例:在Python中以最大精度打印十进制数而不带尾随零的最佳方法,python,format,decimal,repr,Python,Format,Decimal,Repr,显示我的用例的示例: 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 pr
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.
对于这个问题,最好的Python解决方案是什么
编辑:如果16的精度是float
除法的限制,那么获得8位小数精度的python方法是什么。是否有比'{0:.8f}.format(a).rstrip('0')
更好的解决方案?我相信getcontext()将是您在十进制库中的朋友
这允许您设置精度并操纵重要的图形结果
精度实际上不是16位,因为正如您所看到的,它以
714结尾,这是不正确的。为什么要在浮点数实际上没有16位精度时显示16位数字?这是否意味着不可能获得18位有效数字(包括16位精度)使用浮点除法?18位有效数字完全不可能。我所说的精度是有效数字的数量,其中浮点数略低于16。如果你需要更有效的数字,考虑一下你的计算。本着编程的精神,我们这样做是因为我们可以。它不需要是实际的。如果他想知道怎么做,这就是他要问的地方。这只适用于使用decimal.decimal
执行的计算,而这对显示精度没有任何影响。