python - Decimal.quantize 引发 InvalidOperation

标签 python python-3.4

查看 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/

相关文章:

python - 访问对象内部结构中的指针

python - 错误 324 空响应 - AttributeError : 'NoneType' object has no attribute 'select'

python - 交叉比较列表中数百万个哈希值的最有效方法

python-2.7 - 在 python3 中使用 h5py 发现 key

linux - Windows 与 Linux 上的 Python 3.4.2 Popen 差异

python - 在Python 3.4中更改直方图的范围

python - 如何使用 Spark Data Frame 中前一行的两列计算一行中的列?

python - 将列表内容存储为具有相同索引的两个不同列表

python - 如何从 Kivy 中的一组小部件动态创建纹理?

python - Python 3.4 中的 `async for`