blob: bbac0d4647f06fdb63f1e9b95f6c8cd8f166d405 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`decimal` --- Decimal floating point arithmetic
3====================================================
4
5.. module:: decimal
6 :synopsis: Implementation of the General Decimal Arithmetic Specification.
7
Georg Brandl116aa622007-08-15 14:28:22 +00008.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
9.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
10.. moduleauthor:: Raymond Hettinger <python at rcn.com>
11.. moduleauthor:: Aahz <aahz at pobox.com>
12.. moduleauthor:: Tim Peters <tim.one at comcast.net>
Georg Brandl116aa622007-08-15 14:28:22 +000013.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
14
15
Georg Brandl116aa622007-08-15 14:28:22 +000016The :mod:`decimal` module provides support for decimal floating point
Thomas Wouters1b7f8912007-09-19 03:06:30 +000017arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl116aa622007-08-15 14:28:22 +000018
19* Decimal numbers can be represented exactly. In contrast, numbers like
20 :const:`1.1` do not have an exact representation in binary floating point. End
21 users typically would not expect :const:`1.1` to display as
22 :const:`1.1000000000000001` as it does with binary floating point.
23
24* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000025 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl116aa622007-08-15 14:28:22 +000026 is :const:`5.5511151231257827e-017`. While near to zero, the differences
27 prevent reliable equality testing and differences can accumulate. For this
28 reason, decimal would be preferred in accounting applications which have strict
29 equality invariants.
30
31* The decimal module incorporates a notion of significant places so that ``1.30
32 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
33 This is the customary presentation for monetary applications. For
34 multiplication, the "schoolbook" approach uses all the figures in the
35 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
36 1.20`` gives :const:`1.5600`.
37
38* Unlike hardware based binary floating point, the decimal module has a user
Thomas Wouters1b7f8912007-09-19 03:06:30 +000039 alterable precision (defaulting to 28 places) which can be as large as needed for
Georg Brandl116aa622007-08-15 14:28:22 +000040 a given problem::
41
42 >>> getcontext().prec = 6
43 >>> Decimal(1) / Decimal(7)
44 Decimal("0.142857")
45 >>> getcontext().prec = 28
46 >>> Decimal(1) / Decimal(7)
47 Decimal("0.1428571428571428571428571429")
48
49* Both binary and decimal floating point are implemented in terms of published
50 standards. While the built-in float type exposes only a modest portion of its
51 capabilities, the decimal module exposes all required parts of the standard.
52 When needed, the programmer has full control over rounding and signal handling.
53
54The module design is centered around three concepts: the decimal number, the
55context for arithmetic, and signals.
56
57A decimal number is immutable. It has a sign, coefficient digits, and an
58exponent. To preserve significance, the coefficient digits do not truncate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000059trailing zeros. Decimals also include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +000060:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
61differentiates :const:`-0` from :const:`+0`.
62
63The context for arithmetic is an environment specifying precision, rounding
64rules, limits on exponents, flags indicating the results of operations, and trap
65enablers which determine whether signals are treated as exceptions. Rounding
66options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
67:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +000068:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl116aa622007-08-15 14:28:22 +000069
70Signals are groups of exceptional conditions arising during the course of
71computation. Depending on the needs of the application, signals may be ignored,
72considered as informational, or treated as exceptions. The signals in the
73decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
74:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
75:const:`Overflow`, and :const:`Underflow`.
76
77For each signal there is a flag and a trap enabler. When a signal is
78encountered, its flag is incremented from zero and, then, if the trap enabler is
79set to one, an exception is raised. Flags are sticky, so the user needs to
80reset them before monitoring a calculation.
81
82
83.. seealso::
84
Thomas Wouters1b7f8912007-09-19 03:06:30 +000085 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
86 Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +000087
Thomas Wouters1b7f8912007-09-19 03:06:30 +000088 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
89 <http://www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +000090
91.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
92
93
94.. _decimal-tutorial:
95
96Quick-start Tutorial
97--------------------
98
99The usual start to using decimals is importing the module, viewing the current
100context with :func:`getcontext` and, if necessary, setting new values for
101precision, rounding, or enabled traps::
102
103 >>> from decimal import *
104 >>> getcontext()
105 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
106 capitals=1, flags=[], traps=[Overflow, InvalidOperation,
107 DivisionByZero])
108
109 >>> getcontext().prec = 7 # Set a new precision
110
111Decimal instances can be constructed from integers, strings, or tuples. To
112create a Decimal from a :class:`float`, first convert it to a string. This
113serves as an explicit reminder of the details of the conversion (including
114representation error). Decimal numbers include special values such as
115:const:`NaN` which stands for "Not a number", positive and negative
116:const:`Infinity`, and :const:`-0`. ::
117
118 >>> Decimal(10)
119 Decimal("10")
120 >>> Decimal("3.14")
121 Decimal("3.14")
122 >>> Decimal((0, (3, 1, 4), -2))
123 Decimal("3.14")
124 >>> Decimal(str(2.0 ** 0.5))
125 Decimal("1.41421356237")
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000126 >>> Decimal(2) ** Decimal("0.5")
127 Decimal("1.414213562373095048801688724")
Georg Brandl116aa622007-08-15 14:28:22 +0000128 >>> Decimal("NaN")
129 Decimal("NaN")
130 >>> Decimal("-Infinity")
131 Decimal("-Infinity")
132
133The significance of a new Decimal is determined solely by the number of digits
134input. Context precision and rounding only come into play during arithmetic
135operations. ::
136
137 >>> getcontext().prec = 6
138 >>> Decimal('3.0')
139 Decimal("3.0")
140 >>> Decimal('3.1415926535')
141 Decimal("3.1415926535")
142 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
143 Decimal("5.85987")
144 >>> getcontext().rounding = ROUND_UP
145 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
146 Decimal("5.85988")
147
148Decimals interact well with much of the rest of Python. Here is a small decimal
149floating point flying circus::
150
151 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
152 >>> max(data)
153 Decimal("9.25")
154 >>> min(data)
155 Decimal("0.03")
156 >>> sorted(data)
157 [Decimal("0.03"), Decimal("1.00"), Decimal("1.34"), Decimal("1.87"),
158 Decimal("2.35"), Decimal("3.45"), Decimal("9.25")]
159 >>> sum(data)
160 Decimal("19.29")
161 >>> a,b,c = data[:3]
162 >>> str(a)
163 '1.34'
164 >>> float(a)
165 1.3400000000000001
166 >>> round(a, 1) # round() first converts to binary floating point
167 1.3
168 >>> int(a)
169 1
170 >>> a * 5
171 Decimal("6.70")
172 >>> a * b
173 Decimal("2.5058")
174 >>> c % a
175 Decimal("0.77")
176
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000177And some mathematic functions are also available to Decimal::
178
179 >>> Decimal(2).sqrt()
180 Decimal("1.414213562373095048801688724")
181 >>> Decimal(1).exp()
182 Decimal("2.718281828459045235360287471")
183 >>> Decimal("10").ln()
184 Decimal("2.302585092994045684017991455")
185 >>> Decimal("10").log10()
186 Decimal("1")
187
Georg Brandl116aa622007-08-15 14:28:22 +0000188The :meth:`quantize` method rounds a number to a fixed exponent. This method is
189useful for monetary applications that often round results to a fixed number of
190places::
191
192 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
193 Decimal("7.32")
194 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
195 Decimal("8")
196
197As shown above, the :func:`getcontext` function accesses the current context and
198allows the settings to be changed. This approach meets the needs of most
199applications.
200
201For more advanced work, it may be useful to create alternate contexts using the
202Context() constructor. To make an alternate active, use the :func:`setcontext`
203function.
204
205In accordance with the standard, the :mod:`Decimal` module provides two ready to
206use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
207former is especially useful for debugging because many of the traps are
208enabled::
209
210 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
211 >>> setcontext(myothercontext)
212 >>> Decimal(1) / Decimal(7)
213 Decimal("0.142857142857142857142857142857142857142857142857142857142857")
214
215 >>> ExtendedContext
216 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
217 capitals=1, flags=[], traps=[])
218 >>> setcontext(ExtendedContext)
219 >>> Decimal(1) / Decimal(7)
220 Decimal("0.142857143")
221 >>> Decimal(42) / Decimal(0)
222 Decimal("Infinity")
223
224 >>> setcontext(BasicContext)
225 >>> Decimal(42) / Decimal(0)
226 Traceback (most recent call last):
227 File "<pyshell#143>", line 1, in -toplevel-
228 Decimal(42) / Decimal(0)
229 DivisionByZero: x / 0
230
231Contexts also have signal flags for monitoring exceptional conditions
232encountered during computations. The flags remain set until explicitly cleared,
233so it is best to clear the flags before each set of monitored computations by
234using the :meth:`clear_flags` method. ::
235
236 >>> setcontext(ExtendedContext)
237 >>> getcontext().clear_flags()
238 >>> Decimal(355) / Decimal(113)
239 Decimal("3.14159292")
240 >>> getcontext()
241 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
242 capitals=1, flags=[Inexact, Rounded], traps=[])
243
244The *flags* entry shows that the rational approximation to :const:`Pi` was
245rounded (digits beyond the context precision were thrown away) and that the
246result is inexact (some of the discarded digits were non-zero).
247
248Individual traps are set using the dictionary in the :attr:`traps` field of a
249context::
250
251 >>> Decimal(1) / Decimal(0)
252 Decimal("Infinity")
253 >>> getcontext().traps[DivisionByZero] = 1
254 >>> Decimal(1) / Decimal(0)
255 Traceback (most recent call last):
256 File "<pyshell#112>", line 1, in -toplevel-
257 Decimal(1) / Decimal(0)
258 DivisionByZero: x / 0
259
260Most programs adjust the current context only once, at the beginning of the
261program. And, in many applications, data is converted to :class:`Decimal` with
262a single cast inside a loop. With context set and decimals created, the bulk of
263the program manipulates the data no differently than with other Python numeric
264types.
265
266.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
267
268
269.. _decimal-decimal:
270
271Decimal objects
272---------------
273
274
275.. class:: Decimal([value [, context]])
276
277 Constructs a new :class:`Decimal` object based from *value*.
278
279 *value* can be an integer, string, tuple, or another :class:`Decimal` object. If
280 no *value* is given, returns ``Decimal("0")``. If *value* is a string, it
281 should conform to the decimal numeric string syntax::
282
283 sign ::= '+' | '-'
284 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
285 indicator ::= 'e' | 'E'
286 digits ::= digit [digit]...
287 decimal-part ::= digits '.' [digits] | ['.'] digits
288 exponent-part ::= indicator [sign] digits
289 infinity ::= 'Infinity' | 'Inf'
290 nan ::= 'NaN' [digits] | 'sNaN' [digits]
291 numeric-value ::= decimal-part [exponent-part] | infinity
292 numeric-string ::= [sign] numeric-value | [sign] nan
293
294 If *value* is a :class:`tuple`, it should have three components, a sign
295 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
296 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
297 returns ``Decimal("1.414")``.
298
299 The *context* precision does not affect how many digits are stored. That is
300 determined exclusively by the number of digits in *value*. For example,
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000301 ``Decimal("3.00000")`` records all five zeros even if the context precision is
Georg Brandl116aa622007-08-15 14:28:22 +0000302 only three.
303
304 The purpose of the *context* argument is determining what to do if *value* is a
305 malformed string. If the context traps :const:`InvalidOperation`, an exception
306 is raised; otherwise, the constructor returns a new Decimal with the value of
307 :const:`NaN`.
308
309 Once constructed, :class:`Decimal` objects are immutable.
310
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000311Decimal floating point objects share many properties with the other built-in
Georg Brandl116aa622007-08-15 14:28:22 +0000312numeric types such as :class:`float` and :class:`int`. All of the usual math
313operations and special methods apply. Likewise, decimal objects can be copied,
314pickled, printed, used as dictionary keys, used as set elements, compared,
315sorted, and coerced to another type (such as :class:`float` or :class:`long`).
316
317In addition to the standard numeric properties, decimal floating point objects
318also have a number of specialized methods:
319
320
321.. method:: Decimal.adjusted()
322
323 Return the adjusted exponent after shifting out the coefficient's rightmost
324 digits until only the lead digit remains: ``Decimal("321e+5").adjusted()``
325 returns seven. Used for determining the position of the most significant digit
326 with respect to the decimal point.
327
328
329.. method:: Decimal.as_tuple()
330
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000331 Return a tuple representation of the number: ``(sign, digit_tuple, exponent)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000332
333
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000334.. method:: Decimal.canonical()
335
336 Return the canonical encoding of the argument. Currently, the
337 encoding of a :class:`Decimal` instance is always canonical, so
338 this operation returns its argument unchanged.
339
340 .. versionadded:: 2.6
341
Georg Brandl116aa622007-08-15 14:28:22 +0000342.. method:: Decimal.compare(other[, context])
343
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000344 Compare the values of two Decimal instances. This operation
345 behaves in the same way as the usual comparison method
346 :meth:`__cmp__`, except that :meth:`compare` returns a Decimal
347 instance rather than an integer, and if either operand is a NaN
348 then the result is a NaN::
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350 a or b is a NaN ==> Decimal("NaN")
351 a < b ==> Decimal("-1")
352 a == b ==> Decimal("0")
353 a > b ==> Decimal("1")
354
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000355.. method:: Decimal.compare_signal(other[, context])
356
357 This operation is identical to the :meth:`compare` method, except
358 that all NaNs signal. That is, if neither operand is a signaling
359 NaN then any quiet NaN operand is treated as though it were a
360 signaling NaN.
361
362 .. versionadded:: 2.6
363
364.. method:: Decimal.compare_total(other)
365
366 Compare two operands using their abstract representation rather
367 than their numerical value. Similar to the :meth:`compare` method,
368 but the result gives a total ordering on :class:`Decimal`
369 instances. Two :class:`Decimal` instances with the same numeric
370 value but different representations compare unequal in this
371 ordering::
372
373 >>> Decimal("12.0").compare_total(Decimal("12"))
374 Decimal("-1")
375
376 Quiet and signaling NaNs are also included in the total ordering.
377 The result of this function is ``Decimal("0")`` if both operands
378 have the same representation, ``Decimal("-1")`` if the first
379 operand is lower in the total order than the second, and
380 ``Decimal("1")`` if the first operand is higher in the total order
381 than the second operand. See the specification for details of the
382 total order.
383
384 .. versionadded:: 2.6
385
386.. method:: Decimal.compare_total_mag(other)
387
388 Compare two operands using their abstract representation rather
389 than their value as in :meth:`compare_total`, but ignoring the sign
390 of each operand. ``x.compare_total_mag(y)`` is equivalent to
391 ``x.copy_abs().compare_total(y.copy_abs())``.
392
393 .. versionadded:: 2.6
394
395.. method:: Decimal.copy_abs()
396
397 Return the absolute value of the argument. This operation is
398 unaffected by the context and is quiet: no flags are changed and no
399 rounding is performed.
400
401 .. versionadded:: 2.6
402
403.. method:: Decimal.copy_negate()
404
405 Return the negation of the argument. This operation is unaffected
406 by the context and is quiet: no flags are changed and no rounding
407 is performed.
408
409 .. versionadded:: 2.6
410
411.. method:: Decimal.copy_sign(other)
412
413 Return a copy of the first operand with the sign set to be the
414 same as the sign of the second operand. For example::
415
416 >>> Decimal("2.3").copy_sign(Decimal("-1.5"))
417 Decimal("-2.3")
418
419 This operation is unaffected by the context and is quiet: no flags
420 are changed and no rounding is performed.
421
422 .. versionadded:: 2.6
423
424.. method:: Decimal.exp([context])
425
426 Return the value of the (natural) exponential function ``e**x`` at the
427 given number. The result is correctly rounded using the
428 :const:`ROUND_HALF_EVEN` rounding mode.
429
430 >>> Decimal(1).exp()
431 Decimal("2.718281828459045235360287471")
432 >>> Decimal(321).exp()
433 Decimal("2.561702493119680037517373933E+139")
434
435 .. versionadded:: 2.6
436
437.. method:: Decimal.fma(other, third[, context])
438
439 Fused multiply-add. Return self*other+third with no rounding of
440 the intermediate product self*other.
441
442 >>> Decimal(2).fma(3, 5)
443 Decimal("11")
444
445 .. versionadded:: 2.6
446
447.. method:: Decimal.is_canonical()
448
449 Return :const:`True` if the argument is canonical and
450 :const:`False` otherwise. Currently, a :class:`Decimal` instance
451 is always canonical, so this operation always returns
452 :const:`True`.
453
454 .. versionadded:: 2.6
455
456.. method:: is_finite()
457
458 Return :const:`True` if the argument is a finite number, and
459 :const:`False` if the argument is an infinity or a NaN.
460
461 .. versionadded:: 2.6
462
463.. method:: is_infinite()
464
465 Return :const:`True` if the argument is either positive or
466 negative infinity and :const:`False` otherwise.
467
468 .. versionadded:: 2.6
469
470.. method:: is_nan()
471
472 Return :const:`True` if the argument is a (quiet or signaling)
473 NaN and :const:`False` otherwise.
474
475 .. versionadded:: 2.6
476
477.. method:: is_normal()
478
479 Return :const:`True` if the argument is a *normal* finite number.
480 Return :const:`False` if the argument is zero, subnormal, infinite
481 or a NaN.
482
483 .. versionadded:: 2.6
484
485.. method:: is_qnan()
486
487 Return :const:`True` if the argument is a quiet NaN, and
488 :const:`False` otherwise.
489
490 .. versionadded:: 2.6
491
492.. method:: is_signed()
493
494 Return :const:`True` if the argument has a negative sign and
495 :const:`False` otherwise. Note that zeros and NaNs can both carry
496 signs.
497
498 .. versionadded:: 2.6
499
500.. method:: is_snan()
501
502 Return :const:`True` if the argument is a signaling NaN and
503 :const:`False` otherwise.
504
505 .. versionadded:: 2.6
506
507.. method:: is_subnormal()
508
509 Return :const:`True` if the argument is subnormal, and
510 :const:`False` otherwise.
511
512 .. versionadded:: 2.6
513
514.. method:: is_zero()
515
516 Return :const:`True` if the argument is a (positive or negative)
517 zero and :const:`False` otherwise.
518
519 .. versionadded:: 2.6
520
521.. method:: Decimal.ln([context])
522
523 Return the natural (base e) logarithm of the operand. The result
524 is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
525 mode.
526
527 .. versionadded:: 2.6
528
529.. method:: Decimal.log10([context])
530
531 Return the base ten logarithm of the operand. The result is
532 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
533
534 .. versionadded:: 2.6
535
536.. method: Decimal.logb([context])
537
538 For a nonzero number, return the adjusted exponent of its operand
539 as a :class:`Decimal` instance. If the operand is a zero then
540 ``Decimal("-Infinity")`` is returned and the
541 :const:`DivisionByZero` flag is raised. If the operand is an
542 infinity then ``Decimal("Infinity")`` is returned.
543
544 .. versionadded:: 2.6
545
546.. method:: Decimal.logical_and(other[, context])
547
548 :meth:`logical_and` is a logical operation which takes two
549 *logical operands* (see :ref:`logical_operands_label`). The result
550 is the digit-wise ``and`` of the two operands.
551
552 .. versionadded:: 2.6
553
554.. method:: Decimal.logical_invert(other[, context])
555
556 :meth:`logical_invert` is a logical operation. The argument must
557 be a *logical operand* (see :ref:`logical_operands_label`). The
558 result is the digit-wise inversion of the operand.
559
560 .. versionadded:: 2.6
561
562.. method:: Decimal.logical_or(other[, context])
563
564 :meth:`logical_or` is a logical operation which takes two *logical
565 operands* (see :ref:`logical_operands_label`). The result is the
566 digit-wise ``or`` of the two operands.
567
568 .. versionadded:: 2.6
569
570.. method:: Decimal.logical_xor(other[, context])
571
572 :meth:`logical_xor` is a logical operation which takes two
573 *logical operands* (see :ref:`logical_operands_label`). The result
574 is the digit-wise exclusive or of the two operands.
575
576 .. versionadded:: 2.6
Georg Brandl116aa622007-08-15 14:28:22 +0000577
578.. method:: Decimal.max(other[, context])
579
580 Like ``max(self, other)`` except that the context rounding rule is applied
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000581 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl116aa622007-08-15 14:28:22 +0000582 (depending on the context and whether they are signaling or quiet).
583
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000584.. method:: Decimal.max_mag(other[, context])
585
586 Similar to the :meth:`max` method, but the comparison is done using
587 the absolute values of the operands.
588
589 .. versionadded:: 2.6
Georg Brandl116aa622007-08-15 14:28:22 +0000590
591.. method:: Decimal.min(other[, context])
592
593 Like ``min(self, other)`` except that the context rounding rule is applied
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000594 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl116aa622007-08-15 14:28:22 +0000595 (depending on the context and whether they are signaling or quiet).
596
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000597.. method:: Decimal.min_mag(other[, context])
598
599 Similar to the :meth:`min` method, but the comparison is done using
600 the absolute values of the operands.
601
602 .. versionadded:: 2.6
603
604.. method:: Decimal.next_minus([context])
605
606 Return the largest number representable in the given context (or
607 in the current thread's context if no context is given) that is smaller
608 than the given operand.
609
610 .. versionadded:: 2.6
611
612.. method:: Decimal.next_plus([context])
613
614 Return the smallest number representable in the given context (or
615 in the current thread's context if no context is given) that is
616 larger than the given operand.
617
618 .. versionadded:: 2.6
619
620.. method:: Decimal.next_toward(other[, context])
621
622 If the two operands are unequal, return the number closest to the
623 first operand in the direction of the second operand. If both
624 operands are numerically equal, return a copy of the first operand
625 with the sign set to be the same as the sign of the second operand.
626
627 .. versionadded:: 2.6
Georg Brandl116aa622007-08-15 14:28:22 +0000628
629.. method:: Decimal.normalize([context])
630
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000631 Normalize the number by stripping the rightmost trailing zeros and converting
Georg Brandl116aa622007-08-15 14:28:22 +0000632 any result equal to :const:`Decimal("0")` to :const:`Decimal("0e0")`. Used for
633 producing canonical values for members of an equivalence class. For example,
634 ``Decimal("32.100")`` and ``Decimal("0.321000e+2")`` both normalize to the
635 equivalent value ``Decimal("32.1")``.
636
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000637.. method:: Decimal.number_class([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000638
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000639 Return a string describing the *class* of the operand. The
640 returned value is one of the following ten strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000641
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000642 * ``"-Infinity"``, indicating that the operand is negative infinity.
643 * ``"-Normal"``, indicating that the operand is a negative normal number.
644 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
645 * ``"-Zero"``, indicating that the operand is a negative zero.
646 * ``"+Zero"``, indicating that the operand is a positive zero.
647 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
648 * ``"+Normal"``, indicating that the operand is a positive normal number.
649 * ``"+Infinity"``, indicating that the operand is positive infinity.
650 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
651 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000652
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653 .. versionadded:: 2.6
Georg Brandl116aa622007-08-15 14:28:22 +0000654
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000655.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]])
656
657 Returns a value equal to the first operand after rounding and
658 having the exponent of the second operand.
659
660 >>> Decimal("1.41421356").quantize(Decimal("1.000"))
661 Decimal("1.414")
662
663 Unlike other operations, if the length of the coefficient after the
664 quantize operation would be greater than precision, then an
665 :const:`InvalidOperation` is signaled. This guarantees that, unless
666 there is an error condition, the quantized exponent is always equal
667 to that of the right-hand operand.
668
669 Also unlike other operations, quantize never signals Underflow,
670 even if the result is subnormal and inexact.
671
672 If the exponent of the second operand is larger than that of the
673 first then rounding may be necessary. In this case, the rounding
674 mode is determined by the ``rounding`` argument if given, else by
675 the given ``context`` argument; if neither argument is given the
676 rounding mode of the current thread's context is used.
677
678 If watchexp is set (default), then an error is returned whenever
679 the resulting exponent is greater than Emax or less than Etiny.
680
681.. method:: Decimal.radix()
682
683 Return ``Decimal(10)``, the radix (base) in which the
684 :class:`Decimal` class does all its arithmetic. Included for
685 compatibility with the specification.
686
687 .. versionadded:: 2.6
Georg Brandl116aa622007-08-15 14:28:22 +0000688
689.. method:: Decimal.remainder_near(other[, context])
690
691 Computes the modulo as either a positive or negative value depending on which is
692 closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
693 ``Decimal("-2")`` which is closer to zero than ``Decimal("4")``.
694
695 If both are equally close, the one chosen will have the same sign as *self*.
696
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000697.. method:: Decimal.rotate(other[, context])
698
699 Return the result of rotating the digits of the first operand by
700 an amount specified by the second operand. The second operand
701 must be an integer in the range -precision through precision. The
702 absolute value of the second operand gives the number of places to
703 rotate. If the second operand is positive then rotation is to the
704 left; otherwise rotation is to the right. The coefficient of the
705 first operand is padded on the left with zeros to length precision
706 if necessary. The sign and exponent of the first operand are
707 unchanged.
708
709 .. versionadded:: 2.6
Georg Brandl116aa622007-08-15 14:28:22 +0000710
711.. method:: Decimal.same_quantum(other[, context])
712
713 Test whether self and other have the same exponent or whether both are
714 :const:`NaN`.
715
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000716.. method:: Decimal.scaleb(other[, context])
717
718 Return the first operand with exponent adjusted by the second.
719 Equivalently, return the first operand multiplied by ``10**other``.
720 The second operand must be an integer.
721
722 .. versionadded:: 2.6
723
724.. method:: Decimal.shift(other[, context])
725
726 Return the result of shifting the digits of the first operand by
727 an amount specified by the second operand. The second operand must
728 be an integer in the range -precision through precision. The
729 absolute value of the second operand gives the number of places to
730 shift. If the second operand is positive then the shift is to the
731 left; otherwise the shift is to the right. Digits shifted into the
732 coefficient are zeros. The sign and exponent of the first operand
733 are unchanged.
734
735 .. versionadded:: 2.6
Georg Brandl116aa622007-08-15 14:28:22 +0000736
737.. method:: Decimal.sqrt([context])
738
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000739 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000740
741
742.. method:: Decimal.to_eng_string([context])
743
744 Convert to an engineering-type string.
745
746 Engineering notation has an exponent which is a multiple of 3, so there are up
747 to 3 digits left of the decimal place. For example, converts
748 ``Decimal('123E+1')`` to ``Decimal("1.23E+3")``
749
Georg Brandl116aa622007-08-15 14:28:22 +0000750.. method:: Decimal.to_integral([rounding[, context]])
751
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000752 Identical to the :meth:`to_integral_value` method. The ``to_integral``
753 name has been kept for compatibility with older versions.
754
755.. method:: Decimal.to_integral_exact([rounding[, context]])
756
757 Round the argument to the nearest integer, signaling
758 :const:`Inexact` or :const:`Rounded` as appropriate if rounding
759 occurs. The rounding mode is determined by the ``rounding``
760 parameter if given, else by the given ``context``. If neither
761 parameter is given then the rounding mode of the current context is
762 used.
763
764 .. versionadded:: 2.6
765
766.. method:: Decimal.to_integral_value([rounding[, context]])
767
Georg Brandl116aa622007-08-15 14:28:22 +0000768 Rounds to the nearest integer without signaling :const:`Inexact` or
769 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding
770 method in either the supplied *context* or the current context.
771
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000772 .. versionchanged:: 2.6
773 renamed from ``to_integral`` to ``to_integral_value``. The old name
774 remains valid for compatibility.
775
776.. method:: Decimal.trim()
777
778 Returns its argument with *insignificant* trailing zeros removed.
779 Here, a trailing zero is considered insignificant either if it
780 follows the decimal point, or if the exponent of the argument (that
781 is, the last element of the :meth:`as_tuple` representation) is
782 positive.
783
784 .. versionadded:: 2.6
785
786.. _logical_operands_label:
787
788Logical operands
789^^^^^^^^^^^^^^^^
790
791The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
792and :meth:`logical_xor` methods expect their arguments to be *logical
793operands*. A *logical operand* is a :class:`Decimal` instance whose
794exponent and sign are both zero, and whose digits are all either
795:const:`0` or :const:`1`.
796
Georg Brandl116aa622007-08-15 14:28:22 +0000797.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
798
799
800.. _decimal-context:
801
802Context objects
803---------------
804
805Contexts are environments for arithmetic operations. They govern precision, set
806rules for rounding, determine which signals are treated as exceptions, and limit
807the range for exponents.
808
809Each thread has its own current context which is accessed or changed using the
810:func:`getcontext` and :func:`setcontext` functions:
811
812
813.. function:: getcontext()
814
815 Return the current context for the active thread.
816
817
818.. function:: setcontext(c)
819
820 Set the current context for the active thread to *c*.
821
822Beginning with Python 2.5, you can also use the :keyword:`with` statement and
823the :func:`localcontext` function to temporarily change the active context.
824
825
826.. function:: localcontext([c])
827
828 Return a context manager that will set the current context for the active thread
829 to a copy of *c* on entry to the with-statement and restore the previous context
830 when exiting the with-statement. If no context is specified, a copy of the
831 current context is used.
832
Georg Brandl116aa622007-08-15 14:28:22 +0000833 For example, the following code sets the current decimal precision to 42 places,
834 performs a calculation, and then automatically restores the previous context::
835
836 from __future__ import with_statement
837 from decimal import localcontext
838
839 with localcontext() as ctx:
840 ctx.prec = 42 # Perform a high precision calculation
841 s = calculate_something()
842 s = +s # Round the final result back to the default precision
843
844New contexts can also be created using the :class:`Context` constructor
845described below. In addition, the module provides three pre-made contexts:
846
847
848.. class:: BasicContext
849
850 This is a standard context defined by the General Decimal Arithmetic
851 Specification. Precision is set to nine. Rounding is set to
852 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
853 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
854 :const:`Subnormal`.
855
856 Because many of the traps are enabled, this context is useful for debugging.
857
858
859.. class:: ExtendedContext
860
861 This is a standard context defined by the General Decimal Arithmetic
862 Specification. Precision is set to nine. Rounding is set to
863 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
864 exceptions are not raised during computations).
865
866 Because the trapped are disabled, this context is useful for applications that
867 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
868 raising exceptions. This allows an application to complete a run in the
869 presence of conditions that would otherwise halt the program.
870
871
872.. class:: DefaultContext
873
874 This context is used by the :class:`Context` constructor as a prototype for new
875 contexts. Changing a field (such a precision) has the effect of changing the
876 default for new contexts creating by the :class:`Context` constructor.
877
878 This context is most useful in multi-threaded environments. Changing one of the
879 fields before threads are started has the effect of setting system-wide
880 defaults. Changing the fields after threads have started is not recommended as
881 it would require thread synchronization to prevent race conditions.
882
883 In single threaded environments, it is preferable to not use this context at
884 all. Instead, simply create contexts explicitly as described below.
885
886 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
887 for Overflow, InvalidOperation, and DivisionByZero.
888
889In addition to the three supplied contexts, new contexts can be created with the
890:class:`Context` constructor.
891
892
893.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
894
895 Creates a new context. If a field is not specified or is :const:`None`, the
896 default values are copied from the :const:`DefaultContext`. If the *flags*
897 field is not specified or is :const:`None`, all flags are cleared.
898
899 The *prec* field is a positive integer that sets the precision for arithmetic
900 operations in the context.
901
902 The *rounding* option is one of:
903
904 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
905 * :const:`ROUND_DOWN` (towards zero),
906 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
907 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
908 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
909 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
910 * :const:`ROUND_UP` (away from zero).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
912 would have been 0 or 5; otherwise towards zero)
Georg Brandl116aa622007-08-15 14:28:22 +0000913
914 The *traps* and *flags* fields list any signals to be set. Generally, new
915 contexts should only set traps and leave the flags clear.
916
917 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
918 for exponents.
919
920 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
921 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
922 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
923
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000924 .. versionchanged:: 2.6
925 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000926
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000927The :class:`Context` class defines several general purpose methods as
928well as a large number of methods for doing arithmetic directly in a
929given context. In addition, for each of the :class:`Decimal` methods
930described above (with the exception of the :meth:`adjusted` and
931:meth:`as_tuple` methods) there is a corresponding :class:`Context`
932method. For example, ``C.exp(x)`` is equivalent to
933``x.exp(context=C)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000934
935.. method:: Context.clear_flags()
936
937 Resets all of the flags to :const:`0`.
938
939
940.. method:: Context.copy()
941
942 Return a duplicate of the context.
943
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000944.. method:: Context.copy_decimal(num)
945
946 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +0000947
948.. method:: Context.create_decimal(num)
949
950 Creates a new Decimal instance from *num* but using *self* as context. Unlike
951 the :class:`Decimal` constructor, the context precision, rounding method, flags,
952 and traps are applied to the conversion.
953
954 This is useful because constants are often given to a greater precision than is
955 needed by the application. Another benefit is that rounding immediately
956 eliminates unintended effects from digits beyond the current precision. In the
957 following example, using unrounded inputs means that adding zero to a sum can
958 change the result::
959
960 >>> getcontext().prec = 3
961 >>> Decimal("3.4445") + Decimal("1.0023")
962 Decimal("4.45")
963 >>> Decimal("3.4445") + Decimal(0) + Decimal("1.0023")
964 Decimal("4.44")
965
966
967.. method:: Context.Etiny()
968
969 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
970 for subnormal results. When underflow occurs, the exponent is set to
971 :const:`Etiny`.
972
973
974.. method:: Context.Etop()
975
976 Returns a value equal to ``Emax - prec + 1``.
977
978The usual approach to working with decimals is to create :class:`Decimal`
979instances and then apply arithmetic operations which take place within the
980current context for the active thread. An alternate approach is to use context
981methods for calculating within a specific context. The methods are similar to
982those for the :class:`Decimal` class and are only briefly recounted here.
983
984
985.. method:: Context.abs(x)
986
987 Returns the absolute value of *x*.
988
989
990.. method:: Context.add(x, y)
991
992 Return the sum of *x* and *y*.
993
994
Georg Brandl116aa622007-08-15 14:28:22 +0000995.. method:: Context.divide(x, y)
996
997 Return *x* divided by *y*.
998
999
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000.. method:: Context.divide_int(x, y)
1001
1002 Return *x* divided by *y*, truncated to an integer.
1003
1004
Georg Brandl116aa622007-08-15 14:28:22 +00001005.. method:: Context.divmod(x, y)
1006
1007 Divides two numbers and returns the integer part of the result.
1008
1009
Georg Brandl116aa622007-08-15 14:28:22 +00001010.. method:: Context.minus(x)
1011
1012 Minus corresponds to the unary prefix minus operator in Python.
1013
1014
1015.. method:: Context.multiply(x, y)
1016
1017 Return the product of *x* and *y*.
1018
1019
Georg Brandl116aa622007-08-15 14:28:22 +00001020.. method:: Context.plus(x)
1021
1022 Plus corresponds to the unary prefix plus operator in Python. This operation
1023 applies the context precision and rounding, so it is *not* an identity
1024 operation.
1025
1026
1027.. method:: Context.power(x, y[, modulo])
1028
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001029 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if
1030 given.
Georg Brandl116aa622007-08-15 14:28:22 +00001031
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001032 With two arguments, compute ``x**y``. If ``x`` is negative then
1033 ``y`` must be integral. The result will be inexact unless ``y`` is
1034 integral and the result is finite and can be expressed exactly in
1035 'precision' digits. The result should always be correctly rounded,
1036 using the rounding mode of the current thread's context.
Georg Brandl116aa622007-08-15 14:28:22 +00001037
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001038 With three arguments, compute ``(x**y) % modulo``. For the three
1039 argument form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +00001040
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001041 - all three arguments must be integral
1042 - ``y`` must be nonnegative
1043 - at least one of ``x`` or ``y`` must be nonzero
1044 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +00001045
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001046 The result of ``Context.power(x, y, modulo)`` is identical to
1047 the result that would be obtained by computing ``(x**y) %
1048 modulo`` with unbounded precision, but is computed more
1049 efficiently. It is always exact.
Georg Brandl116aa622007-08-15 14:28:22 +00001050
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001051 .. versionchanged:: 2.6
1052 ``y`` may now be nonintegral in ``x**y``.
1053 Stricter requirements for the three-argument version.
Georg Brandl116aa622007-08-15 14:28:22 +00001054
1055
1056.. method:: Context.remainder(x, y)
1057
1058 Returns the remainder from integer division.
1059
1060 The sign of the result, if non-zero, is the same as that of the original
1061 dividend.
1062
Georg Brandl116aa622007-08-15 14:28:22 +00001063.. method:: Context.subtract(x, y)
1064
1065 Return the difference between *x* and *y*.
1066
Georg Brandl116aa622007-08-15 14:28:22 +00001067.. method:: Context.to_sci_string(x)
1068
1069 Converts a number to a string using scientific notation.
1070
1071.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1072
1073
1074.. _decimal-signals:
1075
1076Signals
1077-------
1078
1079Signals represent conditions that arise during computation. Each corresponds to
1080one context flag and one context trap enabler.
1081
1082The context flag is incremented whenever the condition is encountered. After the
1083computation, flags may be checked for informational purposes (for instance, to
1084determine whether a computation was exact). After checking the flags, be sure to
1085clear all flags before starting the next computation.
1086
1087If the context's trap enabler is set for the signal, then the condition causes a
1088Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1089is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1090condition.
1091
1092
1093.. class:: Clamped
1094
1095 Altered an exponent to fit representation constraints.
1096
1097 Typically, clamping occurs when an exponent falls outside the context's
1098 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001099 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001100
1101
1102.. class:: DecimalException
1103
1104 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1105
1106
1107.. class:: DivisionByZero
1108
1109 Signals the division of a non-infinite number by zero.
1110
1111 Can occur with division, modulo division, or when raising a number to a negative
1112 power. If this signal is not trapped, returns :const:`Infinity` or
1113 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1114
1115
1116.. class:: Inexact
1117
1118 Indicates that rounding occurred and the result is not exact.
1119
1120 Signals when non-zero digits were discarded during rounding. The rounded result
1121 is returned. The signal flag or trap is used to detect when results are
1122 inexact.
1123
1124
1125.. class:: InvalidOperation
1126
1127 An invalid operation was performed.
1128
1129 Indicates that an operation was requested that does not make sense. If not
1130 trapped, returns :const:`NaN`. Possible causes include::
1131
1132 Infinity - Infinity
1133 0 * Infinity
1134 Infinity / Infinity
1135 x % 0
1136 Infinity % x
1137 x._rescale( non-integer )
1138 sqrt(-x) and x > 0
1139 0 ** 0
1140 x ** (non-integer)
1141 x ** Infinity
1142
1143
1144.. class:: Overflow
1145
1146 Numerical overflow.
1147
1148 Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
1149 If not trapped, the result depends on the rounding mode, either pulling inward
1150 to the largest representable finite number or rounding outward to
1151 :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are
1152 also signaled.
1153
1154
1155.. class:: Rounded
1156
1157 Rounding occurred though possibly no information was lost.
1158
1159 Signaled whenever rounding discards digits; even if those digits are zero (such
1160 as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result
1161 unchanged. This signal is used to detect loss of significant digits.
1162
1163
1164.. class:: Subnormal
1165
1166 Exponent was lower than :attr:`Emin` prior to rounding.
1167
1168 Occurs when an operation result is subnormal (the exponent is too small). If not
1169 trapped, returns the result unchanged.
1170
1171
1172.. class:: Underflow
1173
1174 Numerical underflow with result rounded to zero.
1175
1176 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1177 and :class:`Subnormal` are also signaled.
1178
1179The following table summarizes the hierarchy of signals::
1180
1181 exceptions.ArithmeticError(exceptions.Exception)
1182 DecimalException
1183 Clamped
1184 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1185 Inexact
1186 Overflow(Inexact, Rounded)
1187 Underflow(Inexact, Rounded, Subnormal)
1188 InvalidOperation
1189 Rounded
1190 Subnormal
1191
1192.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1193
1194
1195.. _decimal-notes:
1196
1197Floating Point Notes
1198--------------------
1199
1200
1201Mitigating round-off error with increased precision
1202^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1203
1204The use of decimal floating point eliminates decimal representation error
1205(making it possible to represent :const:`0.1` exactly); however, some operations
1206can still incur round-off error when non-zero digits exceed the fixed precision.
1207
1208The effects of round-off error can be amplified by the addition or subtraction
1209of nearly offsetting quantities resulting in loss of significance. Knuth
1210provides two instructive examples where rounded floating point arithmetic with
1211insufficient precision causes the breakdown of the associative and distributive
1212properties of addition::
1213
1214 # Examples from Seminumerical Algorithms, Section 4.2.2.
1215 >>> from decimal import Decimal, getcontext
1216 >>> getcontext().prec = 8
1217
1218 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1219 >>> (u + v) + w
1220 Decimal("9.5111111")
1221 >>> u + (v + w)
1222 Decimal("10")
1223
1224 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1225 >>> (u*v) + (u*w)
1226 Decimal("0.01")
1227 >>> u * (v+w)
1228 Decimal("0.0060000")
1229
1230The :mod:`decimal` module makes it possible to restore the identities by
1231expanding the precision sufficiently to avoid loss of significance::
1232
1233 >>> getcontext().prec = 20
1234 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1235 >>> (u + v) + w
1236 Decimal("9.51111111")
1237 >>> u + (v + w)
1238 Decimal("9.51111111")
1239 >>>
1240 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1241 >>> (u*v) + (u*w)
1242 Decimal("0.0060000")
1243 >>> u * (v+w)
1244 Decimal("0.0060000")
1245
1246
1247Special values
1248^^^^^^^^^^^^^^
1249
1250The number system for the :mod:`decimal` module provides special values
1251including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001252and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001253
1254Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1255they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1256not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1257can result from rounding beyond the limits of the largest representable number.
1258
1259The infinities are signed (affine) and can be used in arithmetic operations
1260where they get treated as very large, indeterminate numbers. For instance,
1261adding a constant to infinity gives another infinite result.
1262
1263Some operations are indeterminate and return :const:`NaN`, or if the
1264:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1265``0/0`` returns :const:`NaN` which means "not a number". This variety of
1266:const:`NaN` is quiet and, once created, will flow through other computations
1267always resulting in another :const:`NaN`. This behavior can be useful for a
1268series of computations that occasionally have missing inputs --- it allows the
1269calculation to proceed while flagging specific results as invalid.
1270
1271A variant is :const:`sNaN` which signals rather than remaining quiet after every
1272operation. This is a useful return value when an invalid result needs to
1273interrupt a calculation for special handling.
1274
1275The signed zeros can result from calculations that underflow. They keep the sign
1276that would have resulted if the calculation had been carried out to greater
1277precision. Since their magnitude is zero, both positive and negative zeros are
1278treated as equal and their sign is informational.
1279
1280In addition to the two signed zeros which are distinct yet equal, there are
1281various representations of zero with differing precisions yet equivalent in
1282value. This takes a bit of getting used to. For an eye accustomed to
1283normalized floating point representations, it is not immediately obvious that
1284the following calculation returns a value equal to zero::
1285
1286 >>> 1 / Decimal('Infinity')
1287 Decimal("0E-1000000026")
1288
1289.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1290
1291
1292.. _decimal-threads:
1293
1294Working with threads
1295--------------------
1296
1297The :func:`getcontext` function accesses a different :class:`Context` object for
1298each thread. Having separate thread contexts means that threads may make
1299changes (such as ``getcontext.prec=10``) without interfering with other threads.
1300
1301Likewise, the :func:`setcontext` function automatically assigns its target to
1302the current thread.
1303
1304If :func:`setcontext` has not been called before :func:`getcontext`, then
1305:func:`getcontext` will automatically create a new context for use in the
1306current thread.
1307
1308The new context is copied from a prototype context called *DefaultContext*. To
1309control the defaults so that each thread will use the same values throughout the
1310application, directly modify the *DefaultContext* object. This should be done
1311*before* any threads are started so that there won't be a race condition between
1312threads calling :func:`getcontext`. For example::
1313
1314 # Set applicationwide defaults for all threads about to be launched
1315 DefaultContext.prec = 12
1316 DefaultContext.rounding = ROUND_DOWN
1317 DefaultContext.traps = ExtendedContext.traps.copy()
1318 DefaultContext.traps[InvalidOperation] = 1
1319 setcontext(DefaultContext)
1320
1321 # Afterwards, the threads can be started
1322 t1.start()
1323 t2.start()
1324 t3.start()
1325 . . .
1326
1327.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1328
1329
1330.. _decimal-recipes:
1331
1332Recipes
1333-------
1334
1335Here are a few recipes that serve as utility functions and that demonstrate ways
1336to work with the :class:`Decimal` class::
1337
1338 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1339 pos='', neg='-', trailneg=''):
1340 """Convert Decimal to a money formatted string.
1341
1342 places: required number of places after the decimal point
1343 curr: optional currency symbol before the sign (may be blank)
1344 sep: optional grouping separator (comma, period, space, or blank)
1345 dp: decimal point indicator (comma or period)
1346 only specify as blank when places is zero
1347 pos: optional sign for positive numbers: '+', space or blank
1348 neg: optional sign for negative numbers: '-', '(', space or blank
1349 trailneg:optional trailing minus indicator: '-', ')', space or blank
1350
1351 >>> d = Decimal('-1234567.8901')
1352 >>> moneyfmt(d, curr='$')
1353 '-$1,234,567.89'
1354 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1355 '1.234.568-'
1356 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1357 '($1,234,567.89)'
1358 >>> moneyfmt(Decimal(123456789), sep=' ')
1359 '123 456 789.00'
1360 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1361 '<.02>'
1362
1363 """
1364 q = Decimal((0, (1,), -places)) # 2 places --> '0.01'
1365 sign, digits, exp = value.quantize(q).as_tuple()
1366 assert exp == -places
1367 result = []
1368 digits = map(str, digits)
1369 build, next = result.append, digits.pop
1370 if sign:
1371 build(trailneg)
1372 for i in range(places):
1373 if digits:
1374 build(next())
1375 else:
1376 build('0')
1377 build(dp)
1378 i = 0
1379 while digits:
1380 build(next())
1381 i += 1
1382 if i == 3 and digits:
1383 i = 0
1384 build(sep)
1385 build(curr)
1386 if sign:
1387 build(neg)
1388 else:
1389 build(pos)
1390 result.reverse()
1391 return ''.join(result)
1392
1393 def pi():
1394 """Compute Pi to the current precision.
1395
Georg Brandl6911e3c2007-09-04 07:15:32 +00001396 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001397 3.141592653589793238462643383
1398
1399 """
1400 getcontext().prec += 2 # extra digits for intermediate steps
1401 three = Decimal(3) # substitute "three=3.0" for regular floats
1402 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1403 while s != lasts:
1404 lasts = s
1405 n, na = n+na, na+8
1406 d, da = d+da, da+32
1407 t = (t * n) / d
1408 s += t
1409 getcontext().prec -= 2
1410 return +s # unary plus applies the new precision
1411
1412 def exp(x):
1413 """Return e raised to the power of x. Result type matches input type.
1414
Georg Brandl6911e3c2007-09-04 07:15:32 +00001415 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001416 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001417 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001418 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001419 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001420 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001421 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001422 (7.38905609893+0j)
1423
1424 """
1425 getcontext().prec += 2
1426 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1427 while s != lasts:
1428 lasts = s
1429 i += 1
1430 fact *= i
1431 num *= x
1432 s += num / fact
1433 getcontext().prec -= 2
1434 return +s
1435
1436 def cos(x):
1437 """Return the cosine of x as measured in radians.
1438
Georg Brandl6911e3c2007-09-04 07:15:32 +00001439 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001440 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001441 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001442 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001443 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001444 (0.87758256189+0j)
1445
1446 """
1447 getcontext().prec += 2
1448 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1449 while s != lasts:
1450 lasts = s
1451 i += 2
1452 fact *= i * (i-1)
1453 num *= x * x
1454 sign *= -1
1455 s += num / fact * sign
1456 getcontext().prec -= 2
1457 return +s
1458
1459 def sin(x):
1460 """Return the sine of x as measured in radians.
1461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001462 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001463 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001464 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001465 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001466 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001467 (0.479425538604+0j)
1468
1469 """
1470 getcontext().prec += 2
1471 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1472 while s != lasts:
1473 lasts = s
1474 i += 2
1475 fact *= i * (i-1)
1476 num *= x * x
1477 sign *= -1
1478 s += num / fact * sign
1479 getcontext().prec -= 2
1480 return +s
1481
1482
1483.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1484
1485
1486.. _decimal-faq:
1487
1488Decimal FAQ
1489-----------
1490
1491Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1492minimize typing when using the interactive interpreter?
1493
1494\A. Some users abbreviate the constructor to just a single letter::
1495
1496 >>> D = decimal.Decimal
1497 >>> D('1.23') + D('3.45')
1498 Decimal("4.68")
1499
1500Q. In a fixed-point application with two decimal places, some inputs have many
1501places and need to be rounded. Others are not supposed to have excess digits
1502and need to be validated. What methods should be used?
1503
1504A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
1505the :const:`Inexact` trap is set, it is also useful for validation::
1506
1507 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1508
1509 >>> # Round to two places
1510 >>> Decimal("3.214").quantize(TWOPLACES)
1511 Decimal("3.21")
1512
1513 >>> # Validate that a number does not exceed two places
1514 >>> Decimal("3.21").quantize(TWOPLACES, context=Context(traps=[Inexact]))
1515 Decimal("3.21")
1516
1517 >>> Decimal("3.214").quantize(TWOPLACES, context=Context(traps=[Inexact]))
1518 Traceback (most recent call last):
1519 ...
1520 Inexact: Changed in rounding
1521
1522Q. Once I have valid two place inputs, how do I maintain that invariant
1523throughout an application?
1524
1525A. Some operations like addition and subtraction automatically preserve fixed
1526point. Others, like multiplication and division, change the number of decimal
1527places and need to be followed-up with a :meth:`quantize` step.
1528
1529Q. There are many ways to express the same value. The numbers :const:`200`,
1530:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1531various precisions. Is there a way to transform them to a single recognizable
1532canonical value?
1533
1534A. The :meth:`normalize` method maps all equivalent values to a single
1535representative::
1536
1537 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1538 >>> [v.normalize() for v in values]
1539 [Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2")]
1540
1541Q. Some decimal values always print with exponential notation. Is there a way
1542to get a non-exponential representation?
1543
1544A. For some values, exponential notation is the only way to express the number
1545of significant places in the coefficient. For example, expressing
1546:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1547original's two-place significance.
1548
1549Q. Is there a way to convert a regular float to a :class:`Decimal`?
1550
1551A. Yes, all binary floating point numbers can be exactly expressed as a
1552Decimal. An exact conversion may take more precision than intuition would
1553suggest, so trapping :const:`Inexact` will signal a need for more precision::
1554
1555 def floatToDecimal(f):
1556 "Convert a floating point number to a Decimal with no loss of information"
1557 # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an
1558 # exponent. Double the mantissa until it is an integer. Use the integer
1559 # mantissa and exponent to compute an equivalent Decimal. If this cannot
1560 # be done exactly, then retry with more precision.
1561
1562 mantissa, exponent = math.frexp(f)
1563 while mantissa != int(mantissa):
1564 mantissa *= 2.0
1565 exponent -= 1
1566 mantissa = int(mantissa)
1567
1568 oldcontext = getcontext()
1569 setcontext(Context(traps=[Inexact]))
1570 try:
1571 while True:
1572 try:
1573 return mantissa * Decimal(2) ** exponent
1574 except Inexact:
1575 getcontext().prec += 1
1576 finally:
1577 setcontext(oldcontext)
1578
1579Q. Why isn't the :func:`floatToDecimal` routine included in the module?
1580
1581A. There is some question about whether it is advisable to mix binary and
1582decimal floating point. Also, its use requires some care to avoid the
1583representation issues associated with binary floating point::
1584
1585 >>> floatToDecimal(1.1)
1586 Decimal("1.100000000000000088817841970012523233890533447265625")
1587
1588Q. Within a complex calculation, how can I make sure that I haven't gotten a
1589spurious result because of insufficient precision or rounding anomalies.
1590
1591A. The decimal module makes it easy to test results. A best practice is to
1592re-run calculations using greater precision and with various rounding modes.
1593Widely differing results indicate insufficient precision, rounding mode issues,
1594ill-conditioned inputs, or a numerically unstable algorithm.
1595
1596Q. I noticed that context precision is applied to the results of operations but
1597not to the inputs. Is there anything to watch out for when mixing values of
1598different precisions?
1599
1600A. Yes. The principle is that all values are considered to be exact and so is
1601the arithmetic on those values. Only the results are rounded. The advantage
1602for inputs is that "what you type is what you get". A disadvantage is that the
1603results can look odd if you forget that the inputs haven't been rounded::
1604
1605 >>> getcontext().prec = 3
1606 >>> Decimal('3.104') + D('2.104')
1607 Decimal("5.21")
1608 >>> Decimal('3.104') + D('0.000') + D('2.104')
1609 Decimal("5.20")
1610
1611The solution is either to increase precision or to force rounding of inputs
1612using the unary plus operation::
1613
1614 >>> getcontext().prec = 3
1615 >>> +Decimal('1.23456789') # unary plus triggers rounding
1616 Decimal("1.23")
1617
1618Alternatively, inputs can be rounded upon creation using the
1619:meth:`Context.create_decimal` method::
1620
1621 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
1622 Decimal("1.2345")
1623