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