Module decimal
[hide private]
[frames] | no frames]

Module decimal


This is a Py2.3 implementation of decimal floating point arithmetic based on
the General Decimal Arithmetic Specification:

    www2.hursley.ibm.com/decimal/decarith.html

and IEEE standard 854-1987:

    www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html

Decimal floating point has finite precision with arbitrarily large bounds.

The purpose of the module is to support arithmetic using familiar
"schoolhouse" rules and to avoid the some of tricky representation
issues associated with binary floating point.  The package is especially
useful for financial applications or for contexts where users have
expectations that are at odds with binary floating point (for instance,
in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
of the expected Decimal("0.00") returned by decimal floating point).

Here are some examples of using the decimal module:

>>> from decimal import *
>>> setcontext(ExtendedContext)
>>> Decimal(0)
Decimal("0")
>>> Decimal("1")
Decimal("1")
>>> Decimal("-.0123")
Decimal("-0.0123")
>>> Decimal(123456)
Decimal("123456")
>>> Decimal("123.45e12345678901234567890")
Decimal("1.2345E+12345678901234567892")
>>> Decimal("1.33") + Decimal("1.27")
Decimal("2.60")
>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
Decimal("-2.20")
>>> dig = Decimal(1)
>>> print dig / Decimal(3)
0.333333333
>>> getcontext().prec = 18
>>> print dig / Decimal(3)
0.333333333333333333
>>> print dig.sqrt()
1
>>> print Decimal(3).sqrt()
1.73205080756887729
>>> print Decimal(3) ** 123
4.85192780976896427E+58
>>> inf = Decimal(1) / Decimal(0)
>>> print inf
Infinity
>>> neginf = Decimal(-1) / Decimal(0)
>>> print neginf
-Infinity
>>> print neginf + inf
NaN
>>> print neginf * inf
-Infinity
>>> print dig / 0
Infinity
>>> getcontext().traps[DivisionByZero] = 1
>>> print dig / 0
Traceback (most recent call last):
  ...
  ...
  ...
DivisionByZero: x / 0
>>> c = Context()
>>> c.traps[InvalidOperation] = 0
>>> print c.flags[InvalidOperation]
0
>>> c.divide(Decimal(0), Decimal(0))
Decimal("NaN")
>>> c.traps[InvalidOperation] = 1
>>> print c.flags[InvalidOperation]
1
>>> c.flags[InvalidOperation] = 0
>>> print c.flags[InvalidOperation]
0
>>> print c.divide(Decimal(0), Decimal(0))
Traceback (most recent call last):
  ...
  ...
  ...
InvalidOperation: 0 / 0
>>> print c.flags[InvalidOperation]
1
>>> c.flags[InvalidOperation] = 0
>>> c.traps[InvalidOperation] = 0
>>> print c.divide(Decimal(0), Decimal(0))
NaN
>>> print c.flags[InvalidOperation]
1
>>>

Classes [hide private]
DecimalException
Base exception class.
Clamped
Exponent of a 0 changed to fit bounds.
InvalidOperation
An invalid operation was performed.
ConversionSyntax
Trying to convert badly formed string.
DivisionByZero
Division by 0.
DivisionImpossible
Cannot perform the division adequately.
DivisionUndefined
Undefined result of division.
Inexact
Had to round, losing information.
InvalidContext
Invalid context.
Rounded
Number got rounded (not necessarily changed during rounding).
Subnormal
Exponent < Emin before rounding.
Overflow
Numerical overflow.
Underflow
Numerical underflow with result rounded to 0.
Decimal
Floating point class for decimal arithmetic.
_ContextManager
Context manager class to support localcontext().
Context
Contains the context for a Decimal instance.
_WorkRep
Functions [hide private]
 
getcontext(_local=local)
Returns this thread's context.
 
setcontext(context, _local=local)
Set this thread's context to context.
 
localcontext(ctx=None)
Return a context manager for a copy of the supplied context
 
_normalize(op1, op2, shouldround=0, prec=0)
Normalizes op1, op2 to have the same exp and length of coefficient.
 
_adjust_coefficients(op1, op2)
Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
 
_convert_other(other)
Convert other to Decimal.
 
_isinfinity(num)
Determines whether a string or float is infinity.
 
_isnan(num)
Determines whether a string or float is NaN
 
_parser(...)
match(string[, pos[, endpos]]) --> match object or None.
 
