gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:46:57 25 4
gpt4 key购买 nike

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.Inexactdecimal.Rounded 标志,告诉您 Decimal('0.6') 返回值为不准确。

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

关于python - 如何获取 decimal.Inexact 异常的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23322605/

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