Domanda

In the decimal module documentation I read:

class decimal.Inexact

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

How do I get the rounded result? Here's an example:

>>> 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
È stato utile?

Soluzione

You misinterpret the documentation; the operation returns the rounded result only when you don't trap, instead the Inexact flag is set on the context.

But when you trap the exception instead, it is raised and no rounded result is returned.

From the 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}

Here the decimal.Inexact and decimal.Rounded flags are set, telling you that the Decimal('0.6') return value is inexact.

Use trapping only when the specific signal should be an error; e.g. when rounding would be a problem for your application.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top