rest25/library/decimal.rst => rest262/library/decimal.rst
f1
n2-:mod:`decimal` --- Decimal floating point arithmetic
n2+:mod:`decimal` --- Decimal fixed point and floating point arithmetic
3-====================================================
3+====================================================================
4
5.. module:: decimal
6   :synopsis: Implementation of the General Decimal Arithmetic  Specification.
7
8
9.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
10.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
11.. moduleauthor:: Raymond Hettinger <python at rcn.com>
12.. moduleauthor:: Aahz <aahz at pobox.com>
13.. moduleauthor:: Tim Peters <tim.one at comcast.net>
14
15
16.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
17
n18- 
19.. versionadded:: 2.4
20
n20+.. import modules for testing inline doctests with the Sphinx doctest builder
21+.. testsetup:: *
22+ 
23+   import decimal
24+   import math
25+   from decimal import *
26+   # make sure each group gets a fresh context
27+   setcontext(Context())
28+ 
21The :mod:`decimal` module provides support for decimal floating point
n22-arithmetic.  It offers several advantages over the :class:`float()` datatype:
n30+arithmetic.  It offers several advantages over the :class:`float` datatype:
31+ 
32+* Decimal "is based on a floating-point model which was designed with people
33+  in mind, and necessarily has a paramount guiding principle -- computers must
34+  provide an arithmetic that works in the same way as the arithmetic that
35+  people learn at school." -- excerpt from the decimal arithmetic specification.
23
24* Decimal numbers can be represented exactly.  In contrast, numbers like
25  :const:`1.1` do not have an exact representation in binary floating point. End
26  users typically would not expect :const:`1.1` to display as
27  :const:`1.1000000000000001` as it does with binary floating point.
28
29* The exactness carries over into arithmetic.  In decimal floating point, ``0.1
n30-  + 0.1 + 0.1 - 0.3`` is exactly equal to zero.  In binary floating point, result
n43+  + 0.1 + 0.1 - 0.3`` is exactly equal to zero.  In binary floating point, the result
31  is :const:`5.5511151231257827e-017`.  While near to zero, the differences
32  prevent reliable equality testing and differences can accumulate. For this
n33-  reason, decimal would be preferred in accounting applications which have strict
n46+  reason, decimal is preferred in accounting applications which have strict
34  equality invariants.
35
36* The decimal module incorporates a notion of significant places so that ``1.30
37  + 1.20`` is :const:`2.50`.  The trailing zero is kept to indicate significance.
38  This is the customary presentation for monetary applications. For
39  multiplication, the "schoolbook" approach uses all the figures in the
40  multiplicands.  For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
41  1.20`` gives :const:`1.5600`.
42
43* Unlike hardware based binary floating point, the decimal module has a user
n44-  settable precision (defaulting to 28 places) which can be as large as needed for
n57+  alterable precision (defaulting to 28 places) which can be as large as needed for
45-  a given problem::
58+  a given problem:
46
47     >>> getcontext().prec = 6
48     >>> Decimal(1) / Decimal(7)
n49-     Decimal("0.142857")
n62+     Decimal('0.142857')
50     >>> getcontext().prec = 28
51     >>> Decimal(1) / Decimal(7)
n52-     Decimal("0.1428571428571428571428571429")
n65+     Decimal('0.1428571428571428571428571429')
53
54* Both binary and decimal floating point are implemented in terms of published
55  standards.  While the built-in float type exposes only a modest portion of its
56  capabilities, the decimal module exposes all required parts of the standard.
57  When needed, the programmer has full control over rounding and signal handling.
n71+  This includes an option to enforce exact arithmetic by using exceptions
72+  to block any inexact operations.
73+ 
74+* The decimal module was designed to support "without prejudice, both exact
75+  unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
76+  and rounded floating-point arithmetic."  -- excerpt from the decimal
77+  arithmetic specification.
58
59The module design is centered around three concepts:  the decimal number, the
60context for arithmetic, and signals.
61
62A decimal number is immutable.  It has a sign, coefficient digits, and an
63exponent.  To preserve significance, the coefficient digits do not truncate
n64-trailing zeroes.  Decimals also include special values such as
n84+trailing zeros.  Decimals also include special values such as
65:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`.  The standard also
66differentiates :const:`-0` from :const:`+0`.
67
68The context for arithmetic is an environment specifying precision, rounding
69rules, limits on exponents, flags indicating the results of operations, and trap
70enablers which determine whether signals are treated as exceptions.  Rounding
71options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
72:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
n73-:const:`ROUND_HALF_UP`, and :const:`ROUND_UP`.
n93+:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
74
75Signals are groups of exceptional conditions arising during the course of
76computation.  Depending on the needs of the application, signals may be ignored,
77considered as informational, or treated as exceptions. The signals in the
78decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
79:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
80:const:`Overflow`, and :const:`Underflow`.
81
82For each signal there is a flag and a trap enabler.  When a signal is
n83-encountered, its flag is incremented from zero and, then, if the trap enabler is
n103+encountered, its flag is set to one, then, if the trap enabler is
84set to one, an exception is raised.  Flags are sticky, so the user needs to
85reset them before monitoring a calculation.
86
87
88.. seealso::
89
n90-   IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
n110+   * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
91-   Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_.
111+     Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_.
92
n93-   IEEE standard 854-1987, `Unofficial IEEE 854 Text
n113+   * IEEE standard 854-1987, `Unofficial IEEE 854 Text
94-   <http://www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html>`_.
114+     <http://754r.ucbtest.org/standards/854.pdf>`_.
95
n96-.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
n116+.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
97
98
99.. _decimal-tutorial:
100
101Quick-start Tutorial
102--------------------
103
104The usual start to using decimals is importing the module, viewing the current
105context with :func:`getcontext` and, if necessary, setting new values for
106precision, rounding, or enabled traps::
107
108   >>> from decimal import *
109   >>> getcontext()
110   Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
n111-           capitals=1, flags=[], traps=[Overflow, InvalidOperation,
n131+           capitals=1, flags=[], traps=[Overflow, DivisionByZero,
112-           DivisionByZero])
132+           InvalidOperation])
113
114   >>> getcontext().prec = 7       # Set a new precision
115
116Decimal instances can be constructed from integers, strings, or tuples.  To
117create a Decimal from a :class:`float`, first convert it to a string.  This
118serves as an explicit reminder of the details of the conversion (including
119representation error).  Decimal numbers include special values such as
120:const:`NaN` which stands for "Not a number", positive and negative
n121-:const:`Infinity`, and :const:`-0`.         ::
n141+:const:`Infinity`, and :const:`-0`.
122
n143+   >>> getcontext().prec = 28
123   >>> Decimal(10)
n124-   Decimal("10")
n145+   Decimal('10')
125-   >>> Decimal("3.14")
146+   >>> Decimal('3.14')
126-   Decimal("3.14")
147+   Decimal('3.14')
127   >>> Decimal((0, (3, 1, 4), -2))
n128-   Decimal("3.14")
n149+   Decimal('3.14')
129   >>> Decimal(str(2.0 ** 0.5))
n130-   Decimal("1.41421356237")
n151+   Decimal('1.41421356237')
152+   >>> Decimal(2) ** Decimal('0.5')
153+   Decimal('1.414213562373095048801688724')
131-   >>> Decimal("NaN")
154+   >>> Decimal('NaN')
132-   Decimal("NaN")
155+   Decimal('NaN')
133-   >>> Decimal("-Infinity")
156+   >>> Decimal('-Infinity')
134-   Decimal("-Infinity")
157+   Decimal('-Infinity')
135
136The significance of a new Decimal is determined solely by the number of digits
137input.  Context precision and rounding only come into play during arithmetic
n138-operations. ::
n161+operations.
162+ 
163+.. doctest:: newcontext
139
140   >>> getcontext().prec = 6
141   >>> Decimal('3.0')
n142-   Decimal("3.0")
n167+   Decimal('3.0')
143   >>> Decimal('3.1415926535')
n144-   Decimal("3.1415926535")
n169+   Decimal('3.1415926535')
145   >>> Decimal('3.1415926535') + Decimal('2.7182818285')
n146-   Decimal("5.85987")
n171+   Decimal('5.85987')
147   >>> getcontext().rounding = ROUND_UP
148   >>> Decimal('3.1415926535') + Decimal('2.7182818285')
n149-   Decimal("5.85988")
n174+   Decimal('5.85988')
150
151Decimals interact well with much of the rest of Python.  Here is a small decimal
n152-floating point flying circus::
n177+floating point flying circus:
178+ 
179+.. doctest::
180+   :options: +NORMALIZE_WHITESPACE
153
154   >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
155   >>> max(data)
n156-   Decimal("9.25")
n184+   Decimal('9.25')
157   >>> min(data)
n158-   Decimal("0.03")
n186+   Decimal('0.03')
159   >>> sorted(data)
n160-   [Decimal("0.03"), Decimal("1.00"), Decimal("1.34"), Decimal("1.87"),
n188+   [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
161-    Decimal("2.35"), Decimal("3.45"), Decimal("9.25")]
189+    Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
162   >>> sum(data)
n163-   Decimal("19.29")
n191+   Decimal('19.29')
164   >>> a,b,c = data[:3]
165   >>> str(a)
166   '1.34'
167   >>> float(a)
168   1.3400000000000001
169   >>> round(a, 1)     # round() first converts to binary floating point
170   1.3
171   >>> int(a)
172   1
173   >>> a * 5
n174-   Decimal("6.70")
n202+   Decimal('6.70')
175   >>> a * b
n176-   Decimal("2.5058")
n204+   Decimal('2.5058')
177   >>> c % a
n178-   Decimal("0.77")
n206+   Decimal('0.77')
207+ 
208+And some mathematical functions are also available to Decimal:
209+ 
210+   >>> getcontext().prec = 28
211+   >>> Decimal(2).sqrt()
212+   Decimal('1.414213562373095048801688724')
213+   >>> Decimal(1).exp()
214+   Decimal('2.718281828459045235360287471')
215+   >>> Decimal('10').ln()
216+   Decimal('2.302585092994045684017991455')
217+   >>> Decimal('10').log10()
218+   Decimal('1')
179
180The :meth:`quantize` method rounds a number to a fixed exponent.  This method is
181useful for monetary applications that often round results to a fixed number of
n182-places::
n222+places:
183
184   >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
n185-   Decimal("7.32")
n225+   Decimal('7.32')
186   >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
n187-   Decimal("8")
n227+   Decimal('8')
188
189As shown above, the :func:`getcontext` function accesses the current context and
190allows the settings to be changed.  This approach meets the needs of most
191applications.
192
193For more advanced work, it may be useful to create alternate contexts using the
194Context() constructor.  To make an alternate active, use the :func:`setcontext`
195function.
196
197In accordance with the standard, the :mod:`Decimal` module provides two ready to
198use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
199former is especially useful for debugging because many of the traps are
n200-enabled::
n240+enabled:
241+ 
242+.. doctest:: newcontext
243+   :options: +NORMALIZE_WHITESPACE
201
202   >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
203   >>> setcontext(myothercontext)
204   >>> Decimal(1) / Decimal(7)
n205-   Decimal("0.142857142857142857142857142857142857142857142857142857142857")
n248+   Decimal('0.142857142857142857142857142857142857142857142857142857142857')
206
207   >>> ExtendedContext
208   Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
209           capitals=1, flags=[], traps=[])
210   >>> setcontext(ExtendedContext)
211   >>> Decimal(1) / Decimal(7)
n212-   Decimal("0.142857143")
n255+   Decimal('0.142857143')
213   >>> Decimal(42) / Decimal(0)
n214-   Decimal("Infinity")
n257+   Decimal('Infinity')
215
216   >>> setcontext(BasicContext)
217   >>> Decimal(42) / Decimal(0)
218   Traceback (most recent call last):
219     File "<pyshell#143>", line 1, in -toplevel-
220       Decimal(42) / Decimal(0)
221   DivisionByZero: x / 0
222
223Contexts also have signal flags for monitoring exceptional conditions
224encountered during computations.  The flags remain set until explicitly cleared,
225so it is best to clear the flags before each set of monitored computations by
226using the :meth:`clear_flags` method. ::
227
228   >>> setcontext(ExtendedContext)
229   >>> getcontext().clear_flags()
230   >>> Decimal(355) / Decimal(113)
n231-   Decimal("3.14159292")
n274+   Decimal('3.14159292')
232   >>> getcontext()
233   Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
n234-           capitals=1, flags=[Inexact, Rounded], traps=[])
n277+           capitals=1, flags=[Rounded, Inexact], traps=[])
235
236The *flags* entry shows that the rational approximation to :const:`Pi` was
237rounded (digits beyond the context precision were thrown away) and that the
238result is inexact (some of the discarded digits were non-zero).
239
240Individual traps are set using the dictionary in the :attr:`traps` field of a
n241-context::
n284+context:
242
n286+.. doctest:: newcontext
287+ 
288+   >>> setcontext(ExtendedContext)
243   >>> Decimal(1) / Decimal(0)
n244-   Decimal("Infinity")
n290+   Decimal('Infinity')
245   >>> getcontext().traps[DivisionByZero] = 1
246   >>> Decimal(1) / Decimal(0)
247   Traceback (most recent call last):
248     File "<pyshell#112>", line 1, in -toplevel-
249       Decimal(1) / Decimal(0)
250   DivisionByZero: x / 0
251
252Most programs adjust the current context only once, at the beginning of the
253program.  And, in many applications, data is converted to :class:`Decimal` with
254a single cast inside a loop.  With context set and decimals created, the bulk of
255the program manipulates the data no differently than with other Python numeric
256types.
257
n258-.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
n304+.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
259
260
261.. _decimal-decimal:
262
263Decimal objects
264---------------
265
266
267.. class:: Decimal([value [, context]])
268
n269-   Constructs a new :class:`Decimal` object based from *value*.
n315+   Construct a new :class:`Decimal` object based from *value*.
270
n271-   *value* can be an integer, string, tuple, or another :class:`Decimal` object. If
n317+   *value* can be an integer, string, tuple, or another :class:`Decimal`
272-   no *value* is given, returns ``Decimal("0")``.  If *value* is a string, it
318+   object. If no *value* is given, returns ``Decimal('0')``.  If *value* is a
273-   should conform to the decimal numeric string syntax::
319+   string, it should conform to the decimal numeric string syntax after leading
320+   and trailing whitespace characters are removed::
274
275      sign           ::=  '+' | '-'
276      digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
277      indicator      ::=  'e' | 'E'
278      digits         ::=  digit [digit]...
279      decimal-part   ::=  digits '.' [digits] | ['.'] digits
280      exponent-part  ::=  indicator [sign] digits
281      infinity       ::=  'Infinity' | 'Inf'
282      nan            ::=  'NaN' [digits] | 'sNaN' [digits]
283      numeric-value  ::=  decimal-part [exponent-part] | infinity
n284-      numeric-string ::=  [sign] numeric-value | [sign] nan  
n331+      numeric-string ::=  [sign] numeric-value | [sign] nan
285
286   If *value* is a :class:`tuple`, it should have three components, a sign
287   (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
288   digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
n289-   returns ``Decimal("1.414")``.
n336+   returns ``Decimal('1.414')``.
290
291   The *context* precision does not affect how many digits are stored. That is
292   determined exclusively by the number of digits in *value*. For example,
n293-   ``Decimal("3.00000")`` records all five zeroes even if the context precision is
n340+   ``Decimal('3.00000')`` records all five zeros even if the context precision is
294   only three.
295
296   The purpose of the *context* argument is determining what to do if *value* is a
297   malformed string.  If the context traps :const:`InvalidOperation`, an exception
298   is raised; otherwise, the constructor returns a new Decimal with the value of
299   :const:`NaN`.
300
301   Once constructed, :class:`Decimal` objects are immutable.
302
n350+   .. versionchanged:: 2.6
351+      leading and trailing whitespace characters are permitted when
352+      creating a Decimal instance from a string.
353+ 
303-Decimal floating point objects share many properties with the other builtin
354+   Decimal floating point objects share many properties with the other built-in
304-numeric types such as :class:`float` and :class:`int`.  All of the usual math
355+   numeric types such as :class:`float` and :class:`int`.  All of the usual math
305-operations and special methods apply.  Likewise, decimal objects can be copied,
356+   operations and special methods apply.  Likewise, decimal objects can be
306-pickled, printed, used as dictionary keys, used as set elements, compared,
357+   copied, pickled, printed, used as dictionary keys, used as set elements,
307-sorted, and coerced to another type (such as :class:`float` or :class:`long`).
358+   compared, sorted, and coerced to another type (such as :class:`float` or
359+   :class:`long`).
308
n309-In addition to the standard numeric properties, decimal floating point objects
n361+   In addition to the standard numeric properties, decimal floating point
310-also have a number of specialized methods:
362+   objects also have a number of specialized methods:
311
312
n313-.. method:: Decimal.adjusted()
n365+   .. method:: adjusted()
314
n315-   Return the adjusted exponent after shifting out the coefficient's rightmost
n367+      Return the adjusted exponent after shifting out the coefficient's
316-   digits until only the lead digit remains: ``Decimal("321e+5").adjusted()``
368+      rightmost digits until only the lead digit remains:
317-   returns seven.  Used for determining the position of the most significant digit
369+      ``Decimal('321e+5').adjusted()`` returns seven.  Used for determining the
318-   with respect to the decimal point.
370+      position of the most significant digit with respect to the decimal point.
319
320
n321-.. method:: Decimal.as_tuple()
n373+   .. method:: as_tuple()
322
n323-   Returns a tuple representation of the number: ``(sign, digittuple, exponent)``.
n375+      Return a :term:`named tuple` representation of the number:
376+      ``DecimalTuple(sign, digits, exponent)``.
324
n378+      .. versionchanged:: 2.6
379+         Use a named tuple.
325
n381+ 
382+   .. method:: canonical()
383+ 
384+      Return the canonical encoding of the argument.  Currently, the encoding of
385+      a :class:`Decimal` instance is always canonical, so this operation returns
386+      its argument unchanged.
387+ 
388+      .. versionadded:: 2.6
389+ 
326-.. method:: Decimal.compare(other[, context])
390+   .. method:: compare(other[, context])
327
n328-   Compares like :meth:`__cmp__` but returns a decimal instance::
n392+      Compare the values of two Decimal instances.  This operation behaves in
393+      the same way as the usual comparison method :meth:`__cmp__`, except that
394+      :meth:`compare` returns a Decimal instance rather than an integer, and if
395+      either operand is a NaN then the result is a NaN::
329
n330-      a or b is a NaN ==> Decimal("NaN")
n397+         a or b is a NaN ==> Decimal('NaN')
331-      a < b           ==> Decimal("-1")
398+         a < b           ==> Decimal('-1')
332-      a == b          ==> Decimal("0")
399+         a == b          ==> Decimal('0')
333-      a > b           ==> Decimal("1")
400+         a > b           ==> Decimal('1')
334
n402+   .. method:: compare_signal(other[, context])
335
n404+      This operation is identical to the :meth:`compare` method, except that all
405+      NaNs signal.  That is, if neither operand is a signaling NaN then any
406+      quiet NaN operand is treated as though it were a signaling NaN.
407+ 
408+      .. versionadded:: 2.6
409+ 
410+   .. method:: compare_total(other)
411+ 
412+      Compare two operands using their abstract representation rather than their
413+      numerical value.  Similar to the :meth:`compare` method, but the result
414+      gives a total ordering on :class:`Decimal` instances.  Two
415+      :class:`Decimal` instances with the same numeric value but different
416+      representations compare unequal in this ordering:
417+ 
418+         >>> Decimal('12.0').compare_total(Decimal('12'))
419+         Decimal('-1')
420+ 
421+      Quiet and signaling NaNs are also included in the total ordering.  The
422+      result of this function is ``Decimal('0')`` if both operands have the same
423+      representation, ``Decimal('-1')`` if the first operand is lower in the
424+      total order than the second, and ``Decimal('1')`` if the first operand is
425+      higher in the total order than the second operand.  See the specification
426+      for details of the total order.
427+ 
428+      .. versionadded:: 2.6
429+ 
430+   .. method:: compare_total_mag(other)
431+ 
432+      Compare two operands using their abstract representation rather than their
433+      value as in :meth:`compare_total`, but ignoring the sign of each operand.
434+      ``x.compare_total_mag(y)`` is equivalent to
435+      ``x.copy_abs().compare_total(y.copy_abs())``.
436+ 
437+      .. versionadded:: 2.6
438+ 
439+   .. method:: conjugate()
440+ 
441+      Just returns self, this method is only to comply with the Decimal
442+      Specification.
443+ 
444+      .. versionadded:: 2.6
445+ 
446+   .. method:: copy_abs()
447+ 
448+      Return the absolute value of the argument.  This operation is unaffected
449+      by the context and is quiet: no flags are changed and no rounding is
450+      performed.
451+ 
452+      .. versionadded:: 2.6
453+ 
454+   .. method:: copy_negate()
455+ 
456+      Return the negation of the argument.  This operation is unaffected by the
457+      context and is quiet: no flags are changed and no rounding is performed.
458+ 
459+      .. versionadded:: 2.6
460+ 
461+   .. method:: copy_sign(other)
462+ 
463+      Return a copy of the first operand with the sign set to be the same as the
464+      sign of the second operand.  For example:
465+ 
466+         >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
467+         Decimal('-2.3')
468+ 
469+      This operation is unaffected by the context and is quiet: no flags are
470+      changed and no rounding is performed.
471+ 
472+      .. versionadded:: 2.6
473+ 
474+   .. method:: exp([context])
475+ 
476+      Return the value of the (natural) exponential function ``e**x`` at the
477+      given number.  The result is correctly rounded using the
478+      :const:`ROUND_HALF_EVEN` rounding mode.
479+ 
480+      >>> Decimal(1).exp()
481+      Decimal('2.718281828459045235360287471')
482+      >>> Decimal(321).exp()
483+      Decimal('2.561702493119680037517373933E+139')
484+ 
485+      .. versionadded:: 2.6
486+ 
487+   .. method:: fma(other, third[, context])
488+ 
489+      Fused multiply-add.  Return self*other+third with no rounding of the
490+      intermediate product self*other.
491+ 
492+      >>> Decimal(2).fma(3, 5)
493+      Decimal('11')
494+ 
495+      .. versionadded:: 2.6
496+ 
497+   .. method:: is_canonical()
498+ 
499+      Return :const:`True` if the argument is canonical and :const:`False`
500+      otherwise.  Currently, a :class:`Decimal` instance is always canonical, so
501+      this operation always returns :const:`True`.
502+ 
503+      .. versionadded:: 2.6
504+ 
505+   .. method:: is_finite()
506+ 
507+      Return :const:`True` if the argument is a finite number, and
508+      :const:`False` if the argument is an infinity or a NaN.
509+ 
510+      .. versionadded:: 2.6
511+ 
512+   .. method:: is_infinite()
513+ 
514+      Return :const:`True` if the argument is either positive or negative
515+      infinity and :const:`False` otherwise.
516+ 
517+      .. versionadded:: 2.6
518+ 
519+   .. method:: is_nan()
520+ 
521+      Return :const:`True` if the argument is a (quiet or signaling) NaN and
522+      :const:`False` otherwise.
523+ 
524+      .. versionadded:: 2.6
525+ 
526+   .. method:: is_normal()
527+ 
528+      Return :const:`True` if the argument is a *normal* finite number.  Return
529+      :const:`False` if the argument is zero, subnormal, infinite or a NaN.
530+ 
531+      .. versionadded:: 2.6
532+ 
533+   .. method:: is_qnan()
534+ 
535+      Return :const:`True` if the argument is a quiet NaN, and
536+      :const:`False` otherwise.
537+ 
538+      .. versionadded:: 2.6
539+ 
540+   .. method:: is_signed()
541+ 
542+      Return :const:`True` if the argument has a negative sign and
543+      :const:`False` otherwise.  Note that zeros and NaNs can both carry signs.
544+ 
545+      .. versionadded:: 2.6
546+ 
547+   .. method:: is_snan()
548+ 
549+      Return :const:`True` if the argument is a signaling NaN and :const:`False`
550+      otherwise.
551+ 
552+      .. versionadded:: 2.6
553+ 
554+   .. method:: is_subnormal()
555+ 
556+      Return :const:`True` if the argument is subnormal, and :const:`False`
557+      otherwise.
558+ 
559+      .. versionadded:: 2.6
560+ 
561+   .. method:: is_zero()
562+ 
563+      Return :const:`True` if the argument is a (positive or negative) zero and
564+      :const:`False` otherwise.
565+ 
566+      .. versionadded:: 2.6
567+ 
568+   .. method:: ln([context])
569+ 
570+      Return the natural (base e) logarithm of the operand.  The result is
571+      correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
572+ 
573+      .. versionadded:: 2.6
574+ 
575+   .. method:: log10([context])
576+ 
577+      Return the base ten logarithm of the operand.  The result is correctly
578+      rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
579+ 
580+      .. versionadded:: 2.6
581+ 
582+   .. method:: logb([context])
583+ 
584+      For a nonzero number, return the adjusted exponent of its operand as a
585+      :class:`Decimal` instance.  If the operand is a zero then
586+      ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
587+      is raised.  If the operand is an infinity then ``Decimal('Infinity')`` is
588+      returned.
589+ 
590+      .. versionadded:: 2.6
591+ 
592+   .. method:: logical_and(other[, context])
593+ 
594+      :meth:`logical_and` is a logical operation which takes two *logical
595+      operands* (see :ref:`logical_operands_label`).  The result is the
596+      digit-wise ``and`` of the two operands.
597+ 
598+      .. versionadded:: 2.6
599+ 
600+   .. method:: logical_invert(other[, context])
601+ 
602+      :meth:`logical_invert` is a logical operation.  The argument must
603+      be a *logical operand* (see :ref:`logical_operands_label`).  The
604+      result is the digit-wise inversion of the operand.
605+ 
606+      .. versionadded:: 2.6
607+ 
608+   .. method:: logical_or(other[, context])
609+ 
610+      :meth:`logical_or` is a logical operation which takes two *logical
611+      operands* (see :ref:`logical_operands_label`).  The result is the
612+      digit-wise ``or`` of the two operands.
613+ 
614+      .. versionadded:: 2.6
615+ 
616+   .. method:: logical_xor(other[, context])
617+ 
618+      :meth:`logical_xor` is a logical operation which takes two *logical
619+      operands* (see :ref:`logical_operands_label`).  The result is the
620+      digit-wise exclusive or of the two operands.
621+ 
622+      .. versionadded:: 2.6
623+ 
336-.. method:: Decimal.max(other[, context])
624+   .. method:: max(other[, context])
337
n338-   Like ``max(self, other)`` except that the context rounding rule is applied
n626+      Like ``max(self, other)`` except that the context rounding rule is applied
339-   before returning and that :const:`NaN` values are either signalled or ignored
627+      before returning and that :const:`NaN` values are either signaled or
340-   (depending on the context and whether they are signaling or quiet).
628+      ignored (depending on the context and whether they are signaling or
629+      quiet).
341
n631+   .. method:: max_mag(other[, context])
342
n633+      Similar to the :meth:`max` method, but the comparison is done using the
634+      absolute values of the operands.
635+ 
636+      .. versionadded:: 2.6
637+ 
343-.. method:: Decimal.min(other[, context])
638+   .. method:: min(other[, context])
344
n345-   Like ``min(self, other)`` except that the context rounding rule is applied
n640+      Like ``min(self, other)`` except that the context rounding rule is applied
346-   before returning and that :const:`NaN` values are either signalled or ignored
641+      before returning and that :const:`NaN` values are either signaled or
347-   (depending on the context and whether they are signaling or quiet).
642+      ignored (depending on the context and whether they are signaling or
643+      quiet).
348
n645+   .. method:: min_mag(other[, context])
349
n647+      Similar to the :meth:`min` method, but the comparison is done using the
648+      absolute values of the operands.
649+ 
650+      .. versionadded:: 2.6
651+ 
652+   .. method:: next_minus([context])
653+ 
654+      Return the largest number representable in the given context (or in the
655+      current thread's context if no context is given) that is smaller than the
656+      given operand.
657+ 
658+      .. versionadded:: 2.6
659+ 
660+   .. method:: next_plus([context])
661+ 
662+      Return the smallest number representable in the given context (or in the
663+      current thread's context if no context is given) that is larger than the
664+      given operand.
665+ 
666+      .. versionadded:: 2.6
667+ 
668+   .. method:: next_toward(other[, context])
669+ 
670+      If the two operands are unequal, return the number closest to the first
671+      operand in the direction of the second operand.  If both operands are
672+      numerically equal, return a copy of the first operand with the sign set to
673+      be the same as the sign of the second operand.
674+ 
675+      .. versionadded:: 2.6
676+ 
350-.. method:: Decimal.normalize([context])
677+   .. method:: normalize([context])
351
n352-   Normalize the number by stripping the rightmost trailing zeroes and converting
n679+      Normalize the number by stripping the rightmost trailing zeros and
353-   any result equal to :const:`Decimal("0")` to :const:`Decimal("0e0")`. Used for
680+      converting any result equal to :const:`Decimal('0')` to
354-   producing canonical values for members of an equivalence class. For example,
681+      :const:`Decimal('0e0')`. Used for producing canonical values for members
355-   ``Decimal("32.100")`` and ``Decimal("0.321000e+2")`` both normalize to the
682+      of an equivalence class. For example, ``Decimal('32.100')`` and
356-   equivalent value ``Decimal("32.1")``.
683+      ``Decimal('0.321000e+2')`` both normalize to the equivalent value
684+      ``Decimal('32.1')``.
357
n686+   .. method:: number_class([context])
358
n688+      Return a string describing the *class* of the operand.  The returned value
689+      is one of the following ten strings.
690+ 
691+      * ``"-Infinity"``, indicating that the operand is negative infinity.
692+      * ``"-Normal"``, indicating that the operand is a negative normal number.
693+      * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
694+      * ``"-Zero"``, indicating that the operand is a negative zero.
695+      * ``"+Zero"``, indicating that the operand is a positive zero.
696+      * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
697+      * ``"+Normal"``, indicating that the operand is a positive normal number.
698+      * ``"+Infinity"``, indicating that the operand is positive infinity.
699+      * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
700+      * ``"sNaN"``, indicating that the operand is a signaling NaN.
701+ 
702+      .. versionadded:: 2.6
703+ 
359-.. method:: Decimal.quantize(exp [, rounding[, context[, watchexp]]])
704+   .. method:: quantize(exp[, rounding[, context[, watchexp]]])
360
n361-   Quantize makes the exponent the same as *exp*.  Searches for a rounding method
n706+      Return a value equal to the first operand after rounding and having the
362-   in *rounding*, then in *context*, and then in the current context.
707+      exponent of the second operand.
363
n709+      >>> Decimal('1.41421356').quantize(Decimal('1.000'))
710+      Decimal('1.414')
711+ 
712+      Unlike other operations, if the length of the coefficient after the
713+      quantize operation would be greater than precision, then an
714+      :const:`InvalidOperation` is signaled. This guarantees that, unless there
715+      is an error condition, the quantized exponent is always equal to that of
716+      the right-hand operand.
717+ 
718+      Also unlike other operations, quantize never signals Underflow, even if
719+      the result is subnormal and inexact.
720+ 
721+      If the exponent of the second operand is larger than that of the first
722+      then rounding may be necessary.  In this case, the rounding mode is
723+      determined by the ``rounding`` argument if given, else by the given
724+      ``context`` argument; if neither argument is given the rounding mode of
725+      the current thread's context is used.
726+ 
364-   If *watchexp* is set (default), then an error is returned whenever the resulting
727+      If *watchexp* is set (default), then an error is returned whenever the
365-   exponent is greater than :attr:`Emax` or less than :attr:`Etiny`.
728+      resulting exponent is greater than :attr:`Emax` or less than
729+      :attr:`Etiny`.
366
n731+   .. method:: radix()
367
n733+      Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
734+      class does all its arithmetic.  Included for compatibility with the
735+      specification.
736+ 
737+      .. versionadded:: 2.6
738+ 
368-.. method:: Decimal.remainder_near(other[, context])
739+   .. method:: remainder_near(other[, context])
369
n370-   Computes the modulo as either a positive or negative value depending on which is
n741+      Compute the modulo as either a positive or negative value depending on
371-   closest to zero.  For instance, ``Decimal(10).remainder_near(6)`` returns
742+      which is closest to zero.  For instance, ``Decimal(10).remainder_near(6)``
372-   ``Decimal("-2")`` which is closer to zero than ``Decimal("4")``.
743+      returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
373
n374-   If both are equally close, the one chosen will have the same sign as *self*.
n745+      If both are equally close, the one chosen will have the same sign as
746+      *self*.
375
n748+   .. method:: rotate(other[, context])
376
n750+      Return the result of rotating the digits of the first operand by an amount
751+      specified by the second operand.  The second operand must be an integer in
752+      the range -precision through precision.  The absolute value of the second
753+      operand gives the number of places to rotate.  If the second operand is
754+      positive then rotation is to the left; otherwise rotation is to the right.
755+      The coefficient of the first operand is padded on the left with zeros to
756+      length precision if necessary.  The sign and exponent of the first operand
757+      are unchanged.
758+ 
759+      .. versionadded:: 2.6
760+ 
377-.. method:: Decimal.same_quantum(other[, context])
761+   .. method:: same_quantum(other[, context])
378
n379-   Test whether self and other have the same exponent or whether both are
n763+      Test whether self and other have the same exponent or whether both are
380-   :const:`NaN`.
764+      :const:`NaN`.
381
n766+   .. method:: scaleb(other[, context])
382
n768+      Return the first operand with exponent adjusted by the second.
769+      Equivalently, return the first operand multiplied by ``10**other``.  The
770+      second operand must be an integer.
771+ 
772+      .. versionadded:: 2.6
773+ 
774+   .. method:: shift(other[, context])
775+ 
776+      Return the result of shifting the digits of the first operand by an amount
777+      specified by the second operand.  The second operand must be an integer in
778+      the range -precision through precision.  The absolute value of the second
779+      operand gives the number of places to shift.  If the second operand is
780+      positive then the shift is to the left; otherwise the shift is to the
781+      right.  Digits shifted into the coefficient are zeros.  The sign and
782+      exponent of the first operand are unchanged.
783+ 
784+      .. versionadded:: 2.6
785+ 
383-.. method:: Decimal.sqrt([context])
786+   .. method:: sqrt([context])
384
n385-   Return the square root to full precision.
n788+      Return the square root of the argument to full precision.
386
387
n388-.. method:: Decimal.to_eng_string([context])
n791+   .. method:: to_eng_string([context])
389
n390-   Convert to an engineering-type string.
n793+      Convert to an engineering-type string.
391
n392-   Engineering notation has an exponent which is a multiple of 3, so there are up
n795+      Engineering notation has an exponent which is a multiple of 3, so there
393-   to 3 digits left of the decimal place.  For example, converts
796+      are up to 3 digits left of the decimal place.  For example, converts
394-   ``Decimal('123E+1')`` to ``Decimal("1.23E+3")``
797+      ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
395
n396- 
397-.. method:: Decimal.to_integral([rounding[, context]])
799+   .. method:: to_integral([rounding[, context]])
398
n801+      Identical to the :meth:`to_integral_value` method.  The ``to_integral``
802+      name has been kept for compatibility with older versions.
803+ 
804+   .. method:: to_integral_exact([rounding[, context]])
805+ 
806+      Round to the nearest integer, signaling :const:`Inexact` or
807+      :const:`Rounded` as appropriate if rounding occurs.  The rounding mode is
808+      determined by the ``rounding`` parameter if given, else by the given
809+      ``context``.  If neither parameter is given then the rounding mode of the
810+      current context is used.
811+ 
812+      .. versionadded:: 2.6
813+ 
814+   .. method:: to_integral_value([rounding[, context]])
815+ 
399-   Rounds to the nearest integer without signaling :const:`Inexact` or
816+      Round to the nearest integer without signaling :const:`Inexact` or
400-   :const:`Rounded`.  If given, applies *rounding*; otherwise, uses the rounding
817+      :const:`Rounded`.  If given, applies *rounding*; otherwise, uses the
401-   method in either the supplied *context* or the current context.
818+      rounding method in either the supplied *context* or the current context.
402
n820+      .. versionchanged:: 2.6
821+         renamed from ``to_integral`` to ``to_integral_value``.  The old name
822+         remains valid for compatibility.
823+ 
824+.. _logical_operands_label:
825+ 
826+Logical operands
827+^^^^^^^^^^^^^^^^
828+ 
829+The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
830+and :meth:`logical_xor` methods expect their arguments to be *logical
831+operands*.  A *logical operand* is a :class:`Decimal` instance whose
832+exponent and sign are both zero, and whose digits are all either
833+:const:`0` or :const:`1`.
834+ 
403-.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
835+.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
404
405
n406-.. _decimal-decimal:
n838+.. _decimal-context:
407
408Context objects
409---------------
410
411Contexts are environments for arithmetic operations.  They govern precision, set
412rules for rounding, determine which signals are treated as exceptions, and limit
413the range for exponents.
414
436   when exiting the with-statement. If no context is specified, a copy of the
437   current context is used.
438
439   .. versionadded:: 2.5
440
441   For example, the following code sets the current decimal precision to 42 places,
442   performs a calculation, and then automatically restores the previous context::
443
n444-      from __future__ import with_statement
445      from decimal import localcontext
446
447      with localcontext() as ctx:
448          ctx.prec = 42   # Perform a high precision calculation
449          s = calculate_something()
450      s = +s  # Round the final result back to the default precision
451
452New contexts can also be created using the :class:`Context` constructor
466
467.. class:: ExtendedContext
468
469   This is a standard context defined by the General Decimal Arithmetic
470   Specification.  Precision is set to nine.  Rounding is set to
471   :const:`ROUND_HALF_EVEN`.  All flags are cleared.  No traps are enabled (so that
472   exceptions are not raised during computations).
473
n474-   Because the trapped are disabled, this context is useful for applications that
n905+   Because the traps are disabled, this context is useful for applications that
475   prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
476   raising exceptions.  This allows an application to complete a run in the
477   presence of conditions that would otherwise halt the program.
478
479
480.. class:: DefaultContext
481
482   This context is used by the :class:`Context` constructor as a prototype for new
504   default values are copied from the :const:`DefaultContext`.  If the *flags*
505   field is not specified or is :const:`None`, all flags are cleared.
506
507   The *prec* field is a positive integer that sets the precision for arithmetic
508   operations in the context.
509
510   The *rounding* option is one of:
511
n512-* :const:`ROUND_CEILING` (towards :const:`Infinity`),
n943+   * :const:`ROUND_CEILING` (towards :const:`Infinity`),
513- 
514-* :const:`ROUND_DOWN` (towards zero),
944+   * :const:`ROUND_DOWN` (towards zero),
515- 
516-* :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
945+   * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
517- 
518-* :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
946+   * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
519- 
520-* :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
947+   * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
521- 
522-* :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
948+   * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
523- 
524-* :const:`ROUND_UP` (away from zero).
949+   * :const:`ROUND_UP` (away from zero).
950+   * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
951+     would have been 0 or 5; otherwise towards zero)
525
526   The *traps* and *flags* fields list any signals to be set. Generally, new
527   contexts should only set traps and leave the flags clear.
528
529   The *Emin* and *Emax* fields are integers specifying the outer limits allowable
530   for exponents.
531
532   The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
533   :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
534   lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
535
n963+   .. versionchanged:: 2.6
964+      The :const:`ROUND_05UP` rounding mode was added.
965+ 
536-The :class:`Context` class defines several general purpose methods as well as a
966+   The :class:`Context` class defines several general purpose methods as well as
537-large number of methods for doing arithmetic directly in a given context.
967+   a large number of methods for doing arithmetic directly in a given context.
968+   In addition, for each of the :class:`Decimal` methods described above (with
969+   the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
970+   a corresponding :class:`Context` method.  For example, ``C.exp(x)`` is
971+   equivalent to ``x.exp(context=C)``.
538
539
n540-.. method:: Context.clear_flags()
n974+   .. method:: clear_flags()
541
n542-   Resets all of the flags to :const:`0`.
n976+      Resets all of the flags to :const:`0`.
543
n544- 
545-.. method:: Context.copy()
978+   .. method:: copy()
546
n547-   Return a duplicate of the context.
n980+      Return a duplicate of the context.
548
n982+   .. method:: copy_decimal(num)
549
n984+      Return a copy of the Decimal instance num.
985+ 
550-.. method:: Context.create_decimal(num)
986+   .. method:: create_decimal(num)
551
n552-   Creates a new Decimal instance from *num* but using *self* as context. Unlike
n988+      Creates a new Decimal instance from *num* but using *self* as
553-   the :class:`Decimal` constructor, the context precision, rounding method, flags,
989+      context. Unlike the :class:`Decimal` constructor, the context precision,
554-   and traps are applied to the conversion.
990+      rounding method, flags, and traps are applied to the conversion.
555
n556-   This is useful because constants are often given to a greater precision than is
n992+      This is useful because constants are often given to a greater precision
557-   needed by the application.  Another benefit is that rounding immediately
993+      than is needed by the application.  Another benefit is that rounding
558-   eliminates unintended effects from digits beyond the current precision. In the
994+      immediately eliminates unintended effects from digits beyond the current
559-   following example, using unrounded inputs means that adding zero to a sum can
995+      precision. In the following example, using unrounded inputs means that
560-   change the result::
996+      adding zero to a sum can change the result:
561
n998+      .. doctest:: newcontext
999+ 
562-      >>> getcontext().prec = 3
1000+         >>> getcontext().prec = 3
563-      >>> Decimal("3.4445") + Decimal("1.0023")
1001+         >>> Decimal('3.4445') + Decimal('1.0023')
564-      Decimal("4.45")
1002+         Decimal('4.45')
565-      >>> Decimal("3.4445") + Decimal(0) + Decimal("1.0023")
1003+         >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
566-      Decimal("4.44")
1004+         Decimal('4.44')
567
n1006+      This method implements the to-number operation of the IBM specification.
1007+      If the argument is a string, no leading or trailing whitespace is
1008+      permitted.
568
n569-.. method:: Context.Etiny()
n1010+   .. method:: Etiny()
570
n571-   Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
n1012+      Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
572-   for subnormal results.  When underflow occurs, the exponent is set to
1013+      value for subnormal results.  When underflow occurs, the exponent is set
573-   :const:`Etiny`.
1014+      to :const:`Etiny`.
574
575
n576-.. method:: Context.Etop()
n1017+   .. method:: Etop()
577
n578-   Returns a value equal to ``Emax - prec + 1``.
n1019+      Returns a value equal to ``Emax - prec + 1``.
579
n580-The usual approach to working with decimals is to create :class:`Decimal`
n1021+   The usual approach to working with decimals is to create :class:`Decimal`
581-instances and then apply arithmetic operations which take place within the
1022+   instances and then apply arithmetic operations which take place within the
582-current context for the active thread.  An alternate approach is to use context
1023+   current context for the active thread.  An alternative approach is to use
583-methods for calculating within a specific context.  The methods are similar to
1024+   context methods for calculating within a specific context.  The methods are
584-those for the :class:`Decimal` class and are only briefly recounted here.
1025+   similar to those for the :class:`Decimal` class and are only briefly
1026+   recounted here.
585
586
n587-.. method:: Context.abs(x)
n1029+   .. method:: abs(x)
588
n589-   Returns the absolute value of *x*.
n1031+      Returns the absolute value of *x*.
590
591
n592-.. method:: Context.add(x, y)
n1034+   .. method:: add(x, y)
593
n594-   Return the sum of *x* and *y*.
n1036+      Return the sum of *x* and *y*.
595
596
n1039+   .. method:: canonical(x)
1040+ 
1041+      Returns the same Decimal object *x*.
1042+ 
1043+ 
597-.. method:: Context.compare(x, y)
1044+   .. method:: compare(x, y)
598
n599-   Compares values numerically.
n1046+      Compares *x* and *y* numerically.
600
n601-   Like :meth:`__cmp__` but returns a decimal instance::
602
n603-      a or b is a NaN ==> Decimal("NaN")
n1049+   .. method:: compare_signal(x, y)
604-      a < b           ==> Decimal("-1")
605-      a == b          ==> Decimal("0")
606-      a > b           ==> Decimal("1")
607
n1051+      Compares the values of the two operands numerically.
608
n1053+ 
1054+   .. method:: compare_total(x, y)
1055+ 
1056+      Compares two operands using their abstract representation.
1057+ 
1058+ 
1059+   .. method:: compare_total_mag(x, y)
1060+ 
1061+      Compares two operands using their abstract representation, ignoring sign.
1062+ 
1063+ 
1064+   .. method:: copy_abs(x)
1065+ 
1066+      Returns a copy of *x* with the sign set to 0.
1067+ 
1068+ 
1069+   .. method:: copy_negate(x)
1070+ 
1071+      Returns a copy of *x* with the sign inverted.
1072+ 
1073+ 
1074+   .. method:: copy_sign(x, y)
1075+ 
1076+      Copies the sign from *y* to *x*.
1077+ 
1078+ 
609-.. method:: Context.divide(x, y)
1079+   .. method:: divide(x, y)
610
n611-   Return *x* divided by *y*.
n1081+      Return *x* divided by *y*.
612
613
n1084+   .. method:: divide_int(x, y)
1085+ 
1086+      Return *x* divided by *y*, truncated to an integer.
1087+ 
1088+ 
614-.. method:: Context.divmod(x, y)
1089+   .. method:: divmod(x, y)
615
n616-   Divides two numbers and returns the integer part of the result.
n1091+      Divides two numbers and returns the integer part of the result.
617
618
n1094+   .. method:: exp(x)
1095+ 
1096+      Returns `e ** x`.
1097+ 
1098+ 
1099+   .. method:: fma(x, y, z)
1100+ 
1101+      Returns *x* multiplied by *y*, plus *z*.
1102+ 
1103+ 
1104+   .. method:: is_canonical(x)
1105+ 
1106+      Returns True if *x* is canonical; otherwise returns False.
1107+ 
1108+ 
1109+   .. method:: is_finite(x)
1110+ 
1111+      Returns True if *x* is finite; otherwise returns False.
1112+ 
1113+ 
1114+   .. method:: is_infinite(x)
1115+ 
1116+      Returns True if *x* is infinite; otherwise returns False.
1117+ 
1118+ 
1119+   .. method:: is_nan(x)
1120+ 
1121+      Returns True if *x* is a qNaN or sNaN; otherwise returns False.
1122+ 
1123+ 
1124+   .. method:: is_normal(x)
1125+ 
1126+      Returns True if *x* is a normal number; otherwise returns False.
1127+ 
1128+ 
1129+   .. method:: is_qnan(x)
1130+ 
1131+      Returns True if *x* is a quiet NaN; otherwise returns False.
1132+ 
1133+ 
1134+   .. method:: is_signed(x)
1135+ 
1136+      Returns True if *x* is negative; otherwise returns False.
1137+ 
1138+ 
1139+   .. method:: is_snan(x)
1140+ 
1141+      Returns True if *x* is a signaling NaN; otherwise returns False.
1142+ 
1143+ 
1144+   .. method:: is_subnormal(x)
1145+ 
1146+      Returns True if *x* is subnormal; otherwise returns False.
1147+ 
1148+ 
1149+   .. method:: is_zero(x)
1150+ 
1151+      Returns True if *x* is a zero; otherwise returns False.
1152+ 
1153+ 
1154+   .. method:: ln(x)
1155+ 
1156+      Returns the natural (base e) logarithm of *x*.
1157+ 
1158+ 
1159+   .. method:: log10(x)
1160+ 
1161+      Returns the base 10 logarithm of *x*.
1162+ 
1163+ 
1164+   .. method:: logb(x)
1165+ 
1166+       Returns the exponent of the magnitude of the operand's MSD.
1167+ 
1168+ 
1169+   .. method:: logical_and(x, y)
1170+ 
1171+      Applies the logical operation *and* between each operand's digits.
1172+ 
1173+ 
1174+   .. method:: logical_invert(x)
1175+ 
1176+      Invert all the digits in *x*.
1177+ 
1178+ 
1179+   .. method:: logical_or(x, y)
1180+ 
1181+      Applies the logical operation *or* between each operand's digits.
1182+ 
1183+ 
1184+   .. method:: logical_xor(x, y)
1185+ 
1186+      Applies the logical operation *xor* between each operand's digits.
1187+ 
1188+ 
619-.. method:: Context.max(x, y)
1189+   .. method:: max(x, y)
620
n621-   Compare two values numerically and return the maximum.
n1191+      Compares two values numerically and returns the maximum.
622
n623-   If they are numerically equal then the left-hand operand is chosen as the
624-   result.
625
n1194+   .. method:: max_mag(x, y)
626
n1196+      Compares the values numerically with their sign ignored.
1197+ 
1198+ 
627-.. method:: Context.min(x, y)
1199+   .. method:: min(x, y)
628
n629-   Compare two values numerically and return the minimum.
n1201+      Compares two values numerically and returns the minimum.
630
n631-   If they are numerically equal then the left-hand operand is chosen as the
632-   result.
633
n1204+   .. method:: min_mag(x, y)
634
n1206+      Compares the values numerically with their sign ignored.
1207+ 
1208+ 
635-.. method:: Context.minus(x)
1209+   .. method:: minus(x)
636
n637-   Minus corresponds to the unary prefix minus operator in Python.
n1211+      Minus corresponds to the unary prefix minus operator in Python.
638
639
n640-.. method:: Context.multiply(x, y)
n1214+   .. method:: multiply(x, y)
641
n642-   Return the product of *x* and *y*.
n1216+      Return the product of *x* and *y*.
643
644
n645-.. method:: Context.normalize(x)
n1219+   .. method:: next_minus(x)
646
n647-   Normalize reduces an operand to its simplest form.
n1221+      Returns the largest representable number smaller than *x*.
648
n649-   Essentially a :meth:`plus` operation with all trailing zeros removed from the
650-   result.
651
n652- 
653-.. method:: Context.plus(x)
1224+   .. method:: next_plus(x)
654
n1226+      Returns the smallest representable number larger than *x*.
1227+ 
1228+ 
1229+   .. method:: next_toward(x, y)
1230+ 
1231+      Returns the number closest to *x*, in direction towards *y*.
1232+ 
1233+ 
1234+   .. method:: normalize(x)
1235+ 
1236+      Reduces *x* to its simplest form.
1237+ 
1238+ 
1239+   .. method:: number_class(x)
1240+ 
1241+      Returns an indication of the class of *x*.
1242+ 
1243+ 
1244+   .. method:: plus(x)
1245+ 
655-   Plus corresponds to the unary prefix plus operator in Python.  This operation
1246+      Plus corresponds to the unary prefix plus operator in Python.  This
656-   applies the context precision and rounding, so it is *not* an identity
1247+      operation applies the context precision and rounding, so it is *not* an
657-   operation.
1248+      identity operation.
658
659
n660-.. method:: Context.power(x, y[, modulo])
n1251+   .. method:: power(x, y[, modulo])
661
n662-   Return ``x ** y`` to the *modulo* if given.
n1253+      Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
663
n664-   The right-hand operand must be a whole number whose integer part (after any
n1255+      With two arguments, compute ``x**y``.  If ``x`` is negative then ``y``
665-   exponent has been applied) has no more than 9 digits and whose fractional part
1256+      must be integral.  The result will be inexact unless ``y`` is integral and
666-   (if any) is all zeros before any rounding. The operand may be positive,
1257+      the result is finite and can be expressed exactly in 'precision' digits.
667-   negative, or zero; if negative, the absolute value of the power is used, and the
1258+      The result should always be correctly rounded, using the rounding mode of
668-   left-hand operand is inverted (divided into 1) before use.
1259+      the current thread's context.
669
n670-   If the increased precision needed for the intermediate calculations exceeds the
n1261+      With three arguments, compute ``(x**y) % modulo``.  For the three argument
671-   capabilities of the implementation then an :const:`InvalidOperation` condition
1262+      form, the following restrictions on the arguments hold:
672-   is signaled.
673
n674-   If, when raising to a negative power, an underflow occurs during the division
n1264+         - all three arguments must be integral
675-   into 1, the operation is not halted at that point but continues.
1265+         - ``y`` must be nonnegative
1266+         - at least one of ``x`` or ``y`` must be nonzero
1267+         - ``modulo`` must be nonzero and have at most 'precision' digits
676
n1269+      The result of ``Context.power(x, y, modulo)`` is identical to the result
1270+      that would be obtained by computing ``(x**y) % modulo`` with unbounded
1271+      precision, but is computed more efficiently.  It is always exact.
677
n1273+      .. versionchanged:: 2.6
1274+         ``y`` may now be nonintegral in ``x**y``.
1275+         Stricter requirements for the three-argument version.
1276+ 
1277+ 
678-.. method:: Context.quantize(x, y)
1278+   .. method:: quantize(x, y)
679
n680-   Returns a value equal to *x* after rounding and having the exponent of *y*.
n1280+      Returns a value equal to *x* (rounded), having the exponent of *y*.
681
n682-   Unlike other operations, if the length of the coefficient after the quantize
683-   operation would be greater than precision, then an :const:`InvalidOperation` is
684-   signaled. This guarantees that, unless there is an error condition, the
685-   quantized exponent is always equal to that of the right-hand operand.
686
n687-   Also unlike other operations, quantize never signals Underflow, even if the
n1283+   .. method:: radix()
688-   result is subnormal and inexact.
689
n1285+      Just returns 10, as this is Decimal, :)
690
n1287+ 
691-.. method:: Context.remainder(x, y)
1288+   .. method:: remainder(x, y)
692
n693-   Returns the remainder from integer division.
n1290+      Returns the remainder from integer division.
694
n695-   The sign of the result, if non-zero, is the same as that of the original
n1292+      The sign of the result, if non-zero, is the same as that of the original
696-   dividend.
1293+      dividend.
697
n698- 
699-.. method:: Context.remainder_near(x, y)
1295+   .. method:: remainder_near(x, y)
700
n701-   Computed the modulo as either a positive or negative value depending on which is
n1297+      Returns ``x - y * n``, where *n* is the integer nearest the exact value
702-   closest to zero.  For instance, ``Decimal(10).remainder_near(6)`` returns
1298+      of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
703-   ``Decimal("-2")`` which is closer to zero than ``Decimal("4")``.
704
n705-   If both are equally close, the one chosen will have the same sign as *self*.
706
n1301+   .. method:: rotate(x, y)
707
n1303+      Returns a rotated copy of *x*, *y* times.
1304+ 
1305+ 
708-.. method:: Context.same_quantum(x, y)
1306+   .. method:: same_quantum(x, y)
709
n710-   Test whether *x* and *y* have the same exponent or whether both are
n1308+      Returns True if the two operands have the same exponent.
711-   :const:`NaN`.
712
713
n1311+   .. method:: scaleb (x, y)
1312+ 
1313+      Returns the first operand after adding the second value its exp.
1314+ 
1315+ 
1316+   .. method:: shift(x, y)
1317+ 
1318+      Returns a shifted copy of *x*, *y* times.
1319+ 
1320+ 
714-.. method:: Context.sqrt(x)
1321+   .. method:: sqrt(x)
715
n716-   Return the square root of *x* to full precision.
n1323+      Square root of a non-negative number to context precision.
717
718
n719-.. method:: Context.subtract(x, y)
n1326+   .. method:: subtract(x, y)
720
n721-   Return the difference between *x* and *y*.
n1328+      Return the difference between *x* and *y*.
722
723
n724-.. method:: Context.to_eng_string()
n1331+   .. method:: to_eng_string(x)
725
n726-   Convert to engineering-type string.
n1333+      Converts a number to a string, using scientific notation.
727
n728-   Engineering notation has an exponent which is a multiple of 3, so there are up
729-   to 3 digits left of the decimal place.  For example, converts
730-   ``Decimal('123E+1')`` to ``Decimal("1.23E+3")``
731
n732- 
733-.. method:: Context.to_integral(x)
1336+   .. method:: to_integral_exact(x)
734
n735-   Rounds to the nearest integer without signaling :const:`Inexact` or
n1338+      Rounds to an integer.
736-   :const:`Rounded`.
737
738
n739-.. method:: Context.to_sci_string(x)
n1341+   .. method:: to_sci_string(x)
740
n741-   Converts a number to a string using scientific notation.
n1343+      Converts a number to a string using scientific notation.
742
n743-.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
n1345+.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
744
745
746.. _decimal-signals:
747
748Signals
749-------
750
751Signals represent conditions that arise during computation. Each corresponds to
752one context flag and one context trap enabler.
753
n754-The context flag is incremented whenever the condition is encountered. After the
n1356+The context flag is set whenever the condition is encountered. After the
755computation, flags may be checked for informational purposes (for instance, to
756determine whether a computation was exact). After checking the flags, be sure to
757clear all flags before starting the next computation.
758
759If the context's trap enabler is set for the signal, then the condition causes a
760Python exception to be raised.  For example, if the :class:`DivisionByZero` trap
761is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
762condition.
763
764
765.. class:: Clamped
766
767   Altered an exponent to fit representation constraints.
768
769   Typically, clamping occurs when an exponent falls outside the context's
770   :attr:`Emin` and :attr:`Emax` limits.  If possible, the exponent is reduced to
n771-   fit by adding zeroes to the coefficient.
n1373+   fit by adding zeros to the coefficient.
772
773
774.. class:: DecimalException
775
776   Base class for other signals and a subclass of :exc:`ArithmeticError`.
777
778
779.. class:: DivisionByZero
805      0 * Infinity
806      Infinity / Infinity
807      x % 0
808      Infinity % x
809      x._rescale( non-integer )
810      sqrt(-x) and x > 0
811      0 ** 0
812      x ** (non-integer)
n813-      x ** Infinity      
n1415+      x ** Infinity
814
815
816.. class:: Overflow
817
818   Numerical overflow.
819
n820-   Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
n1422+   Indicates the exponent is larger than :attr:`Emax` after rounding has
821-   If not trapped, the result depends on the rounding mode, either pulling inward
1423+   occurred.  If not trapped, the result depends on the rounding mode, either
822-   to the largest representable finite number or rounding outward to
1424+   pulling inward to the largest representable finite number or rounding outward
823-   :const:`Infinity`.  In either case, :class:`Inexact` and :class:`Rounded` are
1425+   to :const:`Infinity`.  In either case, :class:`Inexact` and :class:`Rounded`
824-   also signaled.
1426+   are also signaled.
825
826
827.. class:: Rounded
828
829   Rounding occurred though possibly no information was lost.
830
n831-   Signaled whenever rounding discards digits; even if those digits are zero (such
n1433+   Signaled whenever rounding discards digits; even if those digits are zero
832-   as rounding :const:`5.00` to :const:`5.0`).   If not trapped, returns the result
1434+   (such as rounding :const:`5.00` to :const:`5.0`).  If not trapped, returns
833-   unchanged.  This signal is used to detect loss of significant digits.
1435+   the result unchanged.  This signal is used to detect loss of significant
1436+   digits.
834
835
836.. class:: Subnormal
837
838   Exponent was lower than :attr:`Emin` prior to rounding.
839
n840-   Occurs when an operation result is subnormal (the exponent is too small). If not
n1443+   Occurs when an operation result is subnormal (the exponent is too small). If
841-   trapped, returns the result unchanged.
1444+   not trapped, returns the result unchanged.
842
843
844.. class:: Underflow
845
846   Numerical underflow with result rounded to zero.
847
848   Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
849   and :class:`Subnormal` are also signaled.
856           DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
857           Inexact
858               Overflow(Inexact, Rounded)
859               Underflow(Inexact, Rounded, Subnormal)
860           InvalidOperation
861           Rounded
862           Subnormal
863
n864-.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
n1467+.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
865
866
867.. _decimal-notes:
868
869Floating Point Notes
870--------------------
871
872
876The use of decimal floating point eliminates decimal representation error
877(making it possible to represent :const:`0.1` exactly); however, some operations
878can still incur round-off error when non-zero digits exceed the fixed precision.
879
880The effects of round-off error can be amplified by the addition or subtraction
881of nearly offsetting quantities resulting in loss of significance.  Knuth
882provides two instructive examples where rounded floating point arithmetic with
883insufficient precision causes the breakdown of the associative and distributive
n884-properties of addition::
n1487+properties of addition:
1488+ 
1489+.. doctest:: newcontext
885
886   # Examples from Seminumerical Algorithms, Section 4.2.2.
887   >>> from decimal import Decimal, getcontext
888   >>> getcontext().prec = 8
889
890   >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
891   >>> (u + v) + w
n892-   Decimal("9.5111111")
n1497+   Decimal('9.5111111')
893   >>> u + (v + w)
n894-   Decimal("10")
n1499+   Decimal('10')
895
896   >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
897   >>> (u*v) + (u*w)
n898-   Decimal("0.01")
n1503+   Decimal('0.01')
899   >>> u * (v+w)
n900-   Decimal("0.0060000")
n1505+   Decimal('0.0060000')
901
902The :mod:`decimal` module makes it possible to restore the identities by
n903-expanding the precision sufficiently to avoid loss of significance::
n1508+expanding the precision sufficiently to avoid loss of significance:
1509+ 
1510+.. doctest:: newcontext
904
905   >>> getcontext().prec = 20
906   >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
907   >>> (u + v) + w
n908-   Decimal("9.51111111")
n1515+   Decimal('9.51111111')
909   >>> u + (v + w)
n910-   Decimal("9.51111111")
n1517+   Decimal('9.51111111')
911-   >>> 
1518+   >>>
912   >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
913   >>> (u*v) + (u*w)
n914-   Decimal("0.0060000")
n1521+   Decimal('0.0060000')
915   >>> u * (v+w)
n916-   Decimal("0.0060000")
n1523+   Decimal('0.0060000')
917
918
919Special values
920^^^^^^^^^^^^^^
921
922The number system for the :mod:`decimal` module provides special values
923including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
n924-and two zeroes, :const:`+0` and :const:`-0`.
n1531+and two zeros, :const:`+0` and :const:`-0`.
925
926Infinities can be constructed directly with:  ``Decimal('Infinity')``. Also,
927they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
928not trapped.  Likewise, when the :exc:`Overflow` signal is not trapped, infinity
929can result from rounding beyond the limits of the largest representable number.
930
931The infinities are signed (affine) and can be used in arithmetic operations
932where they get treated as very large, indeterminate numbers.  For instance,
939always resulting in another :const:`NaN`.  This behavior can be useful for a
940series of computations that occasionally have missing inputs --- it allows the
941calculation to proceed while flagging specific results as invalid.
942
943A variant is :const:`sNaN` which signals rather than remaining quiet after every
944operation.  This is a useful return value when an invalid result needs to
945interrupt a calculation for special handling.
946
n1554+The behavior of Python's comparison operators can be a little surprising where a
1555+:const:`NaN` is involved.  A test for equality where one of the operands is a
1556+quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1557+``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1558+:const:`True`.  An attempt to compare two Decimals using any of the ``<``,
1559+``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1560+if either operand is a :const:`NaN`, and return :const:`False` if this signal is
1561+not trapped.  Note that the General Decimal Arithmetic specification does not
1562+specify the behavior of direct comparisons; these rules for comparisons
1563+involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1564+section 5.7).  To ensure strict standards-compliance, use the :meth:`compare`
1565+and :meth:`compare-signal` methods instead.
1566+ 
947The signed zeros can result from calculations that underflow. They keep the sign
948that would have resulted if the calculation had been carried out to greater
949precision.  Since their magnitude is zero, both positive and negative zeros are
950treated as equal and their sign is informational.
951
952In addition to the two signed zeros which are distinct yet equal, there are
953various representations of zero with differing precisions yet equivalent in
954value.  This takes a bit of getting used to.  For an eye accustomed to
955normalized floating point representations, it is not immediately obvious that
n956-the following calculation returns a value equal to zero::
n1576+the following calculation returns a value equal to zero:
957
958   >>> 1 / Decimal('Infinity')
n959-   Decimal("0E-1000000026")
n1579+   Decimal('0E-1000000026')
960
n961-.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
n1581+.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
962
963
964.. _decimal-threads:
965
966Working with threads
967--------------------
968
969The :func:`getcontext` function accesses a different :class:`Context` object for
991   setcontext(DefaultContext)
992
993   # Afterwards, the threads can be started
994   t1.start()
995   t2.start()
996   t3.start()
997    . . .
998
n999-.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
n1619+.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1000
1001
1002.. _decimal-recipes:
1003
1004Recipes
1005-------
1006
1007Here are a few recipes that serve as utility functions and that demonstrate ways
1025       '-$1,234,567.89'
1026       >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1027       '1.234.568-'
1028       >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1029       '($1,234,567.89)'
1030       >>> moneyfmt(Decimal(123456789), sep=' ')
1031       '123 456 789.00'
1032       >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
n1033-       '<.02>'
n1653+       '<0.02>'
1034
1035       """
n1036-       q = Decimal((0, (1,), -places))    # 2 places --> '0.01'
n1656+       q = Decimal(10) ** -places      # 2 places --> '0.01'
1037       sign, digits, exp = value.quantize(q).as_tuple()
n1038-       assert exp == -places    
1039       result = []
1040       digits = map(str, digits)
1041       build, next = result.append, digits.pop
1042       if sign:
1043           build(trailneg)
1044       for i in range(places):
n1045-           if digits:
n1664+           build(next() if digits else '0')
1046-               build(next())
1047-           else:
1048-               build('0')
1049       build(dp)
n1666+       if not digits:
1667+           build('0')
1050       i = 0
1051       while digits:
1052           build(next())
1053           i += 1
1054           if i == 3 and digits:
1055               i = 0
1056               build(sep)
1057       build(curr)
n1058-       if sign:
n1676+       build(neg if sign else pos)
1059-           build(neg)
1060-       else:
1061-           build(pos)
1062-       result.reverse()
1063-       return ''.join(result)
1677+       return ''.join(reversed(result))
1064
1065   def pi():
1066       """Compute Pi to the current precision.
1067
1068       >>> print pi()
1069       3.141592653589793238462643383
1070
1071       """
1092       7.38905609893
1093       >>> print exp(2+0j)
1094       (7.38905609893+0j)
1095
1096       """
1097       getcontext().prec += 2
1098       i, lasts, s, fact, num = 0, 0, 1, 1, 1
1099       while s != lasts:
n1100-           lasts = s    
n1714+           lasts = s
1101           i += 1
1102           fact *= i
n1103-           num *= x     
n1717+           num *= x
1104-           s += num / fact   
1718+           s += num / fact
1105-       getcontext().prec -= 2        
1719+       getcontext().prec -= 2
1106       return +s
1107
1108   def cos(x):
1109       """Return the cosine of x as measured in radians.
1110
1111       >>> print cos(Decimal('0.5'))
1112       0.8775825618903727161162815826
1113       >>> print cos(0.5)
1114       0.87758256189
1115       >>> print cos(0.5+0j)
1116       (0.87758256189+0j)
1117
1118       """
1119       getcontext().prec += 2
1120       i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1121       while s != lasts:
n1122-           lasts = s    
n1736+           lasts = s
1123           i += 2
1124           fact *= i * (i-1)
1125           num *= x * x
1126           sign *= -1
n1127-           s += num / fact * sign 
n1741+           s += num / fact * sign
1128-       getcontext().prec -= 2        
1742+       getcontext().prec -= 2
1129       return +s
1130
1131   def sin(x):
1132       """Return the sine of x as measured in radians.
1133
1134       >>> print sin(Decimal('0.5'))
1135       0.4794255386042030002732879352
1136       >>> print sin(0.5)
1137       0.479425538604
1138       >>> print sin(0.5+0j)
1139       (0.479425538604+0j)
1140
1141       """
1142       getcontext().prec += 2
1143       i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1144       while s != lasts:
n1145-           lasts = s    
n1759+           lasts = s
1146           i += 2
1147           fact *= i * (i-1)
1148           num *= x * x
1149           sign *= -1
n1150-           s += num / fact * sign 
n1764+           s += num / fact * sign
1151-       getcontext().prec -= 2        
1765+       getcontext().prec -= 2
1152       return +s
1153
1154
n1155-.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
n1769+.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1156
1157
1158.. _decimal-faq:
1159
1160Decimal FAQ
1161-----------
1162
n1163-Q.  It is cumbersome to type ``decimal.Decimal('1234.5')``.  Is there a way to
n1777+Q. It is cumbersome to type ``decimal.Decimal('1234.5')``.  Is there a way to
1164minimize typing when using the interactive interpreter?
1165
n1166-A.  Some users abbreviate the constructor to just a single letter::
n1780+A. Some users abbreviate the constructor to just a single letter:
1167
1168   >>> D = decimal.Decimal
1169   >>> D('1.23') + D('3.45')
n1170-   Decimal("4.68")
n1784+   Decimal('4.68')
1171
n1172-Q.  In a fixed-point application with two decimal places, some inputs have many
n1786+Q. In a fixed-point application with two decimal places, some inputs have many
1173places and need to be rounded.  Others are not supposed to have excess digits
1174and need to be validated.  What methods should be used?
1175
n1176-A.  The :meth:`quantize` method rounds to a fixed number of decimal places. If
n1790+A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
1177-the :const:`Inexact` trap is set, it is also useful for validation::
1791+the :const:`Inexact` trap is set, it is also useful for validation:
1178
1179   >>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')
1180
1181   >>> # Round to two places
n1182-   >>> Decimal("3.214").quantize(TWOPLACES)
n1796+   >>> Decimal('3.214').quantize(TWOPLACES)
1183-   Decimal("3.21")
1797+   Decimal('3.21')
1184
n1185-   >>> # Validate that a number does not exceed two places 
n1799+   >>> # Validate that a number does not exceed two places
1186-   >>> Decimal("3.21").quantize(TWOPLACES, context=Context(traps=[Inexact]))
1800+   >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1187-   Decimal("3.21")
1801+   Decimal('3.21')
1188
n1189-   >>> Decimal("3.214").quantize(TWOPLACES, context=Context(traps=[Inexact]))
n1803+   >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1190   Traceback (most recent call last):
1191      ...
n1192-   Inexact: Changed in rounding
n1806+   Inexact
1193
n1194-Q.  Once I have valid two place inputs, how do I maintain that invariant
n1808+Q. Once I have valid two place inputs, how do I maintain that invariant
1195throughout an application?
1196
n1197-A.  Some operations like addition and subtraction automatically preserve fixed
n1811+A. Some operations like addition, subtraction, and multiplication by an integer
1198-point.  Others, like multiplication and division, change the number of decimal
1812+will automatically preserve fixed point.  Others operations, like division and
1813+non-integer multiplication, will change the number of decimal places and need to
1199-places and need to be followed-up with a :meth:`quantize` step.
1814+be followed-up with a :meth:`quantize` step:
1200
n1816+    >>> a = Decimal('102.72')           # Initial fixed-point values
1817+    >>> b = Decimal('3.17')
1818+    >>> a + b                           # Addition preserves fixed-point
1819+    Decimal('105.89')
1820+    >>> a - b
1821+    Decimal('99.55')
1822+    >>> a * 42                          # So does integer multiplication
1823+    Decimal('4314.24')
1824+    >>> (a * b).quantize(TWOPLACES)     # Must quantize non-integer multiplication
1825+    Decimal('325.62')
1826+    >>> (b / a).quantize(TWOPLACES)     # And quantize division
1827+    Decimal('0.03')
1828+ 
1829+In developing fixed-point applications, it is convenient to define functions
1830+to handle the :meth:`quantize` step:
1831+ 
1832+    >>> def mul(x, y, fp=TWOPLACES):
1833+    ...     return (x * y).quantize(fp)
1834+    >>> def div(x, y, fp=TWOPLACES):
1835+    ...     return (x / y).quantize(fp)
1836+ 
1837+    >>> mul(a, b)                       # Automatically preserve fixed-point
1838+    Decimal('325.62')
1839+    >>> div(b, a)
1840+    Decimal('0.03')
1841+ 
1201-Q.  There are many ways to express the same value.  The numbers :const:`200`,
1842+Q. There are many ways to express the same value.  The numbers :const:`200`,
1202:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1203various precisions. Is there a way to transform them to a single recognizable
1204canonical value?
1205
n1206-A.  The :meth:`normalize` method maps all equivalent values to a single
n1847+A. The :meth:`normalize` method maps all equivalent values to a single
1207-representative::
1848+representative:
1208
1209   >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1210   >>> [v.normalize() for v in values]
n1211-   [Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2")]
n1852+   [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
1212
n1213-Q.  Some decimal values always print with exponential notation.  Is there a way
n1854+Q. Some decimal values always print with exponential notation.  Is there a way
1214to get a non-exponential representation?
1215
n1216-A.  For some values, exponential notation is the only way to express the number
n1857+A. For some values, exponential notation is the only way to express the number
1217of significant places in the coefficient.  For example, expressing
1218:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1219original's two-place significance.
1220
n1862+If an application does not care about tracking significance, it is easy to
1863+remove the exponent and trailing zeroes, losing significance, but keeping the
1864+value unchanged:
1865+ 
1866+    >>> def remove_exponent(d):
1867+    ...     return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1868+ 
1869+    >>> remove_exponent(Decimal('5E+3'))
1870+    Decimal('5000')
1871+ 
1221-Q.  Is there a way to convert a regular float to a :class:`Decimal`?
1872+Q. Is there a way to convert a regular float to a :class:`Decimal`?
1222
n1223-A.  Yes, all binary floating point numbers can be exactly expressed as a
n1874+A. Yes, all binary floating point numbers can be exactly expressed as a
1224Decimal.  An exact conversion may take more precision than intuition would
n1225-suggest, so trapping :const:`Inexact` will signal a need for more precision::
n1876+suggest, so we trap :const:`Inexact` to signal a need for more precision:
1226
n1878+.. testcode::
1879+ 
1227-   def floatToDecimal(f):
1880+    def float_to_decimal(f):
1228-       "Convert a floating point number to a Decimal with no loss of information"
1881+        "Convert a floating point number to a Decimal with no loss of information"
1229-       # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an
1882+        n, d = f.as_integer_ratio()
1230-       # exponent.  Double the mantissa until it is an integer.  Use the integer
1883+        numerator, denominator = Decimal(n), Decimal(d)
1231-       # mantissa and exponent to compute an equivalent Decimal.  If this cannot
1884+        ctx = Context(prec=60)
1232-       # be done exactly, then retry with more precision.
1885+        result = ctx.divide(numerator, denominator)
1886+        while ctx.flags[Inexact]:
1887+            ctx.flags[Inexact] = False
1888+            ctx.prec *= 2
1889+            result = ctx.divide(numerator, denominator)
1890+        return result
1233
n1234-       mantissa, exponent = math.frexp(f)
n1892+.. doctest::
1235-       while mantissa != int(mantissa):
1236-           mantissa *= 2.0
1237-           exponent -= 1
1238-       mantissa = int(mantissa)
1239
n1240-       oldcontext = getcontext()
n1894+    >>> float_to_decimal(math.pi)
1241-       setcontext(Context(traps=[Inexact]))
1895+    Decimal('3.141592653589793115997963468544185161590576171875')
1242-       try:
1243-           while True:
1244-               try:
1245-                  return mantissa * Decimal(2) ** exponent
1246-               except Inexact:
1247-                   getcontext().prec += 1
1248-       finally:
1249-           setcontext(oldcontext)
1250
n1251-Q.  Why isn't the :func:`floatToDecimal` routine included in the module?
n1897+Q. Why isn't the :func:`float_to_decimal` routine included in the module?
1252
n1253-A.  There is some question about whether it is advisable to mix binary and
n1899+A. There is some question about whether it is advisable to mix binary and
1254decimal floating point.  Also, its use requires some care to avoid the
n1255-representation issues associated with binary floating point::
n1901+representation issues associated with binary floating point:
1256
n1257-   >>> floatToDecimal(1.1)
n1903+   >>> float_to_decimal(1.1)
1258-   Decimal("1.100000000000000088817841970012523233890533447265625")
1904+   Decimal('1.100000000000000088817841970012523233890533447265625')
1259
n1260-Q.  Within a complex calculation, how can I make sure that I haven't gotten a
n1906+Q. Within a complex calculation, how can I make sure that I haven't gotten a
1261spurious result because of insufficient precision or rounding anomalies.
1262
n1263-A.  The decimal module makes it easy to test results.  A best practice is to re-
n1909+A. The decimal module makes it easy to test results.  A best practice is to
1264-run calculations using greater precision and with various rounding modes. Widely
1910+re-run calculations using greater precision and with various rounding modes.
1265-differing results indicate insufficient precision, rounding mode issues, ill-
1911+Widely differing results indicate insufficient precision, rounding mode issues,
1266-conditioned inputs, or a numerically unstable algorithm.
1912+ill-conditioned inputs, or a numerically unstable algorithm.
1267
n1268-Q.  I noticed that context precision is applied to the results of operations but
n1914+Q. I noticed that context precision is applied to the results of operations but
1269not to the inputs.  Is there anything to watch out for when mixing values of
1270different precisions?
1271
n1272-A.  Yes.  The principle is that all values are considered to be exact and so is
n1918+A. Yes.  The principle is that all values are considered to be exact and so is
1273the arithmetic on those values.  Only the results are rounded.  The advantage
1274for inputs is that "what you type is what you get".  A disadvantage is that the
n1275-results can look odd if you forget that the inputs haven't been rounded::
n1921+results can look odd if you forget that the inputs haven't been rounded:
1922+ 
1923+.. doctest:: newcontext
1276
1277   >>> getcontext().prec = 3
n1278-   >>> Decimal('3.104') + D('2.104')
n1926+   >>> Decimal('3.104') + Decimal('2.104')
1279-   Decimal("5.21")
1927+   Decimal('5.21')
1280-   >>> Decimal('3.104') + D('0.000') + D('2.104')
1928+   >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
1281-   Decimal("5.20")
1929+   Decimal('5.20')
1282
1283The solution is either to increase precision or to force rounding of inputs
n1284-using the unary plus operation::
n1932+using the unary plus operation:
1933+ 
1934+.. doctest:: newcontext
1285
1286   >>> getcontext().prec = 3
1287   >>> +Decimal('1.23456789')      # unary plus triggers rounding
n1288-   Decimal("1.23")
n1938+   Decimal('1.23')
1289
1290Alternatively, inputs can be rounded upon creation using the
n1291-:meth:`Context.create_decimal` method::
n1941+:meth:`Context.create_decimal` method:
1292
1293   >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
t1294-   Decimal("1.2345")
t1944+   Decimal('1.2345')
1295
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op