Python十进制InvalidOperation [英] Python cdecimal InvalidOperation

查看:188
本文介绍了Python十进制InvalidOperation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to read financial data and store it. The place I get the financial data from stores the data with incredible precision, however I am only interested in 5 figures after the decimal point. Therefore, I have decided to use t = .quantize(cdecimal.Decimal('.00001'), rounding=cdecimal.ROUND_UP) on the Decimal I create, but I keep getting an InvalidOperation exception. Why is this?

>>> 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而不是原始值,那也可以!

Why is there an invalid operation here? If I change the precision to 7 (or greater), it works. If I set s to be '0.257585003972054' instead of the original value, that also works! What is going on?

谢谢!

推荐答案

十进制版本给出了错误的更好描述:

decimal version gives a better description of the error:

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
>>> 

文档


与其他操作不同,如果
量化操作后的系数长度大于精度,则发出
InvalidOperation信号。这样可以保证,除非出现
错误条件,否则量化的指数始终等于右手操作数
的指数。

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.

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

But i must confess i don't know what this means.

这篇关于Python十进制InvalidOperation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