根据文档描述quantize函数:
Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision, then an InvalidOperation is signaled.
当设置的context精度小于计算精度时,报错。例如
from decimal import *
getcontext().prec = 4
a = Decimal('2.6364967465656565')
print(a.quantize(Decimal('.0001')))
a.quantize函数计算得到2.6349,非零个数为5,但是getcontext().prec限制了精度只能到4个非零个数,因此报错。删除getcontext.prec=4即可。
还有一种报错的情况,就是本身数的精确度小于你要精确到的位数,例如
from decimal import *
a = Decimal('0')
print(a.quantize(Decimal('.0001')))
也会报上述错误。如果要将0变成0.0000,应该用下面代码
from decimal import *
a = Decimal('0')*Decimal('1.0000000')
print(a.quantize(Decimal('.0001')))
结果会变成0.0000。