blob: eda09e47fb815482e011e5d007b7d432d7b003a6 [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
Georg Brandle3c3db52008-01-11 09:55:53 +0000336 Return a :term:`named tuple` representation of the number:
337 ``DecimalTuple(sign, digits, exponent)``.
338
339 .. versionchanged:: 2.6
340 Use a named tuple.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000341
342
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000343.. method:: Decimal.canonical()
344
345 Return the canonical encoding of the argument. Currently, the
346 encoding of a :class:`Decimal` instance is always canonical, so
347 this operation returns its argument unchanged.
348
349 .. versionadded:: 2.6
350
Georg Brandl8ec7f652007-08-15 14:28:01 +0000351.. method:: Decimal.compare(other[, context])
352
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000353 Compare the values of two Decimal instances. This operation
354 behaves in the same way as the usual comparison method
355 :meth:`__cmp__`, except that :meth:`compare` returns a Decimal
356 instance rather than an integer, and if either operand is a NaN
357 then the result is a NaN::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000358
359 a or b is a NaN ==> Decimal("NaN")
360 a < b ==> Decimal("-1")
361 a == b ==> Decimal("0")
362 a > b ==> Decimal("1")
363
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000364.. method:: Decimal.compare_signal(other[, context])
365
366 This operation is identical to the :meth:`compare` method, except
367 that all NaNs signal. That is, if neither operand is a signaling
368 NaN then any quiet NaN operand is treated as though it were a
369 signaling NaN.
370
371 .. versionadded:: 2.6
372
373.. method:: Decimal.compare_total(other)
374
375 Compare two operands using their abstract representation rather
376 than their numerical value. Similar to the :meth:`compare` method,
377 but the result gives a total ordering on :class:`Decimal`
378 instances. Two :class:`Decimal` instances with the same numeric
379 value but different representations compare unequal in this
380 ordering::
381
382 >>> Decimal("12.0").compare_total(Decimal("12"))
383 Decimal("-1")
384
385 Quiet and signaling NaNs are also included in the total ordering.
386 The result of this function is ``Decimal("0")`` if both operands
387 have the same representation, ``Decimal("-1")`` if the first
388 operand is lower in the total order than the second, and
389 ``Decimal("1")`` if the first operand is higher in the total order
390 than the second operand. See the specification for details of the
391 total order.
392
393 .. versionadded:: 2.6
394
395.. method:: Decimal.compare_total_mag(other)
396
397 Compare two operands using their abstract representation rather
398 than their value as in :meth:`compare_total`, but ignoring the sign
399 of each operand. ``x.compare_total_mag(y)`` is equivalent to
400 ``x.copy_abs().compare_total(y.copy_abs())``.
401
402 .. versionadded:: 2.6
403
404.. method:: Decimal.copy_abs()
405
406 Return the absolute value of the argument. This operation is
407 unaffected by the context and is quiet: no flags are changed and no
408 rounding is performed.
409
410 .. versionadded:: 2.6
411
412.. method:: Decimal.copy_negate()
413
414 Return the negation of the argument. This operation is unaffected
415 by the context and is quiet: no flags are changed and no rounding
416 is performed.
417
418 .. versionadded:: 2.6
419
420.. method:: Decimal.copy_sign(other)
421
422 Return a copy of the first operand with the sign set to be the
423 same as the sign of the second operand. For example::
424
425 >>> Decimal("2.3").copy_sign(Decimal("-1.5"))
426 Decimal("-2.3")
427
428 This operation is unaffected by the context and is quiet: no flags
429 are changed and no rounding is performed.
430
431 .. versionadded:: 2.6
432
433.. method:: Decimal.exp([context])
434
435 Return the value of the (natural) exponential function ``e**x`` at the
436 given number. The result is correctly rounded using the
437 :const:`ROUND_HALF_EVEN` rounding mode.
438
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000439 >>> Decimal(1).exp()
440 Decimal("2.718281828459045235360287471")
441 >>> Decimal(321).exp()
442 Decimal("2.561702493119680037517373933E+139")
443
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000444 .. versionadded:: 2.6
445
446.. method:: Decimal.fma(other, third[, context])
447
448 Fused multiply-add. Return self*other+third with no rounding of
449 the intermediate product self*other.
450
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000451 >>> Decimal(2).fma(3, 5)
452 Decimal("11")
453
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000454 .. versionadded:: 2.6
455
456.. method:: Decimal.is_canonical()
457
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000458 Return :const:`True` if the argument is canonical and
459 :const:`False` otherwise. Currently, a :class:`Decimal` instance
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000460 is always canonical, so this operation always returns
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000461 :const:`True`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000462
463 .. versionadded:: 2.6
464
465.. method:: is_finite()
466
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000467 Return :const:`True` if the argument is a finite number, and
468 :const:`False` if the argument is an infinity or a NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000469
470 .. versionadded:: 2.6
471
472.. method:: is_infinite()
473
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000474 Return :const:`True` if the argument is either positive or
475 negative infinity and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000476
477 .. versionadded:: 2.6
478
479.. method:: is_nan()
480
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000481 Return :const:`True` if the argument is a (quiet or signaling)
482 NaN and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000483
484 .. versionadded:: 2.6
485
486.. method:: is_normal()
487
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000488 Return :const:`True` if the argument is a *normal* finite number.
489 Return :const:`False` if the argument is zero, subnormal, infinite
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000490 or a NaN.
491
492 .. versionadded:: 2.6
493
494.. method:: is_qnan()
495
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000496 Return :const:`True` if the argument is a quiet NaN, and
497 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000498
499 .. versionadded:: 2.6
500
501.. method:: is_signed()
502
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000503 Return :const:`True` if the argument has a negative sign and
504 :const:`False` otherwise. Note that zeros and NaNs can both carry
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000505 signs.
506
507 .. versionadded:: 2.6
508
509.. method:: is_snan()
510
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000511 Return :const:`True` if the argument is a signaling NaN and
512 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000513
514 .. versionadded:: 2.6
515
516.. method:: is_subnormal()
517
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000518 Return :const:`True` if the argument is subnormal, and
519 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000520
521 .. versionadded:: 2.6
522
523.. method:: is_zero()
524
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000525 Return :const:`True` if the argument is a (positive or negative)
526 zero and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000527
528 .. versionadded:: 2.6
529
530.. method:: Decimal.ln([context])
531
532 Return the natural (base e) logarithm of the operand. The result
533 is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
534 mode.
535
536 .. versionadded:: 2.6
537
538.. method:: Decimal.log10([context])
539
540 Return the base ten logarithm of the operand. The result is
541 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
542
543 .. versionadded:: 2.6
544
Georg Brandlb19be572007-12-29 10:57:00 +0000545.. method:: Decimal.logb([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000546
547 For a nonzero number, return the adjusted exponent of its operand
548 as a :class:`Decimal` instance. If the operand is a zero then
549 ``Decimal("-Infinity")`` is returned and the
550 :const:`DivisionByZero` flag is raised. If the operand is an
551 infinity then ``Decimal("Infinity")`` is returned.
552
553 .. versionadded:: 2.6
554
555.. method:: Decimal.logical_and(other[, context])
556
557 :meth:`logical_and` is a logical operation which takes two
558 *logical operands* (see :ref:`logical_operands_label`). The result
559 is the digit-wise ``and`` of the two operands.
560
561 .. versionadded:: 2.6
562
563.. method:: Decimal.logical_invert(other[, context])
564
565 :meth:`logical_invert` is a logical operation. The argument must
566 be a *logical operand* (see :ref:`logical_operands_label`). The
567 result is the digit-wise inversion of the operand.
568
569 .. versionadded:: 2.6
570
571.. method:: Decimal.logical_or(other[, context])
572
573 :meth:`logical_or` is a logical operation which takes two *logical
574 operands* (see :ref:`logical_operands_label`). The result is the
575 digit-wise ``or`` of the two operands.
576
577 .. versionadded:: 2.6
578
579.. method:: Decimal.logical_xor(other[, context])
580
581 :meth:`logical_xor` is a logical operation which takes two
582 *logical operands* (see :ref:`logical_operands_label`). The result
583 is the digit-wise exclusive or of the two operands.
584
585 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000586
587.. method:: Decimal.max(other[, context])
588
589 Like ``max(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000590 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000591 (depending on the context and whether they are signaling or quiet).
592
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000593.. method:: Decimal.max_mag(other[, context])
594
595 Similar to the :meth:`max` method, but the comparison is done using
596 the absolute values of the operands.
597
598 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000599
600.. method:: Decimal.min(other[, context])
601
602 Like ``min(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000603 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000604 (depending on the context and whether they are signaling or quiet).
605
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000606.. method:: Decimal.min_mag(other[, context])
607
608 Similar to the :meth:`min` method, but the comparison is done using
609 the absolute values of the operands.
610
611 .. versionadded:: 2.6
612
613.. method:: Decimal.next_minus([context])
614
615 Return the largest number representable in the given context (or
616 in the current thread's context if no context is given) that is smaller
617 than the given operand.
618
619 .. versionadded:: 2.6
620
621.. method:: Decimal.next_plus([context])
622
623 Return the smallest number representable in the given context (or
624 in the current thread's context if no context is given) that is
625 larger than the given operand.
626
627 .. versionadded:: 2.6
628
629.. method:: Decimal.next_toward(other[, context])
630
631 If the two operands are unequal, return the number closest to the
632 first operand in the direction of the second operand. If both
633 operands are numerically equal, return a copy of the first operand
634 with the sign set to be the same as the sign of the second operand.
635
636 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000637
638.. method:: Decimal.normalize([context])
639
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000640 Normalize the number by stripping the rightmost trailing zeros and converting
Georg Brandl8ec7f652007-08-15 14:28:01 +0000641 any result equal to :const:`Decimal("0")` to :const:`Decimal("0e0")`. Used for
642 producing canonical values for members of an equivalence class. For example,
643 ``Decimal("32.100")`` and ``Decimal("0.321000e+2")`` both normalize to the
644 equivalent value ``Decimal("32.1")``.
645
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000646.. method:: Decimal.number_class([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000647
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000648 Return a string describing the *class* of the operand. The
649 returned value is one of the following ten strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000650
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000651 * ``"-Infinity"``, indicating that the operand is negative infinity.
652 * ``"-Normal"``, indicating that the operand is a negative normal number.
653 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
654 * ``"-Zero"``, indicating that the operand is a negative zero.
655 * ``"+Zero"``, indicating that the operand is a positive zero.
656 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
657 * ``"+Normal"``, indicating that the operand is a positive normal number.
658 * ``"+Infinity"``, indicating that the operand is positive infinity.
659 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
660 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000661
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000662 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000663
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000664.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]])
665
Georg Brandlb19be572007-12-29 10:57:00 +0000666 Return a value equal to the first operand after rounding and
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000667 having the exponent of the second operand.
668
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000669 >>> Decimal("1.41421356").quantize(Decimal("1.000"))
670 Decimal("1.414")
671
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000672 Unlike other operations, if the length of the coefficient after the
673 quantize operation would be greater than precision, then an
674 :const:`InvalidOperation` is signaled. This guarantees that, unless
675 there is an error condition, the quantized exponent is always equal
676 to that of the right-hand operand.
677
678 Also unlike other operations, quantize never signals Underflow,
679 even if the result is subnormal and inexact.
680
681 If the exponent of the second operand is larger than that of the
682 first then rounding may be necessary. In this case, the rounding
683 mode is determined by the ``rounding`` argument if given, else by
684 the given ``context`` argument; if neither argument is given the
685 rounding mode of the current thread's context is used.
686
Georg Brandlb19be572007-12-29 10:57:00 +0000687 If *watchexp* is set (default), then an error is returned whenever the
688 resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000689
690.. method:: Decimal.radix()
691
692 Return ``Decimal(10)``, the radix (base) in which the
693 :class:`Decimal` class does all its arithmetic. Included for
694 compatibility with the specification.
695
696 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000697
698.. method:: Decimal.remainder_near(other[, context])
699
Georg Brandlb19be572007-12-29 10:57:00 +0000700 Compute the modulo as either a positive or negative value depending on which is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000701 closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
702 ``Decimal("-2")`` which is closer to zero than ``Decimal("4")``.
703
704 If both are equally close, the one chosen will have the same sign as *self*.
705
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000706.. method:: Decimal.rotate(other[, context])
707
708 Return the result of rotating the digits of the first operand by
709 an amount specified by the second operand. The second operand
710 must be an integer in the range -precision through precision. The
711 absolute value of the second operand gives the number of places to
712 rotate. If the second operand is positive then rotation is to the
713 left; otherwise rotation is to the right. The coefficient of the
714 first operand is padded on the left with zeros to length precision
715 if necessary. The sign and exponent of the first operand are
716 unchanged.
717
718 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000719
720.. method:: Decimal.same_quantum(other[, context])
721
722 Test whether self and other have the same exponent or whether both are
723 :const:`NaN`.
724
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000725.. method:: Decimal.scaleb(other[, context])
726
727 Return the first operand with exponent adjusted by the second.
728 Equivalently, return the first operand multiplied by ``10**other``.
729 The second operand must be an integer.
730
731 .. versionadded:: 2.6
732
733.. method:: Decimal.shift(other[, context])
734
735 Return the result of shifting the digits of the first operand by
736 an amount specified by the second operand. The second operand must
737 be an integer in the range -precision through precision. The
738 absolute value of the second operand gives the number of places to
739 shift. If the second operand is positive then the shift is to the
740 left; otherwise the shift is to the right. Digits shifted into the
741 coefficient are zeros. The sign and exponent of the first operand
742 are unchanged.
743
744 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000745
746.. method:: Decimal.sqrt([context])
747
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000748 Return the square root of the argument to full precision.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000749
750
751.. method:: Decimal.to_eng_string([context])
752
753 Convert to an engineering-type string.
754
755 Engineering notation has an exponent which is a multiple of 3, so there are up
756 to 3 digits left of the decimal place. For example, converts
757 ``Decimal('123E+1')`` to ``Decimal("1.23E+3")``
758
Georg Brandl8ec7f652007-08-15 14:28:01 +0000759.. method:: Decimal.to_integral([rounding[, context]])
760
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000761 Identical to the :meth:`to_integral_value` method. The ``to_integral``
762 name has been kept for compatibility with older versions.
763
764.. method:: Decimal.to_integral_exact([rounding[, context]])
765
Georg Brandlb19be572007-12-29 10:57:00 +0000766 Round to the nearest integer, signaling
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000767 :const:`Inexact` or :const:`Rounded` as appropriate if rounding
768 occurs. The rounding mode is determined by the ``rounding``
769 parameter if given, else by the given ``context``. If neither
770 parameter is given then the rounding mode of the current context is
771 used.
772
773 .. versionadded:: 2.6
774
775.. method:: Decimal.to_integral_value([rounding[, context]])
776
Georg Brandlb19be572007-12-29 10:57:00 +0000777 Round to the nearest integer without signaling :const:`Inexact` or
Georg Brandl8ec7f652007-08-15 14:28:01 +0000778 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding
779 method in either the supplied *context* or the current context.
780
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000781 .. versionchanged:: 2.6
782 renamed from ``to_integral`` to ``to_integral_value``. The old name
783 remains valid for compatibility.
784
785.. method:: Decimal.trim()
786
Georg Brandlb19be572007-12-29 10:57:00 +0000787 Return the decimal with *insignificant* trailing zeros removed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000788 Here, a trailing zero is considered insignificant either if it
789 follows the decimal point, or if the exponent of the argument (that
790 is, the last element of the :meth:`as_tuple` representation) is
791 positive.
792
793 .. versionadded:: 2.6
794
795.. _logical_operands_label:
796
797Logical operands
798^^^^^^^^^^^^^^^^
799
800The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
801and :meth:`logical_xor` methods expect their arguments to be *logical
802operands*. A *logical operand* is a :class:`Decimal` instance whose
803exponent and sign are both zero, and whose digits are all either
804:const:`0` or :const:`1`.
805
Georg Brandlb19be572007-12-29 10:57:00 +0000806.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000807
808
809.. _decimal-context:
810
811Context objects
812---------------
813
814Contexts are environments for arithmetic operations. They govern precision, set
815rules for rounding, determine which signals are treated as exceptions, and limit
816the range for exponents.
817
818Each thread has its own current context which is accessed or changed using the
819:func:`getcontext` and :func:`setcontext` functions:
820
821
822.. function:: getcontext()
823
824 Return the current context for the active thread.
825
826
827.. function:: setcontext(c)
828
829 Set the current context for the active thread to *c*.
830
831Beginning with Python 2.5, you can also use the :keyword:`with` statement and
832the :func:`localcontext` function to temporarily change the active context.
833
834
835.. function:: localcontext([c])
836
837 Return a context manager that will set the current context for the active thread
838 to a copy of *c* on entry to the with-statement and restore the previous context
839 when exiting the with-statement. If no context is specified, a copy of the
840 current context is used.
841
842 .. versionadded:: 2.5
843
844 For example, the following code sets the current decimal precision to 42 places,
845 performs a calculation, and then automatically restores the previous context::
846
Georg Brandl8ec7f652007-08-15 14:28:01 +0000847 from decimal import localcontext
848
849 with localcontext() as ctx:
850 ctx.prec = 42 # Perform a high precision calculation
851 s = calculate_something()
852 s = +s # Round the final result back to the default precision
853
854New contexts can also be created using the :class:`Context` constructor
855described below. In addition, the module provides three pre-made contexts:
856
857
858.. class:: BasicContext
859
860 This is a standard context defined by the General Decimal Arithmetic
861 Specification. Precision is set to nine. Rounding is set to
862 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
863 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
864 :const:`Subnormal`.
865
866 Because many of the traps are enabled, this context is useful for debugging.
867
868
869.. class:: ExtendedContext
870
871 This is a standard context defined by the General Decimal Arithmetic
872 Specification. Precision is set to nine. Rounding is set to
873 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
874 exceptions are not raised during computations).
875
876 Because the trapped are disabled, this context is useful for applications that
877 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
878 raising exceptions. This allows an application to complete a run in the
879 presence of conditions that would otherwise halt the program.
880
881
882.. class:: DefaultContext
883
884 This context is used by the :class:`Context` constructor as a prototype for new
885 contexts. Changing a field (such a precision) has the effect of changing the
886 default for new contexts creating by the :class:`Context` constructor.
887
888 This context is most useful in multi-threaded environments. Changing one of the
889 fields before threads are started has the effect of setting system-wide
890 defaults. Changing the fields after threads have started is not recommended as
891 it would require thread synchronization to prevent race conditions.
892
893 In single threaded environments, it is preferable to not use this context at
894 all. Instead, simply create contexts explicitly as described below.
895
896 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
897 for Overflow, InvalidOperation, and DivisionByZero.
898
899In addition to the three supplied contexts, new contexts can be created with the
900:class:`Context` constructor.
901
902
903.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
904
905 Creates a new context. If a field is not specified or is :const:`None`, the
906 default values are copied from the :const:`DefaultContext`. If the *flags*
907 field is not specified or is :const:`None`, all flags are cleared.
908
909 The *prec* field is a positive integer that sets the precision for arithmetic
910 operations in the context.
911
912 The *rounding* option is one of:
913
914 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
915 * :const:`ROUND_DOWN` (towards zero),
916 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
917 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
918 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
919 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
920 * :const:`ROUND_UP` (away from zero).
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000921 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
922 would have been 0 or 5; otherwise towards zero)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000923
924 The *traps* and *flags* fields list any signals to be set. Generally, new
925 contexts should only set traps and leave the flags clear.
926
927 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
928 for exponents.
929
930 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
931 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
932 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
933
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000934 .. versionchanged:: 2.6
935 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000936
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000937The :class:`Context` class defines several general purpose methods as
938well as a large number of methods for doing arithmetic directly in a
939given context. In addition, for each of the :class:`Decimal` methods
940described above (with the exception of the :meth:`adjusted` and
941:meth:`as_tuple` methods) there is a corresponding :class:`Context`
942method. For example, ``C.exp(x)`` is equivalent to
943``x.exp(context=C)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000944
945.. method:: Context.clear_flags()
946
947 Resets all of the flags to :const:`0`.
948
949
950.. method:: Context.copy()
951
952 Return a duplicate of the context.
953
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000954.. method:: Context.copy_decimal(num)
955
956 Return a copy of the Decimal instance num.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000957
958.. method:: Context.create_decimal(num)
959
960 Creates a new Decimal instance from *num* but using *self* as context. Unlike
961 the :class:`Decimal` constructor, the context precision, rounding method, flags,
962 and traps are applied to the conversion.
963
964 This is useful because constants are often given to a greater precision than is
965 needed by the application. Another benefit is that rounding immediately
966 eliminates unintended effects from digits beyond the current precision. In the
967 following example, using unrounded inputs means that adding zero to a sum can
968 change the result::
969
970 >>> getcontext().prec = 3
971 >>> Decimal("3.4445") + Decimal("1.0023")
972 Decimal("4.45")
973 >>> Decimal("3.4445") + Decimal(0) + Decimal("1.0023")
974 Decimal("4.44")
975
976
977.. method:: Context.Etiny()
978
979 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
980 for subnormal results. When underflow occurs, the exponent is set to
981 :const:`Etiny`.
982
983
984.. method:: Context.Etop()
985
986 Returns a value equal to ``Emax - prec + 1``.
987
988The usual approach to working with decimals is to create :class:`Decimal`
989instances and then apply arithmetic operations which take place within the
Georg Brandl5d242ee2007-09-20 08:44:59 +0000990current context for the active thread. An alternative approach is to use context
Georg Brandl8ec7f652007-08-15 14:28:01 +0000991methods for calculating within a specific context. The methods are similar to
992those for the :class:`Decimal` class and are only briefly recounted here.
993
994
995.. method:: Context.abs(x)
996
997 Returns the absolute value of *x*.
998
999
1000.. method:: Context.add(x, y)
1001
1002 Return the sum of *x* and *y*.
1003
1004
Georg Brandl8ec7f652007-08-15 14:28:01 +00001005.. method:: Context.divide(x, y)
1006
1007 Return *x* divided by *y*.
1008
1009
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001010.. method:: Context.divide_int(x, y)
1011
1012 Return *x* divided by *y*, truncated to an integer.
1013
1014
Georg Brandl8ec7f652007-08-15 14:28:01 +00001015.. method:: Context.divmod(x, y)
1016
1017 Divides two numbers and returns the integer part of the result.
1018
1019
Georg Brandl8ec7f652007-08-15 14:28:01 +00001020.. method:: Context.minus(x)
1021
1022 Minus corresponds to the unary prefix minus operator in Python.
1023
1024
1025.. method:: Context.multiply(x, y)
1026
1027 Return the product of *x* and *y*.
1028
1029
Georg Brandl8ec7f652007-08-15 14:28:01 +00001030.. method:: Context.plus(x)
1031
1032 Plus corresponds to the unary prefix plus operator in Python. This operation
1033 applies the context precision and rounding, so it is *not* an identity
1034 operation.
1035
1036
1037.. method:: Context.power(x, y[, modulo])
1038
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001039 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if
1040 given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001041
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001042 With two arguments, compute ``x**y``. If ``x`` is negative then
1043 ``y`` must be integral. The result will be inexact unless ``y`` is
1044 integral and the result is finite and can be expressed exactly in
1045 'precision' digits. The result should always be correctly rounded,
1046 using the rounding mode of the current thread's context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001047
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001048 With three arguments, compute ``(x**y) % modulo``. For the three
1049 argument form, the following restrictions on the arguments hold:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001050
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001051 - all three arguments must be integral
1052 - ``y`` must be nonnegative
1053 - at least one of ``x`` or ``y`` must be nonzero
1054 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl8ec7f652007-08-15 14:28:01 +00001055
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001056 The result of ``Context.power(x, y, modulo)`` is identical to
1057 the result that would be obtained by computing ``(x**y) %
1058 modulo`` with unbounded precision, but is computed more
1059 efficiently. It is always exact.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001060
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001061 .. versionchanged:: 2.6
1062 ``y`` may now be nonintegral in ``x**y``.
1063 Stricter requirements for the three-argument version.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001064
1065
1066.. method:: Context.remainder(x, y)
1067
1068 Returns the remainder from integer division.
1069
1070 The sign of the result, if non-zero, is the same as that of the original
1071 dividend.
1072
Georg Brandl8ec7f652007-08-15 14:28:01 +00001073.. method:: Context.subtract(x, y)
1074
1075 Return the difference between *x* and *y*.
1076
Georg Brandl8ec7f652007-08-15 14:28:01 +00001077.. method:: Context.to_sci_string(x)
1078
1079 Converts a number to a string using scientific notation.
1080
Georg Brandlb19be572007-12-29 10:57:00 +00001081.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001082
1083
1084.. _decimal-signals:
1085
1086Signals
1087-------
1088
1089Signals represent conditions that arise during computation. Each corresponds to
1090one context flag and one context trap enabler.
1091
1092The context flag is incremented whenever the condition is encountered. After the
1093computation, flags may be checked for informational purposes (for instance, to
1094determine whether a computation was exact). After checking the flags, be sure to
1095clear all flags before starting the next computation.
1096
1097If the context's trap enabler is set for the signal, then the condition causes a
1098Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1099is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1100condition.
1101
1102
1103.. class:: Clamped
1104
1105 Altered an exponent to fit representation constraints.
1106
1107 Typically, clamping occurs when an exponent falls outside the context's
1108 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001109 fit by adding zeros to the coefficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001110
1111
1112.. class:: DecimalException
1113
1114 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1115
1116
1117.. class:: DivisionByZero
1118
1119 Signals the division of a non-infinite number by zero.
1120
1121 Can occur with division, modulo division, or when raising a number to a negative
1122 power. If this signal is not trapped, returns :const:`Infinity` or
1123 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1124
1125
1126.. class:: Inexact
1127
1128 Indicates that rounding occurred and the result is not exact.
1129
1130 Signals when non-zero digits were discarded during rounding. The rounded result
1131 is returned. The signal flag or trap is used to detect when results are
1132 inexact.
1133
1134
1135.. class:: InvalidOperation
1136
1137 An invalid operation was performed.
1138
1139 Indicates that an operation was requested that does not make sense. If not
1140 trapped, returns :const:`NaN`. Possible causes include::
1141
1142 Infinity - Infinity
1143 0 * Infinity
1144 Infinity / Infinity
1145 x % 0
1146 Infinity % x
1147 x._rescale( non-integer )
1148 sqrt(-x) and x > 0
1149 0 ** 0
1150 x ** (non-integer)
1151 x ** Infinity
1152
1153
1154.. class:: Overflow
1155
1156 Numerical overflow.
1157
1158 Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
1159 If not trapped, the result depends on the rounding mode, either pulling inward
1160 to the largest representable finite number or rounding outward to
1161 :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are
1162 also signaled.
1163
1164
1165.. class:: Rounded
1166
1167 Rounding occurred though possibly no information was lost.
1168
1169 Signaled whenever rounding discards digits; even if those digits are zero (such
1170 as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result
1171 unchanged. This signal is used to detect loss of significant digits.
1172
1173
1174.. class:: Subnormal
1175
1176 Exponent was lower than :attr:`Emin` prior to rounding.
1177
1178 Occurs when an operation result is subnormal (the exponent is too small). If not
1179 trapped, returns the result unchanged.
1180
1181
1182.. class:: Underflow
1183
1184 Numerical underflow with result rounded to zero.
1185
1186 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1187 and :class:`Subnormal` are also signaled.
1188
1189The following table summarizes the hierarchy of signals::
1190
1191 exceptions.ArithmeticError(exceptions.StandardError)
1192 DecimalException
1193 Clamped
1194 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1195 Inexact
1196 Overflow(Inexact, Rounded)
1197 Underflow(Inexact, Rounded, Subnormal)
1198 InvalidOperation
1199 Rounded
1200 Subnormal
1201
Georg Brandlb19be572007-12-29 10:57:00 +00001202.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001203
1204
1205.. _decimal-notes:
1206
1207Floating Point Notes
1208--------------------
1209
1210
1211Mitigating round-off error with increased precision
1212^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1213
1214The use of decimal floating point eliminates decimal representation error
1215(making it possible to represent :const:`0.1` exactly); however, some operations
1216can still incur round-off error when non-zero digits exceed the fixed precision.
1217
1218The effects of round-off error can be amplified by the addition or subtraction
1219of nearly offsetting quantities resulting in loss of significance. Knuth
1220provides two instructive examples where rounded floating point arithmetic with
1221insufficient precision causes the breakdown of the associative and distributive
1222properties of addition::
1223
1224 # Examples from Seminumerical Algorithms, Section 4.2.2.
1225 >>> from decimal import Decimal, getcontext
1226 >>> getcontext().prec = 8
1227
1228 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1229 >>> (u + v) + w
1230 Decimal("9.5111111")
1231 >>> u + (v + w)
1232 Decimal("10")
1233
1234 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1235 >>> (u*v) + (u*w)
1236 Decimal("0.01")
1237 >>> u * (v+w)
1238 Decimal("0.0060000")
1239
1240The :mod:`decimal` module makes it possible to restore the identities by
1241expanding the precision sufficiently to avoid loss of significance::
1242
1243 >>> getcontext().prec = 20
1244 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1245 >>> (u + v) + w
1246 Decimal("9.51111111")
1247 >>> u + (v + w)
1248 Decimal("9.51111111")
1249 >>>
1250 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1251 >>> (u*v) + (u*w)
1252 Decimal("0.0060000")
1253 >>> u * (v+w)
1254 Decimal("0.0060000")
1255
1256
1257Special values
1258^^^^^^^^^^^^^^
1259
1260The number system for the :mod:`decimal` module provides special values
1261including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001262and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001263
1264Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1265they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1266not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1267can result from rounding beyond the limits of the largest representable number.
1268
1269The infinities are signed (affine) and can be used in arithmetic operations
1270where they get treated as very large, indeterminate numbers. For instance,
1271adding a constant to infinity gives another infinite result.
1272
1273Some operations are indeterminate and return :const:`NaN`, or if the
1274:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1275``0/0`` returns :const:`NaN` which means "not a number". This variety of
1276:const:`NaN` is quiet and, once created, will flow through other computations
1277always resulting in another :const:`NaN`. This behavior can be useful for a
1278series of computations that occasionally have missing inputs --- it allows the
1279calculation to proceed while flagging specific results as invalid.
1280
1281A variant is :const:`sNaN` which signals rather than remaining quiet after every
1282operation. This is a useful return value when an invalid result needs to
1283interrupt a calculation for special handling.
1284
1285The signed zeros can result from calculations that underflow. They keep the sign
1286that would have resulted if the calculation had been carried out to greater
1287precision. Since their magnitude is zero, both positive and negative zeros are
1288treated as equal and their sign is informational.
1289
1290In addition to the two signed zeros which are distinct yet equal, there are
1291various representations of zero with differing precisions yet equivalent in
1292value. This takes a bit of getting used to. For an eye accustomed to
1293normalized floating point representations, it is not immediately obvious that
1294the following calculation returns a value equal to zero::
1295
1296 >>> 1 / Decimal('Infinity')
1297 Decimal("0E-1000000026")
1298
Georg Brandlb19be572007-12-29 10:57:00 +00001299.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001300
1301
1302.. _decimal-threads:
1303
1304Working with threads
1305--------------------
1306
1307The :func:`getcontext` function accesses a different :class:`Context` object for
1308each thread. Having separate thread contexts means that threads may make
1309changes (such as ``getcontext.prec=10``) without interfering with other threads.
1310
1311Likewise, the :func:`setcontext` function automatically assigns its target to
1312the current thread.
1313
1314If :func:`setcontext` has not been called before :func:`getcontext`, then
1315:func:`getcontext` will automatically create a new context for use in the
1316current thread.
1317
1318The new context is copied from a prototype context called *DefaultContext*. To
1319control the defaults so that each thread will use the same values throughout the
1320application, directly modify the *DefaultContext* object. This should be done
1321*before* any threads are started so that there won't be a race condition between
1322threads calling :func:`getcontext`. For example::
1323
1324 # Set applicationwide defaults for all threads about to be launched
1325 DefaultContext.prec = 12
1326 DefaultContext.rounding = ROUND_DOWN
1327 DefaultContext.traps = ExtendedContext.traps.copy()
1328 DefaultContext.traps[InvalidOperation] = 1
1329 setcontext(DefaultContext)
1330
1331 # Afterwards, the threads can be started
1332 t1.start()
1333 t2.start()
1334 t3.start()
1335 . . .
1336
Georg Brandlb19be572007-12-29 10:57:00 +00001337.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001338
1339
1340.. _decimal-recipes:
1341
1342Recipes
1343-------
1344
1345Here are a few recipes that serve as utility functions and that demonstrate ways
1346to work with the :class:`Decimal` class::
1347
1348 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1349 pos='', neg='-', trailneg=''):
1350 """Convert Decimal to a money formatted string.
1351
1352 places: required number of places after the decimal point
1353 curr: optional currency symbol before the sign (may be blank)
1354 sep: optional grouping separator (comma, period, space, or blank)
1355 dp: decimal point indicator (comma or period)
1356 only specify as blank when places is zero
1357 pos: optional sign for positive numbers: '+', space or blank
1358 neg: optional sign for negative numbers: '-', '(', space or blank
1359 trailneg:optional trailing minus indicator: '-', ')', space or blank
1360
1361 >>> d = Decimal('-1234567.8901')
1362 >>> moneyfmt(d, curr='$')
1363 '-$1,234,567.89'
1364 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1365 '1.234.568-'
1366 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1367 '($1,234,567.89)'
1368 >>> moneyfmt(Decimal(123456789), sep=' ')
1369 '123 456 789.00'
1370 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1371 '<.02>'
1372
1373 """
1374 q = Decimal((0, (1,), -places)) # 2 places --> '0.01'
1375 sign, digits, exp = value.quantize(q).as_tuple()
1376 assert exp == -places
1377 result = []
1378 digits = map(str, digits)
1379 build, next = result.append, digits.pop
1380 if sign:
1381 build(trailneg)
1382 for i in range(places):
1383 if digits:
1384 build(next())
1385 else:
1386 build('0')
1387 build(dp)
1388 i = 0
1389 while digits:
1390 build(next())
1391 i += 1
1392 if i == 3 and digits:
1393 i = 0
1394 build(sep)
1395 build(curr)
1396 if sign:
1397 build(neg)
1398 else:
1399 build(pos)
1400 result.reverse()
1401 return ''.join(result)
1402
1403 def pi():
1404 """Compute Pi to the current precision.
1405
1406 >>> print pi()
1407 3.141592653589793238462643383
1408
1409 """
1410 getcontext().prec += 2 # extra digits for intermediate steps
1411 three = Decimal(3) # substitute "three=3.0" for regular floats
1412 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1413 while s != lasts:
1414 lasts = s
1415 n, na = n+na, na+8
1416 d, da = d+da, da+32
1417 t = (t * n) / d
1418 s += t
1419 getcontext().prec -= 2
1420 return +s # unary plus applies the new precision
1421
1422 def exp(x):
1423 """Return e raised to the power of x. Result type matches input type.
1424
1425 >>> print exp(Decimal(1))
1426 2.718281828459045235360287471
1427 >>> print exp(Decimal(2))
1428 7.389056098930650227230427461
1429 >>> print exp(2.0)
1430 7.38905609893
1431 >>> print exp(2+0j)
1432 (7.38905609893+0j)
1433
1434 """
1435 getcontext().prec += 2
1436 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1437 while s != lasts:
1438 lasts = s
1439 i += 1
1440 fact *= i
1441 num *= x
1442 s += num / fact
1443 getcontext().prec -= 2
1444 return +s
1445
1446 def cos(x):
1447 """Return the cosine of x as measured in radians.
1448
1449 >>> print cos(Decimal('0.5'))
1450 0.8775825618903727161162815826
1451 >>> print cos(0.5)
1452 0.87758256189
1453 >>> print cos(0.5+0j)
1454 (0.87758256189+0j)
1455
1456 """
1457 getcontext().prec += 2
1458 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1459 while s != lasts:
1460 lasts = s
1461 i += 2
1462 fact *= i * (i-1)
1463 num *= x * x
1464 sign *= -1
1465 s += num / fact * sign
1466 getcontext().prec -= 2
1467 return +s
1468
1469 def sin(x):
1470 """Return the sine of x as measured in radians.
1471
1472 >>> print sin(Decimal('0.5'))
1473 0.4794255386042030002732879352
1474 >>> print sin(0.5)
1475 0.479425538604
1476 >>> print sin(0.5+0j)
1477 (0.479425538604+0j)
1478
1479 """
1480 getcontext().prec += 2
1481 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1482 while s != lasts:
1483 lasts = s
1484 i += 2
1485 fact *= i * (i-1)
1486 num *= x * x
1487 sign *= -1
1488 s += num / fact * sign
1489 getcontext().prec -= 2
1490 return +s
1491
1492
Georg Brandlb19be572007-12-29 10:57:00 +00001493.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001494
1495
1496.. _decimal-faq:
1497
1498Decimal FAQ
1499-----------
1500
1501Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1502minimize typing when using the interactive interpreter?
1503
1504\A. Some users abbreviate the constructor to just a single letter::
1505
1506 >>> D = decimal.Decimal
1507 >>> D('1.23') + D('3.45')
1508 Decimal("4.68")
1509
1510Q. In a fixed-point application with two decimal places, some inputs have many
1511places and need to be rounded. Others are not supposed to have excess digits
1512and need to be validated. What methods should be used?
1513
1514A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
1515the :const:`Inexact` trap is set, it is also useful for validation::
1516
1517 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1518
1519 >>> # Round to two places
1520 >>> Decimal("3.214").quantize(TWOPLACES)
1521 Decimal("3.21")
1522
1523 >>> # Validate that a number does not exceed two places
1524 >>> Decimal("3.21").quantize(TWOPLACES, context=Context(traps=[Inexact]))
1525 Decimal("3.21")
1526
1527 >>> Decimal("3.214").quantize(TWOPLACES, context=Context(traps=[Inexact]))
1528 Traceback (most recent call last):
1529 ...
1530 Inexact: Changed in rounding
1531
1532Q. Once I have valid two place inputs, how do I maintain that invariant
1533throughout an application?
1534
1535A. Some operations like addition and subtraction automatically preserve fixed
1536point. Others, like multiplication and division, change the number of decimal
1537places and need to be followed-up with a :meth:`quantize` step.
1538
1539Q. There are many ways to express the same value. The numbers :const:`200`,
1540:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1541various precisions. Is there a way to transform them to a single recognizable
1542canonical value?
1543
1544A. The :meth:`normalize` method maps all equivalent values to a single
1545representative::
1546
1547 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1548 >>> [v.normalize() for v in values]
1549 [Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2")]
1550
1551Q. Some decimal values always print with exponential notation. Is there a way
1552to get a non-exponential representation?
1553
1554A. For some values, exponential notation is the only way to express the number
1555of significant places in the coefficient. For example, expressing
1556:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1557original's two-place significance.
1558
1559Q. Is there a way to convert a regular float to a :class:`Decimal`?
1560
1561A. Yes, all binary floating point numbers can be exactly expressed as a
1562Decimal. An exact conversion may take more precision than intuition would
1563suggest, so trapping :const:`Inexact` will signal a need for more precision::
1564
1565 def floatToDecimal(f):
1566 "Convert a floating point number to a Decimal with no loss of information"
1567 # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an
1568 # exponent. Double the mantissa until it is an integer. Use the integer
1569 # mantissa and exponent to compute an equivalent Decimal. If this cannot
1570 # be done exactly, then retry with more precision.
1571
1572 mantissa, exponent = math.frexp(f)
1573 while mantissa != int(mantissa):
1574 mantissa *= 2.0
1575 exponent -= 1
1576 mantissa = int(mantissa)
1577
1578 oldcontext = getcontext()
1579 setcontext(Context(traps=[Inexact]))
1580 try:
1581 while True:
1582 try:
1583 return mantissa * Decimal(2) ** exponent
1584 except Inexact:
1585 getcontext().prec += 1
1586 finally:
1587 setcontext(oldcontext)
1588
1589Q. Why isn't the :func:`floatToDecimal` routine included in the module?
1590
1591A. There is some question about whether it is advisable to mix binary and
1592decimal floating point. Also, its use requires some care to avoid the
1593representation issues associated with binary floating point::
1594
1595 >>> floatToDecimal(1.1)
1596 Decimal("1.100000000000000088817841970012523233890533447265625")
1597
1598Q. Within a complex calculation, how can I make sure that I haven't gotten a
1599spurious result because of insufficient precision or rounding anomalies.
1600
1601A. The decimal module makes it easy to test results. A best practice is to
1602re-run calculations using greater precision and with various rounding modes.
1603Widely differing results indicate insufficient precision, rounding mode issues,
1604ill-conditioned inputs, or a numerically unstable algorithm.
1605
1606Q. I noticed that context precision is applied to the results of operations but
1607not to the inputs. Is there anything to watch out for when mixing values of
1608different precisions?
1609
1610A. Yes. The principle is that all values are considered to be exact and so is
1611the arithmetic on those values. Only the results are rounded. The advantage
1612for inputs is that "what you type is what you get". A disadvantage is that the
1613results can look odd if you forget that the inputs haven't been rounded::
1614
1615 >>> getcontext().prec = 3
1616 >>> Decimal('3.104') + D('2.104')
1617 Decimal("5.21")
1618 >>> Decimal('3.104') + D('0.000') + D('2.104')
1619 Decimal("5.20")
1620
1621The solution is either to increase precision or to force rounding of inputs
1622using the unary plus operation::
1623
1624 >>> getcontext().prec = 3
1625 >>> +Decimal('1.23456789') # unary plus triggers rounding
1626 Decimal("1.23")
1627
1628Alternatively, inputs can be rounded upon creation using the
1629:meth:`Context.create_decimal` method::
1630
1631 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
1632 Decimal("1.2345")
1633