Skip to main content
 首页 » 编程设计

python之如何获取 decimal.Inexact 异常的值

2024年11月01日8三少

在decimal我阅读的模块文档:

class decimal.Inexact

Indicates that rounding occurred and the result is not exact. [...] The rounded result is returned. [...]

如何获得四舍五入的结果?这是一个例子:

>>> from decimal import Decimal, Context, Inexact 
>>> (Decimal("1.23")/2).quantize(Decimal("0.1"), context=Context(traps=[Inexact])) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "/usr/lib/python3.4/decimal.py", line 2590, in quantize 
    context._raise_error(Inexact) 
  File "/usr/lib/python3.4/decimal.py", line 4043, in _raise_error 
    raise error(explanation) 
decimal.Inexact: None 

请您参考如下方法:

您误解了文档; operation 仅在您不捕获时返回舍入结果,而不是在上下文中设置 Inexact 标志。

但是当您捕获异常时,它会被引发并且不会返回四舍五入的结果。

来自tutorial portion of the documentation :

Contexts also have signal flags for monitoring exceptional conditions encountered during computations. The flags remain set until explicitly cleared, so it is best to clear the flags before each set of monitored computations by using the clear_flags() method.

>>> from decimal import localcontext 
>>> with localcontext() as ctx: 
...     (Decimal("1.23")/2).quantize(Decimal("0.1")) 
...     print(ctx.flags) 
...  
Decimal('0.6') 
{<class 'decimal.Subnormal'>: 0, <class 'decimal.Underflow'>: 0, <class 'decimal.DivisionByZero'>: 0, <class 'decimal.Inexact'>: 1, <class 'decimal.Rounded'>: 1, <class 'decimal.InvalidOperation'>: 0, <class 'decimal.Overflow'>: 0, <class 'decimal.Clamped'>: 0} 

此处设置了 decimal.Inexact 和 decimal.Rounded 标志,告诉您 Decimal('0.6') 返回值为不准确。

仅当特定信号应该是错误时才使用陷阱;例如当舍入对您的应用程序来说是个问题时。