2 :mod:`decimal` --- Decimal fixed point and floating point arithmetic
3 ====================================================================
6 :synopsis: Implementation of the General Decimal Arithmetic Specification.
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>
16 .. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
20 .. import modules for testing inline doctests with the Sphinx doctest builder
26 # make sure each group gets a fresh context
29 The :mod:`decimal` module provides support for decimal floating point
30 arithmetic. It offers several advantages over the :class:`float` datatype:
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.
37 * Decimal numbers can be represented exactly. In contrast, numbers like
38 :const:`1.1` do not have an exact representation in binary floating point. End
39 users typically would not expect :const:`1.1` to display as
40 :const:`1.1000000000000001` as it does with binary floating point.
42 * The exactness carries over into arithmetic. In decimal floating point, ``0.1
43 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
44 is :const:`5.5511151231257827e-017`. While near to zero, the differences
45 prevent reliable equality testing and differences can accumulate. For this
46 reason, decimal is preferred in accounting applications which have strict
49 * The decimal module incorporates a notion of significant places so that ``1.30
50 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
51 This is the customary presentation for monetary applications. For
52 multiplication, the "schoolbook" approach uses all the figures in the
53 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
54 1.20`` gives :const:`1.5600`.
56 * Unlike hardware based binary floating point, the decimal module has a user
57 alterable precision (defaulting to 28 places) which can be as large as needed for
60 >>> getcontext().prec = 6
61 >>> Decimal(1) / Decimal(7)
63 >>> getcontext().prec = 28
64 >>> Decimal(1) / Decimal(7)
65 Decimal('0.1428571428571428571428571429')
67 * Both binary and decimal floating point are implemented in terms of published
68 standards. While the built-in float type exposes only a modest portion of its
69 capabilities, the decimal module exposes all required parts of the standard.
70 When needed, the programmer has full control over rounding and signal handling.
71 This includes an option to enforce exact arithmetic by using exceptions
72 to block any inexact operations.
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.
79 The module design is centered around three concepts: the decimal number, the
80 context for arithmetic, and signals.
82 A decimal number is immutable. It has a sign, coefficient digits, and an
83 exponent. To preserve significance, the coefficient digits do not truncate
84 trailing zeros. Decimals also include special values such as
85 :const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
86 differentiates :const:`-0` from :const:`+0`.
88 The context for arithmetic is an environment specifying precision, rounding
89 rules, limits on exponents, flags indicating the results of operations, and trap
90 enablers which determine whether signals are treated as exceptions. Rounding
91 options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
92 :const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
93 :const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
95 Signals are groups of exceptional conditions arising during the course of
96 computation. Depending on the needs of the application, signals may be ignored,
97 considered as informational, or treated as exceptions. The signals in the
98 decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
99 :const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
100 :const:`Overflow`, and :const:`Underflow`.
102 For each signal there is a flag and a trap enabler. When a signal is
103 encountered, its flag is set to one, then, if the trap enabler is
104 set to one, an exception is raised. Flags are sticky, so the user needs to
105 reset them before monitoring a calculation.
110 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
111 Specification <http://speleotrove.com/decimal/>`_.
113 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
114 <http://754r.ucbtest.org/standards/854.pdf>`_.
116 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
119 .. _decimal-tutorial:
124 The usual start to using decimals is importing the module, viewing the current
125 context with :func:`getcontext` and, if necessary, setting new values for
126 precision, rounding, or enabled traps::
128 >>> from decimal import *
130 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
131 capitals=1, flags=[], traps=[Overflow, DivisionByZero,
134 >>> getcontext().prec = 7 # Set a new precision
136 Decimal instances can be constructed from integers, strings, or tuples. To
137 create a Decimal from a :class:`float`, first convert it to a string. This
138 serves as an explicit reminder of the details of the conversion (including
139 representation error). Decimal numbers include special values such as
140 :const:`NaN` which stands for "Not a number", positive and negative
141 :const:`Infinity`, and :const:`-0`.
143 >>> getcontext().prec = 28
148 >>> Decimal((0, (3, 1, 4), -2))
150 >>> Decimal(str(2.0 ** 0.5))
151 Decimal('1.41421356237')
152 >>> Decimal(2) ** Decimal('0.5')
153 Decimal('1.414213562373095048801688724')
156 >>> Decimal('-Infinity')
159 The significance of a new Decimal is determined solely by the number of digits
160 input. Context precision and rounding only come into play during arithmetic
163 .. doctest:: newcontext
165 >>> getcontext().prec = 6
168 >>> Decimal('3.1415926535')
169 Decimal('3.1415926535')
170 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
172 >>> getcontext().rounding = ROUND_UP
173 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
176 Decimals interact well with much of the rest of Python. Here is a small decimal
177 floating point flying circus:
180 :options: +NORMALIZE_WHITESPACE
182 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
188 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
189 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
197 >>> round(a, 1) # round() first converts to binary floating point
208 And some mathematical functions are also available to Decimal:
210 >>> getcontext().prec = 28
211 >>> Decimal(2).sqrt()
212 Decimal('1.414213562373095048801688724')
214 Decimal('2.718281828459045235360287471')
215 >>> Decimal('10').ln()
216 Decimal('2.302585092994045684017991455')
217 >>> Decimal('10').log10()
220 The :meth:`quantize` method rounds a number to a fixed exponent. This method is
221 useful for monetary applications that often round results to a fixed number of
224 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
226 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
229 As shown above, the :func:`getcontext` function accesses the current context and
230 allows the settings to be changed. This approach meets the needs of most
233 For more advanced work, it may be useful to create alternate contexts using the
234 Context() constructor. To make an alternate active, use the :func:`setcontext`
237 In accordance with the standard, the :mod:`Decimal` module provides two ready to
238 use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
239 former is especially useful for debugging because many of the traps are
242 .. doctest:: newcontext
243 :options: +NORMALIZE_WHITESPACE
245 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
246 >>> setcontext(myothercontext)
247 >>> Decimal(1) / Decimal(7)
248 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
251 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
252 capitals=1, flags=[], traps=[])
253 >>> setcontext(ExtendedContext)
254 >>> Decimal(1) / Decimal(7)
255 Decimal('0.142857143')
256 >>> Decimal(42) / Decimal(0)
259 >>> setcontext(BasicContext)
260 >>> Decimal(42) / Decimal(0)
261 Traceback (most recent call last):
262 File "<pyshell#143>", line 1, in -toplevel-
263 Decimal(42) / Decimal(0)
264 DivisionByZero: x / 0
266 Contexts also have signal flags for monitoring exceptional conditions
267 encountered during computations. The flags remain set until explicitly cleared,
268 so it is best to clear the flags before each set of monitored computations by
269 using the :meth:`clear_flags` method. ::
271 >>> setcontext(ExtendedContext)
272 >>> getcontext().clear_flags()
273 >>> Decimal(355) / Decimal(113)
274 Decimal('3.14159292')
276 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
277 capitals=1, flags=[Rounded, Inexact], traps=[])
279 The *flags* entry shows that the rational approximation to :const:`Pi` was
280 rounded (digits beyond the context precision were thrown away) and that the
281 result is inexact (some of the discarded digits were non-zero).
283 Individual traps are set using the dictionary in the :attr:`traps` field of a
286 .. doctest:: newcontext
288 >>> setcontext(ExtendedContext)
289 >>> Decimal(1) / Decimal(0)
291 >>> getcontext().traps[DivisionByZero] = 1
292 >>> Decimal(1) / Decimal(0)
293 Traceback (most recent call last):
294 File "<pyshell#112>", line 1, in -toplevel-
295 Decimal(1) / Decimal(0)
296 DivisionByZero: x / 0
298 Most programs adjust the current context only once, at the beginning of the
299 program. And, in many applications, data is converted to :class:`Decimal` with
300 a single cast inside a loop. With context set and decimals created, the bulk of
301 the program manipulates the data no differently than with other Python numeric
304 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
313 .. class:: Decimal([value [, context]])
315 Construct a new :class:`Decimal` object based from *value*.
317 *value* can be an integer, string, tuple, or another :class:`Decimal`
318 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
319 string, it should conform to the decimal numeric string syntax after leading
320 and trailing whitespace characters are removed::
323 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
324 indicator ::= 'e' | 'E'
325 digits ::= digit [digit]...
326 decimal-part ::= digits '.' [digits] | ['.'] digits
327 exponent-part ::= indicator [sign] digits
328 infinity ::= 'Infinity' | 'Inf'
329 nan ::= 'NaN' [digits] | 'sNaN' [digits]
330 numeric-value ::= decimal-part [exponent-part] | infinity
331 numeric-string ::= [sign] numeric-value | [sign] nan
333 If *value* is a :class:`tuple`, it should have three components, a sign
334 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
335 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
336 returns ``Decimal('1.414')``.
338 The *context* precision does not affect how many digits are stored. That is
339 determined exclusively by the number of digits in *value*. For example,
340 ``Decimal('3.00000')`` records all five zeros even if the context precision is
343 The purpose of the *context* argument is determining what to do if *value* is a
344 malformed string. If the context traps :const:`InvalidOperation`, an exception
345 is raised; otherwise, the constructor returns a new Decimal with the value of
348 Once constructed, :class:`Decimal` objects are immutable.
350 .. versionchanged:: 2.6
351 leading and trailing whitespace characters are permitted when
352 creating a Decimal instance from a string.
354 Decimal floating point objects share many properties with the other built-in
355 numeric types such as :class:`float` and :class:`int`. All of the usual math
356 operations and special methods apply. Likewise, decimal objects can be
357 copied, pickled, printed, used as dictionary keys, used as set elements,
358 compared, sorted, and coerced to another type (such as :class:`float` or
361 In addition to the standard numeric properties, decimal floating point
362 objects also have a number of specialized methods:
365 .. method:: adjusted()
367 Return the adjusted exponent after shifting out the coefficient's
368 rightmost digits until only the lead digit remains:
369 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
370 position of the most significant digit with respect to the decimal point.
373 .. method:: as_tuple()
375 Return a :term:`named tuple` representation of the number:
376 ``DecimalTuple(sign, digits, exponent)``.
378 .. versionchanged:: 2.6
382 .. method:: canonical()
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.
388 .. versionadded:: 2.6
390 .. method:: compare(other[, context])
392 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::
397 a or b is a NaN ==> Decimal('NaN')
398 a < b ==> Decimal('-1')
399 a == b ==> Decimal('0')
400 a > b ==> Decimal('1')
402 .. method:: compare_signal(other[, context])
404 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.
408 .. versionadded:: 2.6
410 .. method:: compare_total(other)
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:
418 >>> Decimal('12.0').compare_total(Decimal('12'))
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.
428 .. versionadded:: 2.6
430 .. method:: compare_total_mag(other)
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())``.
437 .. versionadded:: 2.6
439 .. method:: conjugate()
441 Just returns self, this method is only to comply with the Decimal
444 .. versionadded:: 2.6
446 .. method:: copy_abs()
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
452 .. versionadded:: 2.6
454 .. method:: copy_negate()
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.
459 .. versionadded:: 2.6
461 .. method:: copy_sign(other)
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:
466 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
469 This operation is unaffected by the context and is quiet: no flags are
470 changed and no rounding is performed.
472 .. versionadded:: 2.6
474 .. method:: exp([context])
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.
481 Decimal('2.718281828459045235360287471')
482 >>> Decimal(321).exp()
483 Decimal('2.561702493119680037517373933E+139')
485 .. versionadded:: 2.6
487 .. method:: from_float(f)
489 Classmethod that converts a float to a decimal number, exactly.
491 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
492 Since 0.1 is not exactly representable in binary floating point, the
493 value is stored as the nearest representable value which is
494 `0x1.999999999999ap-4`. That equivalent value in decimal is
495 `0.1000000000000000055511151231257827021181583404541015625`.
499 >>> Decimal.from_float(0.1)
500 Decimal('0.1000000000000000055511151231257827021181583404541015625')
501 >>> Decimal.from_float(float('nan'))
503 >>> Decimal.from_float(float('inf'))
505 >>> Decimal.from_float(float('-inf'))
508 .. versionadded:: 2.7
510 .. method:: fma(other, third[, context])
512 Fused multiply-add. Return self*other+third with no rounding of the
513 intermediate product self*other.
515 >>> Decimal(2).fma(3, 5)
518 .. versionadded:: 2.6
520 .. method:: is_canonical()
522 Return :const:`True` if the argument is canonical and :const:`False`
523 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
524 this operation always returns :const:`True`.
526 .. versionadded:: 2.6
528 .. method:: is_finite()
530 Return :const:`True` if the argument is a finite number, and
531 :const:`False` if the argument is an infinity or a NaN.
533 .. versionadded:: 2.6
535 .. method:: is_infinite()
537 Return :const:`True` if the argument is either positive or negative
538 infinity and :const:`False` otherwise.
540 .. versionadded:: 2.6
544 Return :const:`True` if the argument is a (quiet or signaling) NaN and
545 :const:`False` otherwise.
547 .. versionadded:: 2.6
549 .. method:: is_normal()
551 Return :const:`True` if the argument is a *normal* finite non-zero
552 number with an adjusted exponent greater than or equal to *Emin*.
553 Return :const:`False` if the argument is zero, subnormal, infinite or a
554 NaN. Note, the term *normal* is used here in a different sense with
555 the :meth:`normalize` method which is used to create canonical values.
557 .. versionadded:: 2.6
559 .. method:: is_qnan()
561 Return :const:`True` if the argument is a quiet NaN, and
562 :const:`False` otherwise.
564 .. versionadded:: 2.6
566 .. method:: is_signed()
568 Return :const:`True` if the argument has a negative sign and
569 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
571 .. versionadded:: 2.6
573 .. method:: is_snan()
575 Return :const:`True` if the argument is a signaling NaN and :const:`False`
578 .. versionadded:: 2.6
580 .. method:: is_subnormal()
582 Return :const:`True` if the argument is subnormal, and :const:`False`
583 otherwise. A number is subnormal is if it is nonzero, finite, and has an
584 adjusted exponent less than *Emin*.
586 .. versionadded:: 2.6
588 .. method:: is_zero()
590 Return :const:`True` if the argument is a (positive or negative) zero and
591 :const:`False` otherwise.
593 .. versionadded:: 2.6
595 .. method:: ln([context])
597 Return the natural (base e) logarithm of the operand. The result is
598 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
600 .. versionadded:: 2.6
602 .. method:: log10([context])
604 Return the base ten logarithm of the operand. The result is correctly
605 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
607 .. versionadded:: 2.6
609 .. method:: logb([context])
611 For a nonzero number, return the adjusted exponent of its operand as a
612 :class:`Decimal` instance. If the operand is a zero then
613 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
614 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
617 .. versionadded:: 2.6
619 .. method:: logical_and(other[, context])
621 :meth:`logical_and` is a logical operation which takes two *logical
622 operands* (see :ref:`logical_operands_label`). The result is the
623 digit-wise ``and`` of the two operands.
625 .. versionadded:: 2.6
627 .. method:: logical_invert(other[, context])
629 :meth:`logical_invert` is a logical operation. The argument must
630 be a *logical operand* (see :ref:`logical_operands_label`). The
631 result is the digit-wise inversion of the operand.
633 .. versionadded:: 2.6
635 .. method:: logical_or(other[, context])
637 :meth:`logical_or` is a logical operation which takes two *logical
638 operands* (see :ref:`logical_operands_label`). The result is the
639 digit-wise ``or`` of the two operands.
641 .. versionadded:: 2.6
643 .. method:: logical_xor(other[, context])
645 :meth:`logical_xor` is a logical operation which takes two *logical
646 operands* (see :ref:`logical_operands_label`). The result is the
647 digit-wise exclusive or of the two operands.
649 .. versionadded:: 2.6
651 .. method:: max(other[, context])
653 Like ``max(self, other)`` except that the context rounding rule is applied
654 before returning and that :const:`NaN` values are either signaled or
655 ignored (depending on the context and whether they are signaling or
658 .. method:: max_mag(other[, context])
660 Similar to the :meth:`max` method, but the comparison is done using the
661 absolute values of the operands.
663 .. versionadded:: 2.6
665 .. method:: min(other[, context])
667 Like ``min(self, other)`` except that the context rounding rule is applied
668 before returning and that :const:`NaN` values are either signaled or
669 ignored (depending on the context and whether they are signaling or
672 .. method:: min_mag(other[, context])
674 Similar to the :meth:`min` method, but the comparison is done using the
675 absolute values of the operands.
677 .. versionadded:: 2.6
679 .. method:: next_minus([context])
681 Return the largest number representable in the given context (or in the
682 current thread's context if no context is given) that is smaller than the
685 .. versionadded:: 2.6
687 .. method:: next_plus([context])
689 Return the smallest number representable in the given context (or in the
690 current thread's context if no context is given) that is larger than the
693 .. versionadded:: 2.6
695 .. method:: next_toward(other[, context])
697 If the two operands are unequal, return the number closest to the first
698 operand in the direction of the second operand. If both operands are
699 numerically equal, return a copy of the first operand with the sign set to
700 be the same as the sign of the second operand.
702 .. versionadded:: 2.6
704 .. method:: normalize([context])
706 Normalize the number by stripping the rightmost trailing zeros and
707 converting any result equal to :const:`Decimal('0')` to
708 :const:`Decimal('0e0')`. Used for producing canonical values for members
709 of an equivalence class. For example, ``Decimal('32.100')`` and
710 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
713 .. method:: number_class([context])
715 Return a string describing the *class* of the operand. The returned value
716 is one of the following ten strings.
718 * ``"-Infinity"``, indicating that the operand is negative infinity.
719 * ``"-Normal"``, indicating that the operand is a negative normal number.
720 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
721 * ``"-Zero"``, indicating that the operand is a negative zero.
722 * ``"+Zero"``, indicating that the operand is a positive zero.
723 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
724 * ``"+Normal"``, indicating that the operand is a positive normal number.
725 * ``"+Infinity"``, indicating that the operand is positive infinity.
726 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
727 * ``"sNaN"``, indicating that the operand is a signaling NaN.
729 .. versionadded:: 2.6
731 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
733 Return a value equal to the first operand after rounding and having the
734 exponent of the second operand.
736 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
739 Unlike other operations, if the length of the coefficient after the
740 quantize operation would be greater than precision, then an
741 :const:`InvalidOperation` is signaled. This guarantees that, unless there
742 is an error condition, the quantized exponent is always equal to that of
743 the right-hand operand.
745 Also unlike other operations, quantize never signals Underflow, even if
746 the result is subnormal and inexact.
748 If the exponent of the second operand is larger than that of the first
749 then rounding may be necessary. In this case, the rounding mode is
750 determined by the ``rounding`` argument if given, else by the given
751 ``context`` argument; if neither argument is given the rounding mode of
752 the current thread's context is used.
754 If *watchexp* is set (default), then an error is returned whenever the
755 resulting exponent is greater than :attr:`Emax` or less than
760 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
761 class does all its arithmetic. Included for compatibility with the
764 .. versionadded:: 2.6
766 .. method:: remainder_near(other[, context])
768 Compute the modulo as either a positive or negative value depending on
769 which is closest to zero. For instance, ``Decimal(10).remainder_near(6)``
770 returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
772 If both are equally close, the one chosen will have the same sign as
775 .. method:: rotate(other[, context])
777 Return the result of rotating the digits of the first operand by an amount
778 specified by the second operand. The second operand must be an integer in
779 the range -precision through precision. The absolute value of the second
780 operand gives the number of places to rotate. If the second operand is
781 positive then rotation is to the left; otherwise rotation is to the right.
782 The coefficient of the first operand is padded on the left with zeros to
783 length precision if necessary. The sign and exponent of the first operand
786 .. versionadded:: 2.6
788 .. method:: same_quantum(other[, context])
790 Test whether self and other have the same exponent or whether both are
793 .. method:: scaleb(other[, context])
795 Return the first operand with exponent adjusted by the second.
796 Equivalently, return the first operand multiplied by ``10**other``. The
797 second operand must be an integer.
799 .. versionadded:: 2.6
801 .. method:: shift(other[, context])
803 Return the result of shifting the digits of the first operand by an amount
804 specified by the second operand. The second operand must be an integer in
805 the range -precision through precision. The absolute value of the second
806 operand gives the number of places to shift. If the second operand is
807 positive then the shift is to the left; otherwise the shift is to the
808 right. Digits shifted into the coefficient are zeros. The sign and
809 exponent of the first operand are unchanged.
811 .. versionadded:: 2.6
813 .. method:: sqrt([context])
815 Return the square root of the argument to full precision.
818 .. method:: to_eng_string([context])
820 Convert to an engineering-type string.
822 Engineering notation has an exponent which is a multiple of 3, so there
823 are up to 3 digits left of the decimal place. For example, converts
824 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
826 .. method:: to_integral([rounding[, context]])
828 Identical to the :meth:`to_integral_value` method. The ``to_integral``
829 name has been kept for compatibility with older versions.
831 .. method:: to_integral_exact([rounding[, context]])
833 Round to the nearest integer, signaling :const:`Inexact` or
834 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
835 determined by the ``rounding`` parameter if given, else by the given
836 ``context``. If neither parameter is given then the rounding mode of the
837 current context is used.
839 .. versionadded:: 2.6
841 .. method:: to_integral_value([rounding[, context]])
843 Round to the nearest integer without signaling :const:`Inexact` or
844 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
845 rounding method in either the supplied *context* or the current context.
847 .. versionchanged:: 2.6
848 renamed from ``to_integral`` to ``to_integral_value``. The old name
849 remains valid for compatibility.
851 .. _logical_operands_label:
856 The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
857 and :meth:`logical_xor` methods expect their arguments to be *logical
858 operands*. A *logical operand* is a :class:`Decimal` instance whose
859 exponent and sign are both zero, and whose digits are all either
860 :const:`0` or :const:`1`.
862 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
870 Contexts are environments for arithmetic operations. They govern precision, set
871 rules for rounding, determine which signals are treated as exceptions, and limit
872 the range for exponents.
874 Each thread has its own current context which is accessed or changed using the
875 :func:`getcontext` and :func:`setcontext` functions:
878 .. function:: getcontext()
880 Return the current context for the active thread.
883 .. function:: setcontext(c)
885 Set the current context for the active thread to *c*.
887 Beginning with Python 2.5, you can also use the :keyword:`with` statement and
888 the :func:`localcontext` function to temporarily change the active context.
891 .. function:: localcontext([c])
893 Return a context manager that will set the current context for the active thread
894 to a copy of *c* on entry to the with-statement and restore the previous context
895 when exiting the with-statement. If no context is specified, a copy of the
896 current context is used.
898 .. versionadded:: 2.5
900 For example, the following code sets the current decimal precision to 42 places,
901 performs a calculation, and then automatically restores the previous context::
903 from decimal import localcontext
905 with localcontext() as ctx:
906 ctx.prec = 42 # Perform a high precision calculation
907 s = calculate_something()
908 s = +s # Round the final result back to the default precision
910 New contexts can also be created using the :class:`Context` constructor
911 described below. In addition, the module provides three pre-made contexts:
914 .. class:: BasicContext
916 This is a standard context defined by the General Decimal Arithmetic
917 Specification. Precision is set to nine. Rounding is set to
918 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
919 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
922 Because many of the traps are enabled, this context is useful for debugging.
925 .. class:: ExtendedContext
927 This is a standard context defined by the General Decimal Arithmetic
928 Specification. Precision is set to nine. Rounding is set to
929 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
930 exceptions are not raised during computations).
932 Because the traps are disabled, this context is useful for applications that
933 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
934 raising exceptions. This allows an application to complete a run in the
935 presence of conditions that would otherwise halt the program.
938 .. class:: DefaultContext
940 This context is used by the :class:`Context` constructor as a prototype for new
941 contexts. Changing a field (such a precision) has the effect of changing the
942 default for new contexts creating by the :class:`Context` constructor.
944 This context is most useful in multi-threaded environments. Changing one of the
945 fields before threads are started has the effect of setting system-wide
946 defaults. Changing the fields after threads have started is not recommended as
947 it would require thread synchronization to prevent race conditions.
949 In single threaded environments, it is preferable to not use this context at
950 all. Instead, simply create contexts explicitly as described below.
952 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
953 for Overflow, InvalidOperation, and DivisionByZero.
955 In addition to the three supplied contexts, new contexts can be created with the
956 :class:`Context` constructor.
959 .. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
961 Creates a new context. If a field is not specified or is :const:`None`, the
962 default values are copied from the :const:`DefaultContext`. If the *flags*
963 field is not specified or is :const:`None`, all flags are cleared.
965 The *prec* field is a positive integer that sets the precision for arithmetic
966 operations in the context.
968 The *rounding* option is one of:
970 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
971 * :const:`ROUND_DOWN` (towards zero),
972 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
973 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
974 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
975 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
976 * :const:`ROUND_UP` (away from zero).
977 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
978 would have been 0 or 5; otherwise towards zero)
980 The *traps* and *flags* fields list any signals to be set. Generally, new
981 contexts should only set traps and leave the flags clear.
983 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
986 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
987 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
988 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
990 .. versionchanged:: 2.6
991 The :const:`ROUND_05UP` rounding mode was added.
993 The :class:`Context` class defines several general purpose methods as well as
994 a large number of methods for doing arithmetic directly in a given context.
995 In addition, for each of the :class:`Decimal` methods described above (with
996 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
997 a corresponding :class:`Context` method. For example, ``C.exp(x)`` is
998 equivalent to ``x.exp(context=C)``.
1001 .. method:: clear_flags()
1003 Resets all of the flags to :const:`0`.
1007 Return a duplicate of the context.
1009 .. method:: copy_decimal(num)
1011 Return a copy of the Decimal instance num.
1013 .. method:: create_decimal(num)
1015 Creates a new Decimal instance from *num* but using *self* as
1016 context. Unlike the :class:`Decimal` constructor, the context precision,
1017 rounding method, flags, and traps are applied to the conversion.
1019 This is useful because constants are often given to a greater precision
1020 than is needed by the application. Another benefit is that rounding
1021 immediately eliminates unintended effects from digits beyond the current
1022 precision. In the following example, using unrounded inputs means that
1023 adding zero to a sum can change the result:
1025 .. doctest:: newcontext
1027 >>> getcontext().prec = 3
1028 >>> Decimal('3.4445') + Decimal('1.0023')
1030 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1033 This method implements the to-number operation of the IBM specification.
1034 If the argument is a string, no leading or trailing whitespace is
1037 .. method:: create_decimal_from_float(f)
1039 Creates a new Decimal instance from a float *f* but rounding using *self*
1040 as the context. Unlike the :meth:`Decimal.from_float` class method,
1041 the context precision, rounding method, flags, and traps are applied to
1046 >>> context = Context(prec=5, rounding=ROUND_DOWN)
1047 >>> context.create_decimal_from_float(math.pi)
1049 >>> context = Context(prec=5, traps=[Inexact])
1050 >>> context.create_decimal_from_float(math.pi)
1051 Traceback (most recent call last):
1055 .. versionadded:: 2.7
1059 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
1060 value for subnormal results. When underflow occurs, the exponent is set
1066 Returns a value equal to ``Emax - prec + 1``.
1068 The usual approach to working with decimals is to create :class:`Decimal`
1069 instances and then apply arithmetic operations which take place within the
1070 current context for the active thread. An alternative approach is to use
1071 context methods for calculating within a specific context. The methods are
1072 similar to those for the :class:`Decimal` class and are only briefly
1078 Returns the absolute value of *x*.
1081 .. method:: add(x, y)
1083 Return the sum of *x* and *y*.
1086 .. method:: canonical(x)
1088 Returns the same Decimal object *x*.
1091 .. method:: compare(x, y)
1093 Compares *x* and *y* numerically.
1096 .. method:: compare_signal(x, y)
1098 Compares the values of the two operands numerically.
1101 .. method:: compare_total(x, y)
1103 Compares two operands using their abstract representation.
1106 .. method:: compare_total_mag(x, y)
1108 Compares two operands using their abstract representation, ignoring sign.
1111 .. method:: copy_abs(x)
1113 Returns a copy of *x* with the sign set to 0.
1116 .. method:: copy_negate(x)
1118 Returns a copy of *x* with the sign inverted.
1121 .. method:: copy_sign(x, y)
1123 Copies the sign from *y* to *x*.
1126 .. method:: divide(x, y)
1128 Return *x* divided by *y*.
1131 .. method:: divide_int(x, y)
1133 Return *x* divided by *y*, truncated to an integer.
1136 .. method:: divmod(x, y)
1138 Divides two numbers and returns the integer part of the result.
1146 .. method:: fma(x, y, z)
1148 Returns *x* multiplied by *y*, plus *z*.
1151 .. method:: is_canonical(x)
1153 Returns True if *x* is canonical; otherwise returns False.
1156 .. method:: is_finite(x)
1158 Returns True if *x* is finite; otherwise returns False.
1161 .. method:: is_infinite(x)
1163 Returns True if *x* is infinite; otherwise returns False.
1166 .. method:: is_nan(x)
1168 Returns True if *x* is a qNaN or sNaN; otherwise returns False.
1171 .. method:: is_normal(x)
1173 Returns True if *x* is a normal number; otherwise returns False.
1176 .. method:: is_qnan(x)
1178 Returns True if *x* is a quiet NaN; otherwise returns False.
1181 .. method:: is_signed(x)
1183 Returns True if *x* is negative; otherwise returns False.
1186 .. method:: is_snan(x)
1188 Returns True if *x* is a signaling NaN; otherwise returns False.
1191 .. method:: is_subnormal(x)
1193 Returns True if *x* is subnormal; otherwise returns False.
1196 .. method:: is_zero(x)
1198 Returns True if *x* is a zero; otherwise returns False.
1203 Returns the natural (base e) logarithm of *x*.
1206 .. method:: log10(x)
1208 Returns the base 10 logarithm of *x*.
1213 Returns the exponent of the magnitude of the operand's MSD.
1216 .. method:: logical_and(x, y)
1218 Applies the logical operation *and* between each operand's digits.
1221 .. method:: logical_invert(x)
1223 Invert all the digits in *x*.
1226 .. method:: logical_or(x, y)
1228 Applies the logical operation *or* between each operand's digits.
1231 .. method:: logical_xor(x, y)
1233 Applies the logical operation *xor* between each operand's digits.
1236 .. method:: max(x, y)
1238 Compares two values numerically and returns the maximum.
1241 .. method:: max_mag(x, y)
1243 Compares the values numerically with their sign ignored.
1246 .. method:: min(x, y)
1248 Compares two values numerically and returns the minimum.
1251 .. method:: min_mag(x, y)
1253 Compares the values numerically with their sign ignored.
1256 .. method:: minus(x)
1258 Minus corresponds to the unary prefix minus operator in Python.
1261 .. method:: multiply(x, y)
1263 Return the product of *x* and *y*.
1266 .. method:: next_minus(x)
1268 Returns the largest representable number smaller than *x*.
1271 .. method:: next_plus(x)
1273 Returns the smallest representable number larger than *x*.
1276 .. method:: next_toward(x, y)
1278 Returns the number closest to *x*, in direction towards *y*.
1281 .. method:: normalize(x)
1283 Reduces *x* to its simplest form.
1286 .. method:: number_class(x)
1288 Returns an indication of the class of *x*.
1293 Plus corresponds to the unary prefix plus operator in Python. This
1294 operation applies the context precision and rounding, so it is *not* an
1298 .. method:: power(x, y[, modulo])
1300 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
1302 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1303 must be integral. The result will be inexact unless ``y`` is integral and
1304 the result is finite and can be expressed exactly in 'precision' digits.
1305 The result should always be correctly rounded, using the rounding mode of
1306 the current thread's context.
1308 With three arguments, compute ``(x**y) % modulo``. For the three argument
1309 form, the following restrictions on the arguments hold:
1311 - all three arguments must be integral
1312 - ``y`` must be nonnegative
1313 - at least one of ``x`` or ``y`` must be nonzero
1314 - ``modulo`` must be nonzero and have at most 'precision' digits
1316 The result of ``Context.power(x, y, modulo)`` is identical to the result
1317 that would be obtained by computing ``(x**y) % modulo`` with unbounded
1318 precision, but is computed more efficiently. It is always exact.
1320 .. versionchanged:: 2.6
1321 ``y`` may now be nonintegral in ``x**y``.
1322 Stricter requirements for the three-argument version.
1325 .. method:: quantize(x, y)
1327 Returns a value equal to *x* (rounded), having the exponent of *y*.
1332 Just returns 10, as this is Decimal, :)
1335 .. method:: remainder(x, y)
1337 Returns the remainder from integer division.
1339 The sign of the result, if non-zero, is the same as that of the original
1342 .. method:: remainder_near(x, y)
1344 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1345 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
1348 .. method:: rotate(x, y)
1350 Returns a rotated copy of *x*, *y* times.
1353 .. method:: same_quantum(x, y)
1355 Returns True if the two operands have the same exponent.
1358 .. method:: scaleb (x, y)
1360 Returns the first operand after adding the second value its exp.
1363 .. method:: shift(x, y)
1365 Returns a shifted copy of *x*, *y* times.
1370 Square root of a non-negative number to context precision.
1373 .. method:: subtract(x, y)
1375 Return the difference between *x* and *y*.
1378 .. method:: to_eng_string(x)
1380 Converts a number to a string, using scientific notation.
1383 .. method:: to_integral_exact(x)
1385 Rounds to an integer.
1388 .. method:: to_sci_string(x)
1390 Converts a number to a string using scientific notation.
1392 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1395 .. _decimal-signals:
1400 Signals represent conditions that arise during computation. Each corresponds to
1401 one context flag and one context trap enabler.
1403 The context flag is set whenever the condition is encountered. After the
1404 computation, flags may be checked for informational purposes (for instance, to
1405 determine whether a computation was exact). After checking the flags, be sure to
1406 clear all flags before starting the next computation.
1408 If the context's trap enabler is set for the signal, then the condition causes a
1409 Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1410 is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1416 Altered an exponent to fit representation constraints.
1418 Typically, clamping occurs when an exponent falls outside the context's
1419 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
1420 fit by adding zeros to the coefficient.
1423 .. class:: DecimalException
1425 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1428 .. class:: DivisionByZero
1430 Signals the division of a non-infinite number by zero.
1432 Can occur with division, modulo division, or when raising a number to a negative
1433 power. If this signal is not trapped, returns :const:`Infinity` or
1434 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1439 Indicates that rounding occurred and the result is not exact.
1441 Signals when non-zero digits were discarded during rounding. The rounded result
1442 is returned. The signal flag or trap is used to detect when results are
1446 .. class:: InvalidOperation
1448 An invalid operation was performed.
1450 Indicates that an operation was requested that does not make sense. If not
1451 trapped, returns :const:`NaN`. Possible causes include::
1458 x._rescale( non-integer )
1469 Indicates the exponent is larger than :attr:`Emax` after rounding has
1470 occurred. If not trapped, the result depends on the rounding mode, either
1471 pulling inward to the largest representable finite number or rounding outward
1472 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1478 Rounding occurred though possibly no information was lost.
1480 Signaled whenever rounding discards digits; even if those digits are zero
1481 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1482 the result unchanged. This signal is used to detect loss of significant
1486 .. class:: Subnormal
1488 Exponent was lower than :attr:`Emin` prior to rounding.
1490 Occurs when an operation result is subnormal (the exponent is too small). If
1491 not trapped, returns the result unchanged.
1494 .. class:: Underflow
1496 Numerical underflow with result rounded to zero.
1498 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1499 and :class:`Subnormal` are also signaled.
1501 The following table summarizes the hierarchy of signals::
1503 exceptions.ArithmeticError(exceptions.StandardError)
1506 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1508 Overflow(Inexact, Rounded)
1509 Underflow(Inexact, Rounded, Subnormal)
1514 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1519 Floating Point Notes
1520 --------------------
1523 Mitigating round-off error with increased precision
1524 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1526 The use of decimal floating point eliminates decimal representation error
1527 (making it possible to represent :const:`0.1` exactly); however, some operations
1528 can still incur round-off error when non-zero digits exceed the fixed precision.
1530 The effects of round-off error can be amplified by the addition or subtraction
1531 of nearly offsetting quantities resulting in loss of significance. Knuth
1532 provides two instructive examples where rounded floating point arithmetic with
1533 insufficient precision causes the breakdown of the associative and distributive
1534 properties of addition:
1536 .. doctest:: newcontext
1538 # Examples from Seminumerical Algorithms, Section 4.2.2.
1539 >>> from decimal import Decimal, getcontext
1540 >>> getcontext().prec = 8
1542 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1544 Decimal('9.5111111')
1548 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1552 Decimal('0.0060000')
1554 The :mod:`decimal` module makes it possible to restore the identities by
1555 expanding the precision sufficiently to avoid loss of significance:
1557 .. doctest:: newcontext
1559 >>> getcontext().prec = 20
1560 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1562 Decimal('9.51111111')
1564 Decimal('9.51111111')
1566 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1568 Decimal('0.0060000')
1570 Decimal('0.0060000')
1576 The number system for the :mod:`decimal` module provides special values
1577 including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
1578 and two zeros, :const:`+0` and :const:`-0`.
1580 Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1581 they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1582 not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1583 can result from rounding beyond the limits of the largest representable number.
1585 The infinities are signed (affine) and can be used in arithmetic operations
1586 where they get treated as very large, indeterminate numbers. For instance,
1587 adding a constant to infinity gives another infinite result.
1589 Some operations are indeterminate and return :const:`NaN`, or if the
1590 :exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1591 ``0/0`` returns :const:`NaN` which means "not a number". This variety of
1592 :const:`NaN` is quiet and, once created, will flow through other computations
1593 always resulting in another :const:`NaN`. This behavior can be useful for a
1594 series of computations that occasionally have missing inputs --- it allows the
1595 calculation to proceed while flagging specific results as invalid.
1597 A variant is :const:`sNaN` which signals rather than remaining quiet after every
1598 operation. This is a useful return value when an invalid result needs to
1599 interrupt a calculation for special handling.
1601 The behavior of Python's comparison operators can be a little surprising where a
1602 :const:`NaN` is involved. A test for equality where one of the operands is a
1603 quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1604 ``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1605 :const:`True`. An attempt to compare two Decimals using any of the ``<``,
1606 ``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1607 if either operand is a :const:`NaN`, and return :const:`False` if this signal is
1608 not trapped. Note that the General Decimal Arithmetic specification does not
1609 specify the behavior of direct comparisons; these rules for comparisons
1610 involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1611 section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1612 and :meth:`compare-signal` methods instead.
1614 The signed zeros can result from calculations that underflow. They keep the sign
1615 that would have resulted if the calculation had been carried out to greater
1616 precision. Since their magnitude is zero, both positive and negative zeros are
1617 treated as equal and their sign is informational.
1619 In addition to the two signed zeros which are distinct yet equal, there are
1620 various representations of zero with differing precisions yet equivalent in
1621 value. This takes a bit of getting used to. For an eye accustomed to
1622 normalized floating point representations, it is not immediately obvious that
1623 the following calculation returns a value equal to zero:
1625 >>> 1 / Decimal('Infinity')
1626 Decimal('0E-1000000026')
1628 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1631 .. _decimal-threads:
1633 Working with threads
1634 --------------------
1636 The :func:`getcontext` function accesses a different :class:`Context` object for
1637 each thread. Having separate thread contexts means that threads may make
1638 changes (such as ``getcontext.prec=10``) without interfering with other threads.
1640 Likewise, the :func:`setcontext` function automatically assigns its target to
1643 If :func:`setcontext` has not been called before :func:`getcontext`, then
1644 :func:`getcontext` will automatically create a new context for use in the
1647 The new context is copied from a prototype context called *DefaultContext*. To
1648 control the defaults so that each thread will use the same values throughout the
1649 application, directly modify the *DefaultContext* object. This should be done
1650 *before* any threads are started so that there won't be a race condition between
1651 threads calling :func:`getcontext`. For example::
1653 # Set applicationwide defaults for all threads about to be launched
1654 DefaultContext.prec = 12
1655 DefaultContext.rounding = ROUND_DOWN
1656 DefaultContext.traps = ExtendedContext.traps.copy()
1657 DefaultContext.traps[InvalidOperation] = 1
1658 setcontext(DefaultContext)
1660 # Afterwards, the threads can be started
1666 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1669 .. _decimal-recipes:
1674 Here are a few recipes that serve as utility functions and that demonstrate ways
1675 to work with the :class:`Decimal` class::
1677 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1678 pos='', neg='-', trailneg=''):
1679 """Convert Decimal to a money formatted string.
1681 places: required number of places after the decimal point
1682 curr: optional currency symbol before the sign (may be blank)
1683 sep: optional grouping separator (comma, period, space, or blank)
1684 dp: decimal point indicator (comma or period)
1685 only specify as blank when places is zero
1686 pos: optional sign for positive numbers: '+', space or blank
1687 neg: optional sign for negative numbers: '-', '(', space or blank
1688 trailneg:optional trailing minus indicator: '-', ')', space or blank
1690 >>> d = Decimal('-1234567.8901')
1691 >>> moneyfmt(d, curr='$')
1693 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1695 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1697 >>> moneyfmt(Decimal(123456789), sep=' ')
1699 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1703 q = Decimal(10) ** -places # 2 places --> '0.01'
1704 sign, digits, exp = value.quantize(q).as_tuple()
1706 digits = map(str, digits)
1707 build, next = result.append, digits.pop
1710 for i in range(places):
1711 build(next() if digits else '0')
1719 if i == 3 and digits:
1723 build(neg if sign else pos)
1724 return ''.join(reversed(result))
1727 """Compute Pi to the current precision.
1730 3.141592653589793238462643383
1733 getcontext().prec += 2 # extra digits for intermediate steps
1734 three = Decimal(3) # substitute "three=3.0" for regular floats
1735 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1742 getcontext().prec -= 2
1743 return +s # unary plus applies the new precision
1746 """Return e raised to the power of x. Result type matches input type.
1748 >>> print exp(Decimal(1))
1749 2.718281828459045235360287471
1750 >>> print exp(Decimal(2))
1751 7.389056098930650227230427461
1758 getcontext().prec += 2
1759 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1766 getcontext().prec -= 2
1770 """Return the cosine of x as measured in radians.
1772 >>> print cos(Decimal('0.5'))
1773 0.8775825618903727161162815826
1776 >>> print cos(0.5+0j)
1780 getcontext().prec += 2
1781 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1788 s += num / fact * sign
1789 getcontext().prec -= 2
1793 """Return the sine of x as measured in radians.
1795 >>> print sin(Decimal('0.5'))
1796 0.4794255386042030002732879352
1799 >>> print sin(0.5+0j)
1803 getcontext().prec += 2
1804 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1811 s += num / fact * sign
1812 getcontext().prec -= 2
1816 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1824 Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1825 minimize typing when using the interactive interpreter?
1827 A. Some users abbreviate the constructor to just a single letter:
1829 >>> D = decimal.Decimal
1830 >>> D('1.23') + D('3.45')
1833 Q. In a fixed-point application with two decimal places, some inputs have many
1834 places and need to be rounded. Others are not supposed to have excess digits
1835 and need to be validated. What methods should be used?
1837 A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
1838 the :const:`Inexact` trap is set, it is also useful for validation:
1840 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1842 >>> # Round to two places
1843 >>> Decimal('3.214').quantize(TWOPLACES)
1846 >>> # Validate that a number does not exceed two places
1847 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1850 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1851 Traceback (most recent call last):
1855 Q. Once I have valid two place inputs, how do I maintain that invariant
1856 throughout an application?
1858 A. Some operations like addition, subtraction, and multiplication by an integer
1859 will automatically preserve fixed point. Others operations, like division and
1860 non-integer multiplication, will change the number of decimal places and need to
1861 be followed-up with a :meth:`quantize` step:
1863 >>> a = Decimal('102.72') # Initial fixed-point values
1864 >>> b = Decimal('3.17')
1865 >>> a + b # Addition preserves fixed-point
1869 >>> a * 42 # So does integer multiplication
1871 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1873 >>> (b / a).quantize(TWOPLACES) # And quantize division
1876 In developing fixed-point applications, it is convenient to define functions
1877 to handle the :meth:`quantize` step:
1879 >>> def mul(x, y, fp=TWOPLACES):
1880 ... return (x * y).quantize(fp)
1881 >>> def div(x, y, fp=TWOPLACES):
1882 ... return (x / y).quantize(fp)
1884 >>> mul(a, b) # Automatically preserve fixed-point
1889 Q. There are many ways to express the same value. The numbers :const:`200`,
1890 :const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1891 various precisions. Is there a way to transform them to a single recognizable
1894 A. The :meth:`normalize` method maps all equivalent values to a single
1897 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1898 >>> [v.normalize() for v in values]
1899 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
1901 Q. Some decimal values always print with exponential notation. Is there a way
1902 to get a non-exponential representation?
1904 A. For some values, exponential notation is the only way to express the number
1905 of significant places in the coefficient. For example, expressing
1906 :const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1907 original's two-place significance.
1909 If an application does not care about tracking significance, it is easy to
1910 remove the exponent and trailing zeros, losing significance, but keeping the
1913 def remove_exponent(d):
1914 '''Remove exponent and trailing zeros.
1916 >>> remove_exponent(Decimal('5E+3'))
1920 return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1922 Q. Is there a way to convert a regular float to a Decimal?
1924 A. Yes, the classmethod :meth:`from_float` makes an exact conversion.
1926 The regular decimal constructor does not do this by default because there is
1927 some question about whether it is advisable to mix binary and decimal floating
1928 point. Also, its use requires some care to avoid the representation issues
1929 associated with binary floating point:
1931 >>> Decimal.from_float(1.1)
1932 Decimal('1.100000000000000088817841970012523233890533447265625')
1934 Q. Within a complex calculation, how can I make sure that I haven't gotten a
1935 spurious result because of insufficient precision or rounding anomalies.
1937 A. The decimal module makes it easy to test results. A best practice is to
1938 re-run calculations using greater precision and with various rounding modes.
1939 Widely differing results indicate insufficient precision, rounding mode issues,
1940 ill-conditioned inputs, or a numerically unstable algorithm.
1942 Q. I noticed that context precision is applied to the results of operations but
1943 not to the inputs. Is there anything to watch out for when mixing values of
1944 different precisions?
1946 A. Yes. The principle is that all values are considered to be exact and so is
1947 the arithmetic on those values. Only the results are rounded. The advantage
1948 for inputs is that "what you type is what you get". A disadvantage is that the
1949 results can look odd if you forget that the inputs haven't been rounded:
1951 .. doctest:: newcontext
1953 >>> getcontext().prec = 3
1954 >>> Decimal('3.104') + Decimal('2.104')
1956 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
1959 The solution is either to increase precision or to force rounding of inputs
1960 using the unary plus operation:
1962 .. doctest:: newcontext
1964 >>> getcontext().prec = 3
1965 >>> +Decimal('1.23456789') # unary plus triggers rounding
1968 Alternatively, inputs can be rounded upon creation using the
1969 :meth:`Context.create_decimal` method:
1971 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')