gpt4 book ai didi

Python cdecimal InvalidOperation

转载 作者:太空狗 更新时间:2023-10-29 20:14:42 26 4
gpt4 key购买 nike

我正在尝试读取财务数据并将其存储。我从中获取财务数据的地方以惊人的精度存储数据,但我只对小数点后的 5 位数字感兴趣。因此,我决定在我创建的 Decimal 上使用 t = .quantize(cdecimal.Decimal('.00001'), rounding=cdecimal.ROUND_UP),但我一直收到 InvalidOperation 异常。这是为什么?

>>> import cdecimal
>>> c = cdecimal.getcontext()
>>> c.prec = 5
>>> s = '45.2091000080109'
>>> # s = '0.257585003972054' works!
>>> t = cdecimal.Decimal(s).quantize(cdecimal.Decimal('.00001'), rounding=cdecimal.ROUND_UP)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
cdecimal.InvalidOperation: [<class 'cdecimal.InvalidOperation'>]

这里为什么会出现无效操作?如果我将精度更改为 7(或更高),它就会起作用。如果我将 s 设置为 '0.257585003972054' 而不是原始值,那也可以!这是怎么回事?

谢谢!

最佳答案

十进制版本可以更好地描述错误:

Python 2.7.2+ (default, Feb 16 2012, 18:47:58) 
>>> import decimal
>>> s = '45.2091000080109'
>>> decimal.getcontext().prec = 5
>>> decimal.Decimal(s).quantize(decimal.Decimal('.00001'), rounding=decimal.ROUND_UP)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/decimal.py", line 2464, in quantize
'quantize result has too many digits for current context')
File "/usr/lib/python2.7/decimal.py", line 3866, in _raise_error
raise error(explanation)
decimal.InvalidOperation: quantize result has too many digits for current context
>>>

Docs :

Unlike other operations, if the length of the coefficient after thequantize operation would be greater than precision, then anInvalidOperation is signaled. This guarantees that, unless there is anerror condition, the quantized exponent is always equal to that of theright-hand operand.

但我必须承认我不知道这意味着什么。

关于Python cdecimal InvalidOperation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9648650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com