Python-cdecimal无效操作

2024-06-26 04:13:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着阅读和存储财务数据。我从那里得到的财务数据以难以置信的精度存储数据,但我只对小数点后5位数感兴趣。因此,我决定对创建的十进制使用t=.quantize(cdecimal.Decimal('.00001'),rounding=cdecimal.ROUND_UP),但我一直收到invalidooperation异常。这是为什么?

>>> 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.2575850003972054”,而不是原始值,那么也可以!怎么回事?

谢谢!


Tags: 数据import精度感兴趣decimalroundingup位数
1条回答
网友
1楼 · 发布于 2024-06-26 04:13:53

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

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 the quantize operation would be greater than precision, then an InvalidOperation is signaled. This guarantees that, unless there is an error condition, the quantized exponent is always equal to that of the right-hand operand.

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

相关问题 更多 >