blob: be8f41d713ba8fa53e52f733dcb0a64cc394b079 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`decimal` --- Decimal floating point arithmetic
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
18
19.. versionadded:: 2.4
20
21The :mod:`decimal` module provides support for decimal floating point
Facundo Batista7c82a3e92007-09-14 18:58:34 +000022arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl8ec7f652007-08-15 14:28:01 +000023
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
Facundo Batista7c82a3e92007-09-14 18:58:34 +000030 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl8ec7f652007-08-15 14:28:01 +000031 is :const:`5.5511151231257827e-017`. While near to zero, the differences
32 prevent reliable equality testing and differences can accumulate. For this
33 reason, decimal would be 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
Facundo Batista7c82a3e92007-09-14 18:58:34 +000044 alterable precision (defaulting to 28 places) which can be as large as needed for
Georg Brandl8ec7f652007-08-15 14:28:01 +000045 a given problem::
46
47 >>> getcontext().prec = 6
48 >>> Decimal(1) / Decimal(7)
49 Decimal("0.142857")
50 >>> getcontext().prec = 28
51 >>> Decimal(1) / Decimal(7)
52 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.
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
Facundo Batista7c82a3e92007-09-14 18:58:34 +000064trailing zeros. Decimals also include special values such as
Georg Brandl8ec7f652007-08-15 14:28:01 +000065: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`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +000073:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000074
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
83encountered, its flag is incremented from zero and, 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
Facundo Batista7c82a3e92007-09-14 18:58:34 +000090 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
91 Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_.
Georg Brandl8ec7f652007-08-15 14:28:01 +000092
Facundo Batista7c82a3e92007-09-14 18:58:34 +000093 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
94 <http://www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html>`_.
Georg Brandl8ec7f652007-08-15 14:28:01 +000095
96.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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,
111 capitals=1, flags=[], traps=[Overflow, InvalidOperation,
112 DivisionByZero])
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
121:const:`Infinity`, and :const:`-0`. ::
122
123 >>> Decimal(10)
124 Decimal("10")
125 >>> Decimal("3.14")
126 Decimal("3.14")
127 >>> Decimal((0, (3, 1, 4), -2))
128 Decimal("3.14")
129 >>> Decimal(str(2.0 ** 0.5))
130 Decimal("1.41421356237")
131 >>> Decimal("NaN")
132 Decimal("NaN")
133 >>> Decimal("-Infinity")
134 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
138operations. ::
139
140 >>> getcontext().prec = 6
141 >>> Decimal('3.0')
142 Decimal("3.0")
143 >>> Decimal('3.1415926535')
144 Decimal("3.1415926535")
145 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
146 Decimal("5.85987")
147 >>> getcontext().rounding = ROUND_UP
148 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
149 Decimal("5.85988")
150
151Decimals interact well with much of the rest of Python. Here is a small decimal
152floating point flying circus::
153
154 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
155 >>> max(data)
156 Decimal("9.25")
157 >>> min(data)
158 Decimal("0.03")
159 >>> sorted(data)
160 [Decimal("0.03"), Decimal("1.00"), Decimal("1.34"), Decimal("1.87"),
161 Decimal("2.35"), Decimal("3.45"), Decimal("9.25")]
162 >>> sum(data)
163 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
174 Decimal("6.70")
175 >>> a * b
176 Decimal("2.5058")
177 >>> c % a
178 Decimal("0.77")
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
182places::
183
184 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
185 Decimal("7.32")
186 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
187 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
200enabled::
201
202 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
203 >>> setcontext(myothercontext)
204 >>> Decimal(1) / Decimal(7)
205 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)
212 Decimal("0.142857143")
213 >>> Decimal(42) / Decimal(0)
214 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)
231 Decimal("3.14159292")
232 >>> getcontext()
233 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
234 capitals=1, flags=[Inexact, Rounded], 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
241context::
242
243 >>> Decimal(1) / Decimal(0)
244 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
258.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
259
260
261.. _decimal-decimal:
262
263Decimal objects
264---------------
265
266
267.. class:: Decimal([value [, context]])
268
269 Constructs a new :class:`Decimal` object based from *value*.
270
271 *value* can be an integer, string, tuple, or another :class:`Decimal` object. If
272 no *value* is given, returns ``Decimal("0")``. If *value* is a string, it
273 should conform to the decimal numeric string syntax::
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
284 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))``
289 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,
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000293 ``Decimal("3.00000")`` records all five zeros even if the context precision is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000294 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
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000303Decimal floating point objects share many properties with the other built-in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000304numeric types such as :class:`float` and :class:`int`. All of the usual math
305operations and special methods apply. Likewise, decimal objects can be copied,
306pickled, printed, used as dictionary keys, used as set elements, compared,
307sorted, and coerced to another type (such as :class:`float` or :class:`long`).
308
309In addition to the standard numeric properties, decimal floating point objects
310also have a number of specialized methods:
311
312
313.. method:: Decimal.adjusted()
314
315 Return the adjusted exponent after shifting out the coefficient's rightmost
316 digits until only the lead digit remains: ``Decimal("321e+5").adjusted()``
317 returns seven. Used for determining the position of the most significant digit
318 with respect to the decimal point.
319
320
321.. method:: Decimal.as_tuple()
322
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000323 Return a tuple representation of the number: ``(sign, digit_tuple, exponent)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000324
325
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000326.. method:: Decimal.canonical()
327
328 Return the canonical encoding of the argument. Currently, the
329 encoding of a :class:`Decimal` instance is always canonical, so
330 this operation returns its argument unchanged.
331
332 .. versionadded:: 2.6
333
Georg Brandl8ec7f652007-08-15 14:28:01 +0000334.. method:: Decimal.compare(other[, context])
335
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000336 Compare the values of two Decimal instances. This operation
337 behaves in the same way as the usual comparison method
338 :meth:`__cmp__`, except that :meth:`compare` returns a Decimal
339 instance rather than an integer, and if either operand is a NaN
340 then the result is a NaN::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000341
342 a or b is a NaN ==> Decimal("NaN")
343 a < b ==> Decimal("-1")
344 a == b ==> Decimal("0")
345 a > b ==> Decimal("1")
346
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000347.. method:: Decimal.compare_signal(other[, context])
348
349 This operation is identical to the :meth:`compare` method, except
350 that all NaNs signal. That is, if neither operand is a signaling
351 NaN then any quiet NaN operand is treated as though it were a
352 signaling NaN.
353
354 .. versionadded:: 2.6
355
356.. method:: Decimal.compare_total(other)
357
358 Compare two operands using their abstract representation rather
359 than their numerical value. Similar to the :meth:`compare` method,
360 but the result gives a total ordering on :class:`Decimal`
361 instances. Two :class:`Decimal` instances with the same numeric
362 value but different representations compare unequal in this
363 ordering::
364
365 >>> Decimal("12.0").compare_total(Decimal("12"))
366 Decimal("-1")
367
368 Quiet and signaling NaNs are also included in the total ordering.
369 The result of this function is ``Decimal("0")`` if both operands
370 have the same representation, ``Decimal("-1")`` if the first
371 operand is lower in the total order than the second, and
372 ``Decimal("1")`` if the first operand is higher in the total order
373 than the second operand. See the specification for details of the
374 total order.
375
376 .. versionadded:: 2.6
377
378.. method:: Decimal.compare_total_mag(other)
379
380 Compare two operands using their abstract representation rather
381 than their value as in :meth:`compare_total`, but ignoring the sign
382 of each operand. ``x.compare_total_mag(y)`` is equivalent to
383 ``x.copy_abs().compare_total(y.copy_abs())``.
384
385 .. versionadded:: 2.6
386
387.. method:: Decimal.copy_abs()
388
389 Return the absolute value of the argument. This operation is
390 unaffected by the context and is quiet: no flags are changed and no
391 rounding is performed.
392
393 .. versionadded:: 2.6
394
395.. method:: Decimal.copy_negate()
396
397 Return the negation of the argument. This operation is unaffected
398 by the context and is quiet: no flags are changed and no rounding
399 is performed.
400
401 .. versionadded:: 2.6
402
403.. method:: Decimal.copy_sign(other)
404
405 Return a copy of the first operand with the sign set to be the
406 same as the sign of the second operand. For example::
407
408 >>> Decimal("2.3").copy_sign(Decimal("-1.5"))
409 Decimal("-2.3")
410
411 This operation is unaffected by the context and is quiet: no flags
412 are changed and no rounding is performed.
413
414 .. versionadded:: 2.6
415
416.. method:: Decimal.exp([context])
417
418 Return the value of the (natural) exponential function ``e**x`` at the
419 given number. The result is correctly rounded using the
420 :const:`ROUND_HALF_EVEN` rounding mode.
421
422 .. versionadded:: 2.6
423
424.. method:: Decimal.fma(other, third[, context])
425
426 Fused multiply-add. Return self*other+third with no rounding of
427 the intermediate product self*other.
428
429 .. versionadded:: 2.6
430
431.. method:: Decimal.is_canonical()
432
433 Return ``Decimal(1)`` if the argument is canonical and
434 ``Decimal(0)`` otherwise. Currently, a :class:`Decimal` instance
435 is always canonical, so this operation always returns
436 ``Decimal(1)``.
437
438 .. versionadded:: 2.6
439
440.. method:: is_finite()
441
442 Return ``Decimal(1)`` if the argument is a finite number, and
443 ``Decimal(0)`` if the argument is an infinity or a NaN.
444
445 .. versionadded:: 2.6
446
447.. method:: is_infinite()
448
449 Return ``Decimal(1)`` if the argument is either positive or
450 negative infinity and ``Decimal(0)`` otherwise.
451
452 .. versionadded:: 2.6
453
454.. method:: is_nan()
455
456 Return ``Decimal(1)`` if the argument is a (quiet or signaling)
457 NaN and ``Decimal(0)`` otherwise.
458
459 .. versionadded:: 2.6
460
461.. method:: is_normal()
462
463 Return ``Decimal(1)`` if the argument is a *normal* finite number.
464 Return ``Decimal(0)`` if the argument is zero, subnormal, infinite
465 or a NaN.
466
467 .. versionadded:: 2.6
468
469.. method:: is_qnan()
470
471 Return ``Decimal(1)`` if the argument is a quiet NaN, and ``Decimal(0)`` otherwise.
472
473 .. versionadded:: 2.6
474
475.. method:: is_signed()
476
477 Return ``Decimal(1)`` if the argument has a negative sign and
478 ``Decimal(0)`` otherwise. Note that zeros and NaNs can both carry
479 signs.
480
481 .. versionadded:: 2.6
482
483.. method:: is_snan()
484
485 Return ``Decimal(1)`` if the argument is a signaling NaN and
486 ``Decimal(0)`` otherwise.
487
488 .. versionadded:: 2.6
489
490.. method:: is_subnormal()
491
492 Return ``Decimal(1)`` if the argument is subnormal, and
493 ``Decimal(0)`` otherwise.
494
495 .. versionadded:: 2.6
496
497.. method:: is_zero()
498
499 Return ``Decimal(1)`` if the argument is a (positive or negative)
500 zero and ``Decimal(0)`` otherwise.
501
502 .. versionadded:: 2.6
503
504.. method:: Decimal.ln([context])
505
506 Return the natural (base e) logarithm of the operand. The result
507 is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
508 mode.
509
510 .. versionadded:: 2.6
511
512.. method:: Decimal.log10([context])
513
514 Return the base ten logarithm of the operand. The result is
515 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
516
517 .. versionadded:: 2.6
518
519.. method: Decimal.logb([context])
520
521 For a nonzero number, return the adjusted exponent of its operand
522 as a :class:`Decimal` instance. If the operand is a zero then
523 ``Decimal("-Infinity")`` is returned and the
524 :const:`DivisionByZero` flag is raised. If the operand is an
525 infinity then ``Decimal("Infinity")`` is returned.
526
527 .. versionadded:: 2.6
528
529.. method:: Decimal.logical_and(other[, context])
530
531 :meth:`logical_and` is a logical operation which takes two
532 *logical operands* (see :ref:`logical_operands_label`). The result
533 is the digit-wise ``and`` of the two operands.
534
535 .. versionadded:: 2.6
536
537.. method:: Decimal.logical_invert(other[, context])
538
539 :meth:`logical_invert` is a logical operation. The argument must
540 be a *logical operand* (see :ref:`logical_operands_label`). The
541 result is the digit-wise inversion of the operand.
542
543 .. versionadded:: 2.6
544
545.. method:: Decimal.logical_or(other[, context])
546
547 :meth:`logical_or` is a logical operation which takes two *logical
548 operands* (see :ref:`logical_operands_label`). The result is the
549 digit-wise ``or`` of the two operands.
550
551 .. versionadded:: 2.6
552
553.. method:: Decimal.logical_xor(other[, context])
554
555 :meth:`logical_xor` is a logical operation which takes two
556 *logical operands* (see :ref:`logical_operands_label`). The result
557 is the digit-wise exclusive or of the two operands.
558
559 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000560
561.. method:: Decimal.max(other[, context])
562
563 Like ``max(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000564 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000565 (depending on the context and whether they are signaling or quiet).
566
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000567.. method:: Decimal.max_mag(other[, context])
568
569 Similar to the :meth:`max` method, but the comparison is done using
570 the absolute values of the operands.
571
572 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000573
574.. method:: Decimal.min(other[, context])
575
576 Like ``min(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000577 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000578 (depending on the context and whether they are signaling or quiet).
579
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000580.. method:: Decimal.min_mag(other[, context])
581
582 Similar to the :meth:`min` method, but the comparison is done using
583 the absolute values of the operands.
584
585 .. versionadded:: 2.6
586
587.. method:: Decimal.next_minus([context])
588
589 Return the largest number representable in the given context (or
590 in the current thread's context if no context is given) that is smaller
591 than the given operand.
592
593 .. versionadded:: 2.6
594
595.. method:: Decimal.next_plus([context])
596
597 Return the smallest number representable in the given context (or
598 in the current thread's context if no context is given) that is
599 larger than the given operand.
600
601 .. versionadded:: 2.6
602
603.. method:: Decimal.next_toward(other[, context])
604
605 If the two operands are unequal, return the number closest to the
606 first operand in the direction of the second operand. If both
607 operands are numerically equal, return a copy of the first operand
608 with the sign set to be the same as the sign of the second operand.
609
610 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000611
612.. method:: Decimal.normalize([context])
613
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000614 Normalize the number by stripping the rightmost trailing zeros and converting
Georg Brandl8ec7f652007-08-15 14:28:01 +0000615 any result equal to :const:`Decimal("0")` to :const:`Decimal("0e0")`. Used for
616 producing canonical values for members of an equivalence class. For example,
617 ``Decimal("32.100")`` and ``Decimal("0.321000e+2")`` both normalize to the
618 equivalent value ``Decimal("32.1")``.
619
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000620.. method:: Decimal.number_class([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000621
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000622 Return a string describing the *class* of the operand. The
623 returned value is one of the following ten strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000624
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000625 * ``"-Infinity"``, indicating that the operand is negative infinity.
626 * ``"-Normal"``, indicating that the operand is a negative normal number.
627 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
628 * ``"-Zero"``, indicating that the operand is a negative zero.
629 * ``"+Zero"``, indicating that the operand is a positive zero.
630 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
631 * ``"+Normal"``, indicating that the operand is a positive normal number.
632 * ``"+Infinity"``, indicating that the operand is positive infinity.
633 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
634 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000635
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000636 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000637
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000638.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]])
639
640 Returns a value equal to the first operand after rounding and
641 having the exponent of the second operand.
642
643 Unlike other operations, if the length of the coefficient after the
644 quantize operation would be greater than precision, then an
645 :const:`InvalidOperation` is signaled. This guarantees that, unless
646 there is an error condition, the quantized exponent is always equal
647 to that of the right-hand operand.
648
649 Also unlike other operations, quantize never signals Underflow,
650 even if the result is subnormal and inexact.
651
652 If the exponent of the second operand is larger than that of the
653 first then rounding may be necessary. In this case, the rounding
654 mode is determined by the ``rounding`` argument if given, else by
655 the given ``context`` argument; if neither argument is given the
656 rounding mode of the current thread's context is used.
657
658 If watchexp is set (default), then an error is returned whenever
659 the resulting exponent is greater than Emax or less than Etiny.
660
661.. method:: Decimal.radix()
662
663 Return ``Decimal(10)``, the radix (base) in which the
664 :class:`Decimal` class does all its arithmetic. Included for
665 compatibility with the specification.
666
667 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000668
669.. method:: Decimal.remainder_near(other[, context])
670
671 Computes the modulo as either a positive or negative value depending on which is
672 closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
673 ``Decimal("-2")`` which is closer to zero than ``Decimal("4")``.
674
675 If both are equally close, the one chosen will have the same sign as *self*.
676
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000677.. method:: Decimal.rotate(other[, context])
678
679 Return the result of rotating the digits of the first operand by
680 an amount specified by the second operand. The second operand
681 must be an integer in the range -precision through precision. The
682 absolute value of the second operand gives the number of places to
683 rotate. If the second operand is positive then rotation is to the
684 left; otherwise rotation is to the right. The coefficient of the
685 first operand is padded on the left with zeros to length precision
686 if necessary. The sign and exponent of the first operand are
687 unchanged.
688
689 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000690
691.. method:: Decimal.same_quantum(other[, context])
692
693 Test whether self and other have the same exponent or whether both are
694 :const:`NaN`.
695
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000696.. method:: Decimal.scaleb(other[, context])
697
698 Return the first operand with exponent adjusted by the second.
699 Equivalently, return the first operand multiplied by ``10**other``.
700 The second operand must be an integer.
701
702 .. versionadded:: 2.6
703
704.. method:: Decimal.shift(other[, context])
705
706 Return the result of shifting the digits of the first operand by
707 an amount specified by the second operand. The second operand must
708 be an integer in the range -precision through precision. The
709 absolute value of the second operand gives the number of places to
710 shift. If the second operand is positive then the shift is to the
711 left; otherwise the shift is to the right. Digits shifted into the
712 coefficient are zeros. The sign and exponent of the first operand
713 are unchanged.
714
715 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000716
717.. method:: Decimal.sqrt([context])
718
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000719 Return the square root of the argument to full precision.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000720
721
722.. method:: Decimal.to_eng_string([context])
723
724 Convert to an engineering-type string.
725
726 Engineering notation has an exponent which is a multiple of 3, so there are up
727 to 3 digits left of the decimal place. For example, converts
728 ``Decimal('123E+1')`` to ``Decimal("1.23E+3")``
729
Georg Brandl8ec7f652007-08-15 14:28:01 +0000730.. method:: Decimal.to_integral([rounding[, context]])
731
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000732 Identical to the :meth:`to_integral_value` method. The ``to_integral``
733 name has been kept for compatibility with older versions.
734
735.. method:: Decimal.to_integral_exact([rounding[, context]])
736
737 Round the argument to the nearest integer, signaling
738 :const:`Inexact` or :const:`Rounded` as appropriate if rounding
739 occurs. The rounding mode is determined by the ``rounding``
740 parameter if given, else by the given ``context``. If neither
741 parameter is given then the rounding mode of the current context is
742 used.
743
744 .. versionadded:: 2.6
745
746.. method:: Decimal.to_integral_value([rounding[, context]])
747
Georg Brandl8ec7f652007-08-15 14:28:01 +0000748 Rounds to the nearest integer without signaling :const:`Inexact` or
749 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding
750 method in either the supplied *context* or the current context.
751
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000752 .. versionchanged:: 2.6
753 renamed from ``to_integral`` to ``to_integral_value``. The old name
754 remains valid for compatibility.
755
756.. method:: Decimal.trim()
757
758 Returns its argument with *insignificant* trailing zeros removed.
759 Here, a trailing zero is considered insignificant either if it
760 follows the decimal point, or if the exponent of the argument (that
761 is, the last element of the :meth:`as_tuple` representation) is
762 positive.
763
764 .. versionadded:: 2.6
765
766.. _logical_operands_label:
767
768Logical operands
769^^^^^^^^^^^^^^^^
770
771The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
772and :meth:`logical_xor` methods expect their arguments to be *logical
773operands*. A *logical operand* is a :class:`Decimal` instance whose
774exponent and sign are both zero, and whose digits are all either
775:const:`0` or :const:`1`.
776
Georg Brandl8ec7f652007-08-15 14:28:01 +0000777.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
778
779
780.. _decimal-context:
781
782Context objects
783---------------
784
785Contexts are environments for arithmetic operations. They govern precision, set
786rules for rounding, determine which signals are treated as exceptions, and limit
787the range for exponents.
788
789Each thread has its own current context which is accessed or changed using the
790:func:`getcontext` and :func:`setcontext` functions:
791
792
793.. function:: getcontext()
794
795 Return the current context for the active thread.
796
797
798.. function:: setcontext(c)
799
800 Set the current context for the active thread to *c*.
801
802Beginning with Python 2.5, you can also use the :keyword:`with` statement and
803the :func:`localcontext` function to temporarily change the active context.
804
805
806.. function:: localcontext([c])
807
808 Return a context manager that will set the current context for the active thread
809 to a copy of *c* on entry to the with-statement and restore the previous context
810 when exiting the with-statement. If no context is specified, a copy of the
811 current context is used.
812
813 .. versionadded:: 2.5
814
815 For example, the following code sets the current decimal precision to 42 places,
816 performs a calculation, and then automatically restores the previous context::
817
818 from __future__ import with_statement
819 from decimal import localcontext
820
821 with localcontext() as ctx:
822 ctx.prec = 42 # Perform a high precision calculation
823 s = calculate_something()
824 s = +s # Round the final result back to the default precision
825
826New contexts can also be created using the :class:`Context` constructor
827described below. In addition, the module provides three pre-made contexts:
828
829
830.. class:: BasicContext
831
832 This is a standard context defined by the General Decimal Arithmetic
833 Specification. Precision is set to nine. Rounding is set to
834 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
835 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
836 :const:`Subnormal`.
837
838 Because many of the traps are enabled, this context is useful for debugging.
839
840
841.. class:: ExtendedContext
842
843 This is a standard context defined by the General Decimal Arithmetic
844 Specification. Precision is set to nine. Rounding is set to
845 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
846 exceptions are not raised during computations).
847
848 Because the trapped are disabled, this context is useful for applications that
849 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
850 raising exceptions. This allows an application to complete a run in the
851 presence of conditions that would otherwise halt the program.
852
853
854.. class:: DefaultContext
855
856 This context is used by the :class:`Context` constructor as a prototype for new
857 contexts. Changing a field (such a precision) has the effect of changing the
858 default for new contexts creating by the :class:`Context` constructor.
859
860 This context is most useful in multi-threaded environments. Changing one of the
861 fields before threads are started has the effect of setting system-wide
862 defaults. Changing the fields after threads have started is not recommended as
863 it would require thread synchronization to prevent race conditions.
864
865 In single threaded environments, it is preferable to not use this context at
866 all. Instead, simply create contexts explicitly as described below.
867
868 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
869 for Overflow, InvalidOperation, and DivisionByZero.
870
871In addition to the three supplied contexts, new contexts can be created with the
872:class:`Context` constructor.
873
874
875.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
876
877 Creates a new context. If a field is not specified or is :const:`None`, the
878 default values are copied from the :const:`DefaultContext`. If the *flags*
879 field is not specified or is :const:`None`, all flags are cleared.
880
881 The *prec* field is a positive integer that sets the precision for arithmetic
882 operations in the context.
883
884 The *rounding* option is one of:
885
886 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
887 * :const:`ROUND_DOWN` (towards zero),
888 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
889 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
890 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
891 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
892 * :const:`ROUND_UP` (away from zero).
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000893 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
894 would have been 0 or 5; otherwise towards zero)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000895
896 The *traps* and *flags* fields list any signals to be set. Generally, new
897 contexts should only set traps and leave the flags clear.
898
899 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
900 for exponents.
901
902 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
903 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
904 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
905
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000906 .. versionchanged:: 2.6
907 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000908
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000909The :class:`Context` class defines several general purpose methods as
910well as a large number of methods for doing arithmetic directly in a
911given context. In addition, for each of the :class:`Decimal` methods
912described above (with the exception of the :meth:`adjusted` and
913:meth:`as_tuple` methods) there is a corresponding :class:`Context`
914method. For example, ``C.exp(x)`` is equivalent to
915``x.exp(context=C)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000916
917.. method:: Context.clear_flags()
918
919 Resets all of the flags to :const:`0`.
920
921
922.. method:: Context.copy()
923
924 Return a duplicate of the context.
925
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000926.. method:: Context.copy_decimal(num)
927
928 Return a copy of the Decimal instance num.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000929
930.. method:: Context.create_decimal(num)
931
932 Creates a new Decimal instance from *num* but using *self* as context. Unlike
933 the :class:`Decimal` constructor, the context precision, rounding method, flags,
934 and traps are applied to the conversion.
935
936 This is useful because constants are often given to a greater precision than is
937 needed by the application. Another benefit is that rounding immediately
938 eliminates unintended effects from digits beyond the current precision. In the
939 following example, using unrounded inputs means that adding zero to a sum can
940 change the result::
941
942 >>> getcontext().prec = 3
943 >>> Decimal("3.4445") + Decimal("1.0023")
944 Decimal("4.45")
945 >>> Decimal("3.4445") + Decimal(0) + Decimal("1.0023")
946 Decimal("4.44")
947
948
949.. method:: Context.Etiny()
950
951 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
952 for subnormal results. When underflow occurs, the exponent is set to
953 :const:`Etiny`.
954
955
956.. method:: Context.Etop()
957
958 Returns a value equal to ``Emax - prec + 1``.
959
960The usual approach to working with decimals is to create :class:`Decimal`
961instances and then apply arithmetic operations which take place within the
962current context for the active thread. An alternate approach is to use context
963methods for calculating within a specific context. The methods are similar to
964those for the :class:`Decimal` class and are only briefly recounted here.
965
966
967.. method:: Context.abs(x)
968
969 Returns the absolute value of *x*.
970
971
972.. method:: Context.add(x, y)
973
974 Return the sum of *x* and *y*.
975
976
Georg Brandl8ec7f652007-08-15 14:28:01 +0000977.. method:: Context.divide(x, y)
978
979 Return *x* divided by *y*.
980
981
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000982.. method:: Context.divide_int(x, y)
983
984 Return *x* divided by *y*, truncated to an integer.
985
986
Georg Brandl8ec7f652007-08-15 14:28:01 +0000987.. method:: Context.divmod(x, y)
988
989 Divides two numbers and returns the integer part of the result.
990
991
Georg Brandl8ec7f652007-08-15 14:28:01 +0000992.. method:: Context.minus(x)
993
994 Minus corresponds to the unary prefix minus operator in Python.
995
996
997.. method:: Context.multiply(x, y)
998
999 Return the product of *x* and *y*.
1000
1001
Georg Brandl8ec7f652007-08-15 14:28:01 +00001002.. method:: Context.plus(x)
1003
1004 Plus corresponds to the unary prefix plus operator in Python. This operation
1005 applies the context precision and rounding, so it is *not* an identity
1006 operation.
1007
1008
1009.. method:: Context.power(x, y[, modulo])
1010
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001011 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if
1012 given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001013
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001014 With two arguments, compute ``x**y``. If ``x`` is negative then
1015 ``y`` must be integral. The result will be inexact unless ``y`` is
1016 integral and the result is finite and can be expressed exactly in
1017 'precision' digits. The result should always be correctly rounded,
1018 using the rounding mode of the current thread's context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001019
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001020 With three arguments, compute ``(x**y) % modulo``. For the three
1021 argument form, the following restrictions on the arguments hold:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001022
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001023 - all three arguments must be integral
1024 - ``y`` must be nonnegative
1025 - at least one of ``x`` or ``y`` must be nonzero
1026 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl8ec7f652007-08-15 14:28:01 +00001027
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001028 The result of ``Context.power(x, y, modulo)`` is identical to
1029 the result that would be obtained by computing ``(x**y) %
1030 modulo`` with unbounded precision, but is computed more
1031 efficiently. It is always exact.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001032
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001033 .. versionchanged:: 2.6
1034 ``y`` may now be nonintegral in ``x**y``.
1035 Stricter requirements for the three-argument version.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001036
1037
1038.. method:: Context.remainder(x, y)
1039
1040 Returns the remainder from integer division.
1041
1042 The sign of the result, if non-zero, is the same as that of the original
1043 dividend.
1044
Georg Brandl8ec7f652007-08-15 14:28:01 +00001045.. method:: Context.subtract(x, y)
1046
1047 Return the difference between *x* and *y*.
1048
Georg Brandl8ec7f652007-08-15 14:28:01 +00001049.. method:: Context.to_sci_string(x)
1050
1051 Converts a number to a string using scientific notation.
1052
1053.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1054
1055
1056.. _decimal-signals:
1057
1058Signals
1059-------
1060
1061Signals represent conditions that arise during computation. Each corresponds to
1062one context flag and one context trap enabler.
1063
1064The context flag is incremented whenever the condition is encountered. After the
1065computation, flags may be checked for informational purposes (for instance, to
1066determine whether a computation was exact). After checking the flags, be sure to
1067clear all flags before starting the next computation.
1068
1069If the context's trap enabler is set for the signal, then the condition causes a
1070Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1071is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1072condition.
1073
1074
1075.. class:: Clamped
1076
1077 Altered an exponent to fit representation constraints.
1078
1079 Typically, clamping occurs when an exponent falls outside the context's
1080 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001081 fit by adding zeros to the coefficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001082
1083
1084.. class:: DecimalException
1085
1086 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1087
1088
1089.. class:: DivisionByZero
1090
1091 Signals the division of a non-infinite number by zero.
1092
1093 Can occur with division, modulo division, or when raising a number to a negative
1094 power. If this signal is not trapped, returns :const:`Infinity` or
1095 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1096
1097
1098.. class:: Inexact
1099
1100 Indicates that rounding occurred and the result is not exact.
1101
1102 Signals when non-zero digits were discarded during rounding. The rounded result
1103 is returned. The signal flag or trap is used to detect when results are
1104 inexact.
1105
1106
1107.. class:: InvalidOperation
1108
1109 An invalid operation was performed.
1110
1111 Indicates that an operation was requested that does not make sense. If not
1112 trapped, returns :const:`NaN`. Possible causes include::
1113
1114 Infinity - Infinity
1115 0 * Infinity
1116 Infinity / Infinity
1117 x % 0
1118 Infinity % x
1119 x._rescale( non-integer )
1120 sqrt(-x) and x > 0
1121 0 ** 0
1122 x ** (non-integer)
1123 x ** Infinity
1124
1125
1126.. class:: Overflow
1127
1128 Numerical overflow.
1129
1130 Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
1131 If not trapped, the result depends on the rounding mode, either pulling inward
1132 to the largest representable finite number or rounding outward to
1133 :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are
1134 also signaled.
1135
1136
1137.. class:: Rounded
1138
1139 Rounding occurred though possibly no information was lost.
1140
1141 Signaled whenever rounding discards digits; even if those digits are zero (such
1142 as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result
1143 unchanged. This signal is used to detect loss of significant digits.
1144
1145
1146.. class:: Subnormal
1147
1148 Exponent was lower than :attr:`Emin` prior to rounding.
1149
1150 Occurs when an operation result is subnormal (the exponent is too small). If not
1151 trapped, returns the result unchanged.
1152
1153
1154.. class:: Underflow
1155
1156 Numerical underflow with result rounded to zero.
1157
1158 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1159 and :class:`Subnormal` are also signaled.
1160
1161The following table summarizes the hierarchy of signals::
1162
1163 exceptions.ArithmeticError(exceptions.StandardError)
1164 DecimalException
1165 Clamped
1166 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1167 Inexact
1168 Overflow(Inexact, Rounded)
1169 Underflow(Inexact, Rounded, Subnormal)
1170 InvalidOperation
1171 Rounded
1172 Subnormal
1173
1174.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1175
1176
1177.. _decimal-notes:
1178
1179Floating Point Notes
1180--------------------
1181
1182
1183Mitigating round-off error with increased precision
1184^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1185
1186The use of decimal floating point eliminates decimal representation error
1187(making it possible to represent :const:`0.1` exactly); however, some operations
1188can still incur round-off error when non-zero digits exceed the fixed precision.
1189
1190The effects of round-off error can be amplified by the addition or subtraction
1191of nearly offsetting quantities resulting in loss of significance. Knuth
1192provides two instructive examples where rounded floating point arithmetic with
1193insufficient precision causes the breakdown of the associative and distributive
1194properties of addition::
1195
1196 # Examples from Seminumerical Algorithms, Section 4.2.2.
1197 >>> from decimal import Decimal, getcontext
1198 >>> getcontext().prec = 8
1199
1200 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1201 >>> (u + v) + w
1202 Decimal("9.5111111")
1203 >>> u + (v + w)
1204 Decimal("10")
1205
1206 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1207 >>> (u*v) + (u*w)
1208 Decimal("0.01")
1209 >>> u * (v+w)
1210 Decimal("0.0060000")
1211
1212The :mod:`decimal` module makes it possible to restore the identities by
1213expanding the precision sufficiently to avoid loss of significance::
1214
1215 >>> getcontext().prec = 20
1216 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1217 >>> (u + v) + w
1218 Decimal("9.51111111")
1219 >>> u + (v + w)
1220 Decimal("9.51111111")
1221 >>>
1222 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1223 >>> (u*v) + (u*w)
1224 Decimal("0.0060000")
1225 >>> u * (v+w)
1226 Decimal("0.0060000")
1227
1228
1229Special values
1230^^^^^^^^^^^^^^
1231
1232The number system for the :mod:`decimal` module provides special values
1233including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001234and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001235
1236Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1237they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1238not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1239can result from rounding beyond the limits of the largest representable number.
1240
1241The infinities are signed (affine) and can be used in arithmetic operations
1242where they get treated as very large, indeterminate numbers. For instance,
1243adding a constant to infinity gives another infinite result.
1244
1245Some operations are indeterminate and return :const:`NaN`, or if the
1246:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1247``0/0`` returns :const:`NaN` which means "not a number". This variety of
1248:const:`NaN` is quiet and, once created, will flow through other computations
1249always resulting in another :const:`NaN`. This behavior can be useful for a
1250series of computations that occasionally have missing inputs --- it allows the
1251calculation to proceed while flagging specific results as invalid.
1252
1253A variant is :const:`sNaN` which signals rather than remaining quiet after every
1254operation. This is a useful return value when an invalid result needs to
1255interrupt a calculation for special handling.
1256
1257The signed zeros can result from calculations that underflow. They keep the sign
1258that would have resulted if the calculation had been carried out to greater
1259precision. Since their magnitude is zero, both positive and negative zeros are
1260treated as equal and their sign is informational.
1261
1262In addition to the two signed zeros which are distinct yet equal, there are
1263various representations of zero with differing precisions yet equivalent in
1264value. This takes a bit of getting used to. For an eye accustomed to
1265normalized floating point representations, it is not immediately obvious that
1266the following calculation returns a value equal to zero::
1267
1268 >>> 1 / Decimal('Infinity')
1269 Decimal("0E-1000000026")
1270
1271.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1272
1273
1274.. _decimal-threads:
1275
1276Working with threads
1277--------------------
1278
1279The :func:`getcontext` function accesses a different :class:`Context` object for
1280each thread. Having separate thread contexts means that threads may make
1281changes (such as ``getcontext.prec=10``) without interfering with other threads.
1282
1283Likewise, the :func:`setcontext` function automatically assigns its target to
1284the current thread.
1285
1286If :func:`setcontext` has not been called before :func:`getcontext`, then
1287:func:`getcontext` will automatically create a new context for use in the
1288current thread.
1289
1290The new context is copied from a prototype context called *DefaultContext*. To
1291control the defaults so that each thread will use the same values throughout the
1292application, directly modify the *DefaultContext* object. This should be done
1293*before* any threads are started so that there won't be a race condition between
1294threads calling :func:`getcontext`. For example::
1295
1296 # Set applicationwide defaults for all threads about to be launched
1297 DefaultContext.prec = 12
1298 DefaultContext.rounding = ROUND_DOWN
1299 DefaultContext.traps = ExtendedContext.traps.copy()
1300 DefaultContext.traps[InvalidOperation] = 1
1301 setcontext(DefaultContext)
1302
1303 # Afterwards, the threads can be started
1304 t1.start()
1305 t2.start()
1306 t3.start()
1307 . . .
1308
1309.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1310
1311
1312.. _decimal-recipes:
1313
1314Recipes
1315-------
1316
1317Here are a few recipes that serve as utility functions and that demonstrate ways
1318to work with the :class:`Decimal` class::
1319
1320 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1321 pos='', neg='-', trailneg=''):
1322 """Convert Decimal to a money formatted string.
1323
1324 places: required number of places after the decimal point
1325 curr: optional currency symbol before the sign (may be blank)
1326 sep: optional grouping separator (comma, period, space, or blank)
1327 dp: decimal point indicator (comma or period)
1328 only specify as blank when places is zero
1329 pos: optional sign for positive numbers: '+', space or blank
1330 neg: optional sign for negative numbers: '-', '(', space or blank
1331 trailneg:optional trailing minus indicator: '-', ')', space or blank
1332
1333 >>> d = Decimal('-1234567.8901')
1334 >>> moneyfmt(d, curr='$')
1335 '-$1,234,567.89'
1336 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1337 '1.234.568-'
1338 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1339 '($1,234,567.89)'
1340 >>> moneyfmt(Decimal(123456789), sep=' ')
1341 '123 456 789.00'
1342 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1343 '<.02>'
1344
1345 """
1346 q = Decimal((0, (1,), -places)) # 2 places --> '0.01'
1347 sign, digits, exp = value.quantize(q).as_tuple()
1348 assert exp == -places
1349 result = []
1350 digits = map(str, digits)
1351 build, next = result.append, digits.pop
1352 if sign:
1353 build(trailneg)
1354 for i in range(places):
1355 if digits:
1356 build(next())
1357 else:
1358 build('0')
1359 build(dp)
1360 i = 0
1361 while digits:
1362 build(next())
1363 i += 1
1364 if i == 3 and digits:
1365 i = 0
1366 build(sep)
1367 build(curr)
1368 if sign:
1369 build(neg)
1370 else:
1371 build(pos)
1372 result.reverse()
1373 return ''.join(result)
1374
1375 def pi():
1376 """Compute Pi to the current precision.
1377
1378 >>> print pi()
1379 3.141592653589793238462643383
1380
1381 """
1382 getcontext().prec += 2 # extra digits for intermediate steps
1383 three = Decimal(3) # substitute "three=3.0" for regular floats
1384 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1385 while s != lasts:
1386 lasts = s
1387 n, na = n+na, na+8
1388 d, da = d+da, da+32
1389 t = (t * n) / d
1390 s += t
1391 getcontext().prec -= 2
1392 return +s # unary plus applies the new precision
1393
1394 def exp(x):
1395 """Return e raised to the power of x. Result type matches input type.
1396
1397 >>> print exp(Decimal(1))
1398 2.718281828459045235360287471
1399 >>> print exp(Decimal(2))
1400 7.389056098930650227230427461
1401 >>> print exp(2.0)
1402 7.38905609893
1403 >>> print exp(2+0j)
1404 (7.38905609893+0j)
1405
1406 """
1407 getcontext().prec += 2
1408 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1409 while s != lasts:
1410 lasts = s
1411 i += 1
1412 fact *= i
1413 num *= x
1414 s += num / fact
1415 getcontext().prec -= 2
1416 return +s
1417
1418 def cos(x):
1419 """Return the cosine of x as measured in radians.
1420
1421 >>> print cos(Decimal('0.5'))
1422 0.8775825618903727161162815826
1423 >>> print cos(0.5)
1424 0.87758256189
1425 >>> print cos(0.5+0j)
1426 (0.87758256189+0j)
1427
1428 """
1429 getcontext().prec += 2
1430 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1431 while s != lasts:
1432 lasts = s
1433 i += 2
1434 fact *= i * (i-1)
1435 num *= x * x
1436 sign *= -1
1437 s += num / fact * sign
1438 getcontext().prec -= 2
1439 return +s
1440
1441 def sin(x):
1442 """Return the sine of x as measured in radians.
1443
1444 >>> print sin(Decimal('0.5'))
1445 0.4794255386042030002732879352
1446 >>> print sin(0.5)
1447 0.479425538604
1448 >>> print sin(0.5+0j)
1449 (0.479425538604+0j)
1450
1451 """
1452 getcontext().prec += 2
1453 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1454 while s != lasts:
1455 lasts = s
1456 i += 2
1457 fact *= i * (i-1)
1458 num *= x * x
1459 sign *= -1
1460 s += num / fact * sign
1461 getcontext().prec -= 2
1462 return +s
1463
1464
1465.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1466
1467
1468.. _decimal-faq:
1469
1470Decimal FAQ
1471-----------
1472
1473Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1474minimize typing when using the interactive interpreter?
1475
1476\A. Some users abbreviate the constructor to just a single letter::
1477
1478 >>> D = decimal.Decimal
1479 >>> D('1.23') + D('3.45')
1480 Decimal("4.68")
1481
1482Q. In a fixed-point application with two decimal places, some inputs have many
1483places and need to be rounded. Others are not supposed to have excess digits
1484and need to be validated. What methods should be used?
1485
1486A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
1487the :const:`Inexact` trap is set, it is also useful for validation::
1488
1489 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1490
1491 >>> # Round to two places
1492 >>> Decimal("3.214").quantize(TWOPLACES)
1493 Decimal("3.21")
1494
1495 >>> # Validate that a number does not exceed two places
1496 >>> Decimal("3.21").quantize(TWOPLACES, context=Context(traps=[Inexact]))
1497 Decimal("3.21")
1498
1499 >>> Decimal("3.214").quantize(TWOPLACES, context=Context(traps=[Inexact]))
1500 Traceback (most recent call last):
1501 ...
1502 Inexact: Changed in rounding
1503
1504Q. Once I have valid two place inputs, how do I maintain that invariant
1505throughout an application?
1506
1507A. Some operations like addition and subtraction automatically preserve fixed
1508point. Others, like multiplication and division, change the number of decimal
1509places and need to be followed-up with a :meth:`quantize` step.
1510
1511Q. There are many ways to express the same value. The numbers :const:`200`,
1512:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1513various precisions. Is there a way to transform them to a single recognizable
1514canonical value?
1515
1516A. The :meth:`normalize` method maps all equivalent values to a single
1517representative::
1518
1519 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1520 >>> [v.normalize() for v in values]
1521 [Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2")]
1522
1523Q. Some decimal values always print with exponential notation. Is there a way
1524to get a non-exponential representation?
1525
1526A. For some values, exponential notation is the only way to express the number
1527of significant places in the coefficient. For example, expressing
1528:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1529original's two-place significance.
1530
1531Q. Is there a way to convert a regular float to a :class:`Decimal`?
1532
1533A. Yes, all binary floating point numbers can be exactly expressed as a
1534Decimal. An exact conversion may take more precision than intuition would
1535suggest, so trapping :const:`Inexact` will signal a need for more precision::
1536
1537 def floatToDecimal(f):
1538 "Convert a floating point number to a Decimal with no loss of information"
1539 # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an
1540 # exponent. Double the mantissa until it is an integer. Use the integer
1541 # mantissa and exponent to compute an equivalent Decimal. If this cannot
1542 # be done exactly, then retry with more precision.
1543
1544 mantissa, exponent = math.frexp(f)
1545 while mantissa != int(mantissa):
1546 mantissa *= 2.0
1547 exponent -= 1
1548 mantissa = int(mantissa)
1549
1550 oldcontext = getcontext()
1551 setcontext(Context(traps=[Inexact]))
1552 try:
1553 while True:
1554 try:
1555 return mantissa * Decimal(2) ** exponent
1556 except Inexact:
1557 getcontext().prec += 1
1558 finally:
1559 setcontext(oldcontext)
1560
1561Q. Why isn't the :func:`floatToDecimal` routine included in the module?
1562
1563A. There is some question about whether it is advisable to mix binary and
1564decimal floating point. Also, its use requires some care to avoid the
1565representation issues associated with binary floating point::
1566
1567 >>> floatToDecimal(1.1)
1568 Decimal("1.100000000000000088817841970012523233890533447265625")
1569
1570Q. Within a complex calculation, how can I make sure that I haven't gotten a
1571spurious result because of insufficient precision or rounding anomalies.
1572
1573A. The decimal module makes it easy to test results. A best practice is to
1574re-run calculations using greater precision and with various rounding modes.
1575Widely differing results indicate insufficient precision, rounding mode issues,
1576ill-conditioned inputs, or a numerically unstable algorithm.
1577
1578Q. I noticed that context precision is applied to the results of operations but
1579not to the inputs. Is there anything to watch out for when mixing values of
1580different precisions?
1581
1582A. Yes. The principle is that all values are considered to be exact and so is
1583the arithmetic on those values. Only the results are rounded. The advantage
1584for inputs is that "what you type is what you get". A disadvantage is that the
1585results can look odd if you forget that the inputs haven't been rounded::
1586
1587 >>> getcontext().prec = 3
1588 >>> Decimal('3.104') + D('2.104')
1589 Decimal("5.21")
1590 >>> Decimal('3.104') + D('0.000') + D('2.104')
1591 Decimal("5.20")
1592
1593The solution is either to increase precision or to force rounding of inputs
1594using the unary plus operation::
1595
1596 >>> getcontext().prec = 3
1597 >>> +Decimal('1.23456789') # unary plus triggers rounding
1598 Decimal("1.23")
1599
1600Alternatively, inputs can be rounded upon creation using the
1601:meth:`Context.create_decimal` method::
1602
1603 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
1604 Decimal("1.2345")
1605