Dec-08-2021, 05:01 AM
>>> from decimal import * >>> getcontext() Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow]) >>> Decimal('1E-999999')*Decimal('1E-99') Decimal('0E-1000026') >>> getcontext() Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[Clamped, Inexact, Rounded, Subnormal, Underflow], traps=[InvalidOperation, DivisionByZero, Overflow]) >>>Compare the differences in the output of
getcontext()
before and after operation that generates the underflow. flags
now has a list of the special conditions. The Underflow flag was set. traps
is a list of the flags, that when set, raise an exception. You can add Underflow
to the traps
if you want to raise an exception.>>> setcontext(DefaultContext) >>> getcontext() Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow]) >>> getcontext().traps[Underflow] = True >>> getcontext() Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow, Underflow]) >>> Decimal('1E-999999')*Decimal('1E-99') Traceback (most recent call last): File "<stdin>", line 1, in <module> decimal.Underflow: [<class 'decimal.Underflow'>] >>>