blob: 444b20a2d80291d41a4d4482dd85c4034fee858a [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
17arithmetic. It offers several advantages over the :class:`float()` datatype:
18
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
25 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, result
26 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
39 settable precision (defaulting to 28 places) which can be as large as needed for
40 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
59trailing zeroes. Decimals also include special values such as
60: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`,
68:const:`ROUND_HALF_UP`, and :const:`ROUND_UP`.
69
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
85 IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
86 Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_.
87
88 IEEE standard 854-1987, `Unofficial IEEE 854 Text
89 <http://www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html>`_.
90
91.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
92
93
94.. _decimal-tutorial:
95
96Quick-start Tutorial
97--------------------
98
99The usual start to using decimals is importing the module, viewing the current
100context with :func:`getcontext` and, if necessary, setting new values for
101precision, rounding, or enabled traps::
102
103 >>> from decimal import *
104 >>> getcontext()
105 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
106 capitals=1, flags=[], traps=[Overflow, InvalidOperation,
107 DivisionByZero])
108
109 >>> getcontext().prec = 7 # Set a new precision
110
111Decimal instances can be constructed from integers, strings, or tuples. To
112create a Decimal from a :class:`float`, first convert it to a string. This
113serves as an explicit reminder of the details of the conversion (including
114representation error). Decimal numbers include special values such as
115:const:`NaN` which stands for "Not a number", positive and negative
116:const:`Infinity`, and :const:`-0`. ::
117
118 >>> Decimal(10)
119 Decimal("10")
120 >>> Decimal("3.14")
121 Decimal("3.14")
122 >>> Decimal((0, (3, 1, 4), -2))
123 Decimal("3.14")
124 >>> Decimal(str(2.0 ** 0.5))
125 Decimal("1.41421356237")
126 >>> Decimal("NaN")
127 Decimal("NaN")
128 >>> Decimal("-Infinity")
129 Decimal("-Infinity")
130
131The significance of a new Decimal is determined solely by the number of digits
132input. Context precision and rounding only come into play during arithmetic
133operations. ::
134
135 >>> getcontext().prec = 6
136 >>> Decimal('3.0')
137 Decimal("3.0")
138 >>> Decimal('3.1415926535')
139 Decimal("3.1415926535")
140 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
141 Decimal("5.85987")
142 >>> getcontext().rounding = ROUND_UP
143 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
144 Decimal("5.85988")
145
146Decimals interact well with much of the rest of Python. Here is a small decimal
147floating point flying circus::
148
149 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
150 >>> max(data)
151 Decimal("9.25")
152 >>> min(data)
153 Decimal("0.03")
154 >>> sorted(data)
155 [Decimal("0.03"), Decimal("1.00"), Decimal("1.34"), Decimal("1.87"),
156 Decimal("2.35"), Decimal("3.45"), Decimal("9.25")]
157 >>> sum(data)
158 Decimal("19.29")
159 >>> a,b,c = data[:3]
160 >>> str(a)
161 '1.34'
162 >>> float(a)
163 1.3400000000000001
164 >>> round(a, 1) # round() first converts to binary floating point
165 1.3
166 >>> int(a)
167 1
168 >>> a * 5
169 Decimal("6.70")
170 >>> a * b
171 Decimal("2.5058")
172 >>> c % a
173 Decimal("0.77")
174
175The :meth:`quantize` method rounds a number to a fixed exponent. This method is
176useful for monetary applications that often round results to a fixed number of
177places::
178
179 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
180 Decimal("7.32")
181 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
182 Decimal("8")
183
184As shown above, the :func:`getcontext` function accesses the current context and
185allows the settings to be changed. This approach meets the needs of most
186applications.
187
188For more advanced work, it may be useful to create alternate contexts using the
189Context() constructor. To make an alternate active, use the :func:`setcontext`
190function.
191
192In accordance with the standard, the :mod:`Decimal` module provides two ready to
193use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
194former is especially useful for debugging because many of the traps are
195enabled::
196
197 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
198 >>> setcontext(myothercontext)
199 >>> Decimal(1) / Decimal(7)
200 Decimal("0.142857142857142857142857142857142857142857142857142857142857")
201
202 >>> ExtendedContext
203 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
204 capitals=1, flags=[], traps=[])
205 >>> setcontext(ExtendedContext)
206 >>> Decimal(1) / Decimal(7)
207 Decimal("0.142857143")
208 >>> Decimal(42) / Decimal(0)
209 Decimal("Infinity")
210
211 >>> setcontext(BasicContext)
212 >>> Decimal(42) / Decimal(0)
213 Traceback (most recent call last):
214 File "<pyshell#143>", line 1, in -toplevel-
215 Decimal(42) / Decimal(0)
216 DivisionByZero: x / 0
217
218Contexts also have signal flags for monitoring exceptional conditions
219encountered during computations. The flags remain set until explicitly cleared,
220so it is best to clear the flags before each set of monitored computations by
221using the :meth:`clear_flags` method. ::
222
223 >>> setcontext(ExtendedContext)
224 >>> getcontext().clear_flags()
225 >>> Decimal(355) / Decimal(113)
226 Decimal("3.14159292")
227 >>> getcontext()
228 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
229 capitals=1, flags=[Inexact, Rounded], traps=[])
230
231The *flags* entry shows that the rational approximation to :const:`Pi` was
232rounded (digits beyond the context precision were thrown away) and that the
233result is inexact (some of the discarded digits were non-zero).
234
235Individual traps are set using the dictionary in the :attr:`traps` field of a
236context::
237
238 >>> Decimal(1) / Decimal(0)
239 Decimal("Infinity")
240 >>> getcontext().traps[DivisionByZero] = 1
241 >>> Decimal(1) / Decimal(0)
242 Traceback (most recent call last):
243 File "<pyshell#112>", line 1, in -toplevel-
244 Decimal(1) / Decimal(0)
245 DivisionByZero: x / 0
246
247Most programs adjust the current context only once, at the beginning of the
248program. And, in many applications, data is converted to :class:`Decimal` with
249a single cast inside a loop. With context set and decimals created, the bulk of
250the program manipulates the data no differently than with other Python numeric
251types.
252
253.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
254
255
256.. _decimal-decimal:
257
258Decimal objects
259---------------
260
261
262.. class:: Decimal([value [, context]])
263
264 Constructs a new :class:`Decimal` object based from *value*.
265
266 *value* can be an integer, string, tuple, or another :class:`Decimal` object. If
267 no *value* is given, returns ``Decimal("0")``. If *value* is a string, it
268 should conform to the decimal numeric string syntax::
269
270 sign ::= '+' | '-'
271 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
272 indicator ::= 'e' | 'E'
273 digits ::= digit [digit]...
274 decimal-part ::= digits '.' [digits] | ['.'] digits
275 exponent-part ::= indicator [sign] digits
276 infinity ::= 'Infinity' | 'Inf'
277 nan ::= 'NaN' [digits] | 'sNaN' [digits]
278 numeric-value ::= decimal-part [exponent-part] | infinity
279 numeric-string ::= [sign] numeric-value | [sign] nan
280
281 If *value* is a :class:`tuple`, it should have three components, a sign
282 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
283 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
284 returns ``Decimal("1.414")``.
285
286 The *context* precision does not affect how many digits are stored. That is
287 determined exclusively by the number of digits in *value*. For example,
288 ``Decimal("3.00000")`` records all five zeroes even if the context precision is
289 only three.
290
291 The purpose of the *context* argument is determining what to do if *value* is a
292 malformed string. If the context traps :const:`InvalidOperation`, an exception
293 is raised; otherwise, the constructor returns a new Decimal with the value of
294 :const:`NaN`.
295
296 Once constructed, :class:`Decimal` objects are immutable.
297
298Decimal floating point objects share many properties with the other builtin
299numeric types such as :class:`float` and :class:`int`. All of the usual math
300operations and special methods apply. Likewise, decimal objects can be copied,
301pickled, printed, used as dictionary keys, used as set elements, compared,
302sorted, and coerced to another type (such as :class:`float` or :class:`long`).
303
304In addition to the standard numeric properties, decimal floating point objects
305also have a number of specialized methods:
306
307
308.. method:: Decimal.adjusted()
309
310 Return the adjusted exponent after shifting out the coefficient's rightmost
311 digits until only the lead digit remains: ``Decimal("321e+5").adjusted()``
312 returns seven. Used for determining the position of the most significant digit
313 with respect to the decimal point.
314
315
316.. method:: Decimal.as_tuple()
317
318 Returns a tuple representation of the number: ``(sign, digittuple, exponent)``.
319
320
321.. method:: Decimal.compare(other[, context])
322
323 Compares like :meth:`__cmp__` but returns a decimal instance::
324
325 a or b is a NaN ==> Decimal("NaN")
326 a < b ==> Decimal("-1")
327 a == b ==> Decimal("0")
328 a > b ==> Decimal("1")
329
330
331.. method:: Decimal.max(other[, context])
332
333 Like ``max(self, other)`` except that the context rounding rule is applied
334 before returning and that :const:`NaN` values are either signalled or ignored
335 (depending on the context and whether they are signaling or quiet).
336
337
338.. method:: Decimal.min(other[, context])
339
340 Like ``min(self, other)`` except that the context rounding rule is applied
341 before returning and that :const:`NaN` values are either signalled or ignored
342 (depending on the context and whether they are signaling or quiet).
343
344
345.. method:: Decimal.normalize([context])
346
347 Normalize the number by stripping the rightmost trailing zeroes and converting
348 any result equal to :const:`Decimal("0")` to :const:`Decimal("0e0")`. Used for
349 producing canonical values for members of an equivalence class. For example,
350 ``Decimal("32.100")`` and ``Decimal("0.321000e+2")`` both normalize to the
351 equivalent value ``Decimal("32.1")``.
352
353
354.. method:: Decimal.quantize(exp [, rounding[, context[, watchexp]]])
355
356 Quantize makes the exponent the same as *exp*. Searches for a rounding method
357 in *rounding*, then in *context*, and then in the current context.
358
359 If *watchexp* is set (default), then an error is returned whenever the resulting
360 exponent is greater than :attr:`Emax` or less than :attr:`Etiny`.
361
362
363.. method:: Decimal.remainder_near(other[, context])
364
365 Computes the modulo as either a positive or negative value depending on which is
366 closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
367 ``Decimal("-2")`` which is closer to zero than ``Decimal("4")``.
368
369 If both are equally close, the one chosen will have the same sign as *self*.
370
371
372.. method:: Decimal.same_quantum(other[, context])
373
374 Test whether self and other have the same exponent or whether both are
375 :const:`NaN`.
376
377
378.. method:: Decimal.sqrt([context])
379
380 Return the square root to full precision.
381
382
383.. method:: Decimal.to_eng_string([context])
384
385 Convert to an engineering-type string.
386
387 Engineering notation has an exponent which is a multiple of 3, so there are up
388 to 3 digits left of the decimal place. For example, converts
389 ``Decimal('123E+1')`` to ``Decimal("1.23E+3")``
390
391
392.. method:: Decimal.to_integral([rounding[, context]])
393
394 Rounds to the nearest integer without signaling :const:`Inexact` or
395 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding
396 method in either the supplied *context* or the current context.
397
398.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
399
400
401.. _decimal-context:
402
403Context objects
404---------------
405
406Contexts are environments for arithmetic operations. They govern precision, set
407rules for rounding, determine which signals are treated as exceptions, and limit
408the range for exponents.
409
410Each thread has its own current context which is accessed or changed using the
411:func:`getcontext` and :func:`setcontext` functions:
412
413
414.. function:: getcontext()
415
416 Return the current context for the active thread.
417
418
419.. function:: setcontext(c)
420
421 Set the current context for the active thread to *c*.
422
423Beginning with Python 2.5, you can also use the :keyword:`with` statement and
424the :func:`localcontext` function to temporarily change the active context.
425
426
427.. function:: localcontext([c])
428
429 Return a context manager that will set the current context for the active thread
430 to a copy of *c* on entry to the with-statement and restore the previous context
431 when exiting the with-statement. If no context is specified, a copy of the
432 current context is used.
433
Georg Brandl116aa622007-08-15 14:28:22 +0000434 For example, the following code sets the current decimal precision to 42 places,
435 performs a calculation, and then automatically restores the previous context::
436
437 from __future__ import with_statement
438 from decimal import localcontext
439
440 with localcontext() as ctx:
441 ctx.prec = 42 # Perform a high precision calculation
442 s = calculate_something()
443 s = +s # Round the final result back to the default precision
444
445New contexts can also be created using the :class:`Context` constructor
446described below. In addition, the module provides three pre-made contexts:
447
448
449.. class:: BasicContext
450
451 This is a standard context defined by the General Decimal Arithmetic
452 Specification. Precision is set to nine. Rounding is set to
453 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
454 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
455 :const:`Subnormal`.
456
457 Because many of the traps are enabled, this context is useful for debugging.
458
459
460.. class:: ExtendedContext
461
462 This is a standard context defined by the General Decimal Arithmetic
463 Specification. Precision is set to nine. Rounding is set to
464 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
465 exceptions are not raised during computations).
466
467 Because the trapped are disabled, this context is useful for applications that
468 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
469 raising exceptions. This allows an application to complete a run in the
470 presence of conditions that would otherwise halt the program.
471
472
473.. class:: DefaultContext
474
475 This context is used by the :class:`Context` constructor as a prototype for new
476 contexts. Changing a field (such a precision) has the effect of changing the
477 default for new contexts creating by the :class:`Context` constructor.
478
479 This context is most useful in multi-threaded environments. Changing one of the
480 fields before threads are started has the effect of setting system-wide
481 defaults. Changing the fields after threads have started is not recommended as
482 it would require thread synchronization to prevent race conditions.
483
484 In single threaded environments, it is preferable to not use this context at
485 all. Instead, simply create contexts explicitly as described below.
486
487 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
488 for Overflow, InvalidOperation, and DivisionByZero.
489
490In addition to the three supplied contexts, new contexts can be created with the
491:class:`Context` constructor.
492
493
494.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
495
496 Creates a new context. If a field is not specified or is :const:`None`, the
497 default values are copied from the :const:`DefaultContext`. If the *flags*
498 field is not specified or is :const:`None`, all flags are cleared.
499
500 The *prec* field is a positive integer that sets the precision for arithmetic
501 operations in the context.
502
503 The *rounding* option is one of:
504
505 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
506 * :const:`ROUND_DOWN` (towards zero),
507 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
508 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
509 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
510 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
511 * :const:`ROUND_UP` (away from zero).
512
513 The *traps* and *flags* fields list any signals to be set. Generally, new
514 contexts should only set traps and leave the flags clear.
515
516 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
517 for exponents.
518
519 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
520 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
521 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
522
523The :class:`Context` class defines several general purpose methods as well as a
524large number of methods for doing arithmetic directly in a given context.
525
526
527.. method:: Context.clear_flags()
528
529 Resets all of the flags to :const:`0`.
530
531
532.. method:: Context.copy()
533
534 Return a duplicate of the context.
535
536
537.. method:: Context.create_decimal(num)
538
539 Creates a new Decimal instance from *num* but using *self* as context. Unlike
540 the :class:`Decimal` constructor, the context precision, rounding method, flags,
541 and traps are applied to the conversion.
542
543 This is useful because constants are often given to a greater precision than is
544 needed by the application. Another benefit is that rounding immediately
545 eliminates unintended effects from digits beyond the current precision. In the
546 following example, using unrounded inputs means that adding zero to a sum can
547 change the result::
548
549 >>> getcontext().prec = 3
550 >>> Decimal("3.4445") + Decimal("1.0023")
551 Decimal("4.45")
552 >>> Decimal("3.4445") + Decimal(0) + Decimal("1.0023")
553 Decimal("4.44")
554
555
556.. method:: Context.Etiny()
557
558 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
559 for subnormal results. When underflow occurs, the exponent is set to
560 :const:`Etiny`.
561
562
563.. method:: Context.Etop()
564
565 Returns a value equal to ``Emax - prec + 1``.
566
567The usual approach to working with decimals is to create :class:`Decimal`
568instances and then apply arithmetic operations which take place within the
569current context for the active thread. An alternate approach is to use context
570methods for calculating within a specific context. The methods are similar to
571those for the :class:`Decimal` class and are only briefly recounted here.
572
573
574.. method:: Context.abs(x)
575
576 Returns the absolute value of *x*.
577
578
579.. method:: Context.add(x, y)
580
581 Return the sum of *x* and *y*.
582
583
584.. method:: Context.compare(x, y)
585
586 Compares values numerically.
587
588 Like :meth:`__cmp__` but returns a decimal instance::
589
590 a or b is a NaN ==> Decimal("NaN")
591 a < b ==> Decimal("-1")
592 a == b ==> Decimal("0")
593 a > b ==> Decimal("1")
594
595
596.. method:: Context.divide(x, y)
597
598 Return *x* divided by *y*.
599
600
601.. method:: Context.divmod(x, y)
602
603 Divides two numbers and returns the integer part of the result.
604
605
606.. method:: Context.max(x, y)
607
608 Compare two values numerically and return the maximum.
609
610 If they are numerically equal then the left-hand operand is chosen as the
611 result.
612
613
614.. method:: Context.min(x, y)
615
616 Compare two values numerically and return the minimum.
617
618 If they are numerically equal then the left-hand operand is chosen as the
619 result.
620
621
622.. method:: Context.minus(x)
623
624 Minus corresponds to the unary prefix minus operator in Python.
625
626
627.. method:: Context.multiply(x, y)
628
629 Return the product of *x* and *y*.
630
631
632.. method:: Context.normalize(x)
633
634 Normalize reduces an operand to its simplest form.
635
636 Essentially a :meth:`plus` operation with all trailing zeros removed from the
637 result.
638
639
640.. method:: Context.plus(x)
641
642 Plus corresponds to the unary prefix plus operator in Python. This operation
643 applies the context precision and rounding, so it is *not* an identity
644 operation.
645
646
647.. method:: Context.power(x, y[, modulo])
648
649 Return ``x ** y`` to the *modulo* if given.
650
651 The right-hand operand must be a whole number whose integer part (after any
652 exponent has been applied) has no more than 9 digits and whose fractional part
653 (if any) is all zeros before any rounding. The operand may be positive,
654 negative, or zero; if negative, the absolute value of the power is used, and the
655 left-hand operand is inverted (divided into 1) before use.
656
657 If the increased precision needed for the intermediate calculations exceeds the
658 capabilities of the implementation then an :const:`InvalidOperation` condition
659 is signaled.
660
661 If, when raising to a negative power, an underflow occurs during the division
662 into 1, the operation is not halted at that point but continues.
663
664
665.. method:: Context.quantize(x, y)
666
667 Returns a value equal to *x* after rounding and having the exponent of *y*.
668
669 Unlike other operations, if the length of the coefficient after the quantize
670 operation would be greater than precision, then an :const:`InvalidOperation` is
671 signaled. This guarantees that, unless there is an error condition, the
672 quantized exponent is always equal to that of the right-hand operand.
673
674 Also unlike other operations, quantize never signals Underflow, even if the
675 result is subnormal and inexact.
676
677
678.. method:: Context.remainder(x, y)
679
680 Returns the remainder from integer division.
681
682 The sign of the result, if non-zero, is the same as that of the original
683 dividend.
684
685
686.. method:: Context.remainder_near(x, y)
687
688 Computed the modulo as either a positive or negative value depending on which is
689 closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
690 ``Decimal("-2")`` which is closer to zero than ``Decimal("4")``.
691
692 If both are equally close, the one chosen will have the same sign as *self*.
693
694
695.. method:: Context.same_quantum(x, y)
696
697 Test whether *x* and *y* have the same exponent or whether both are
698 :const:`NaN`.
699
700
701.. method:: Context.sqrt(x)
702
703 Return the square root of *x* to full precision.
704
705
706.. method:: Context.subtract(x, y)
707
708 Return the difference between *x* and *y*.
709
710
711.. method:: Context.to_eng_string()
712
713 Convert to engineering-type string.
714
715 Engineering notation has an exponent which is a multiple of 3, so there are up
716 to 3 digits left of the decimal place. For example, converts
717 ``Decimal('123E+1')`` to ``Decimal("1.23E+3")``
718
719
720.. method:: Context.to_integral(x)
721
722 Rounds to the nearest integer without signaling :const:`Inexact` or
723 :const:`Rounded`.
724
725
726.. method:: Context.to_sci_string(x)
727
728 Converts a number to a string using scientific notation.
729
730.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
731
732
733.. _decimal-signals:
734
735Signals
736-------
737
738Signals represent conditions that arise during computation. Each corresponds to
739one context flag and one context trap enabler.
740
741The context flag is incremented whenever the condition is encountered. After the
742computation, flags may be checked for informational purposes (for instance, to
743determine whether a computation was exact). After checking the flags, be sure to
744clear all flags before starting the next computation.
745
746If the context's trap enabler is set for the signal, then the condition causes a
747Python exception to be raised. For example, if the :class:`DivisionByZero` trap
748is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
749condition.
750
751
752.. class:: Clamped
753
754 Altered an exponent to fit representation constraints.
755
756 Typically, clamping occurs when an exponent falls outside the context's
757 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
758 fit by adding zeroes to the coefficient.
759
760
761.. class:: DecimalException
762
763 Base class for other signals and a subclass of :exc:`ArithmeticError`.
764
765
766.. class:: DivisionByZero
767
768 Signals the division of a non-infinite number by zero.
769
770 Can occur with division, modulo division, or when raising a number to a negative
771 power. If this signal is not trapped, returns :const:`Infinity` or
772 :const:`-Infinity` with the sign determined by the inputs to the calculation.
773
774
775.. class:: Inexact
776
777 Indicates that rounding occurred and the result is not exact.
778
779 Signals when non-zero digits were discarded during rounding. The rounded result
780 is returned. The signal flag or trap is used to detect when results are
781 inexact.
782
783
784.. class:: InvalidOperation
785
786 An invalid operation was performed.
787
788 Indicates that an operation was requested that does not make sense. If not
789 trapped, returns :const:`NaN`. Possible causes include::
790
791 Infinity - Infinity
792 0 * Infinity
793 Infinity / Infinity
794 x % 0
795 Infinity % x
796 x._rescale( non-integer )
797 sqrt(-x) and x > 0
798 0 ** 0
799 x ** (non-integer)
800 x ** Infinity
801
802
803.. class:: Overflow
804
805 Numerical overflow.
806
807 Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
808 If not trapped, the result depends on the rounding mode, either pulling inward
809 to the largest representable finite number or rounding outward to
810 :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are
811 also signaled.
812
813
814.. class:: Rounded
815
816 Rounding occurred though possibly no information was lost.
817
818 Signaled whenever rounding discards digits; even if those digits are zero (such
819 as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result
820 unchanged. This signal is used to detect loss of significant digits.
821
822
823.. class:: Subnormal
824
825 Exponent was lower than :attr:`Emin` prior to rounding.
826
827 Occurs when an operation result is subnormal (the exponent is too small). If not
828 trapped, returns the result unchanged.
829
830
831.. class:: Underflow
832
833 Numerical underflow with result rounded to zero.
834
835 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
836 and :class:`Subnormal` are also signaled.
837
838The following table summarizes the hierarchy of signals::
839
840 exceptions.ArithmeticError(exceptions.Exception)
841 DecimalException
842 Clamped
843 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
844 Inexact
845 Overflow(Inexact, Rounded)
846 Underflow(Inexact, Rounded, Subnormal)
847 InvalidOperation
848 Rounded
849 Subnormal
850
851.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
852
853
854.. _decimal-notes:
855
856Floating Point Notes
857--------------------
858
859
860Mitigating round-off error with increased precision
861^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
862
863The use of decimal floating point eliminates decimal representation error
864(making it possible to represent :const:`0.1` exactly); however, some operations
865can still incur round-off error when non-zero digits exceed the fixed precision.
866
867The effects of round-off error can be amplified by the addition or subtraction
868of nearly offsetting quantities resulting in loss of significance. Knuth
869provides two instructive examples where rounded floating point arithmetic with
870insufficient precision causes the breakdown of the associative and distributive
871properties of addition::
872
873 # Examples from Seminumerical Algorithms, Section 4.2.2.
874 >>> from decimal import Decimal, getcontext
875 >>> getcontext().prec = 8
876
877 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
878 >>> (u + v) + w
879 Decimal("9.5111111")
880 >>> u + (v + w)
881 Decimal("10")
882
883 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
884 >>> (u*v) + (u*w)
885 Decimal("0.01")
886 >>> u * (v+w)
887 Decimal("0.0060000")
888
889The :mod:`decimal` module makes it possible to restore the identities by
890expanding the precision sufficiently to avoid loss of significance::
891
892 >>> getcontext().prec = 20
893 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
894 >>> (u + v) + w
895 Decimal("9.51111111")
896 >>> u + (v + w)
897 Decimal("9.51111111")
898 >>>
899 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
900 >>> (u*v) + (u*w)
901 Decimal("0.0060000")
902 >>> u * (v+w)
903 Decimal("0.0060000")
904
905
906Special values
907^^^^^^^^^^^^^^
908
909The number system for the :mod:`decimal` module provides special values
910including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
911and two zeroes, :const:`+0` and :const:`-0`.
912
913Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
914they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
915not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
916can result from rounding beyond the limits of the largest representable number.
917
918The infinities are signed (affine) and can be used in arithmetic operations
919where they get treated as very large, indeterminate numbers. For instance,
920adding a constant to infinity gives another infinite result.
921
922Some operations are indeterminate and return :const:`NaN`, or if the
923:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
924``0/0`` returns :const:`NaN` which means "not a number". This variety of
925:const:`NaN` is quiet and, once created, will flow through other computations
926always resulting in another :const:`NaN`. This behavior can be useful for a
927series of computations that occasionally have missing inputs --- it allows the
928calculation to proceed while flagging specific results as invalid.
929
930A variant is :const:`sNaN` which signals rather than remaining quiet after every
931operation. This is a useful return value when an invalid result needs to
932interrupt a calculation for special handling.
933
934The signed zeros can result from calculations that underflow. They keep the sign
935that would have resulted if the calculation had been carried out to greater
936precision. Since their magnitude is zero, both positive and negative zeros are
937treated as equal and their sign is informational.
938
939In addition to the two signed zeros which are distinct yet equal, there are
940various representations of zero with differing precisions yet equivalent in
941value. This takes a bit of getting used to. For an eye accustomed to
942normalized floating point representations, it is not immediately obvious that
943the following calculation returns a value equal to zero::
944
945 >>> 1 / Decimal('Infinity')
946 Decimal("0E-1000000026")
947
948.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
949
950
951.. _decimal-threads:
952
953Working with threads
954--------------------
955
956The :func:`getcontext` function accesses a different :class:`Context` object for
957each thread. Having separate thread contexts means that threads may make
958changes (such as ``getcontext.prec=10``) without interfering with other threads.
959
960Likewise, the :func:`setcontext` function automatically assigns its target to
961the current thread.
962
963If :func:`setcontext` has not been called before :func:`getcontext`, then
964:func:`getcontext` will automatically create a new context for use in the
965current thread.
966
967The new context is copied from a prototype context called *DefaultContext*. To
968control the defaults so that each thread will use the same values throughout the
969application, directly modify the *DefaultContext* object. This should be done
970*before* any threads are started so that there won't be a race condition between
971threads calling :func:`getcontext`. For example::
972
973 # Set applicationwide defaults for all threads about to be launched
974 DefaultContext.prec = 12
975 DefaultContext.rounding = ROUND_DOWN
976 DefaultContext.traps = ExtendedContext.traps.copy()
977 DefaultContext.traps[InvalidOperation] = 1
978 setcontext(DefaultContext)
979
980 # Afterwards, the threads can be started
981 t1.start()
982 t2.start()
983 t3.start()
984 . . .
985
986.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
987
988
989.. _decimal-recipes:
990
991Recipes
992-------
993
994Here are a few recipes that serve as utility functions and that demonstrate ways
995to work with the :class:`Decimal` class::
996
997 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
998 pos='', neg='-', trailneg=''):
999 """Convert Decimal to a money formatted string.
1000
1001 places: required number of places after the decimal point
1002 curr: optional currency symbol before the sign (may be blank)
1003 sep: optional grouping separator (comma, period, space, or blank)
1004 dp: decimal point indicator (comma or period)
1005 only specify as blank when places is zero
1006 pos: optional sign for positive numbers: '+', space or blank
1007 neg: optional sign for negative numbers: '-', '(', space or blank
1008 trailneg:optional trailing minus indicator: '-', ')', space or blank
1009
1010 >>> d = Decimal('-1234567.8901')
1011 >>> moneyfmt(d, curr='$')
1012 '-$1,234,567.89'
1013 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1014 '1.234.568-'
1015 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1016 '($1,234,567.89)'
1017 >>> moneyfmt(Decimal(123456789), sep=' ')
1018 '123 456 789.00'
1019 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1020 '<.02>'
1021
1022 """
1023 q = Decimal((0, (1,), -places)) # 2 places --> '0.01'
1024 sign, digits, exp = value.quantize(q).as_tuple()
1025 assert exp == -places
1026 result = []
1027 digits = map(str, digits)
1028 build, next = result.append, digits.pop
1029 if sign:
1030 build(trailneg)
1031 for i in range(places):
1032 if digits:
1033 build(next())
1034 else:
1035 build('0')
1036 build(dp)
1037 i = 0
1038 while digits:
1039 build(next())
1040 i += 1
1041 if i == 3 and digits:
1042 i = 0
1043 build(sep)
1044 build(curr)
1045 if sign:
1046 build(neg)
1047 else:
1048 build(pos)
1049 result.reverse()
1050 return ''.join(result)
1051
1052 def pi():
1053 """Compute Pi to the current precision.
1054
Georg Brandl6911e3c2007-09-04 07:15:32 +00001055 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001056 3.141592653589793238462643383
1057
1058 """
1059 getcontext().prec += 2 # extra digits for intermediate steps
1060 three = Decimal(3) # substitute "three=3.0" for regular floats
1061 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1062 while s != lasts:
1063 lasts = s
1064 n, na = n+na, na+8
1065 d, da = d+da, da+32
1066 t = (t * n) / d
1067 s += t
1068 getcontext().prec -= 2
1069 return +s # unary plus applies the new precision
1070
1071 def exp(x):
1072 """Return e raised to the power of x. Result type matches input type.
1073
Georg Brandl6911e3c2007-09-04 07:15:32 +00001074 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001075 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001076 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001077 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001078 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001079 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001080 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001081 (7.38905609893+0j)
1082
1083 """
1084 getcontext().prec += 2
1085 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1086 while s != lasts:
1087 lasts = s
1088 i += 1
1089 fact *= i
1090 num *= x
1091 s += num / fact
1092 getcontext().prec -= 2
1093 return +s
1094
1095 def cos(x):
1096 """Return the cosine of x as measured in radians.
1097
Georg Brandl6911e3c2007-09-04 07:15:32 +00001098 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001099 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001100 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001101 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001102 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001103 (0.87758256189+0j)
1104
1105 """
1106 getcontext().prec += 2
1107 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1108 while s != lasts:
1109 lasts = s
1110 i += 2
1111 fact *= i * (i-1)
1112 num *= x * x
1113 sign *= -1
1114 s += num / fact * sign
1115 getcontext().prec -= 2
1116 return +s
1117
1118 def sin(x):
1119 """Return the sine of x as measured in radians.
1120
Georg Brandl6911e3c2007-09-04 07:15:32 +00001121 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001122 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001123 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001124 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001125 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001126 (0.479425538604+0j)
1127
1128 """
1129 getcontext().prec += 2
1130 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1131 while s != lasts:
1132 lasts = s
1133 i += 2
1134 fact *= i * (i-1)
1135 num *= x * x
1136 sign *= -1
1137 s += num / fact * sign
1138 getcontext().prec -= 2
1139 return +s
1140
1141
1142.. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1143
1144
1145.. _decimal-faq:
1146
1147Decimal FAQ
1148-----------
1149
1150Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1151minimize typing when using the interactive interpreter?
1152
1153\A. Some users abbreviate the constructor to just a single letter::
1154
1155 >>> D = decimal.Decimal
1156 >>> D('1.23') + D('3.45')
1157 Decimal("4.68")
1158
1159Q. In a fixed-point application with two decimal places, some inputs have many
1160places and need to be rounded. Others are not supposed to have excess digits
1161and need to be validated. What methods should be used?
1162
1163A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
1164the :const:`Inexact` trap is set, it is also useful for validation::
1165
1166 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1167
1168 >>> # Round to two places
1169 >>> Decimal("3.214").quantize(TWOPLACES)
1170 Decimal("3.21")
1171
1172 >>> # Validate that a number does not exceed two places
1173 >>> Decimal("3.21").quantize(TWOPLACES, context=Context(traps=[Inexact]))
1174 Decimal("3.21")
1175
1176 >>> Decimal("3.214").quantize(TWOPLACES, context=Context(traps=[Inexact]))
1177 Traceback (most recent call last):
1178 ...
1179 Inexact: Changed in rounding
1180
1181Q. Once I have valid two place inputs, how do I maintain that invariant
1182throughout an application?
1183
1184A. Some operations like addition and subtraction automatically preserve fixed
1185point. Others, like multiplication and division, change the number of decimal
1186places and need to be followed-up with a :meth:`quantize` step.
1187
1188Q. There are many ways to express the same value. The numbers :const:`200`,
1189:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1190various precisions. Is there a way to transform them to a single recognizable
1191canonical value?
1192
1193A. The :meth:`normalize` method maps all equivalent values to a single
1194representative::
1195
1196 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1197 >>> [v.normalize() for v in values]
1198 [Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2")]
1199
1200Q. Some decimal values always print with exponential notation. Is there a way
1201to get a non-exponential representation?
1202
1203A. For some values, exponential notation is the only way to express the number
1204of significant places in the coefficient. For example, expressing
1205:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1206original's two-place significance.
1207
1208Q. Is there a way to convert a regular float to a :class:`Decimal`?
1209
1210A. Yes, all binary floating point numbers can be exactly expressed as a
1211Decimal. An exact conversion may take more precision than intuition would
1212suggest, so trapping :const:`Inexact` will signal a need for more precision::
1213
1214 def floatToDecimal(f):
1215 "Convert a floating point number to a Decimal with no loss of information"
1216 # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an
1217 # exponent. Double the mantissa until it is an integer. Use the integer
1218 # mantissa and exponent to compute an equivalent Decimal. If this cannot
1219 # be done exactly, then retry with more precision.
1220
1221 mantissa, exponent = math.frexp(f)
1222 while mantissa != int(mantissa):
1223 mantissa *= 2.0
1224 exponent -= 1
1225 mantissa = int(mantissa)
1226
1227 oldcontext = getcontext()
1228 setcontext(Context(traps=[Inexact]))
1229 try:
1230 while True:
1231 try:
1232 return mantissa * Decimal(2) ** exponent
1233 except Inexact:
1234 getcontext().prec += 1
1235 finally:
1236 setcontext(oldcontext)
1237
1238Q. Why isn't the :func:`floatToDecimal` routine included in the module?
1239
1240A. There is some question about whether it is advisable to mix binary and
1241decimal floating point. Also, its use requires some care to avoid the
1242representation issues associated with binary floating point::
1243
1244 >>> floatToDecimal(1.1)
1245 Decimal("1.100000000000000088817841970012523233890533447265625")
1246
1247Q. Within a complex calculation, how can I make sure that I haven't gotten a
1248spurious result because of insufficient precision or rounding anomalies.
1249
1250A. The decimal module makes it easy to test results. A best practice is to
1251re-run calculations using greater precision and with various rounding modes.
1252Widely differing results indicate insufficient precision, rounding mode issues,
1253ill-conditioned inputs, or a numerically unstable algorithm.
1254
1255Q. I noticed that context precision is applied to the results of operations but
1256not to the inputs. Is there anything to watch out for when mixing values of
1257different precisions?
1258
1259A. Yes. The principle is that all values are considered to be exact and so is
1260the arithmetic on those values. Only the results are rounded. The advantage
1261for inputs is that "what you type is what you get". A disadvantage is that the
1262results can look odd if you forget that the inputs haven't been rounded::
1263
1264 >>> getcontext().prec = 3
1265 >>> Decimal('3.104') + D('2.104')
1266 Decimal("5.21")
1267 >>> Decimal('3.104') + D('0.000') + D('2.104')
1268 Decimal("5.20")
1269
1270The solution is either to increase precision or to force rounding of inputs
1271using the unary plus operation::
1272
1273 >>> getcontext().prec = 3
1274 >>> +Decimal('1.23456789') # unary plus triggers rounding
1275 Decimal("1.23")
1276
1277Alternatively, inputs can be rounded upon creation using the
1278:meth:`Context.create_decimal` method::
1279
1280 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
1281 Decimal("1.2345")
1282