blob: d8942f823e30e75ec847e0c1f31d0f8a025f19f8 [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
Georg Brandlb19be572007-12-29 10:57:00 +000096.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +000097
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")
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000131 >>> Decimal(2) ** Decimal("0.5")
132 Decimal("1.414213562373095048801688724")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000133 >>> Decimal("NaN")
134 Decimal("NaN")
135 >>> Decimal("-Infinity")
136 Decimal("-Infinity")
137
138The significance of a new Decimal is determined solely by the number of digits
139input. Context precision and rounding only come into play during arithmetic
140operations. ::
141
142 >>> getcontext().prec = 6
143 >>> Decimal('3.0')
144 Decimal("3.0")
145 >>> Decimal('3.1415926535')
146 Decimal("3.1415926535")
147 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
148 Decimal("5.85987")
149 >>> getcontext().rounding = ROUND_UP
150 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
151 Decimal("5.85988")
152
153Decimals interact well with much of the rest of Python. Here is a small decimal
154floating point flying circus::
155
156 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
157 >>> max(data)
158 Decimal("9.25")
159 >>> min(data)
160 Decimal("0.03")
161 >>> sorted(data)
162 [Decimal("0.03"), Decimal("1.00"), Decimal("1.34"), Decimal("1.87"),
163 Decimal("2.35"), Decimal("3.45"), Decimal("9.25")]
164 >>> sum(data)
165 Decimal("19.29")
166 >>> a,b,c = data[:3]
167 >>> str(a)
168 '1.34'
169 >>> float(a)
170 1.3400000000000001
171 >>> round(a, 1) # round() first converts to binary floating point
172 1.3
173 >>> int(a)
174 1
175 >>> a * 5
176 Decimal("6.70")
177 >>> a * b
178 Decimal("2.5058")
179 >>> c % a
180 Decimal("0.77")
181
Andrew M. Kuchling6d407e42007-09-24 23:46:28 +0000182And some mathematical functions are also available to Decimal::
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000183
184 >>> Decimal(2).sqrt()
185 Decimal("1.414213562373095048801688724")
186 >>> Decimal(1).exp()
187 Decimal("2.718281828459045235360287471")
188 >>> Decimal("10").ln()
189 Decimal("2.302585092994045684017991455")
190 >>> Decimal("10").log10()
191 Decimal("1")
192
Georg Brandl8ec7f652007-08-15 14:28:01 +0000193The :meth:`quantize` method rounds a number to a fixed exponent. This method is
194useful for monetary applications that often round results to a fixed number of
195places::
196
197 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
198 Decimal("7.32")
199 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
200 Decimal("8")
201
202As shown above, the :func:`getcontext` function accesses the current context and
203allows the settings to be changed. This approach meets the needs of most
204applications.
205
206For more advanced work, it may be useful to create alternate contexts using the
207Context() constructor. To make an alternate active, use the :func:`setcontext`
208function.
209
210In accordance with the standard, the :mod:`Decimal` module provides two ready to
211use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
212former is especially useful for debugging because many of the traps are
213enabled::
214
215 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
216 >>> setcontext(myothercontext)
217 >>> Decimal(1) / Decimal(7)
218 Decimal("0.142857142857142857142857142857142857142857142857142857142857")
219
220 >>> ExtendedContext
221 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
222 capitals=1, flags=[], traps=[])
223 >>> setcontext(ExtendedContext)
224 >>> Decimal(1) / Decimal(7)
225 Decimal("0.142857143")
226 >>> Decimal(42) / Decimal(0)
227 Decimal("Infinity")
228
229 >>> setcontext(BasicContext)
230 >>> Decimal(42) / Decimal(0)
231 Traceback (most recent call last):
232 File "<pyshell#143>", line 1, in -toplevel-
233 Decimal(42) / Decimal(0)
234 DivisionByZero: x / 0
235
236Contexts also have signal flags for monitoring exceptional conditions
237encountered during computations. The flags remain set until explicitly cleared,
238so it is best to clear the flags before each set of monitored computations by
239using the :meth:`clear_flags` method. ::
240
241 >>> setcontext(ExtendedContext)
242 >>> getcontext().clear_flags()
243 >>> Decimal(355) / Decimal(113)
244 Decimal("3.14159292")
245 >>> getcontext()
246 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
247 capitals=1, flags=[Inexact, Rounded], traps=[])
248
249The *flags* entry shows that the rational approximation to :const:`Pi` was
250rounded (digits beyond the context precision were thrown away) and that the
251result is inexact (some of the discarded digits were non-zero).
252
253Individual traps are set using the dictionary in the :attr:`traps` field of a
254context::
255
256 >>> Decimal(1) / Decimal(0)
257 Decimal("Infinity")
258 >>> getcontext().traps[DivisionByZero] = 1
259 >>> Decimal(1) / Decimal(0)
260 Traceback (most recent call last):
261 File "<pyshell#112>", line 1, in -toplevel-
262 Decimal(1) / Decimal(0)
263 DivisionByZero: x / 0
264
265Most programs adjust the current context only once, at the beginning of the
266program. And, in many applications, data is converted to :class:`Decimal` with
267a single cast inside a loop. With context set and decimals created, the bulk of
268the program manipulates the data no differently than with other Python numeric
269types.
270
Georg Brandlb19be572007-12-29 10:57:00 +0000271.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000272
273
274.. _decimal-decimal:
275
276Decimal objects
277---------------
278
279
280.. class:: Decimal([value [, context]])
281
Georg Brandlb19be572007-12-29 10:57:00 +0000282 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283
284 *value* can be an integer, string, tuple, or another :class:`Decimal` object. If
285 no *value* is given, returns ``Decimal("0")``. If *value* is a string, it
286 should conform to the decimal numeric string syntax::
287
288 sign ::= '+' | '-'
289 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
290 indicator ::= 'e' | 'E'
291 digits ::= digit [digit]...
292 decimal-part ::= digits '.' [digits] | ['.'] digits
293 exponent-part ::= indicator [sign] digits
294 infinity ::= 'Infinity' | 'Inf'
295 nan ::= 'NaN' [digits] | 'sNaN' [digits]
296 numeric-value ::= decimal-part [exponent-part] | infinity
297 numeric-string ::= [sign] numeric-value | [sign] nan
298
299 If *value* is a :class:`tuple`, it should have three components, a sign
300 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
301 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
302 returns ``Decimal("1.414")``.
303
304 The *context* precision does not affect how many digits are stored. That is
305 determined exclusively by the number of digits in *value*. For example,
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000306 ``Decimal("3.00000")`` records all five zeros even if the context precision is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000307 only three.
308
309 The purpose of the *context* argument is determining what to do if *value* is a
310 malformed string. If the context traps :const:`InvalidOperation`, an exception
311 is raised; otherwise, the constructor returns a new Decimal with the value of
312 :const:`NaN`.
313
314 Once constructed, :class:`Decimal` objects are immutable.
315
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000316Decimal floating point objects share many properties with the other built-in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000317numeric types such as :class:`float` and :class:`int`. All of the usual math
318operations and special methods apply. Likewise, decimal objects can be copied,
319pickled, printed, used as dictionary keys, used as set elements, compared,
320sorted, and coerced to another type (such as :class:`float` or :class:`long`).
321
322In addition to the standard numeric properties, decimal floating point objects
323also have a number of specialized methods:
324
325
326.. method:: Decimal.adjusted()
327
328 Return the adjusted exponent after shifting out the coefficient's rightmost
329 digits until only the lead digit remains: ``Decimal("321e+5").adjusted()``
330 returns seven. Used for determining the position of the most significant digit
331 with respect to the decimal point.
332
333
334.. method:: Decimal.as_tuple()
335
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000336 Return a tuple representation of the number: ``(sign, digit_tuple, exponent)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000337
338
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000339.. method:: Decimal.canonical()
340
341 Return the canonical encoding of the argument. Currently, the
342 encoding of a :class:`Decimal` instance is always canonical, so
343 this operation returns its argument unchanged.
344
345 .. versionadded:: 2.6
346
Georg Brandl8ec7f652007-08-15 14:28:01 +0000347.. method:: Decimal.compare(other[, context])
348
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000349 Compare the values of two Decimal instances. This operation
350 behaves in the same way as the usual comparison method
351 :meth:`__cmp__`, except that :meth:`compare` returns a Decimal
352 instance rather than an integer, and if either operand is a NaN
353 then the result is a NaN::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000354
355 a or b is a NaN ==> Decimal("NaN")
356 a < b ==> Decimal("-1")
357 a == b ==> Decimal("0")
358 a > b ==> Decimal("1")
359
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000360.. method:: Decimal.compare_signal(other[, context])
361
362 This operation is identical to the :meth:`compare` method, except
363 that all NaNs signal. That is, if neither operand is a signaling
364 NaN then any quiet NaN operand is treated as though it were a
365 signaling NaN.
366
367 .. versionadded:: 2.6
368
369.. method:: Decimal.compare_total(other)
370
371 Compare two operands using their abstract representation rather
372 than their numerical value. Similar to the :meth:`compare` method,
373 but the result gives a total ordering on :class:`Decimal`
374 instances. Two :class:`Decimal` instances with the same numeric
375 value but different representations compare unequal in this
376 ordering::
377
378 >>> Decimal("12.0").compare_total(Decimal("12"))
379 Decimal("-1")
380
381 Quiet and signaling NaNs are also included in the total ordering.
382 The result of this function is ``Decimal("0")`` if both operands
383 have the same representation, ``Decimal("-1")`` if the first
384 operand is lower in the total order than the second, and
385 ``Decimal("1")`` if the first operand is higher in the total order
386 than the second operand. See the specification for details of the
387 total order.
388
389 .. versionadded:: 2.6
390
391.. method:: Decimal.compare_total_mag(other)
392
393 Compare two operands using their abstract representation rather
394 than their value as in :meth:`compare_total`, but ignoring the sign
395 of each operand. ``x.compare_total_mag(y)`` is equivalent to
396 ``x.copy_abs().compare_total(y.copy_abs())``.
397
398 .. versionadded:: 2.6
399
400.. method:: Decimal.copy_abs()
401
402 Return the absolute value of the argument. This operation is
403 unaffected by the context and is quiet: no flags are changed and no
404 rounding is performed.
405
406 .. versionadded:: 2.6
407
408.. method:: Decimal.copy_negate()
409
410 Return the negation of the argument. This operation is unaffected
411 by the context and is quiet: no flags are changed and no rounding
412 is performed.
413
414 .. versionadded:: 2.6
415
416.. method:: Decimal.copy_sign(other)
417
418 Return a copy of the first operand with the sign set to be the
419 same as the sign of the second operand. For example::
420
421 >>> Decimal("2.3").copy_sign(Decimal("-1.5"))
422 Decimal("-2.3")
423
424 This operation is unaffected by the context and is quiet: no flags
425 are changed and no rounding is performed.
426
427 .. versionadded:: 2.6
428
429.. method:: Decimal.exp([context])
430
431 Return the value of the (natural) exponential function ``e**x`` at the
432 given number. The result is correctly rounded using the
433 :const:`ROUND_HALF_EVEN` rounding mode.
434
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000435 >>> Decimal(1).exp()
436 Decimal("2.718281828459045235360287471")
437 >>> Decimal(321).exp()
438 Decimal("2.561702493119680037517373933E+139")
439
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000440 .. versionadded:: 2.6
441
442.. method:: Decimal.fma(other, third[, context])
443
444 Fused multiply-add. Return self*other+third with no rounding of
445 the intermediate product self*other.
446
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000447 >>> Decimal(2).fma(3, 5)
448 Decimal("11")
449
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000450 .. versionadded:: 2.6
451
452.. method:: Decimal.is_canonical()
453
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000454 Return :const:`True` if the argument is canonical and
455 :const:`False` otherwise. Currently, a :class:`Decimal` instance
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000456 is always canonical, so this operation always returns
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000457 :const:`True`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000458
459 .. versionadded:: 2.6
460
461.. method:: is_finite()
462
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000463 Return :const:`True` if the argument is a finite number, and
464 :const:`False` if the argument is an infinity or a NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000465
466 .. versionadded:: 2.6
467
468.. method:: is_infinite()
469
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000470 Return :const:`True` if the argument is either positive or
471 negative infinity and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000472
473 .. versionadded:: 2.6
474
475.. method:: is_nan()
476
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000477 Return :const:`True` if the argument is a (quiet or signaling)
478 NaN and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000479
480 .. versionadded:: 2.6
481
482.. method:: is_normal()
483
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000484 Return :const:`True` if the argument is a *normal* finite number.
485 Return :const:`False` if the argument is zero, subnormal, infinite
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000486 or a NaN.
487
488 .. versionadded:: 2.6
489
490.. method:: is_qnan()
491
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000492 Return :const:`True` if the argument is a quiet NaN, and
493 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000494
495 .. versionadded:: 2.6
496
497.. method:: is_signed()
498
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000499 Return :const:`True` if the argument has a negative sign and
500 :const:`False` otherwise. Note that zeros and NaNs can both carry
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000501 signs.
502
503 .. versionadded:: 2.6
504
505.. method:: is_snan()
506
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000507 Return :const:`True` if the argument is a signaling NaN and
508 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000509
510 .. versionadded:: 2.6
511
512.. method:: is_subnormal()
513
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000514 Return :const:`True` if the argument is subnormal, and
515 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000516
517 .. versionadded:: 2.6
518
519.. method:: is_zero()
520
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000521 Return :const:`True` if the argument is a (positive or negative)
522 zero and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000523
524 .. versionadded:: 2.6
525
526.. method:: Decimal.ln([context])
527
528 Return the natural (base e) logarithm of the operand. The result
529 is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
530 mode.
531
532 .. versionadded:: 2.6
533
534.. method:: Decimal.log10([context])
535
536 Return the base ten logarithm of the operand. The result is
537 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
538
539 .. versionadded:: 2.6
540
Georg Brandlb19be572007-12-29 10:57:00 +0000541.. method:: Decimal.logb([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000542
543 For a nonzero number, return the adjusted exponent of its operand
544 as a :class:`Decimal` instance. If the operand is a zero then
545 ``Decimal("-Infinity")`` is returned and the
546 :const:`DivisionByZero` flag is raised. If the operand is an
547 infinity then ``Decimal("Infinity")`` is returned.
548
549 .. versionadded:: 2.6
550
551.. method:: Decimal.logical_and(other[, context])
552
553 :meth:`logical_and` is a logical operation which takes two
554 *logical operands* (see :ref:`logical_operands_label`). The result
555 is the digit-wise ``and`` of the two operands.
556
557 .. versionadded:: 2.6
558
559.. method:: Decimal.logical_invert(other[, context])
560
561 :meth:`logical_invert` is a logical operation. The argument must
562 be a *logical operand* (see :ref:`logical_operands_label`). The
563 result is the digit-wise inversion of the operand.
564
565 .. versionadded:: 2.6
566
567.. method:: Decimal.logical_or(other[, context])
568
569 :meth:`logical_or` is a logical operation which takes two *logical
570 operands* (see :ref:`logical_operands_label`). The result is the
571 digit-wise ``or`` of the two operands.
572
573 .. versionadded:: 2.6
574
575.. method:: Decimal.logical_xor(other[, context])
576
577 :meth:`logical_xor` is a logical operation which takes two
578 *logical operands* (see :ref:`logical_operands_label`). The result
579 is the digit-wise exclusive or of the two operands.
580
581 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000582
583.. method:: Decimal.max(other[, context])
584
585 Like ``max(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000586 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000587 (depending on the context and whether they are signaling or quiet).
588
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000589.. method:: Decimal.max_mag(other[, context])
590
591 Similar to the :meth:`max` method, but the comparison is done using
592 the absolute values of the operands.
593
594 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000595
596.. method:: Decimal.min(other[, context])
597
598 Like ``min(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000599 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000600 (depending on the context and whether they are signaling or quiet).
601
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000602.. method:: Decimal.min_mag(other[, context])
603
604 Similar to the :meth:`min` method, but the comparison is done using
605 the absolute values of the operands.
606
607 .. versionadded:: 2.6
608
609.. method:: Decimal.next_minus([context])
610
611 Return the largest number representable in the given context (or
612 in the current thread's context if no context is given) that is smaller
613 than the given operand.
614
615 .. versionadded:: 2.6
616
617.. method:: Decimal.next_plus([context])
618
619 Return the smallest number representable in the given context (or
620 in the current thread's context if no context is given) that is
621 larger than the given operand.
622
623 .. versionadded:: 2.6
624
625.. method:: Decimal.next_toward(other[, context])
626
627 If the two operands are unequal, return the number closest to the
628 first operand in the direction of the second operand. If both
629 operands are numerically equal, return a copy of the first operand
630 with the sign set to be the same as the sign of the second operand.
631
632 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000633
634.. method:: Decimal.normalize([context])
635
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000636 Normalize the number by stripping the rightmost trailing zeros and converting
Georg Brandl8ec7f652007-08-15 14:28:01 +0000637 any result equal to :const:`Decimal("0")` to :const:`Decimal("0e0")`. Used for
638 producing canonical values for members of an equivalence class. For example,
639 ``Decimal("32.100")`` and ``Decimal("0.321000e+2")`` both normalize to the
640 equivalent value ``Decimal("32.1")``.
641
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000642.. method:: Decimal.number_class([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000643
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000644 Return a string describing the *class* of the operand. The
645 returned value is one of the following ten strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000646
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000647 * ``"-Infinity"``, indicating that the operand is negative infinity.
648 * ``"-Normal"``, indicating that the operand is a negative normal number.
649 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
650 * ``"-Zero"``, indicating that the operand is a negative zero.
651 * ``"+Zero"``, indicating that the operand is a positive zero.
652 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
653 * ``"+Normal"``, indicating that the operand is a positive normal number.
654 * ``"+Infinity"``, indicating that the operand is positive infinity.
655 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
656 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000657
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000658 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000659
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000660.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]])
661
Georg Brandlb19be572007-12-29 10:57:00 +0000662 Return a value equal to the first operand after rounding and
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000663 having the exponent of the second operand.
664
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000665 >>> Decimal("1.41421356").quantize(Decimal("1.000"))
666 Decimal("1.414")
667
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000668 Unlike other operations, if the length of the coefficient after the
669 quantize operation would be greater than precision, then an
670 :const:`InvalidOperation` is signaled. This guarantees that, unless
671 there is an error condition, the quantized exponent is always equal
672 to that of the right-hand operand.
673
674 Also unlike other operations, quantize never signals Underflow,
675 even if the result is subnormal and inexact.
676
677 If the exponent of the second operand is larger than that of the
678 first then rounding may be necessary. In this case, the rounding
679 mode is determined by the ``rounding`` argument if given, else by
680 the given ``context`` argument; if neither argument is given the
681 rounding mode of the current thread's context is used.
682
Georg Brandlb19be572007-12-29 10:57:00 +0000683 If *watchexp* is set (default), then an error is returned whenever the
684 resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000685
686.. method:: Decimal.radix()
687
688 Return ``Decimal(10)``, the radix (base) in which the
689 :class:`Decimal` class does all its arithmetic. Included for
690 compatibility with the specification.
691
692 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000693
694.. method:: Decimal.remainder_near(other[, context])
695
Georg Brandlb19be572007-12-29 10:57:00 +0000696 Compute the modulo as either a positive or negative value depending on which is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000697 closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
698 ``Decimal("-2")`` which is closer to zero than ``Decimal("4")``.
699
700 If both are equally close, the one chosen will have the same sign as *self*.
701
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000702.. method:: Decimal.rotate(other[, context])
703
704 Return the result of rotating the digits of the first operand by
705 an amount specified by the second operand. The second operand
706 must be an integer in the range -precision through precision. The
707 absolute value of the second operand gives the number of places to
708 rotate. If the second operand is positive then rotation is to the
709 left; otherwise rotation is to the right. The coefficient of the
710 first operand is padded on the left with zeros to length precision
711 if necessary. The sign and exponent of the first operand are
712 unchanged.
713
714 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000715
716.. method:: Decimal.same_quantum(other[, context])
717
718 Test whether self and other have the same exponent or whether both are
719 :const:`NaN`.
720
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000721.. method:: Decimal.scaleb(other[, context])
722
723 Return the first operand with exponent adjusted by the second.
724 Equivalently, return the first operand multiplied by ``10**other``.
725 The second operand must be an integer.
726
727 .. versionadded:: 2.6
728
729.. method:: Decimal.shift(other[, context])
730
731 Return the result of shifting the digits of the first operand by
732 an amount specified by the second operand. The second operand must
733 be an integer in the range -precision through precision. The
734 absolute value of the second operand gives the number of places to
735 shift. If the second operand is positive then the shift is to the
736 left; otherwise the shift is to the right. Digits shifted into the
737 coefficient are zeros. The sign and exponent of the first operand
738 are unchanged.
739
740 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000741
742.. method:: Decimal.sqrt([context])
743
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000744 Return the square root of the argument to full precision.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000745
746
747.. method:: Decimal.to_eng_string([context])
748
749 Convert to an engineering-type string.
750
751 Engineering notation has an exponent which is a multiple of 3, so there are up
752 to 3 digits left of the decimal place. For example, converts
753 ``Decimal('123E+1')`` to ``Decimal("1.23E+3")``
754
Georg Brandl8ec7f652007-08-15 14:28:01 +0000755.. method:: Decimal.to_integral([rounding[, context]])
756
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000757 Identical to the :meth:`to_integral_value` method. The ``to_integral``
758 name has been kept for compatibility with older versions.
759
760.. method:: Decimal.to_integral_exact([rounding[, context]])
761
Georg Brandlb19be572007-12-29 10:57:00 +0000762 Round to the nearest integer, signaling
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000763 :const:`Inexact` or :const:`Rounded` as appropriate if rounding
764 occurs. The rounding mode is determined by the ``rounding``
765 parameter if given, else by the given ``context``. If neither
766 parameter is given then the rounding mode of the current context is
767 used.
768
769 .. versionadded:: 2.6
770
771.. method:: Decimal.to_integral_value([rounding[, context]])
772
Georg Brandlb19be572007-12-29 10:57:00 +0000773 Round to the nearest integer without signaling :const:`Inexact` or
Georg Brandl8ec7f652007-08-15 14:28:01 +0000774 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding
775 method in either the supplied *context* or the current context.
776
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000777 .. versionchanged:: 2.6
778 renamed from ``to_integral`` to ``to_integral_value``. The old name
779 remains valid for compatibility.
780
781.. method:: Decimal.trim()
782
Georg Brandlb19be572007-12-29 10:57:00 +0000783 Return the decimal with *insignificant* trailing zeros removed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000784 Here, a trailing zero is considered insignificant either if it
785 follows the decimal point, or if the exponent of the argument (that
786 is, the last element of the :meth:`as_tuple` representation) is
787 positive.
788
789 .. versionadded:: 2.6
790
791.. _logical_operands_label:
792
793Logical operands
794^^^^^^^^^^^^^^^^
795
796The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
797and :meth:`logical_xor` methods expect their arguments to be *logical
798operands*. A *logical operand* is a :class:`Decimal` instance whose
799exponent and sign are both zero, and whose digits are all either
800:const:`0` or :const:`1`.
801
Georg Brandlb19be572007-12-29 10:57:00 +0000802.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000803
804
805.. _decimal-context:
806
807Context objects
808---------------
809
810Contexts are environments for arithmetic operations. They govern precision, set
811rules for rounding, determine which signals are treated as exceptions, and limit
812the range for exponents.
813
814Each thread has its own current context which is accessed or changed using the
815:func:`getcontext` and :func:`setcontext` functions:
816
817
818.. function:: getcontext()
819
820 Return the current context for the active thread.
821
822
823.. function:: setcontext(c)
824
825 Set the current context for the active thread to *c*.
826
827Beginning with Python 2.5, you can also use the :keyword:`with` statement and
828the :func:`localcontext` function to temporarily change the active context.
829
830
831.. function:: localcontext([c])
832
833 Return a context manager that will set the current context for the active thread
834 to a copy of *c* on entry to the with-statement and restore the previous context
835 when exiting the with-statement. If no context is specified, a copy of the
836 current context is used.
837
838 .. versionadded:: 2.5
839
840 For example, the following code sets the current decimal precision to 42 places,
841 performs a calculation, and then automatically restores the previous context::
842
Georg Brandl8ec7f652007-08-15 14:28:01 +0000843 from decimal import localcontext
844
845 with localcontext() as ctx:
846 ctx.prec = 42 # Perform a high precision calculation
847 s = calculate_something()
848 s = +s # Round the final result back to the default precision
849
850New contexts can also be created using the :class:`Context` constructor
851described below. In addition, the module provides three pre-made contexts:
852
853
854.. class:: BasicContext
855
856 This is a standard context defined by the General Decimal Arithmetic
857 Specification. Precision is set to nine. Rounding is set to
858 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
859 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
860 :const:`Subnormal`.
861
862 Because many of the traps are enabled, this context is useful for debugging.
863
864
865.. class:: ExtendedContext
866
867 This is a standard context defined by the General Decimal Arithmetic
868 Specification. Precision is set to nine. Rounding is set to
869 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
870 exceptions are not raised during computations).
871
872 Because the trapped are disabled, this context is useful for applications that
873 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
874 raising exceptions. This allows an application to complete a run in the
875 presence of conditions that would otherwise halt the program.
876
877
878.. class:: DefaultContext
879
880 This context is used by the :class:`Context` constructor as a prototype for new
881 contexts. Changing a field (such a precision) has the effect of changing the
882 default for new contexts creating by the :class:`Context` constructor.
883
884 This context is most useful in multi-threaded environments. Changing one of the
885 fields before threads are started has the effect of setting system-wide
886 defaults. Changing the fields after threads have started is not recommended as
887 it would require thread synchronization to prevent race conditions.
888
889 In single threaded environments, it is preferable to not use this context at
890 all. Instead, simply create contexts explicitly as described below.
891
892 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
893 for Overflow, InvalidOperation, and DivisionByZero.
894
895In addition to the three supplied contexts, new contexts can be created with the
896:class:`Context` constructor.
897
898
899.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
900
901 Creates a new context. If a field is not specified or is :const:`None`, the
902 default values are copied from the :const:`DefaultContext`. If the *flags*
903 field is not specified or is :const:`None`, all flags are cleared.
904
905 The *prec* field is a positive integer that sets the precision for arithmetic
906 operations in the context.
907
908 The *rounding* option is one of:
909
910 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
911 * :const:`ROUND_DOWN` (towards zero),
912 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
913 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
914 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
915 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
916 * :const:`ROUND_UP` (away from zero).
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000917 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
918 would have been 0 or 5; otherwise towards zero)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000919
920 The *traps* and *flags* fields list any signals to be set. Generally, new
921 contexts should only set traps and leave the flags clear.
922
923 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
924 for exponents.
925
926 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
927 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
928 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
929
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000930 .. versionchanged:: 2.6
931 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000932
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000933The :class:`Context` class defines several general purpose methods as
934well as a large number of methods for doing arithmetic directly in a
935given context. In addition, for each of the :class:`Decimal` methods
936described above (with the exception of the :meth:`adjusted` and
937:meth:`as_tuple` methods) there is a corresponding :class:`Context`
938method. For example, ``C.exp(x)`` is equivalent to
939``x.exp(context=C)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000940
941.. method:: Context.clear_flags()
942
943 Resets all of the flags to :const:`0`.
944
945
946.. method:: Context.copy()
947
948 Return a duplicate of the context.
949
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000950.. method:: Context.copy_decimal(num)
951
952 Return a copy of the Decimal instance num.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000953
954.. method:: Context.create_decimal(num)
955
956 Creates a new Decimal instance from *num* but using *self* as context. Unlike
957 the :class:`Decimal` constructor, the context precision, rounding method, flags,
958 and traps are applied to the conversion.
959
960 This is useful because constants are often given to a greater precision than is
961 needed by the application. Another benefit is that rounding immediately
962 eliminates unintended effects from digits beyond the current precision. In the
963 following example, using unrounded inputs means that adding zero to a sum can
964 change the result::
965
966 >>> getcontext().prec = 3
967 >>> Decimal("3.4445") + Decimal("1.0023")
968 Decimal("4.45")
969 >>> Decimal("3.4445") + Decimal(0) + Decimal("1.0023")
970 Decimal("4.44")
971
972
973.. method:: Context.Etiny()
974
975 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
976 for subnormal results. When underflow occurs, the exponent is set to
977 :const:`Etiny`.
978
979
980.. method:: Context.Etop()
981
982 Returns a value equal to ``Emax - prec + 1``.
983
984The usual approach to working with decimals is to create :class:`Decimal`
985instances and then apply arithmetic operations which take place within the
Georg Brandl5d242ee2007-09-20 08:44:59 +0000986current context for the active thread. An alternative approach is to use context
Georg Brandl8ec7f652007-08-15 14:28:01 +0000987methods for calculating within a specific context. The methods are similar to
988those for the :class:`Decimal` class and are only briefly recounted here.
989
990
991.. method:: Context.abs(x)
992
993 Returns the absolute value of *x*.
994
995
996.. method:: Context.add(x, y)
997
998 Return the sum of *x* and *y*.
999
1000
Georg Brandl8ec7f652007-08-15 14:28:01 +00001001.. method:: Context.divide(x, y)
1002
1003 Return *x* divided by *y*.
1004
1005
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001006.. method:: Context.divide_int(x, y)
1007
1008 Return *x* divided by *y*, truncated to an integer.
1009
1010
Georg Brandl8ec7f652007-08-15 14:28:01 +00001011.. method:: Context.divmod(x, y)
1012
1013 Divides two numbers and returns the integer part of the result.
1014
1015
Georg Brandl8ec7f652007-08-15 14:28:01 +00001016.. method:: Context.minus(x)
1017
1018 Minus corresponds to the unary prefix minus operator in Python.
1019
1020
1021.. method:: Context.multiply(x, y)
1022
1023 Return the product of *x* and *y*.
1024
1025
Georg Brandl8ec7f652007-08-15 14:28:01 +00001026.. method:: Context.plus(x)
1027
1028 Plus corresponds to the unary prefix plus operator in Python. This operation
1029 applies the context precision and rounding, so it is *not* an identity
1030 operation.
1031
1032
1033.. method:: Context.power(x, y[, modulo])
1034
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001035 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if
1036 given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001037
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001038 With two arguments, compute ``x**y``. If ``x`` is negative then
1039 ``y`` must be integral. The result will be inexact unless ``y`` is
1040 integral and the result is finite and can be expressed exactly in
1041 'precision' digits. The result should always be correctly rounded,
1042 using the rounding mode of the current thread's context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001043
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001044 With three arguments, compute ``(x**y) % modulo``. For the three
1045 argument form, the following restrictions on the arguments hold:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001046
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001047 - all three arguments must be integral
1048 - ``y`` must be nonnegative
1049 - at least one of ``x`` or ``y`` must be nonzero
1050 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl8ec7f652007-08-15 14:28:01 +00001051
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001052 The result of ``Context.power(x, y, modulo)`` is identical to
1053 the result that would be obtained by computing ``(x**y) %
1054 modulo`` with unbounded precision, but is computed more
1055 efficiently. It is always exact.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001056
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001057 .. versionchanged:: 2.6
1058 ``y`` may now be nonintegral in ``x**y``.
1059 Stricter requirements for the three-argument version.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001060
1061
1062.. method:: Context.remainder(x, y)
1063
1064 Returns the remainder from integer division.
1065
1066 The sign of the result, if non-zero, is the same as that of the original
1067 dividend.
1068
Georg Brandl8ec7f652007-08-15 14:28:01 +00001069.. method:: Context.subtract(x, y)
1070
1071 Return the difference between *x* and *y*.
1072
Georg Brandl8ec7f652007-08-15 14:28:01 +00001073.. method:: Context.to_sci_string(x)
1074
1075 Converts a number to a string using scientific notation.
1076
Georg Brandlb19be572007-12-29 10:57:00 +00001077.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001078
1079
1080.. _decimal-signals:
1081
1082Signals
1083-------
1084
1085Signals represent conditions that arise during computation. Each corresponds to
1086one context flag and one context trap enabler.
1087
1088The context flag is incremented whenever the condition is encountered. After the
1089computation, flags may be checked for informational purposes (for instance, to
1090determine whether a computation was exact). After checking the flags, be sure to
1091clear all flags before starting the next computation.
1092
1093If the context's trap enabler is set for the signal, then the condition causes a
1094Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1095is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1096condition.
1097
1098
1099.. class:: Clamped
1100
1101 Altered an exponent to fit representation constraints.
1102
1103 Typically, clamping occurs when an exponent falls outside the context's
1104 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001105 fit by adding zeros to the coefficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001106
1107
1108.. class:: DecimalException
1109
1110 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1111
1112
1113.. class:: DivisionByZero
1114
1115 Signals the division of a non-infinite number by zero.
1116
1117 Can occur with division, modulo division, or when raising a number to a negative
1118 power. If this signal is not trapped, returns :const:`Infinity` or
1119 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1120
1121
1122.. class:: Inexact
1123
1124 Indicates that rounding occurred and the result is not exact.
1125
1126 Signals when non-zero digits were discarded during rounding. The rounded result
1127 is returned. The signal flag or trap is used to detect when results are
1128 inexact.
1129
1130
1131.. class:: InvalidOperation
1132
1133 An invalid operation was performed.
1134
1135 Indicates that an operation was requested that does not make sense. If not
1136 trapped, returns :const:`NaN`. Possible causes include::
1137
1138 Infinity - Infinity
1139 0 * Infinity
1140 Infinity / Infinity
1141 x % 0
1142 Infinity % x
1143 x._rescale( non-integer )
1144 sqrt(-x) and x > 0
1145 0 ** 0
1146 x ** (non-integer)
1147 x ** Infinity
1148
1149
1150.. class:: Overflow
1151
1152 Numerical overflow.
1153
1154 Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
1155 If not trapped, the result depends on the rounding mode, either pulling inward
1156 to the largest representable finite number or rounding outward to
1157 :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are
1158 also signaled.
1159
1160
1161.. class:: Rounded
1162
1163 Rounding occurred though possibly no information was lost.
1164
1165 Signaled whenever rounding discards digits; even if those digits are zero (such
1166 as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result
1167 unchanged. This signal is used to detect loss of significant digits.
1168
1169
1170.. class:: Subnormal
1171
1172 Exponent was lower than :attr:`Emin` prior to rounding.
1173
1174 Occurs when an operation result is subnormal (the exponent is too small). If not
1175 trapped, returns the result unchanged.
1176
1177
1178.. class:: Underflow
1179
1180 Numerical underflow with result rounded to zero.
1181
1182 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1183 and :class:`Subnormal` are also signaled.
1184
1185The following table summarizes the hierarchy of signals::
1186
1187 exceptions.ArithmeticError(exceptions.StandardError)
1188 DecimalException
1189 Clamped
1190 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1191 Inexact
1192 Overflow(Inexact, Rounded)
1193 Underflow(Inexact, Rounded, Subnormal)
1194 InvalidOperation
1195 Rounded
1196 Subnormal
1197
Georg Brandlb19be572007-12-29 10:57:00 +00001198.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001199
1200
1201.. _decimal-notes:
1202
1203Floating Point Notes
1204--------------------
1205
1206
1207Mitigating round-off error with increased precision
1208^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1209
1210The use of decimal floating point eliminates decimal representation error
1211(making it possible to represent :const:`0.1` exactly); however, some operations
1212can still incur round-off error when non-zero digits exceed the fixed precision.
1213
1214The effects of round-off error can be amplified by the addition or subtraction
1215of nearly offsetting quantities resulting in loss of significance. Knuth
1216provides two instructive examples where rounded floating point arithmetic with
1217insufficient precision causes the breakdown of the associative and distributive
1218properties of addition::
1219
1220 # Examples from Seminumerical Algorithms, Section 4.2.2.
1221 >>> from decimal import Decimal, getcontext
1222 >>> getcontext().prec = 8
1223
1224 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1225 >>> (u + v) + w
1226 Decimal("9.5111111")
1227 >>> u + (v + w)
1228 Decimal("10")
1229
1230 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1231 >>> (u*v) + (u*w)
1232 Decimal("0.01")
1233 >>> u * (v+w)
1234 Decimal("0.0060000")
1235
1236The :mod:`decimal` module makes it possible to restore the identities by
1237expanding the precision sufficiently to avoid loss of significance::
1238
1239 >>> getcontext().prec = 20
1240 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1241 >>> (u + v) + w
1242 Decimal("9.51111111")
1243 >>> u + (v + w)
1244 Decimal("9.51111111")
1245 >>>
1246 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1247 >>> (u*v) + (u*w)
1248 Decimal("0.0060000")
1249 >>> u * (v+w)
1250 Decimal("0.0060000")
1251
1252
1253Special values
1254^^^^^^^^^^^^^^
1255
1256The number system for the :mod:`decimal` module provides special values
1257including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001258and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001259
1260Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1261they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1262not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1263can result from rounding beyond the limits of the largest representable number.
1264
1265The infinities are signed (affine) and can be used in arithmetic operations
1266where they get treated as very large, indeterminate numbers. For instance,
1267adding a constant to infinity gives another infinite result.
1268
1269Some operations are indeterminate and return :const:`NaN`, or if the
1270:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1271``0/0`` returns :const:`NaN` which means "not a number". This variety of
1272:const:`NaN` is quiet and, once created, will flow through other computations
1273always resulting in another :const:`NaN`. This behavior can be useful for a
1274series of computations that occasionally have missing inputs --- it allows the
1275calculation to proceed while flagging specific results as invalid.
1276
1277A variant is :const:`sNaN` which signals rather than remaining quiet after every
1278operation. This is a useful return value when an invalid result needs to
1279interrupt a calculation for special handling.
1280
1281The signed zeros can result from calculations that underflow. They keep the sign
1282that would have resulted if the calculation had been carried out to greater
1283precision. Since their magnitude is zero, both positive and negative zeros are
1284treated as equal and their sign is informational.
1285
1286In addition to the two signed zeros which are distinct yet equal, there are
1287various representations of zero with differing precisions yet equivalent in
1288value. This takes a bit of getting used to. For an eye accustomed to
1289normalized floating point representations, it is not immediately obvious that
1290the following calculation returns a value equal to zero::
1291
1292 >>> 1 / Decimal('Infinity')
1293 Decimal("0E-1000000026")
1294
Georg Brandlb19be572007-12-29 10:57:00 +00001295.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001296
1297
1298.. _decimal-threads:
1299
1300Working with threads
1301--------------------
1302
1303The :func:`getcontext` function accesses a different :class:`Context` object for
1304each thread. Having separate thread contexts means that threads may make
1305changes (such as ``getcontext.prec=10``) without interfering with other threads.
1306
1307Likewise, the :func:`setcontext` function automatically assigns its target to
1308the current thread.
1309
1310If :func:`setcontext` has not been called before :func:`getcontext`, then
1311:func:`getcontext` will automatically create a new context for use in the
1312current thread.
1313
1314The new context is copied from a prototype context called *DefaultContext*. To
1315control the defaults so that each thread will use the same values throughout the
1316application, directly modify the *DefaultContext* object. This should be done
1317*before* any threads are started so that there won't be a race condition between
1318threads calling :func:`getcontext`. For example::
1319
1320 # Set applicationwide defaults for all threads about to be launched
1321 DefaultContext.prec = 12
1322 DefaultContext.rounding = ROUND_DOWN
1323 DefaultContext.traps = ExtendedContext.traps.copy()
1324 DefaultContext.traps[InvalidOperation] = 1
1325 setcontext(DefaultContext)
1326
1327 # Afterwards, the threads can be started
1328 t1.start()
1329 t2.start()
1330 t3.start()
1331 . . .
1332
Georg Brandlb19be572007-12-29 10:57:00 +00001333.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001334
1335
1336.. _decimal-recipes:
1337
1338Recipes
1339-------
1340
1341Here are a few recipes that serve as utility functions and that demonstrate ways
1342to work with the :class:`Decimal` class::
1343
1344 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1345 pos='', neg='-', trailneg=''):
1346 """Convert Decimal to a money formatted string.
1347
1348 places: required number of places after the decimal point
1349 curr: optional currency symbol before the sign (may be blank)
1350 sep: optional grouping separator (comma, period, space, or blank)
1351 dp: decimal point indicator (comma or period)
1352 only specify as blank when places is zero
1353 pos: optional sign for positive numbers: '+', space or blank
1354 neg: optional sign for negative numbers: '-', '(', space or blank
1355 trailneg:optional trailing minus indicator: '-', ')', space or blank
1356
1357 >>> d = Decimal('-1234567.8901')
1358 >>> moneyfmt(d, curr='$')
1359 '-$1,234,567.89'
1360 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1361 '1.234.568-'
1362 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1363 '($1,234,567.89)'
1364 >>> moneyfmt(Decimal(123456789), sep=' ')
1365 '123 456 789.00'
1366 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1367 '<.02>'
1368
1369 """
1370 q = Decimal((0, (1,), -places)) # 2 places --> '0.01'
1371 sign, digits, exp = value.quantize(q).as_tuple()
1372 assert exp == -places
1373 result = []
1374 digits = map(str, digits)
1375 build, next = result.append, digits.pop
1376 if sign:
1377 build(trailneg)
1378 for i in range(places):
1379 if digits:
1380 build(next())
1381 else:
1382 build('0')
1383 build(dp)
1384 i = 0
1385 while digits:
1386 build(next())
1387 i += 1
1388 if i == 3 and digits:
1389 i = 0
1390 build(sep)
1391 build(curr)
1392 if sign:
1393 build(neg)
1394 else:
1395 build(pos)
1396 result.reverse()
1397 return ''.join(result)
1398
1399 def pi():
1400 """Compute Pi to the current precision.
1401
1402 >>> print pi()
1403 3.141592653589793238462643383
1404
1405 """
1406 getcontext().prec += 2 # extra digits for intermediate steps
1407 three = Decimal(3) # substitute "three=3.0" for regular floats
1408 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1409 while s != lasts:
1410 lasts = s
1411 n, na = n+na, na+8
1412 d, da = d+da, da+32
1413 t = (t * n) / d
1414 s += t
1415 getcontext().prec -= 2
1416 return +s # unary plus applies the new precision
1417
1418 def exp(x):
1419 """Return e raised to the power of x. Result type matches input type.
1420
1421 >>> print exp(Decimal(1))
1422 2.718281828459045235360287471
1423 >>> print exp(Decimal(2))
1424 7.389056098930650227230427461
1425 >>> print exp(2.0)
1426 7.38905609893
1427 >>> print exp(2+0j)
1428 (7.38905609893+0j)
1429
1430 """
1431 getcontext().prec += 2
1432 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1433 while s != lasts:
1434 lasts = s
1435 i += 1
1436 fact *= i
1437 num *= x
1438 s += num / fact
1439 getcontext().prec -= 2
1440 return +s
1441
1442 def cos(x):
1443 """Return the cosine of x as measured in radians.
1444
1445 >>> print cos(Decimal('0.5'))
1446 0.8775825618903727161162815826
1447 >>> print cos(0.5)
1448 0.87758256189
1449 >>> print cos(0.5+0j)
1450 (0.87758256189+0j)
1451
1452 """
1453 getcontext().prec += 2
1454 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1455 while s != lasts:
1456 lasts = s
1457 i += 2
1458 fact *= i * (i-1)
1459 num *= x * x
1460 sign *= -1
1461 s += num / fact * sign
1462 getcontext().prec -= 2
1463 return +s
1464
1465 def sin(x):
1466 """Return the sine of x as measured in radians.
1467
1468 >>> print sin(Decimal('0.5'))
1469 0.4794255386042030002732879352
1470 >>> print sin(0.5)
1471 0.479425538604
1472 >>> print sin(0.5+0j)
1473 (0.479425538604+0j)
1474
1475 """
1476 getcontext().prec += 2
1477 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1478 while s != lasts:
1479 lasts = s
1480 i += 2
1481 fact *= i * (i-1)
1482 num *= x * x
1483 sign *= -1
1484 s += num / fact * sign
1485 getcontext().prec -= 2
1486 return +s
1487
1488
Georg Brandlb19be572007-12-29 10:57:00 +00001489.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001490
1491
1492.. _decimal-faq:
1493
1494Decimal FAQ
1495-----------
1496
1497Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1498minimize typing when using the interactive interpreter?
1499
1500\A. Some users abbreviate the constructor to just a single letter::
1501
1502 >>> D = decimal.Decimal
1503 >>> D('1.23') + D('3.45')
1504 Decimal("4.68")
1505
1506Q. In a fixed-point application with two decimal places, some inputs have many
1507places and need to be rounded. Others are not supposed to have excess digits
1508and need to be validated. What methods should be used?
1509
1510A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
1511the :const:`Inexact` trap is set, it is also useful for validation::
1512
1513 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1514
1515 >>> # Round to two places
1516 >>> Decimal("3.214").quantize(TWOPLACES)
1517 Decimal("3.21")
1518
1519 >>> # Validate that a number does not exceed two places
1520 >>> Decimal("3.21").quantize(TWOPLACES, context=Context(traps=[Inexact]))
1521 Decimal("3.21")
1522
1523 >>> Decimal("3.214").quantize(TWOPLACES, context=Context(traps=[Inexact]))
1524 Traceback (most recent call last):
1525 ...
1526 Inexact: Changed in rounding
1527
1528Q. Once I have valid two place inputs, how do I maintain that invariant
1529throughout an application?
1530
1531A. Some operations like addition and subtraction automatically preserve fixed
1532point. Others, like multiplication and division, change the number of decimal
1533places and need to be followed-up with a :meth:`quantize` step.
1534
1535Q. There are many ways to express the same value. The numbers :const:`200`,
1536:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1537various precisions. Is there a way to transform them to a single recognizable
1538canonical value?
1539
1540A. The :meth:`normalize` method maps all equivalent values to a single
1541representative::
1542
1543 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1544 >>> [v.normalize() for v in values]
1545 [Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2")]
1546
1547Q. Some decimal values always print with exponential notation. Is there a way
1548to get a non-exponential representation?
1549
1550A. For some values, exponential notation is the only way to express the number
1551of significant places in the coefficient. For example, expressing
1552:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1553original's two-place significance.
1554
1555Q. Is there a way to convert a regular float to a :class:`Decimal`?
1556
1557A. Yes, all binary floating point numbers can be exactly expressed as a
1558Decimal. An exact conversion may take more precision than intuition would
1559suggest, so trapping :const:`Inexact` will signal a need for more precision::
1560
1561 def floatToDecimal(f):
1562 "Convert a floating point number to a Decimal with no loss of information"
1563 # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an
1564 # exponent. Double the mantissa until it is an integer. Use the integer
1565 # mantissa and exponent to compute an equivalent Decimal. If this cannot
1566 # be done exactly, then retry with more precision.
1567
1568 mantissa, exponent = math.frexp(f)
1569 while mantissa != int(mantissa):
1570 mantissa *= 2.0
1571 exponent -= 1
1572 mantissa = int(mantissa)
1573
1574 oldcontext = getcontext()
1575 setcontext(Context(traps=[Inexact]))
1576 try:
1577 while True:
1578 try:
1579 return mantissa * Decimal(2) ** exponent
1580 except Inexact:
1581 getcontext().prec += 1
1582 finally:
1583 setcontext(oldcontext)
1584
1585Q. Why isn't the :func:`floatToDecimal` routine included in the module?
1586
1587A. There is some question about whether it is advisable to mix binary and
1588decimal floating point. Also, its use requires some care to avoid the
1589representation issues associated with binary floating point::
1590
1591 >>> floatToDecimal(1.1)
1592 Decimal("1.100000000000000088817841970012523233890533447265625")
1593
1594Q. Within a complex calculation, how can I make sure that I haven't gotten a
1595spurious result because of insufficient precision or rounding anomalies.
1596
1597A. The decimal module makes it easy to test results. A best practice is to
1598re-run calculations using greater precision and with various rounding modes.
1599Widely differing results indicate insufficient precision, rounding mode issues,
1600ill-conditioned inputs, or a numerically unstable algorithm.
1601
1602Q. I noticed that context precision is applied to the results of operations but
1603not to the inputs. Is there anything to watch out for when mixing values of
1604different precisions?
1605
1606A. Yes. The principle is that all values are considered to be exact and so is
1607the arithmetic on those values. Only the results are rounded. The advantage
1608for inputs is that "what you type is what you get". A disadvantage is that the
1609results can look odd if you forget that the inputs haven't been rounded::
1610
1611 >>> getcontext().prec = 3
1612 >>> Decimal('3.104') + D('2.104')
1613 Decimal("5.21")
1614 >>> Decimal('3.104') + D('0.000') + D('2.104')
1615 Decimal("5.20")
1616
1617The solution is either to increase precision or to force rounding of inputs
1618using the unary plus operation::
1619
1620 >>> getcontext().prec = 3
1621 >>> +Decimal('1.23456789') # unary plus triggers rounding
1622 Decimal("1.23")
1623
1624Alternatively, inputs can be rounded upon creation using the
1625:meth:`Context.create_decimal` method::
1626
1627 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
1628 Decimal("1.2345")
1629