查看 Decimal
我尝试将 pi
转换为各种精度。我可以使用下面的前两个选项调用 pi.quantize()
但它会引发 InvalidOperation
与第三个选项。 pi
的精度远不及...
from decimal import Decimal
pi = Decimal('3.1415926535897932384626433832795028841971693993751058209749445'
'923078164062862089986280348253421170679')
print(pi) # prints same as the string above
# just print formatted
print('{:1.7f}'.format(pi))
print(pi.quantize(Decimal('1.0'))) # 3.1
print(pi.quantize(Decimal('1.00'))) # 3.14
print(pi.quantize(Decimal('1.000'))) # raises InvalidOperation
这里发生了什么?我误解了这个功能应该做什么吗?为什么此异常发生在 1.000
而不是之前/之后?
同样的异常发生在 '0.001'
作为 quantize
的参数时。
最佳答案
根据 the documentation :
...if the length of the coefficient after the quantize operation would be greater than precision, then an
InvalidOperation
is signaled.
因此您的精度必须设置为3
;要检查这一点,请尝试:
from decimal import Decimal, getcontext
print(getcontext().prec)
您应该通读关于 contexts 的文档了解它们的用途以及如何使用它们。例如,您可以尝试:
from decimal import Context, Decimal, getcontext
...
print(pi.quantize(Decimal('1.000'), context=Context(prec=4)))
关于python - Decimal.quantize 引发 InvalidOperation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31795109/