如何获取decimal.Inexact异常的值?
在decimal模块的文档中,我看到:
class decimal.Inexact
表示发生了四舍五入,结果不是精确的。[...] 返回的是四舍五入后的结果。[...]
我该如何获取四舍五入后的结果呢?这里有一个例子:
>>> 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
1 个回答
3
你可能误解了文档的意思;这个操作只有在你没有捕获异常的情况下,才会返回四舍五入的结果,而此时Inexact
标志会在上下文中被设置。
但是如果你捕获了异常,那么就会抛出异常,而不会返回四舍五入的结果。
根据文档中的教程部分:
上下文还具有信号标志,用于监控计算过程中遇到的异常情况。这些标志会一直保持设置状态,直到被明确清除,所以最好在每次进行监控计算之前,使用
clear_flags()
方法来清除这些标志。
>>> 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')
的返回值是不精确的。
只有在特定信号应该被视为错误时,才使用捕获;例如,当四舍五入对你的应用程序来说会造成问题时。