_string2exact(s)
Variables [hide private]
  ROUND_DOWN = 'ROUND_DOWN'
  ROUND_HALF_UP = 'ROUND_HALF_UP'
  ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
  ROUND_CEILING = 'ROUND_CEILING'
  ROUND_FLOOR = 'ROUND_FLOOR'
  ROUND_UP = 'ROUND_UP'
  ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
  NEVER_ROUND = 'NEVER_ROUND'
  ALWAYS_ROUND = 'ALWAYS_ROUND'
  _signals = [<class 'decimal.Clamped'>, <class 'decimal.Divisio...
  _condition_map = {<class 'decimal.ConversionSyntax'>: <class '...
  _infinity_map = {'+inf': 1, '+infinity': 1, '-inf': -1, '-infi...
  DefaultContext = Context(prec=28, rounding=ROUND_HALF_EVEN, Em...
  BasicContext = Context(prec=9, rounding=ROUND_HALF_UP, Emin=-9...
  ExtendedContext = Context(prec=9, rounding=ROUND_HALF_EVEN, Em...
  Inf = Decimal("Infinity")
  negInf = Decimal("-Infinity")
  Infsign = (Decimal("Infinity"), Decimal("-Infinity"))
  NaN = Decimal("NaN")

Imports: _copy


Function Details [hide private]

getcontext(_local=local)

 

Returns this thread's context.

If this thread does not yet have a context, returns a new context and sets this thread's context. New contexts are copies of DefaultContext.

localcontext(ctx=None)

 
Return a context manager for a copy of the supplied context

Uses a copy of the current context if no context is specified
The returned context manager creates a local decimal context
in a with statement:
    def sin(x):
         with localcontext() as ctx:
             ctx.prec += 2
             # Rest of sin calculation algorithm
             # uses a precision 2 greater than normal
         return +s # Convert result to normal precision

     def sin(x):
         with localcontext(ExtendedContext):
             # Rest of sin calculation algorithm
             # uses the Extended Context from the
             # General Decimal Arithmetic Specification
         return +s # Convert result to normal context

_normalize(op1, op2, shouldround=0, prec=0)

 

Normalizes op1, op2 to have the same exp and length of coefficient.

Done during addition.

_adjust_coefficients(op1, op2)

 

Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.

Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp.

Used on _WorkRep instances during division.

_convert_other(other)

 

Convert other to Decimal.

Verifies that it's ok to use in an implicit construction.

_isinfinity(num)

 

Determines whether a string or float is infinity.

+1 for negative infinity; 0 for finite ; +1 for positive infinity

_isnan(num)

 

Determines whether a string or float is NaN

(1, sign, diagnostic info as string) => NaN (2, sign, diagnostic info as string) => sNaN 0 => not a NaN

_parser(...)

 

match(string[, pos[, endpos]]) --> match object or None. Matches zero or more characters at the beginning of the string


Variables Details [hide private]

_signals

Value:
[<class 'decimal.Clamped'>,
 <class 'decimal.DivisionByZero'>,
 <class 'decimal.Inexact'>,
 <class 'decimal.Overflow'>,
 <class 'decimal.Rounded'>,
 <class 'decimal.Underflow'>,
 <class 'decimal.InvalidOperation'>,
 <class 'decimal.Subnormal'>]

_condition_map

Value:
{<class 'decimal.ConversionSyntax'>: <class 'decimal.InvalidOperation'\
>,
 <class 'decimal.DivisionImpossible'>: <class 'decimal.InvalidOperatio\
n'>,
 <class 'decimal.DivisionUndefined'>: <class 'decimal.InvalidOperation\
'>,
 <class 'decimal.InvalidContext'>: <class 'decimal.InvalidOperation'>}

_infinity_map

Value:
{'+inf': 1,
 '+infinity': 1,
 '-inf': -1,
 '-infinity': -1,
 'inf': 1,
 'infinity': 1}

DefaultContext

Value:
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=99999\
9999, capitals=1, flags=[], traps=[InvalidOperation, Overflow, Divisio\
nByZero])

BasicContext

Value:
Context(prec=9, rounding=ROUND_HALF_UP, Emin=-999999999, Emax=99999999\
9, capitals=1, flags=[], traps=[Underflow, InvalidOperation, Overflow,\
 Clamped, DivisionByZero])

ExtendedContext

Value:
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999\
999, capitals=1, flags=[], traps=[])