The cdecimal module is compatible with decimal.py. Since the
official documentation
is valid, the rest of this document focuses on the few remaining differences
as well as extra features.
prec, Emin, Emax, rounding, capitals and clamp are implemented as
getters/setters.
An additional field _allcr toggles correct rounding for exp,
ln and log10. If enabled (default), all methods except
power and invroot are correctly rounded.
traps and flags have the custom type SignalDict, which behaves
like a dictionary for most purposes. This is the familiar interface from
decimal.py.
Internally, traps and flags are just C unsigned integers. cdecimal
provides the option to access the integers directly using the getters/setters
_traps and _flags.
The use of the two interfaces can be mixed freely. The following table
shows how the SignalDict items and the C-flags are related:
The choice whether the default context is thread local or global is made at
compile time. If thread local contexts are enabled, the module constant
HAVE_THREADS has a value of 1. Otherwise, the value is 0.
The Decimal constructor does not observe the current context, i.e. any
value is read exactly as entered. Since the context of cdecimal has limits,
the following approach is used:
If an Inexact or Rounded condition occurs during conversion,
InvalidOperation is raised and the result is NaN. In this case, the
create_decimal context method has to be used.
The power method in decimal.py is correctly rounded. cdecimal
currently only guarantees an error less than 1ULP+t, where t has a maximum of
0.1ULP, but is almost always less than 0.01ULP.
In Python2.7 and 3.2 the rules for mixing decimals and floats were
relaxed. This can give rise to mistakes:
>>> Decimal(1.29299)# meaning Decimal("1.29299")Decimal('1.292990000000000083701934272539801895618438720703125')>>> x=Decimal("1.9")>>> x>1.9# meaning Decimal(1.9)True
In order to prevent accidental mixing, cdecimal has an additional
FloatOperation signal. Here is the behavior with the trap set:
>>> c=getcontext()>>> c.traps[FloatOperation]=True>>> Decimal(1.9)Traceback (most recent call last):
File "<stdin>", line 1, in <module>cdecimal.FloatOperation: [<class 'cdecimal.FloatOperation'>]>>>>>> x=Decimal("1.9")>>> x>1.9Traceback (most recent call last):
File "<stdin>", line 1, in <module>cdecimal.FloatOperation: [<class 'cdecimal.FloatOperation'>]>>>
For compatibility with decimal.py the FloatOperation signal is
off by default. This is the standard behavior for mixed operations
across several Python versions:
Return a context object initialized to the proper values for one of the
IEEE interchange formats. The argument must be a multiple of 32 and less
than IEEE_CONTEXT_MAX_BITS.
For the most common values, the following constants are provided: