blob: d46f850fd7c43c6812f21a13bb1dd98ec8a86409 [file] [log] [blame]
Christian Heimes3feef612008-02-11 06:19:17 +00001:mod:`decimal` --- Decimal fixed point and floating point arithmetic
2====================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: decimal
5 :synopsis: Implementation of the General Decimal Arithmetic Specification.
6
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
8.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
9.. moduleauthor:: Raymond Hettinger <python at rcn.com>
10.. moduleauthor:: Aahz <aahz at pobox.com>
11.. moduleauthor:: Tim Peters <tim.one at comcast.net>
Stefan Krah1919b7e2012-03-21 18:25:23 +010012.. moduleauthor:: Stefan Krah <skrah at bytereef.org>
Georg Brandl116aa622007-08-15 14:28:22 +000013.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
14
Andrew Kuchling2e3743c2014-03-19 16:23:01 -040015**Source code:** :source:`Lib/decimal.py`
16
Christian Heimesfe337bf2008-03-23 21:54:12 +000017.. import modules for testing inline doctests with the Sphinx doctest builder
18.. testsetup:: *
19
20 import decimal
21 import math
22 from decimal import *
23 # make sure each group gets a fresh context
24 setcontext(Context())
Georg Brandl116aa622007-08-15 14:28:22 +000025
Stefan Krah1919b7e2012-03-21 18:25:23 +010026The :mod:`decimal` module provides support for fast correctly-rounded
27decimal floating point arithmetic. It offers several advantages over the
28:class:`float` datatype:
Georg Brandl116aa622007-08-15 14:28:22 +000029
Christian Heimes3feef612008-02-11 06:19:17 +000030* Decimal "is based on a floating-point model which was designed with people
31 in mind, and necessarily has a paramount guiding principle -- computers must
32 provide an arithmetic that works in the same way as the arithmetic that
33 people learn at school." -- excerpt from the decimal arithmetic specification.
34
Georg Brandl116aa622007-08-15 14:28:22 +000035* Decimal numbers can be represented exactly. In contrast, numbers like
Terry Jan Reedya9314632012-01-13 23:43:13 -050036 :const:`1.1` and :const:`2.2` do not have exact representations in binary
Raymond Hettingerd258d1e2009-04-23 22:06:12 +000037 floating point. End users typically would not expect ``1.1 + 2.2`` to display
38 as :const:`3.3000000000000003` as it does with binary floating point.
Georg Brandl116aa622007-08-15 14:28:22 +000039
40* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000041 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl116aa622007-08-15 14:28:22 +000042 is :const:`5.5511151231257827e-017`. While near to zero, the differences
43 prevent reliable equality testing and differences can accumulate. For this
Christian Heimes3feef612008-02-11 06:19:17 +000044 reason, decimal is preferred in accounting applications which have strict
Georg Brandl116aa622007-08-15 14:28:22 +000045 equality invariants.
46
47* The decimal module incorporates a notion of significant places so that ``1.30
48 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
49 This is the customary presentation for monetary applications. For
50 multiplication, the "schoolbook" approach uses all the figures in the
51 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
52 1.20`` gives :const:`1.5600`.
53
54* Unlike hardware based binary floating point, the decimal module has a user
Thomas Wouters1b7f8912007-09-19 03:06:30 +000055 alterable precision (defaulting to 28 places) which can be as large as needed for
Christian Heimesfe337bf2008-03-23 21:54:12 +000056 a given problem:
Georg Brandl116aa622007-08-15 14:28:22 +000057
Mark Dickinson43ef32a2010-11-07 11:24:44 +000058 >>> from decimal import *
Georg Brandl116aa622007-08-15 14:28:22 +000059 >>> getcontext().prec = 6
60 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000061 Decimal('0.142857')
Georg Brandl116aa622007-08-15 14:28:22 +000062 >>> getcontext().prec = 28
63 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000064 Decimal('0.1428571428571428571428571429')
Georg Brandl116aa622007-08-15 14:28:22 +000065
66* Both binary and decimal floating point are implemented in terms of published
67 standards. While the built-in float type exposes only a modest portion of its
68 capabilities, the decimal module exposes all required parts of the standard.
69 When needed, the programmer has full control over rounding and signal handling.
Christian Heimes3feef612008-02-11 06:19:17 +000070 This includes an option to enforce exact arithmetic by using exceptions
71 to block any inexact operations.
72
73* The decimal module was designed to support "without prejudice, both exact
74 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
75 and rounded floating-point arithmetic." -- excerpt from the decimal
76 arithmetic specification.
Georg Brandl116aa622007-08-15 14:28:22 +000077
78The module design is centered around three concepts: the decimal number, the
79context for arithmetic, and signals.
80
81A decimal number is immutable. It has a sign, coefficient digits, and an
82exponent. To preserve significance, the coefficient digits do not truncate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000083trailing zeros. Decimals also include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +000084:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
85differentiates :const:`-0` from :const:`+0`.
86
87The context for arithmetic is an environment specifying precision, rounding
88rules, limits on exponents, flags indicating the results of operations, and trap
89enablers which determine whether signals are treated as exceptions. Rounding
90options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
91:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +000092:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl116aa622007-08-15 14:28:22 +000093
94Signals are groups of exceptional conditions arising during the course of
95computation. Depending on the needs of the application, signals may be ignored,
96considered as informational, or treated as exceptions. The signals in the
97decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
98:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
Stefan Krah1919b7e2012-03-21 18:25:23 +010099:const:`Overflow`, :const:`Underflow` and :const:`FloatOperation`.
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101For each signal there is a flag and a trap enabler. When a signal is
Raymond Hettinger86173da2008-02-01 20:38:12 +0000102encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl116aa622007-08-15 14:28:22 +0000103set to one, an exception is raised. Flags are sticky, so the user needs to
104reset them before monitoring a calculation.
105
106
107.. seealso::
108
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000109 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
Raymond Hettinger960dc362009-04-21 03:43:15 +0000110 Specification <http://speleotrove.com/decimal/decarith.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000111
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000112.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000113
114
115.. _decimal-tutorial:
116
117Quick-start Tutorial
118--------------------
119
120The usual start to using decimals is importing the module, viewing the current
121context with :func:`getcontext` and, if necessary, setting new values for
122precision, rounding, or enabled traps::
123
124 >>> from decimal import *
125 >>> getcontext()
Stefan Krah1919b7e2012-03-21 18:25:23 +0100126 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000127 capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000128 InvalidOperation])
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130 >>> getcontext().prec = 7 # Set a new precision
131
Mark Dickinsone534a072010-04-04 22:13:14 +0000132Decimal instances can be constructed from integers, strings, floats, or tuples.
133Construction from an integer or a float performs an exact conversion of the
134value of that integer or float. Decimal numbers include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +0000135:const:`NaN` which stands for "Not a number", positive and negative
Stefan Krah1919b7e2012-03-21 18:25:23 +0100136:const:`Infinity`, and :const:`-0`::
Georg Brandl116aa622007-08-15 14:28:22 +0000137
Facundo Batista789bdf02008-06-21 17:29:41 +0000138 >>> getcontext().prec = 28
Georg Brandl116aa622007-08-15 14:28:22 +0000139 >>> Decimal(10)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000140 Decimal('10')
141 >>> Decimal('3.14')
142 Decimal('3.14')
Mark Dickinsone534a072010-04-04 22:13:14 +0000143 >>> Decimal(3.14)
144 Decimal('3.140000000000000124344978758017532527446746826171875')
Georg Brandl116aa622007-08-15 14:28:22 +0000145 >>> Decimal((0, (3, 1, 4), -2))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000146 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000147 >>> Decimal(str(2.0 ** 0.5))
Alexander Belopolsky287d1fd2011-01-12 16:37:14 +0000148 Decimal('1.4142135623730951')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000149 >>> Decimal(2) ** Decimal('0.5')
150 Decimal('1.414213562373095048801688724')
151 >>> Decimal('NaN')
152 Decimal('NaN')
153 >>> Decimal('-Infinity')
154 Decimal('-Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Stefan Krah1919b7e2012-03-21 18:25:23 +0100156If the :exc:`FloatOperation` signal is trapped, accidental mixing of
157decimals and floats in constructors or ordering comparisons raises
158an exception::
159
160 >>> c = getcontext()
161 >>> c.traps[FloatOperation] = True
162 >>> Decimal(3.14)
163 Traceback (most recent call last):
164 File "<stdin>", line 1, in <module>
165 decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
166 >>> Decimal('3.5') < 3.7
167 Traceback (most recent call last):
168 File "<stdin>", line 1, in <module>
169 decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
170 >>> Decimal('3.5') == 3.5
171 True
172
173.. versionadded:: 3.3
174
Georg Brandl116aa622007-08-15 14:28:22 +0000175The significance of a new Decimal is determined solely by the number of digits
176input. Context precision and rounding only come into play during arithmetic
Christian Heimesfe337bf2008-03-23 21:54:12 +0000177operations.
178
179.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181 >>> getcontext().prec = 6
182 >>> Decimal('3.0')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000183 Decimal('3.0')
Georg Brandl116aa622007-08-15 14:28:22 +0000184 >>> Decimal('3.1415926535')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000185 Decimal('3.1415926535')
Georg Brandl116aa622007-08-15 14:28:22 +0000186 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000187 Decimal('5.85987')
Georg Brandl116aa622007-08-15 14:28:22 +0000188 >>> getcontext().rounding = ROUND_UP
189 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000190 Decimal('5.85988')
Georg Brandl116aa622007-08-15 14:28:22 +0000191
Stefan Krah1919b7e2012-03-21 18:25:23 +0100192If the internal limits of the C version are exceeded, constructing
193a decimal raises :class:`InvalidOperation`::
194
195 >>> Decimal("1e9999999999999999999")
196 Traceback (most recent call last):
197 File "<stdin>", line 1, in <module>
198 decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]
199
200.. versionchanged:: 3.3
201
Georg Brandl116aa622007-08-15 14:28:22 +0000202Decimals interact well with much of the rest of Python. Here is a small decimal
Christian Heimesfe337bf2008-03-23 21:54:12 +0000203floating point flying circus:
204
205.. doctest::
206 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000207
Facundo Batista789bdf02008-06-21 17:29:41 +0000208 >>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
Georg Brandl116aa622007-08-15 14:28:22 +0000209 >>> max(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000210 Decimal('9.25')
Georg Brandl116aa622007-08-15 14:28:22 +0000211 >>> min(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000212 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +0000213 >>> sorted(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000214 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
215 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl116aa622007-08-15 14:28:22 +0000216 >>> sum(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000217 Decimal('19.29')
Georg Brandl116aa622007-08-15 14:28:22 +0000218 >>> a,b,c = data[:3]
219 >>> str(a)
220 '1.34'
221 >>> float(a)
Mark Dickinson8dad7df2009-06-28 20:36:54 +0000222 1.34
223 >>> round(a, 1)
224 Decimal('1.3')
Georg Brandl116aa622007-08-15 14:28:22 +0000225 >>> int(a)
226 1
227 >>> a * 5
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000228 Decimal('6.70')
Georg Brandl116aa622007-08-15 14:28:22 +0000229 >>> a * b
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000230 Decimal('2.5058')
Georg Brandl116aa622007-08-15 14:28:22 +0000231 >>> c % a
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000232 Decimal('0.77')
Georg Brandl116aa622007-08-15 14:28:22 +0000233
Christian Heimesfe337bf2008-03-23 21:54:12 +0000234And some mathematical functions are also available to Decimal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000235
Facundo Batista789bdf02008-06-21 17:29:41 +0000236 >>> getcontext().prec = 28
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000237 >>> Decimal(2).sqrt()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000238 Decimal('1.414213562373095048801688724')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000239 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000240 Decimal('2.718281828459045235360287471')
241 >>> Decimal('10').ln()
242 Decimal('2.302585092994045684017991455')
243 >>> Decimal('10').log10()
244 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000245
Georg Brandl116aa622007-08-15 14:28:22 +0000246The :meth:`quantize` method rounds a number to a fixed exponent. This method is
247useful for monetary applications that often round results to a fixed number of
Christian Heimesfe337bf2008-03-23 21:54:12 +0000248places:
Georg Brandl116aa622007-08-15 14:28:22 +0000249
250 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000251 Decimal('7.32')
Georg Brandl116aa622007-08-15 14:28:22 +0000252 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000253 Decimal('8')
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255As shown above, the :func:`getcontext` function accesses the current context and
256allows the settings to be changed. This approach meets the needs of most
257applications.
258
259For more advanced work, it may be useful to create alternate contexts using the
260Context() constructor. To make an alternate active, use the :func:`setcontext`
261function.
262
Serhiy Storchakab19542d2015-03-14 21:32:57 +0200263In accordance with the standard, the :mod:`decimal` module provides two ready to
Georg Brandl116aa622007-08-15 14:28:22 +0000264use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
265former is especially useful for debugging because many of the traps are
Christian Heimesfe337bf2008-03-23 21:54:12 +0000266enabled:
267
268.. doctest:: newcontext
269 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000270
271 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
272 >>> setcontext(myothercontext)
273 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000274 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276 >>> ExtendedContext
Stefan Krah1919b7e2012-03-21 18:25:23 +0100277 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000278 capitals=1, clamp=0, flags=[], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000279 >>> setcontext(ExtendedContext)
280 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000281 Decimal('0.142857143')
Georg Brandl116aa622007-08-15 14:28:22 +0000282 >>> Decimal(42) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000283 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000284
285 >>> setcontext(BasicContext)
286 >>> Decimal(42) / Decimal(0)
287 Traceback (most recent call last):
288 File "<pyshell#143>", line 1, in -toplevel-
289 Decimal(42) / Decimal(0)
290 DivisionByZero: x / 0
291
292Contexts also have signal flags for monitoring exceptional conditions
293encountered during computations. The flags remain set until explicitly cleared,
294so it is best to clear the flags before each set of monitored computations by
295using the :meth:`clear_flags` method. ::
296
297 >>> setcontext(ExtendedContext)
298 >>> getcontext().clear_flags()
299 >>> Decimal(355) / Decimal(113)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000300 Decimal('3.14159292')
Georg Brandl116aa622007-08-15 14:28:22 +0000301 >>> getcontext()
Stefan Krah1919b7e2012-03-21 18:25:23 +0100302 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000303 capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305The *flags* entry shows that the rational approximation to :const:`Pi` was
306rounded (digits beyond the context precision were thrown away) and that the
307result is inexact (some of the discarded digits were non-zero).
308
309Individual traps are set using the dictionary in the :attr:`traps` field of a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000310context:
Georg Brandl116aa622007-08-15 14:28:22 +0000311
Christian Heimesfe337bf2008-03-23 21:54:12 +0000312.. doctest:: newcontext
313
314 >>> setcontext(ExtendedContext)
Georg Brandl116aa622007-08-15 14:28:22 +0000315 >>> Decimal(1) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000316 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000317 >>> getcontext().traps[DivisionByZero] = 1
318 >>> Decimal(1) / Decimal(0)
319 Traceback (most recent call last):
320 File "<pyshell#112>", line 1, in -toplevel-
321 Decimal(1) / Decimal(0)
322 DivisionByZero: x / 0
323
324Most programs adjust the current context only once, at the beginning of the
325program. And, in many applications, data is converted to :class:`Decimal` with
326a single cast inside a loop. With context set and decimals created, the bulk of
327the program manipulates the data no differently than with other Python numeric
328types.
329
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000330.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332
333.. _decimal-decimal:
334
335Decimal objects
336---------------
337
338
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000339.. class:: Decimal(value="0", context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000340
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000341 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl116aa622007-08-15 14:28:22 +0000342
Raymond Hettinger96798592010-04-02 16:58:27 +0000343 *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal`
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000344 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Christian Heimesa62da1d2008-01-12 19:39:10 +0000345 string, it should conform to the decimal numeric string syntax after leading
346 and trailing whitespace characters are removed::
Georg Brandl116aa622007-08-15 14:28:22 +0000347
348 sign ::= '+' | '-'
349 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
350 indicator ::= 'e' | 'E'
351 digits ::= digit [digit]...
352 decimal-part ::= digits '.' [digits] | ['.'] digits
353 exponent-part ::= indicator [sign] digits
354 infinity ::= 'Infinity' | 'Inf'
355 nan ::= 'NaN' [digits] | 'sNaN' [digits]
356 numeric-value ::= decimal-part [exponent-part] | infinity
Georg Brandl48310cd2009-01-03 21:18:54 +0000357 numeric-string ::= [sign] numeric-value | [sign] nan
Georg Brandl116aa622007-08-15 14:28:22 +0000358
Mark Dickinson345adc42009-08-02 10:14:23 +0000359 Other Unicode decimal digits are also permitted where ``digit``
360 appears above. These include decimal digits from various other
361 alphabets (for example, Arabic-Indic and Devanāgarī digits) along
362 with the fullwidth digits ``'\uff10'`` through ``'\uff19'``.
363
Georg Brandl116aa622007-08-15 14:28:22 +0000364 If *value* is a :class:`tuple`, it should have three components, a sign
365 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
366 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000367 returns ``Decimal('1.414')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000368
Raymond Hettinger96798592010-04-02 16:58:27 +0000369 If *value* is a :class:`float`, the binary floating point value is losslessly
370 converted to its exact decimal equivalent. This conversion can often require
Mark Dickinsone534a072010-04-04 22:13:14 +0000371 53 or more digits of precision. For example, ``Decimal(float('1.1'))``
372 converts to
373 ``Decimal('1.100000000000000088817841970012523233890533447265625')``.
Raymond Hettinger96798592010-04-02 16:58:27 +0000374
Georg Brandl116aa622007-08-15 14:28:22 +0000375 The *context* precision does not affect how many digits are stored. That is
376 determined exclusively by the number of digits in *value*. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000377 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl116aa622007-08-15 14:28:22 +0000378 only three.
379
380 The purpose of the *context* argument is determining what to do if *value* is a
381 malformed string. If the context traps :const:`InvalidOperation`, an exception
382 is raised; otherwise, the constructor returns a new Decimal with the value of
383 :const:`NaN`.
384
385 Once constructed, :class:`Decimal` objects are immutable.
386
Mark Dickinsone534a072010-04-04 22:13:14 +0000387 .. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000388 The argument to the constructor is now permitted to be a :class:`float`
389 instance.
Mark Dickinsone534a072010-04-04 22:13:14 +0000390
Stefan Krah1919b7e2012-03-21 18:25:23 +0100391 .. versionchanged:: 3.3
392 :class:`float` arguments raise an exception if the :exc:`FloatOperation`
393 trap is set. By default the trap is off.
394
Benjamin Petersone41251e2008-04-25 01:59:09 +0000395 Decimal floating point objects share many properties with the other built-in
396 numeric types such as :class:`float` and :class:`int`. All of the usual math
397 operations and special methods apply. Likewise, decimal objects can be
398 copied, pickled, printed, used as dictionary keys, used as set elements,
399 compared, sorted, and coerced to another type (such as :class:`float` or
Mark Dickinson5d233fd2010-02-18 14:54:37 +0000400 :class:`int`).
Christian Heimesa62da1d2008-01-12 19:39:10 +0000401
Mark Dickinsona3f37402012-11-18 10:22:05 +0000402 There are some small differences between arithmetic on Decimal objects and
403 arithmetic on integers and floats. When the remainder operator ``%`` is
404 applied to Decimal objects, the sign of the result is the sign of the
405 *dividend* rather than the sign of the divisor::
406
407 >>> (-7) % 4
408 1
409 >>> Decimal(-7) % Decimal(4)
410 Decimal('-3')
411
412 The integer division operator ``//`` behaves analogously, returning the
413 integer part of the true quotient (truncating towards zero) rather than its
Mark Dickinsonec967242012-11-18 10:42:07 +0000414 floor, so as to preserve the usual identity ``x == (x // y) * y + x % y``::
Mark Dickinsona3f37402012-11-18 10:22:05 +0000415
416 >>> -7 // 4
417 -2
418 >>> Decimal(-7) // Decimal(4)
419 Decimal('-1')
420
421 The ``%`` and ``//`` operators implement the ``remainder`` and
422 ``divide-integer`` operations (respectively) as described in the
423 specification.
424
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000425 Decimal objects cannot generally be combined with floats or
426 instances of :class:`fractions.Fraction` in arithmetic operations:
427 an attempt to add a :class:`Decimal` to a :class:`float`, for
428 example, will raise a :exc:`TypeError`. However, it is possible to
429 use Python's comparison operators to compare a :class:`Decimal`
430 instance ``x`` with another number ``y``. This avoids confusing results
431 when doing equality comparisons between numbers of different types.
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000432
Ezio Melotti993a5ee2010-04-04 06:30:08 +0000433 .. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000434 Mixed-type comparisons between :class:`Decimal` instances and other
435 numeric types are now fully supported.
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000436
Benjamin Petersone41251e2008-04-25 01:59:09 +0000437 In addition to the standard numeric properties, decimal floating point
438 objects also have a number of specialized methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000439
Georg Brandl116aa622007-08-15 14:28:22 +0000440
Benjamin Petersone41251e2008-04-25 01:59:09 +0000441 .. method:: adjusted()
Georg Brandl116aa622007-08-15 14:28:22 +0000442
Benjamin Petersone41251e2008-04-25 01:59:09 +0000443 Return the adjusted exponent after shifting out the coefficient's
444 rightmost digits until only the lead digit remains:
445 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
446 position of the most significant digit with respect to the decimal point.
Georg Brandl116aa622007-08-15 14:28:22 +0000447
Georg Brandl116aa622007-08-15 14:28:22 +0000448
Benjamin Petersone41251e2008-04-25 01:59:09 +0000449 .. method:: as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +0000450
Benjamin Petersone41251e2008-04-25 01:59:09 +0000451 Return a :term:`named tuple` representation of the number:
452 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000453
Christian Heimes25bb7832008-01-11 16:17:00 +0000454
Benjamin Petersone41251e2008-04-25 01:59:09 +0000455 .. method:: canonical()
Georg Brandl116aa622007-08-15 14:28:22 +0000456
Benjamin Petersone41251e2008-04-25 01:59:09 +0000457 Return the canonical encoding of the argument. Currently, the encoding of
458 a :class:`Decimal` instance is always canonical, so this operation returns
459 its argument unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000460
Stefan Krah040e3112012-12-15 22:33:33 +0100461 .. method:: compare(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000462
Georg Brandl05f5ab72008-09-24 09:11:47 +0000463 Compare the values of two Decimal instances. :meth:`compare` returns a
464 Decimal instance, and if either operand is a NaN then the result is a
465 NaN::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000466
Georg Brandl05f5ab72008-09-24 09:11:47 +0000467 a or b is a NaN ==> Decimal('NaN')
468 a < b ==> Decimal('-1')
469 a == b ==> Decimal('0')
470 a > b ==> Decimal('1')
Georg Brandl116aa622007-08-15 14:28:22 +0000471
Stefan Krah040e3112012-12-15 22:33:33 +0100472 .. method:: compare_signal(other, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000473
Benjamin Petersone41251e2008-04-25 01:59:09 +0000474 This operation is identical to the :meth:`compare` method, except that all
475 NaNs signal. That is, if neither operand is a signaling NaN then any
476 quiet NaN operand is treated as though it were a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000477
Stefan Krah040e3112012-12-15 22:33:33 +0100478 .. method:: compare_total(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000479
Benjamin Petersone41251e2008-04-25 01:59:09 +0000480 Compare two operands using their abstract representation rather than their
481 numerical value. Similar to the :meth:`compare` method, but the result
482 gives a total ordering on :class:`Decimal` instances. Two
483 :class:`Decimal` instances with the same numeric value but different
484 representations compare unequal in this ordering:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000485
Benjamin Petersone41251e2008-04-25 01:59:09 +0000486 >>> Decimal('12.0').compare_total(Decimal('12'))
487 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000488
Benjamin Petersone41251e2008-04-25 01:59:09 +0000489 Quiet and signaling NaNs are also included in the total ordering. The
490 result of this function is ``Decimal('0')`` if both operands have the same
491 representation, ``Decimal('-1')`` if the first operand is lower in the
492 total order than the second, and ``Decimal('1')`` if the first operand is
493 higher in the total order than the second operand. See the specification
494 for details of the total order.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000495
Stefan Krah040e3112012-12-15 22:33:33 +0100496 This operation is unaffected by context and is quiet: no flags are changed
497 and no rounding is performed. As an exception, the C version may raise
498 InvalidOperation if the second operand cannot be converted exactly.
499
500 .. method:: compare_total_mag(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000501
Benjamin Petersone41251e2008-04-25 01:59:09 +0000502 Compare two operands using their abstract representation rather than their
503 value as in :meth:`compare_total`, but ignoring the sign of each operand.
504 ``x.compare_total_mag(y)`` is equivalent to
505 ``x.copy_abs().compare_total(y.copy_abs())``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000506
Stefan Krah040e3112012-12-15 22:33:33 +0100507 This operation is unaffected by context and is quiet: no flags are changed
508 and no rounding is performed. As an exception, the C version may raise
509 InvalidOperation if the second operand cannot be converted exactly.
510
Facundo Batista789bdf02008-06-21 17:29:41 +0000511 .. method:: conjugate()
512
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000513 Just returns self, this method is only to comply with the Decimal
Facundo Batista789bdf02008-06-21 17:29:41 +0000514 Specification.
515
Benjamin Petersone41251e2008-04-25 01:59:09 +0000516 .. method:: copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000517
Benjamin Petersone41251e2008-04-25 01:59:09 +0000518 Return the absolute value of the argument. This operation is unaffected
519 by the context and is quiet: no flags are changed and no rounding is
520 performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000521
Benjamin Petersone41251e2008-04-25 01:59:09 +0000522 .. method:: copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000523
Benjamin Petersone41251e2008-04-25 01:59:09 +0000524 Return the negation of the argument. This operation is unaffected by the
525 context and is quiet: no flags are changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000526
Stefan Krah040e3112012-12-15 22:33:33 +0100527 .. method:: copy_sign(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000528
Benjamin Petersone41251e2008-04-25 01:59:09 +0000529 Return a copy of the first operand with the sign set to be the same as the
530 sign of the second operand. For example:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000531
Benjamin Petersone41251e2008-04-25 01:59:09 +0000532 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
533 Decimal('-2.3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000534
Stefan Krah040e3112012-12-15 22:33:33 +0100535 This operation is unaffected by context and is quiet: no flags are changed
536 and no rounding is performed. As an exception, the C version may raise
537 InvalidOperation if the second operand cannot be converted exactly.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000538
Stefan Krah040e3112012-12-15 22:33:33 +0100539 .. method:: exp(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000540
Benjamin Petersone41251e2008-04-25 01:59:09 +0000541 Return the value of the (natural) exponential function ``e**x`` at the
542 given number. The result is correctly rounded using the
543 :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000544
Benjamin Petersone41251e2008-04-25 01:59:09 +0000545 >>> Decimal(1).exp()
546 Decimal('2.718281828459045235360287471')
547 >>> Decimal(321).exp()
548 Decimal('2.561702493119680037517373933E+139')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000549
Raymond Hettinger771ed762009-01-03 19:20:32 +0000550 .. method:: from_float(f)
551
552 Classmethod that converts a float to a decimal number, exactly.
553
554 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
555 Since 0.1 is not exactly representable in binary floating point, the
556 value is stored as the nearest representable value which is
557 `0x1.999999999999ap-4`. That equivalent value in decimal is
558 `0.1000000000000000055511151231257827021181583404541015625`.
559
Mark Dickinsone534a072010-04-04 22:13:14 +0000560 .. note:: From Python 3.2 onwards, a :class:`Decimal` instance
561 can also be constructed directly from a :class:`float`.
562
Raymond Hettinger771ed762009-01-03 19:20:32 +0000563 .. doctest::
564
565 >>> Decimal.from_float(0.1)
566 Decimal('0.1000000000000000055511151231257827021181583404541015625')
567 >>> Decimal.from_float(float('nan'))
568 Decimal('NaN')
569 >>> Decimal.from_float(float('inf'))
570 Decimal('Infinity')
571 >>> Decimal.from_float(float('-inf'))
572 Decimal('-Infinity')
573
Georg Brandl45f53372009-01-03 21:15:20 +0000574 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000575
Stefan Krah040e3112012-12-15 22:33:33 +0100576 .. method:: fma(other, third, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000577
Benjamin Petersone41251e2008-04-25 01:59:09 +0000578 Fused multiply-add. Return self*other+third with no rounding of the
579 intermediate product self*other.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000580
Benjamin Petersone41251e2008-04-25 01:59:09 +0000581 >>> Decimal(2).fma(3, 5)
582 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000583
Benjamin Petersone41251e2008-04-25 01:59:09 +0000584 .. method:: is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000585
Benjamin Petersone41251e2008-04-25 01:59:09 +0000586 Return :const:`True` if the argument is canonical and :const:`False`
587 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
588 this operation always returns :const:`True`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000589
Benjamin Petersone41251e2008-04-25 01:59:09 +0000590 .. method:: is_finite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000591
Benjamin Petersone41251e2008-04-25 01:59:09 +0000592 Return :const:`True` if the argument is a finite number, and
593 :const:`False` if the argument is an infinity or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000594
Benjamin Petersone41251e2008-04-25 01:59:09 +0000595 .. method:: is_infinite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000596
Benjamin Petersone41251e2008-04-25 01:59:09 +0000597 Return :const:`True` if the argument is either positive or negative
598 infinity and :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000599
Benjamin Petersone41251e2008-04-25 01:59:09 +0000600 .. method:: is_nan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000601
Benjamin Petersone41251e2008-04-25 01:59:09 +0000602 Return :const:`True` if the argument is a (quiet or signaling) NaN and
603 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
Stefan Krah040e3112012-12-15 22:33:33 +0100605 .. method:: is_normal(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000606
Benjamin Petersone41251e2008-04-25 01:59:09 +0000607 Return :const:`True` if the argument is a *normal* finite number. Return
608 :const:`False` if the argument is zero, subnormal, infinite or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000609
Benjamin Petersone41251e2008-04-25 01:59:09 +0000610 .. method:: is_qnan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000611
Benjamin Petersone41251e2008-04-25 01:59:09 +0000612 Return :const:`True` if the argument is a quiet NaN, and
613 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000614
Benjamin Petersone41251e2008-04-25 01:59:09 +0000615 .. method:: is_signed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616
Benjamin Petersone41251e2008-04-25 01:59:09 +0000617 Return :const:`True` if the argument has a negative sign and
618 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000619
Benjamin Petersone41251e2008-04-25 01:59:09 +0000620 .. method:: is_snan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000621
Benjamin Petersone41251e2008-04-25 01:59:09 +0000622 Return :const:`True` if the argument is a signaling NaN and :const:`False`
623 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624
Stefan Krah040e3112012-12-15 22:33:33 +0100625 .. method:: is_subnormal(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626
Benjamin Petersone41251e2008-04-25 01:59:09 +0000627 Return :const:`True` if the argument is subnormal, and :const:`False`
628 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000629
Benjamin Petersone41251e2008-04-25 01:59:09 +0000630 .. method:: is_zero()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000631
Benjamin Petersone41251e2008-04-25 01:59:09 +0000632 Return :const:`True` if the argument is a (positive or negative) zero and
633 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634
Stefan Krah040e3112012-12-15 22:33:33 +0100635 .. method:: ln(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000636
Benjamin Petersone41251e2008-04-25 01:59:09 +0000637 Return the natural (base e) logarithm of the operand. The result is
638 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000639
Stefan Krah040e3112012-12-15 22:33:33 +0100640 .. method:: log10(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000641
Benjamin Petersone41251e2008-04-25 01:59:09 +0000642 Return the base ten logarithm of the operand. The result is correctly
643 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644
Stefan Krah040e3112012-12-15 22:33:33 +0100645 .. method:: logb(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646
Benjamin Petersone41251e2008-04-25 01:59:09 +0000647 For a nonzero number, return the adjusted exponent of its operand as a
648 :class:`Decimal` instance. If the operand is a zero then
649 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
650 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
651 returned.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000652
Stefan Krah040e3112012-12-15 22:33:33 +0100653 .. method:: logical_and(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000654
Benjamin Petersone41251e2008-04-25 01:59:09 +0000655 :meth:`logical_and` is a logical operation which takes two *logical
656 operands* (see :ref:`logical_operands_label`). The result is the
657 digit-wise ``and`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658
Stefan Krah040e3112012-12-15 22:33:33 +0100659 .. method:: logical_invert(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000660
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000661 :meth:`logical_invert` is a logical operation. The
Benjamin Petersone41251e2008-04-25 01:59:09 +0000662 result is the digit-wise inversion of the operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663
Stefan Krah040e3112012-12-15 22:33:33 +0100664 .. method:: logical_or(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665
Benjamin Petersone41251e2008-04-25 01:59:09 +0000666 :meth:`logical_or` is a logical operation which takes two *logical
667 operands* (see :ref:`logical_operands_label`). The result is the
668 digit-wise ``or`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000669
Stefan Krah040e3112012-12-15 22:33:33 +0100670 .. method:: logical_xor(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000671
Benjamin Petersone41251e2008-04-25 01:59:09 +0000672 :meth:`logical_xor` is a logical operation which takes two *logical
673 operands* (see :ref:`logical_operands_label`). The result is the
674 digit-wise exclusive or of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000675
Stefan Krah040e3112012-12-15 22:33:33 +0100676 .. method:: max(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000677
Benjamin Petersone41251e2008-04-25 01:59:09 +0000678 Like ``max(self, other)`` except that the context rounding rule is applied
679 before returning and that :const:`NaN` values are either signaled or
680 ignored (depending on the context and whether they are signaling or
681 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000682
Stefan Krah040e3112012-12-15 22:33:33 +0100683 .. method:: max_mag(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000684
Georg Brandl502d9a52009-07-26 15:02:41 +0000685 Similar to the :meth:`.max` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000686 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000687
Stefan Krah040e3112012-12-15 22:33:33 +0100688 .. method:: min(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689
Benjamin Petersone41251e2008-04-25 01:59:09 +0000690 Like ``min(self, other)`` except that the context rounding rule is applied
691 before returning and that :const:`NaN` values are either signaled or
692 ignored (depending on the context and whether they are signaling or
693 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000694
Stefan Krah040e3112012-12-15 22:33:33 +0100695 .. method:: min_mag(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000696
Georg Brandl502d9a52009-07-26 15:02:41 +0000697 Similar to the :meth:`.min` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000698 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000699
Stefan Krah040e3112012-12-15 22:33:33 +0100700 .. method:: next_minus(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000701
Benjamin Petersone41251e2008-04-25 01:59:09 +0000702 Return the largest number representable in the given context (or in the
703 current thread's context if no context is given) that is smaller than the
704 given operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705
Stefan Krah040e3112012-12-15 22:33:33 +0100706 .. method:: next_plus(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000707
Benjamin Petersone41251e2008-04-25 01:59:09 +0000708 Return the smallest number representable in the given context (or in the
709 current thread's context if no context is given) that is larger than the
710 given operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000711
Stefan Krah040e3112012-12-15 22:33:33 +0100712 .. method:: next_toward(other, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000713
Benjamin Petersone41251e2008-04-25 01:59:09 +0000714 If the two operands are unequal, return the number closest to the first
715 operand in the direction of the second operand. If both operands are
716 numerically equal, return a copy of the first operand with the sign set to
717 be the same as the sign of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000718
Stefan Krah040e3112012-12-15 22:33:33 +0100719 .. method:: normalize(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000720
Benjamin Petersone41251e2008-04-25 01:59:09 +0000721 Normalize the number by stripping the rightmost trailing zeros and
722 converting any result equal to :const:`Decimal('0')` to
Senthil Kumarana6bac952011-07-04 11:28:30 -0700723 :const:`Decimal('0e0')`. Used for producing canonical values for attributes
Benjamin Petersone41251e2008-04-25 01:59:09 +0000724 of an equivalence class. For example, ``Decimal('32.100')`` and
725 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
726 ``Decimal('32.1')``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000727
Stefan Krah040e3112012-12-15 22:33:33 +0100728 .. method:: number_class(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000729
Benjamin Petersone41251e2008-04-25 01:59:09 +0000730 Return a string describing the *class* of the operand. The returned value
731 is one of the following ten strings.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000732
Benjamin Petersone41251e2008-04-25 01:59:09 +0000733 * ``"-Infinity"``, indicating that the operand is negative infinity.
734 * ``"-Normal"``, indicating that the operand is a negative normal number.
735 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
736 * ``"-Zero"``, indicating that the operand is a negative zero.
737 * ``"+Zero"``, indicating that the operand is a positive zero.
738 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
739 * ``"+Normal"``, indicating that the operand is a positive normal number.
740 * ``"+Infinity"``, indicating that the operand is positive infinity.
741 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
742 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000743
Stefan Krahb151f8f2014-04-30 19:15:38 +0200744 .. method:: quantize(exp, rounding=None, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745
Benjamin Petersone41251e2008-04-25 01:59:09 +0000746 Return a value equal to the first operand after rounding and having the
747 exponent of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000748
Benjamin Petersone41251e2008-04-25 01:59:09 +0000749 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
750 Decimal('1.414')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751
Benjamin Petersone41251e2008-04-25 01:59:09 +0000752 Unlike other operations, if the length of the coefficient after the
753 quantize operation would be greater than precision, then an
754 :const:`InvalidOperation` is signaled. This guarantees that, unless there
755 is an error condition, the quantized exponent is always equal to that of
756 the right-hand operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000757
Benjamin Petersone41251e2008-04-25 01:59:09 +0000758 Also unlike other operations, quantize never signals Underflow, even if
759 the result is subnormal and inexact.
Georg Brandl116aa622007-08-15 14:28:22 +0000760
Benjamin Petersone41251e2008-04-25 01:59:09 +0000761 If the exponent of the second operand is larger than that of the first
762 then rounding may be necessary. In this case, the rounding mode is
763 determined by the ``rounding`` argument if given, else by the given
764 ``context`` argument; if neither argument is given the rounding mode of
765 the current thread's context is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000766
Stefan Krahb151f8f2014-04-30 19:15:38 +0200767 An error is returned whenever the resulting exponent is greater than
768 :attr:`Emax` or less than :attr:`Etiny`.
Stefan Krahaf3f3a72012-08-30 12:33:55 +0200769
Benjamin Petersone41251e2008-04-25 01:59:09 +0000770 .. method:: radix()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000771
Benjamin Petersone41251e2008-04-25 01:59:09 +0000772 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
773 class does all its arithmetic. Included for compatibility with the
774 specification.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000775
Stefan Krah040e3112012-12-15 22:33:33 +0100776 .. method:: remainder_near(other, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000777
Mark Dickinson6ae568b2012-10-31 19:44:36 +0000778 Return the remainder from dividing *self* by *other*. This differs from
779 ``self % other`` in that the sign of the remainder is chosen so as to
780 minimize its absolute value. More precisely, the return value is
781 ``self - n * other`` where ``n`` is the integer nearest to the exact
782 value of ``self / other``, and if two integers are equally near then the
783 even one is chosen.
Georg Brandl116aa622007-08-15 14:28:22 +0000784
Mark Dickinson6ae568b2012-10-31 19:44:36 +0000785 If the result is zero then its sign will be the sign of *self*.
786
787 >>> Decimal(18).remainder_near(Decimal(10))
788 Decimal('-2')
789 >>> Decimal(25).remainder_near(Decimal(10))
790 Decimal('5')
791 >>> Decimal(35).remainder_near(Decimal(10))
792 Decimal('-5')
Georg Brandl116aa622007-08-15 14:28:22 +0000793
Stefan Krah040e3112012-12-15 22:33:33 +0100794 .. method:: rotate(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795
Benjamin Petersone41251e2008-04-25 01:59:09 +0000796 Return the result of rotating the digits of the first operand by an amount
797 specified by the second operand. The second operand must be an integer in
798 the range -precision through precision. The absolute value of the second
799 operand gives the number of places to rotate. If the second operand is
800 positive then rotation is to the left; otherwise rotation is to the right.
801 The coefficient of the first operand is padded on the left with zeros to
802 length precision if necessary. The sign and exponent of the first operand
803 are unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000804
Stefan Krah040e3112012-12-15 22:33:33 +0100805 .. method:: same_quantum(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000806
Benjamin Petersone41251e2008-04-25 01:59:09 +0000807 Test whether self and other have the same exponent or whether both are
808 :const:`NaN`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000809
Stefan Krah040e3112012-12-15 22:33:33 +0100810 This operation is unaffected by context and is quiet: no flags are changed
811 and no rounding is performed. As an exception, the C version may raise
812 InvalidOperation if the second operand cannot be converted exactly.
813
814 .. method:: scaleb(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000815
Benjamin Petersone41251e2008-04-25 01:59:09 +0000816 Return the first operand with exponent adjusted by the second.
817 Equivalently, return the first operand multiplied by ``10**other``. The
818 second operand must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +0000819
Stefan Krah040e3112012-12-15 22:33:33 +0100820 .. method:: shift(other, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000821
Benjamin Petersone41251e2008-04-25 01:59:09 +0000822 Return the result of shifting the digits of the first operand by an amount
823 specified by the second operand. The second operand must be an integer in
824 the range -precision through precision. The absolute value of the second
825 operand gives the number of places to shift. If the second operand is
826 positive then the shift is to the left; otherwise the shift is to the
827 right. Digits shifted into the coefficient are zeros. The sign and
828 exponent of the first operand are unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +0000829
Stefan Krah040e3112012-12-15 22:33:33 +0100830 .. method:: sqrt(context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000831
Benjamin Petersone41251e2008-04-25 01:59:09 +0000832 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000833
Georg Brandl116aa622007-08-15 14:28:22 +0000834
Stefan Krah040e3112012-12-15 22:33:33 +0100835 .. method:: to_eng_string(context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000836
Benjamin Petersone41251e2008-04-25 01:59:09 +0000837 Convert to an engineering-type string.
Georg Brandl116aa622007-08-15 14:28:22 +0000838
Benjamin Petersone41251e2008-04-25 01:59:09 +0000839 Engineering notation has an exponent which is a multiple of 3, so there
840 are up to 3 digits left of the decimal place. For example, converts
Martin Panterd21e0b52015-10-10 10:36:22 +0000841 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000842
Stefan Krah040e3112012-12-15 22:33:33 +0100843 .. method:: to_integral(rounding=None, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000844
Benjamin Petersone41251e2008-04-25 01:59:09 +0000845 Identical to the :meth:`to_integral_value` method. The ``to_integral``
846 name has been kept for compatibility with older versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000847
Stefan Krah040e3112012-12-15 22:33:33 +0100848 .. method:: to_integral_exact(rounding=None, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000849
Benjamin Petersone41251e2008-04-25 01:59:09 +0000850 Round to the nearest integer, signaling :const:`Inexact` or
851 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
852 determined by the ``rounding`` parameter if given, else by the given
853 ``context``. If neither parameter is given then the rounding mode of the
854 current context is used.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000855
Stefan Krah040e3112012-12-15 22:33:33 +0100856 .. method:: to_integral_value(rounding=None, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000857
Benjamin Petersone41251e2008-04-25 01:59:09 +0000858 Round to the nearest integer without signaling :const:`Inexact` or
859 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
860 rounding method in either the supplied *context* or the current context.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000862
863.. _logical_operands_label:
864
865Logical operands
866^^^^^^^^^^^^^^^^
867
868The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
869and :meth:`logical_xor` methods expect their arguments to be *logical
870operands*. A *logical operand* is a :class:`Decimal` instance whose
871exponent and sign are both zero, and whose digits are all either
872:const:`0` or :const:`1`.
873
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000874.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000875
876
877.. _decimal-context:
878
879Context objects
880---------------
881
882Contexts are environments for arithmetic operations. They govern precision, set
883rules for rounding, determine which signals are treated as exceptions, and limit
884the range for exponents.
885
886Each thread has its own current context which is accessed or changed using the
887:func:`getcontext` and :func:`setcontext` functions:
888
889
890.. function:: getcontext()
891
892 Return the current context for the active thread.
893
894
895.. function:: setcontext(c)
896
897 Set the current context for the active thread to *c*.
898
Georg Brandle6bcc912008-05-12 18:05:20 +0000899You can also use the :keyword:`with` statement and the :func:`localcontext`
900function to temporarily change the active context.
Georg Brandl116aa622007-08-15 14:28:22 +0000901
Stefan Krah040e3112012-12-15 22:33:33 +0100902.. function:: localcontext(ctx=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000903
904 Return a context manager that will set the current context for the active thread
Stefan Krah040e3112012-12-15 22:33:33 +0100905 to a copy of *ctx* on entry to the with-statement and restore the previous context
Georg Brandl116aa622007-08-15 14:28:22 +0000906 when exiting the with-statement. If no context is specified, a copy of the
907 current context is used.
908
Georg Brandl116aa622007-08-15 14:28:22 +0000909 For example, the following code sets the current decimal precision to 42 places,
910 performs a calculation, and then automatically restores the previous context::
911
Georg Brandl116aa622007-08-15 14:28:22 +0000912 from decimal import localcontext
913
914 with localcontext() as ctx:
915 ctx.prec = 42 # Perform a high precision calculation
916 s = calculate_something()
917 s = +s # Round the final result back to the default precision
918
919New contexts can also be created using the :class:`Context` constructor
920described below. In addition, the module provides three pre-made contexts:
921
922
923.. class:: BasicContext
924
925 This is a standard context defined by the General Decimal Arithmetic
926 Specification. Precision is set to nine. Rounding is set to
927 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
928 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
929 :const:`Subnormal`.
930
931 Because many of the traps are enabled, this context is useful for debugging.
932
933
934.. class:: ExtendedContext
935
936 This is a standard context defined by the General Decimal Arithmetic
937 Specification. Precision is set to nine. Rounding is set to
938 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
939 exceptions are not raised during computations).
940
Christian Heimes3feef612008-02-11 06:19:17 +0000941 Because the traps are disabled, this context is useful for applications that
Georg Brandl116aa622007-08-15 14:28:22 +0000942 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
943 raising exceptions. This allows an application to complete a run in the
944 presence of conditions that would otherwise halt the program.
945
946
947.. class:: DefaultContext
948
949 This context is used by the :class:`Context` constructor as a prototype for new
950 contexts. Changing a field (such a precision) has the effect of changing the
Stefan Kraha1193932010-05-29 12:59:18 +0000951 default for new contexts created by the :class:`Context` constructor.
Georg Brandl116aa622007-08-15 14:28:22 +0000952
953 This context is most useful in multi-threaded environments. Changing one of the
954 fields before threads are started has the effect of setting system-wide
955 defaults. Changing the fields after threads have started is not recommended as
956 it would require thread synchronization to prevent race conditions.
957
958 In single threaded environments, it is preferable to not use this context at
959 all. Instead, simply create contexts explicitly as described below.
960
Stefan Krah1919b7e2012-03-21 18:25:23 +0100961 The default values are :attr:`prec`\ =\ :const:`28`,
962 :attr:`rounding`\ =\ :const:`ROUND_HALF_EVEN`,
963 and enabled traps for :class:`Overflow`, :class:`InvalidOperation`, and
964 :class:`DivisionByZero`.
Georg Brandl116aa622007-08-15 14:28:22 +0000965
966In addition to the three supplied contexts, new contexts can be created with the
967:class:`Context` constructor.
968
969
Stefan Krah1919b7e2012-03-21 18:25:23 +0100970.. class:: Context(prec=None, rounding=None, Emin=None, Emax=None, capitals=None, clamp=None, flags=None, traps=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000971
972 Creates a new context. If a field is not specified or is :const:`None`, the
973 default values are copied from the :const:`DefaultContext`. If the *flags*
974 field is not specified or is :const:`None`, all flags are cleared.
975
Stefan Krah1919b7e2012-03-21 18:25:23 +0100976 *prec* is an integer in the range [:const:`1`, :const:`MAX_PREC`] that sets
977 the precision for arithmetic operations in the context.
Georg Brandl116aa622007-08-15 14:28:22 +0000978
Stefan Krah1919b7e2012-03-21 18:25:23 +0100979 The *rounding* option is one of the constants listed in the section
980 `Rounding Modes`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000981
982 The *traps* and *flags* fields list any signals to be set. Generally, new
983 contexts should only set traps and leave the flags clear.
984
985 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
Stefan Krah1919b7e2012-03-21 18:25:23 +0100986 for exponents. *Emin* must be in the range [:const:`MIN_EMIN`, :const:`0`],
987 *Emax* in the range [:const:`0`, :const:`MAX_EMAX`].
Georg Brandl116aa622007-08-15 14:28:22 +0000988
989 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
990 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
991 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
992
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000993 The *clamp* field is either :const:`0` (the default) or :const:`1`.
994 If set to :const:`1`, the exponent ``e`` of a :class:`Decimal`
995 instance representable in this context is strictly limited to the
996 range ``Emin - prec + 1 <= e <= Emax - prec + 1``. If *clamp* is
997 :const:`0` then a weaker condition holds: the adjusted exponent of
998 the :class:`Decimal` instance is at most ``Emax``. When *clamp* is
999 :const:`1`, a large normal number will, where possible, have its
1000 exponent reduced and a corresponding number of zeros added to its
1001 coefficient, in order to fit the exponent constraints; this
1002 preserves the value of the number but loses information about
1003 significant trailing zeros. For example::
1004
1005 >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
1006 Decimal('1.23000E+999')
1007
1008 A *clamp* value of :const:`1` allows compatibility with the
1009 fixed-width decimal interchange formats specified in IEEE 754.
Georg Brandl116aa622007-08-15 14:28:22 +00001010
Benjamin Petersone41251e2008-04-25 01:59:09 +00001011 The :class:`Context` class defines several general purpose methods as well as
1012 a large number of methods for doing arithmetic directly in a given context.
1013 In addition, for each of the :class:`Decimal` methods described above (with
1014 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
Mark Dickinson84230a12010-02-18 14:49:50 +00001015 a corresponding :class:`Context` method. For example, for a :class:`Context`
1016 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
1017 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a
Mark Dickinson5d233fd2010-02-18 14:54:37 +00001018 Python integer (an instance of :class:`int`) anywhere that a
Mark Dickinson84230a12010-02-18 14:49:50 +00001019 Decimal instance is accepted.
Georg Brandl116aa622007-08-15 14:28:22 +00001020
1021
Benjamin Petersone41251e2008-04-25 01:59:09 +00001022 .. method:: clear_flags()
Georg Brandl116aa622007-08-15 14:28:22 +00001023
Benjamin Petersone41251e2008-04-25 01:59:09 +00001024 Resets all of the flags to :const:`0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001025
Stefan Krah1919b7e2012-03-21 18:25:23 +01001026 .. method:: clear_traps()
1027
1028 Resets all of the traps to :const:`0`.
1029
1030 .. versionadded:: 3.3
1031
Benjamin Petersone41251e2008-04-25 01:59:09 +00001032 .. method:: copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001033
Benjamin Petersone41251e2008-04-25 01:59:09 +00001034 Return a duplicate of the context.
Georg Brandl116aa622007-08-15 14:28:22 +00001035
Benjamin Petersone41251e2008-04-25 01:59:09 +00001036 .. method:: copy_decimal(num)
Georg Brandl116aa622007-08-15 14:28:22 +00001037
Benjamin Petersone41251e2008-04-25 01:59:09 +00001038 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +00001039
Benjamin Petersone41251e2008-04-25 01:59:09 +00001040 .. method:: create_decimal(num)
Christian Heimesfe337bf2008-03-23 21:54:12 +00001041
Benjamin Petersone41251e2008-04-25 01:59:09 +00001042 Creates a new Decimal instance from *num* but using *self* as
1043 context. Unlike the :class:`Decimal` constructor, the context precision,
1044 rounding method, flags, and traps are applied to the conversion.
Georg Brandl116aa622007-08-15 14:28:22 +00001045
Benjamin Petersone41251e2008-04-25 01:59:09 +00001046 This is useful because constants are often given to a greater precision
1047 than is needed by the application. Another benefit is that rounding
1048 immediately eliminates unintended effects from digits beyond the current
1049 precision. In the following example, using unrounded inputs means that
1050 adding zero to a sum can change the result:
Georg Brandl116aa622007-08-15 14:28:22 +00001051
Benjamin Petersone41251e2008-04-25 01:59:09 +00001052 .. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001053
Benjamin Petersone41251e2008-04-25 01:59:09 +00001054 >>> getcontext().prec = 3
1055 >>> Decimal('3.4445') + Decimal('1.0023')
1056 Decimal('4.45')
1057 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1058 Decimal('4.44')
Georg Brandl116aa622007-08-15 14:28:22 +00001059
Benjamin Petersone41251e2008-04-25 01:59:09 +00001060 This method implements the to-number operation of the IBM specification.
1061 If the argument is a string, no leading or trailing whitespace is
1062 permitted.
1063
Georg Brandl45f53372009-01-03 21:15:20 +00001064 .. method:: create_decimal_from_float(f)
Raymond Hettinger771ed762009-01-03 19:20:32 +00001065
1066 Creates a new Decimal instance from a float *f* but rounding using *self*
Georg Brandl45f53372009-01-03 21:15:20 +00001067 as the context. Unlike the :meth:`Decimal.from_float` class method,
Raymond Hettinger771ed762009-01-03 19:20:32 +00001068 the context precision, rounding method, flags, and traps are applied to
1069 the conversion.
1070
1071 .. doctest::
1072
Georg Brandl45f53372009-01-03 21:15:20 +00001073 >>> context = Context(prec=5, rounding=ROUND_DOWN)
1074 >>> context.create_decimal_from_float(math.pi)
1075 Decimal('3.1415')
1076 >>> context = Context(prec=5, traps=[Inexact])
1077 >>> context.create_decimal_from_float(math.pi)
1078 Traceback (most recent call last):
1079 ...
1080 decimal.Inexact: None
Raymond Hettinger771ed762009-01-03 19:20:32 +00001081
Georg Brandl45f53372009-01-03 21:15:20 +00001082 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +00001083
Benjamin Petersone41251e2008-04-25 01:59:09 +00001084 .. method:: Etiny()
1085
1086 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
1087 value for subnormal results. When underflow occurs, the exponent is set
1088 to :const:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +00001089
Benjamin Petersone41251e2008-04-25 01:59:09 +00001090 .. method:: Etop()
Georg Brandl116aa622007-08-15 14:28:22 +00001091
Benjamin Petersone41251e2008-04-25 01:59:09 +00001092 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001093
Benjamin Petersone41251e2008-04-25 01:59:09 +00001094 The usual approach to working with decimals is to create :class:`Decimal`
1095 instances and then apply arithmetic operations which take place within the
1096 current context for the active thread. An alternative approach is to use
1097 context methods for calculating within a specific context. The methods are
1098 similar to those for the :class:`Decimal` class and are only briefly
1099 recounted here.
Georg Brandl116aa622007-08-15 14:28:22 +00001100
1101
Benjamin Petersone41251e2008-04-25 01:59:09 +00001102 .. method:: abs(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001103
Benjamin Petersone41251e2008-04-25 01:59:09 +00001104 Returns the absolute value of *x*.
Georg Brandl116aa622007-08-15 14:28:22 +00001105
1106
Benjamin Petersone41251e2008-04-25 01:59:09 +00001107 .. method:: add(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001108
Benjamin Petersone41251e2008-04-25 01:59:09 +00001109 Return the sum of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001110
1111
Facundo Batista789bdf02008-06-21 17:29:41 +00001112 .. method:: canonical(x)
1113
1114 Returns the same Decimal object *x*.
1115
1116
1117 .. method:: compare(x, y)
1118
1119 Compares *x* and *y* numerically.
1120
1121
1122 .. method:: compare_signal(x, y)
1123
1124 Compares the values of the two operands numerically.
1125
1126
1127 .. method:: compare_total(x, y)
1128
1129 Compares two operands using their abstract representation.
1130
1131
1132 .. method:: compare_total_mag(x, y)
1133
1134 Compares two operands using their abstract representation, ignoring sign.
1135
1136
1137 .. method:: copy_abs(x)
1138
1139 Returns a copy of *x* with the sign set to 0.
1140
1141
1142 .. method:: copy_negate(x)
1143
1144 Returns a copy of *x* with the sign inverted.
1145
1146
1147 .. method:: copy_sign(x, y)
1148
1149 Copies the sign from *y* to *x*.
1150
1151
Benjamin Petersone41251e2008-04-25 01:59:09 +00001152 .. method:: divide(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001153
Benjamin Petersone41251e2008-04-25 01:59:09 +00001154 Return *x* divided by *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001155
1156
Benjamin Petersone41251e2008-04-25 01:59:09 +00001157 .. method:: divide_int(x, y)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001158
Benjamin Petersone41251e2008-04-25 01:59:09 +00001159 Return *x* divided by *y*, truncated to an integer.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001160
1161
Benjamin Petersone41251e2008-04-25 01:59:09 +00001162 .. method:: divmod(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001163
Benjamin Petersone41251e2008-04-25 01:59:09 +00001164 Divides two numbers and returns the integer part of the result.
Georg Brandl116aa622007-08-15 14:28:22 +00001165
1166
Facundo Batista789bdf02008-06-21 17:29:41 +00001167 .. method:: exp(x)
1168
1169 Returns `e ** x`.
1170
1171
1172 .. method:: fma(x, y, z)
1173
1174 Returns *x* multiplied by *y*, plus *z*.
1175
1176
1177 .. method:: is_canonical(x)
1178
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001179 Returns ``True`` if *x* is canonical; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001180
1181
1182 .. method:: is_finite(x)
1183
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001184 Returns ``True`` if *x* is finite; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001185
1186
1187 .. method:: is_infinite(x)
1188
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001189 Returns ``True`` if *x* is infinite; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001190
1191
1192 .. method:: is_nan(x)
1193
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001194 Returns ``True`` if *x* is a qNaN or sNaN; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001195
1196
1197 .. method:: is_normal(x)
1198
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001199 Returns ``True`` if *x* is a normal number; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001200
1201
1202 .. method:: is_qnan(x)
1203
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001204 Returns ``True`` if *x* is a quiet NaN; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001205
1206
1207 .. method:: is_signed(x)
1208
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001209 Returns ``True`` if *x* is negative; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001210
1211
1212 .. method:: is_snan(x)
1213
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001214 Returns ``True`` if *x* is a signaling NaN; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001215
1216
1217 .. method:: is_subnormal(x)
1218
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001219 Returns ``True`` if *x* is subnormal; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001220
1221
1222 .. method:: is_zero(x)
1223
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001224 Returns ``True`` if *x* is a zero; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001225
1226
1227 .. method:: ln(x)
1228
1229 Returns the natural (base e) logarithm of *x*.
1230
1231
1232 .. method:: log10(x)
1233
1234 Returns the base 10 logarithm of *x*.
1235
1236
1237 .. method:: logb(x)
1238
1239 Returns the exponent of the magnitude of the operand's MSD.
1240
1241
1242 .. method:: logical_and(x, y)
1243
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001244 Applies the logical operation *and* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001245
1246
1247 .. method:: logical_invert(x)
1248
1249 Invert all the digits in *x*.
1250
1251
1252 .. method:: logical_or(x, y)
1253
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001254 Applies the logical operation *or* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001255
1256
1257 .. method:: logical_xor(x, y)
1258
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001259 Applies the logical operation *xor* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001260
1261
1262 .. method:: max(x, y)
1263
1264 Compares two values numerically and returns the maximum.
1265
1266
1267 .. method:: max_mag(x, y)
1268
1269 Compares the values numerically with their sign ignored.
1270
1271
1272 .. method:: min(x, y)
1273
1274 Compares two values numerically and returns the minimum.
1275
1276
1277 .. method:: min_mag(x, y)
1278
1279 Compares the values numerically with their sign ignored.
1280
1281
Benjamin Petersone41251e2008-04-25 01:59:09 +00001282 .. method:: minus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001283
Benjamin Petersone41251e2008-04-25 01:59:09 +00001284 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001285
1286
Benjamin Petersone41251e2008-04-25 01:59:09 +00001287 .. method:: multiply(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001288
Benjamin Petersone41251e2008-04-25 01:59:09 +00001289 Return the product of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001290
1291
Facundo Batista789bdf02008-06-21 17:29:41 +00001292 .. method:: next_minus(x)
1293
1294 Returns the largest representable number smaller than *x*.
1295
1296
1297 .. method:: next_plus(x)
1298
1299 Returns the smallest representable number larger than *x*.
1300
1301
1302 .. method:: next_toward(x, y)
1303
1304 Returns the number closest to *x*, in direction towards *y*.
1305
1306
1307 .. method:: normalize(x)
1308
1309 Reduces *x* to its simplest form.
1310
1311
1312 .. method:: number_class(x)
1313
1314 Returns an indication of the class of *x*.
1315
1316
Benjamin Petersone41251e2008-04-25 01:59:09 +00001317 .. method:: plus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001318
Benjamin Petersone41251e2008-04-25 01:59:09 +00001319 Plus corresponds to the unary prefix plus operator in Python. This
1320 operation applies the context precision and rounding, so it is *not* an
1321 identity operation.
Georg Brandl116aa622007-08-15 14:28:22 +00001322
1323
Stefan Krah040e3112012-12-15 22:33:33 +01001324 .. method:: power(x, y, modulo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001325
Benjamin Petersone41251e2008-04-25 01:59:09 +00001326 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl116aa622007-08-15 14:28:22 +00001327
Benjamin Petersone41251e2008-04-25 01:59:09 +00001328 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1329 must be integral. The result will be inexact unless ``y`` is integral and
1330 the result is finite and can be expressed exactly in 'precision' digits.
Stefan Krah1919b7e2012-03-21 18:25:23 +01001331 The rounding mode of the context is used. Results are always correctly-rounded
1332 in the Python version.
1333
1334 .. versionchanged:: 3.3
1335 The C module computes :meth:`power` in terms of the correctly-rounded
1336 :meth:`exp` and :meth:`ln` functions. The result is well-defined but
1337 only "almost always correctly-rounded".
Georg Brandl116aa622007-08-15 14:28:22 +00001338
Benjamin Petersone41251e2008-04-25 01:59:09 +00001339 With three arguments, compute ``(x**y) % modulo``. For the three argument
1340 form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +00001341
Benjamin Petersone41251e2008-04-25 01:59:09 +00001342 - all three arguments must be integral
1343 - ``y`` must be nonnegative
1344 - at least one of ``x`` or ``y`` must be nonzero
1345 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +00001346
Mark Dickinson5961b0e2010-02-22 15:41:48 +00001347 The value resulting from ``Context.power(x, y, modulo)`` is
1348 equal to the value that would be obtained by computing ``(x**y)
1349 % modulo`` with unbounded precision, but is computed more
1350 efficiently. The exponent of the result is zero, regardless of
1351 the exponents of ``x``, ``y`` and ``modulo``. The result is
1352 always exact.
Georg Brandl116aa622007-08-15 14:28:22 +00001353
Facundo Batista789bdf02008-06-21 17:29:41 +00001354
1355 .. method:: quantize(x, y)
1356
1357 Returns a value equal to *x* (rounded), having the exponent of *y*.
1358
1359
1360 .. method:: radix()
1361
1362 Just returns 10, as this is Decimal, :)
1363
1364
Benjamin Petersone41251e2008-04-25 01:59:09 +00001365 .. method:: remainder(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001366
Benjamin Petersone41251e2008-04-25 01:59:09 +00001367 Returns the remainder from integer division.
Georg Brandl116aa622007-08-15 14:28:22 +00001368
Benjamin Petersone41251e2008-04-25 01:59:09 +00001369 The sign of the result, if non-zero, is the same as that of the original
1370 dividend.
Georg Brandl116aa622007-08-15 14:28:22 +00001371
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001372
Facundo Batista789bdf02008-06-21 17:29:41 +00001373 .. method:: remainder_near(x, y)
1374
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001375 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1376 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
Facundo Batista789bdf02008-06-21 17:29:41 +00001377
1378
1379 .. method:: rotate(x, y)
1380
1381 Returns a rotated copy of *x*, *y* times.
1382
1383
1384 .. method:: same_quantum(x, y)
1385
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001386 Returns ``True`` if the two operands have the same exponent.
Facundo Batista789bdf02008-06-21 17:29:41 +00001387
1388
1389 .. method:: scaleb (x, y)
1390
1391 Returns the first operand after adding the second value its exp.
1392
1393
1394 .. method:: shift(x, y)
1395
1396 Returns a shifted copy of *x*, *y* times.
1397
1398
1399 .. method:: sqrt(x)
1400
1401 Square root of a non-negative number to context precision.
1402
1403
Benjamin Petersone41251e2008-04-25 01:59:09 +00001404 .. method:: subtract(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001405
Benjamin Petersone41251e2008-04-25 01:59:09 +00001406 Return the difference between *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001407
Facundo Batista789bdf02008-06-21 17:29:41 +00001408
1409 .. method:: to_eng_string(x)
1410
1411 Converts a number to a string, using scientific notation.
1412
1413
1414 .. method:: to_integral_exact(x)
1415
1416 Rounds to an integer.
1417
1418
Benjamin Petersone41251e2008-04-25 01:59:09 +00001419 .. method:: to_sci_string(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001420
Benjamin Petersone41251e2008-04-25 01:59:09 +00001421 Converts a number to a string using scientific notation.
Georg Brandl116aa622007-08-15 14:28:22 +00001422
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001423.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001424
Stefan Krah1919b7e2012-03-21 18:25:23 +01001425.. _decimal-rounding-modes:
1426
1427Constants
1428---------
1429
1430The constants in this section are only relevant for the C module. They
1431are also included in the pure Python version for compatibility.
1432
Stefan Krah851a07e2012-03-21 18:47:20 +01001433+---------------------+---------------------+-------------------------------+
1434| | 32-bit | 64-bit |
1435+=====================+=====================+===============================+
1436| .. data:: MAX_PREC | :const:`425000000` | :const:`999999999999999999` |
1437+---------------------+---------------------+-------------------------------+
1438| .. data:: MAX_EMAX | :const:`425000000` | :const:`999999999999999999` |
1439+---------------------+---------------------+-------------------------------+
1440| .. data:: MIN_EMIN | :const:`-425000000` | :const:`-999999999999999999` |
1441+---------------------+---------------------+-------------------------------+
1442| .. data:: MIN_ETINY | :const:`-849999999` | :const:`-1999999999999999997` |
1443+---------------------+---------------------+-------------------------------+
1444
Stefan Krah1919b7e2012-03-21 18:25:23 +01001445
1446.. data:: HAVE_THREADS
1447
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001448 The default value is ``True``. If Python is compiled without threads, the
Stefan Krah1919b7e2012-03-21 18:25:23 +01001449 C version automatically disables the expensive thread local context
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001450 machinery. In this case, the value is ``False``.
Stefan Krah1919b7e2012-03-21 18:25:23 +01001451
1452Rounding modes
1453--------------
1454
1455.. data:: ROUND_CEILING
1456
1457 Round towards :const:`Infinity`.
1458
1459.. data:: ROUND_DOWN
1460
1461 Round towards zero.
1462
1463.. data:: ROUND_FLOOR
1464
1465 Round towards :const:`-Infinity`.
1466
1467.. data:: ROUND_HALF_DOWN
1468
1469 Round to nearest with ties going towards zero.
1470
1471.. data:: ROUND_HALF_EVEN
1472
1473 Round to nearest with ties going to nearest even integer.
1474
1475.. data:: ROUND_HALF_UP
1476
1477 Round to nearest with ties going away from zero.
1478
1479.. data:: ROUND_UP
1480
1481 Round away from zero.
1482
1483.. data:: ROUND_05UP
1484
1485 Round away from zero if last digit after rounding towards zero would have
1486 been 0 or 5; otherwise round towards zero.
1487
Georg Brandl116aa622007-08-15 14:28:22 +00001488
1489.. _decimal-signals:
1490
1491Signals
1492-------
1493
1494Signals represent conditions that arise during computation. Each corresponds to
1495one context flag and one context trap enabler.
1496
Raymond Hettinger86173da2008-02-01 20:38:12 +00001497The context flag is set whenever the condition is encountered. After the
Georg Brandl116aa622007-08-15 14:28:22 +00001498computation, flags may be checked for informational purposes (for instance, to
1499determine whether a computation was exact). After checking the flags, be sure to
1500clear all flags before starting the next computation.
1501
1502If the context's trap enabler is set for the signal, then the condition causes a
1503Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1504is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1505condition.
1506
1507
1508.. class:: Clamped
1509
1510 Altered an exponent to fit representation constraints.
1511
1512 Typically, clamping occurs when an exponent falls outside the context's
1513 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001514 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001515
1516
1517.. class:: DecimalException
1518
1519 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1520
1521
1522.. class:: DivisionByZero
1523
1524 Signals the division of a non-infinite number by zero.
1525
1526 Can occur with division, modulo division, or when raising a number to a negative
1527 power. If this signal is not trapped, returns :const:`Infinity` or
1528 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1529
1530
1531.. class:: Inexact
1532
1533 Indicates that rounding occurred and the result is not exact.
1534
1535 Signals when non-zero digits were discarded during rounding. The rounded result
1536 is returned. The signal flag or trap is used to detect when results are
1537 inexact.
1538
1539
1540.. class:: InvalidOperation
1541
1542 An invalid operation was performed.
1543
1544 Indicates that an operation was requested that does not make sense. If not
1545 trapped, returns :const:`NaN`. Possible causes include::
1546
1547 Infinity - Infinity
1548 0 * Infinity
1549 Infinity / Infinity
1550 x % 0
1551 Infinity % x
Georg Brandl116aa622007-08-15 14:28:22 +00001552 sqrt(-x) and x > 0
1553 0 ** 0
1554 x ** (non-integer)
Georg Brandl48310cd2009-01-03 21:18:54 +00001555 x ** Infinity
Georg Brandl116aa622007-08-15 14:28:22 +00001556
1557
1558.. class:: Overflow
1559
1560 Numerical overflow.
1561
Benjamin Petersone41251e2008-04-25 01:59:09 +00001562 Indicates the exponent is larger than :attr:`Emax` after rounding has
1563 occurred. If not trapped, the result depends on the rounding mode, either
1564 pulling inward to the largest representable finite number or rounding outward
1565 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1566 are also signaled.
Georg Brandl116aa622007-08-15 14:28:22 +00001567
1568
1569.. class:: Rounded
1570
1571 Rounding occurred though possibly no information was lost.
1572
Benjamin Petersone41251e2008-04-25 01:59:09 +00001573 Signaled whenever rounding discards digits; even if those digits are zero
1574 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1575 the result unchanged. This signal is used to detect loss of significant
1576 digits.
Georg Brandl116aa622007-08-15 14:28:22 +00001577
1578
1579.. class:: Subnormal
1580
1581 Exponent was lower than :attr:`Emin` prior to rounding.
1582
Benjamin Petersone41251e2008-04-25 01:59:09 +00001583 Occurs when an operation result is subnormal (the exponent is too small). If
1584 not trapped, returns the result unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +00001585
1586
1587.. class:: Underflow
1588
1589 Numerical underflow with result rounded to zero.
1590
1591 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1592 and :class:`Subnormal` are also signaled.
1593
Stefan Krah1919b7e2012-03-21 18:25:23 +01001594
1595.. class:: FloatOperation
1596
1597 Enable stricter semantics for mixing floats and Decimals.
1598
1599 If the signal is not trapped (default), mixing floats and Decimals is
1600 permitted in the :class:`~decimal.Decimal` constructor,
1601 :meth:`~decimal.Context.create_decimal` and all comparison operators.
1602 Both conversion and comparisons are exact. Any occurrence of a mixed
1603 operation is silently recorded by setting :exc:`FloatOperation` in the
1604 context flags. Explicit conversions with :meth:`~decimal.Decimal.from_float`
1605 or :meth:`~decimal.Context.create_decimal_from_float` do not set the flag.
1606
1607 Otherwise (the signal is trapped), only equality comparisons and explicit
1608 conversions are silent. All other mixed operations raise :exc:`FloatOperation`.
1609
1610
Georg Brandl116aa622007-08-15 14:28:22 +00001611The following table summarizes the hierarchy of signals::
1612
1613 exceptions.ArithmeticError(exceptions.Exception)
1614 DecimalException
1615 Clamped
1616 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1617 Inexact
1618 Overflow(Inexact, Rounded)
1619 Underflow(Inexact, Rounded, Subnormal)
1620 InvalidOperation
1621 Rounded
1622 Subnormal
Stefan Krahb6405ef2012-03-23 14:46:48 +01001623 FloatOperation(DecimalException, exceptions.TypeError)
Georg Brandl116aa622007-08-15 14:28:22 +00001624
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001625.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001626
1627
Stefan Krah1919b7e2012-03-21 18:25:23 +01001628
Georg Brandl116aa622007-08-15 14:28:22 +00001629.. _decimal-notes:
1630
1631Floating Point Notes
1632--------------------
1633
1634
1635Mitigating round-off error with increased precision
1636^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1637
1638The use of decimal floating point eliminates decimal representation error
1639(making it possible to represent :const:`0.1` exactly); however, some operations
1640can still incur round-off error when non-zero digits exceed the fixed precision.
1641
1642The effects of round-off error can be amplified by the addition or subtraction
1643of nearly offsetting quantities resulting in loss of significance. Knuth
1644provides two instructive examples where rounded floating point arithmetic with
1645insufficient precision causes the breakdown of the associative and distributive
Christian Heimesfe337bf2008-03-23 21:54:12 +00001646properties of addition:
1647
1648.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001649
1650 # Examples from Seminumerical Algorithms, Section 4.2.2.
1651 >>> from decimal import Decimal, getcontext
1652 >>> getcontext().prec = 8
1653
1654 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1655 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001656 Decimal('9.5111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001657 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001658 Decimal('10')
Georg Brandl116aa622007-08-15 14:28:22 +00001659
1660 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1661 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001662 Decimal('0.01')
Georg Brandl116aa622007-08-15 14:28:22 +00001663 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001664 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001665
1666The :mod:`decimal` module makes it possible to restore the identities by
Christian Heimesfe337bf2008-03-23 21:54:12 +00001667expanding the precision sufficiently to avoid loss of significance:
1668
1669.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001670
1671 >>> getcontext().prec = 20
1672 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1673 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001674 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001675 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001676 Decimal('9.51111111')
Georg Brandl48310cd2009-01-03 21:18:54 +00001677 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001678 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1679 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001680 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001681 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001682 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001683
1684
1685Special values
1686^^^^^^^^^^^^^^
1687
1688The number system for the :mod:`decimal` module provides special values
1689including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001690and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001691
1692Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1693they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1694not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1695can result from rounding beyond the limits of the largest representable number.
1696
1697The infinities are signed (affine) and can be used in arithmetic operations
1698where they get treated as very large, indeterminate numbers. For instance,
1699adding a constant to infinity gives another infinite result.
1700
1701Some operations are indeterminate and return :const:`NaN`, or if the
1702:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1703``0/0`` returns :const:`NaN` which means "not a number". This variety of
1704:const:`NaN` is quiet and, once created, will flow through other computations
1705always resulting in another :const:`NaN`. This behavior can be useful for a
1706series of computations that occasionally have missing inputs --- it allows the
1707calculation to proceed while flagging specific results as invalid.
1708
1709A variant is :const:`sNaN` which signals rather than remaining quiet after every
1710operation. This is a useful return value when an invalid result needs to
1711interrupt a calculation for special handling.
1712
Christian Heimes77c02eb2008-02-09 02:18:51 +00001713The behavior of Python's comparison operators can be a little surprising where a
1714:const:`NaN` is involved. A test for equality where one of the operands is a
1715quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1716``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1717:const:`True`. An attempt to compare two Decimals using any of the ``<``,
1718``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1719if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes3feef612008-02-11 06:19:17 +00001720not trapped. Note that the General Decimal Arithmetic specification does not
Christian Heimes77c02eb2008-02-09 02:18:51 +00001721specify the behavior of direct comparisons; these rules for comparisons
1722involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1723section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1724and :meth:`compare-signal` methods instead.
1725
Georg Brandl116aa622007-08-15 14:28:22 +00001726The signed zeros can result from calculations that underflow. They keep the sign
1727that would have resulted if the calculation had been carried out to greater
1728precision. Since their magnitude is zero, both positive and negative zeros are
1729treated as equal and their sign is informational.
1730
1731In addition to the two signed zeros which are distinct yet equal, there are
1732various representations of zero with differing precisions yet equivalent in
1733value. This takes a bit of getting used to. For an eye accustomed to
1734normalized floating point representations, it is not immediately obvious that
Christian Heimesfe337bf2008-03-23 21:54:12 +00001735the following calculation returns a value equal to zero:
Georg Brandl116aa622007-08-15 14:28:22 +00001736
1737 >>> 1 / Decimal('Infinity')
Stefan Krah1919b7e2012-03-21 18:25:23 +01001738 Decimal('0E-1000026')
Georg Brandl116aa622007-08-15 14:28:22 +00001739
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001740.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001741
1742
1743.. _decimal-threads:
1744
1745Working with threads
1746--------------------
1747
1748The :func:`getcontext` function accesses a different :class:`Context` object for
1749each thread. Having separate thread contexts means that threads may make
Stefan Krah1919b7e2012-03-21 18:25:23 +01001750changes (such as ``getcontext().prec=10``) without interfering with other threads.
Georg Brandl116aa622007-08-15 14:28:22 +00001751
1752Likewise, the :func:`setcontext` function automatically assigns its target to
1753the current thread.
1754
1755If :func:`setcontext` has not been called before :func:`getcontext`, then
1756:func:`getcontext` will automatically create a new context for use in the
1757current thread.
1758
1759The new context is copied from a prototype context called *DefaultContext*. To
1760control the defaults so that each thread will use the same values throughout the
1761application, directly modify the *DefaultContext* object. This should be done
1762*before* any threads are started so that there won't be a race condition between
1763threads calling :func:`getcontext`. For example::
1764
1765 # Set applicationwide defaults for all threads about to be launched
1766 DefaultContext.prec = 12
1767 DefaultContext.rounding = ROUND_DOWN
1768 DefaultContext.traps = ExtendedContext.traps.copy()
1769 DefaultContext.traps[InvalidOperation] = 1
1770 setcontext(DefaultContext)
1771
1772 # Afterwards, the threads can be started
1773 t1.start()
1774 t2.start()
1775 t3.start()
1776 . . .
1777
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001778.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001779
1780
1781.. _decimal-recipes:
1782
1783Recipes
1784-------
1785
1786Here are a few recipes that serve as utility functions and that demonstrate ways
1787to work with the :class:`Decimal` class::
1788
1789 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1790 pos='', neg='-', trailneg=''):
1791 """Convert Decimal to a money formatted string.
1792
1793 places: required number of places after the decimal point
1794 curr: optional currency symbol before the sign (may be blank)
1795 sep: optional grouping separator (comma, period, space, or blank)
1796 dp: decimal point indicator (comma or period)
1797 only specify as blank when places is zero
1798 pos: optional sign for positive numbers: '+', space or blank
1799 neg: optional sign for negative numbers: '-', '(', space or blank
1800 trailneg:optional trailing minus indicator: '-', ')', space or blank
1801
1802 >>> d = Decimal('-1234567.8901')
1803 >>> moneyfmt(d, curr='$')
1804 '-$1,234,567.89'
1805 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1806 '1.234.568-'
1807 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1808 '($1,234,567.89)'
1809 >>> moneyfmt(Decimal(123456789), sep=' ')
1810 '123 456 789.00'
1811 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Christian Heimesdae2a892008-04-19 00:55:37 +00001812 '<0.02>'
Georg Brandl116aa622007-08-15 14:28:22 +00001813
1814 """
Christian Heimesa156e092008-02-16 07:38:31 +00001815 q = Decimal(10) ** -places # 2 places --> '0.01'
Georg Brandl48310cd2009-01-03 21:18:54 +00001816 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +00001817 result = []
Facundo Batista789bdf02008-06-21 17:29:41 +00001818 digits = list(map(str, digits))
Georg Brandl116aa622007-08-15 14:28:22 +00001819 build, next = result.append, digits.pop
1820 if sign:
1821 build(trailneg)
1822 for i in range(places):
Christian Heimesa156e092008-02-16 07:38:31 +00001823 build(next() if digits else '0')
Raymond Hettinger0ab10e42011-01-08 09:03:11 +00001824 if places:
1825 build(dp)
Christian Heimesdae2a892008-04-19 00:55:37 +00001826 if not digits:
1827 build('0')
Georg Brandl116aa622007-08-15 14:28:22 +00001828 i = 0
1829 while digits:
1830 build(next())
1831 i += 1
1832 if i == 3 and digits:
1833 i = 0
1834 build(sep)
1835 build(curr)
Christian Heimesa156e092008-02-16 07:38:31 +00001836 build(neg if sign else pos)
1837 return ''.join(reversed(result))
Georg Brandl116aa622007-08-15 14:28:22 +00001838
1839 def pi():
1840 """Compute Pi to the current precision.
1841
Georg Brandl6911e3c2007-09-04 07:15:32 +00001842 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001843 3.141592653589793238462643383
1844
1845 """
1846 getcontext().prec += 2 # extra digits for intermediate steps
1847 three = Decimal(3) # substitute "three=3.0" for regular floats
1848 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1849 while s != lasts:
1850 lasts = s
1851 n, na = n+na, na+8
1852 d, da = d+da, da+32
1853 t = (t * n) / d
1854 s += t
1855 getcontext().prec -= 2
1856 return +s # unary plus applies the new precision
1857
1858 def exp(x):
1859 """Return e raised to the power of x. Result type matches input type.
1860
Georg Brandl6911e3c2007-09-04 07:15:32 +00001861 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001862 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001863 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001864 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001865 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001866 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001867 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001868 (7.38905609893+0j)
1869
1870 """
1871 getcontext().prec += 2
1872 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1873 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001874 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001875 i += 1
1876 fact *= i
Georg Brandl48310cd2009-01-03 21:18:54 +00001877 num *= x
1878 s += num / fact
1879 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001880 return +s
1881
1882 def cos(x):
1883 """Return the cosine of x as measured in radians.
1884
Mark Dickinsonb2b23822010-11-21 07:37:49 +00001885 The Taylor series approximation works best for a small value of x.
Raymond Hettinger2a1e3e22010-11-21 02:47:22 +00001886 For larger values, first compute x = x % (2 * pi).
1887
Georg Brandl6911e3c2007-09-04 07:15:32 +00001888 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001889 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001890 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001891 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001892 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001893 (0.87758256189+0j)
1894
1895 """
1896 getcontext().prec += 2
1897 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1898 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001899 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001900 i += 2
1901 fact *= i * (i-1)
1902 num *= x * x
1903 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001904 s += num / fact * sign
1905 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001906 return +s
1907
1908 def sin(x):
1909 """Return the sine of x as measured in radians.
1910
Mark Dickinsonb2b23822010-11-21 07:37:49 +00001911 The Taylor series approximation works best for a small value of x.
Raymond Hettinger2a1e3e22010-11-21 02:47:22 +00001912 For larger values, first compute x = x % (2 * pi).
1913
Georg Brandl6911e3c2007-09-04 07:15:32 +00001914 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001915 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001916 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001917 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001918 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001919 (0.479425538604+0j)
1920
1921 """
1922 getcontext().prec += 2
1923 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1924 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001925 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001926 i += 2
1927 fact *= i * (i-1)
1928 num *= x * x
1929 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001930 s += num / fact * sign
1931 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001932 return +s
1933
1934
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001935.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001936
1937
1938.. _decimal-faq:
1939
1940Decimal FAQ
1941-----------
1942
1943Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1944minimize typing when using the interactive interpreter?
1945
Christian Heimesfe337bf2008-03-23 21:54:12 +00001946A. Some users abbreviate the constructor to just a single letter:
Georg Brandl116aa622007-08-15 14:28:22 +00001947
1948 >>> D = decimal.Decimal
1949 >>> D('1.23') + D('3.45')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001950 Decimal('4.68')
Georg Brandl116aa622007-08-15 14:28:22 +00001951
1952Q. In a fixed-point application with two decimal places, some inputs have many
1953places and need to be rounded. Others are not supposed to have excess digits
1954and need to be validated. What methods should be used?
1955
1956A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Christian Heimesfe337bf2008-03-23 21:54:12 +00001957the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl116aa622007-08-15 14:28:22 +00001958
1959 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1960
1961 >>> # Round to two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001962 >>> Decimal('3.214').quantize(TWOPLACES)
1963 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001964
Georg Brandl48310cd2009-01-03 21:18:54 +00001965 >>> # Validate that a number does not exceed two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001966 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1967 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001968
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001969 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl116aa622007-08-15 14:28:22 +00001970 Traceback (most recent call last):
1971 ...
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001972 Inexact: None
Georg Brandl116aa622007-08-15 14:28:22 +00001973
1974Q. Once I have valid two place inputs, how do I maintain that invariant
1975throughout an application?
1976
Christian Heimesa156e092008-02-16 07:38:31 +00001977A. Some operations like addition, subtraction, and multiplication by an integer
1978will automatically preserve fixed point. Others operations, like division and
1979non-integer multiplication, will change the number of decimal places and need to
Christian Heimesfe337bf2008-03-23 21:54:12 +00001980be followed-up with a :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001981
1982 >>> a = Decimal('102.72') # Initial fixed-point values
1983 >>> b = Decimal('3.17')
1984 >>> a + b # Addition preserves fixed-point
1985 Decimal('105.89')
1986 >>> a - b
1987 Decimal('99.55')
1988 >>> a * 42 # So does integer multiplication
1989 Decimal('4314.24')
1990 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1991 Decimal('325.62')
1992 >>> (b / a).quantize(TWOPLACES) # And quantize division
1993 Decimal('0.03')
1994
1995In developing fixed-point applications, it is convenient to define functions
Christian Heimesfe337bf2008-03-23 21:54:12 +00001996to handle the :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001997
1998 >>> def mul(x, y, fp=TWOPLACES):
1999 ... return (x * y).quantize(fp)
2000 >>> def div(x, y, fp=TWOPLACES):
2001 ... return (x / y).quantize(fp)
2002
2003 >>> mul(a, b) # Automatically preserve fixed-point
2004 Decimal('325.62')
2005 >>> div(b, a)
2006 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +00002007
2008Q. There are many ways to express the same value. The numbers :const:`200`,
2009:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
2010various precisions. Is there a way to transform them to a single recognizable
2011canonical value?
2012
2013A. The :meth:`normalize` method maps all equivalent values to a single
Christian Heimesfe337bf2008-03-23 21:54:12 +00002014representative:
Georg Brandl116aa622007-08-15 14:28:22 +00002015
2016 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
2017 >>> [v.normalize() for v in values]
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002018 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl116aa622007-08-15 14:28:22 +00002019
2020Q. Some decimal values always print with exponential notation. Is there a way
2021to get a non-exponential representation?
2022
2023A. For some values, exponential notation is the only way to express the number
2024of significant places in the coefficient. For example, expressing
2025:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
2026original's two-place significance.
2027
Christian Heimesa156e092008-02-16 07:38:31 +00002028If an application does not care about tracking significance, it is easy to
Christian Heimesc3f30c42008-02-22 16:37:40 +00002029remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimesfe337bf2008-03-23 21:54:12 +00002030value unchanged:
Christian Heimesa156e092008-02-16 07:38:31 +00002031
2032 >>> def remove_exponent(d):
2033 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
2034
2035 >>> remove_exponent(Decimal('5E+3'))
2036 Decimal('5000')
2037
Georg Brandl116aa622007-08-15 14:28:22 +00002038Q. Is there a way to convert a regular float to a :class:`Decimal`?
2039
Mark Dickinsone534a072010-04-04 22:13:14 +00002040A. Yes, any binary floating point number can be exactly expressed as a
Raymond Hettinger96798592010-04-02 16:58:27 +00002041Decimal though an exact conversion may take more precision than intuition would
2042suggest:
Georg Brandl116aa622007-08-15 14:28:22 +00002043
Christian Heimesfe337bf2008-03-23 21:54:12 +00002044.. doctest::
2045
Raymond Hettinger96798592010-04-02 16:58:27 +00002046 >>> Decimal(math.pi)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002047 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl116aa622007-08-15 14:28:22 +00002048
Georg Brandl116aa622007-08-15 14:28:22 +00002049Q. Within a complex calculation, how can I make sure that I haven't gotten a
2050spurious result because of insufficient precision or rounding anomalies.
2051
2052A. The decimal module makes it easy to test results. A best practice is to
2053re-run calculations using greater precision and with various rounding modes.
2054Widely differing results indicate insufficient precision, rounding mode issues,
2055ill-conditioned inputs, or a numerically unstable algorithm.
2056
2057Q. I noticed that context precision is applied to the results of operations but
2058not to the inputs. Is there anything to watch out for when mixing values of
2059different precisions?
2060
2061A. Yes. The principle is that all values are considered to be exact and so is
2062the arithmetic on those values. Only the results are rounded. The advantage
2063for inputs is that "what you type is what you get". A disadvantage is that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00002064results can look odd if you forget that the inputs haven't been rounded:
2065
2066.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00002067
2068 >>> getcontext().prec = 3
Christian Heimesfe337bf2008-03-23 21:54:12 +00002069 >>> Decimal('3.104') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002070 Decimal('5.21')
Christian Heimesfe337bf2008-03-23 21:54:12 +00002071 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002072 Decimal('5.20')
Georg Brandl116aa622007-08-15 14:28:22 +00002073
2074The solution is either to increase precision or to force rounding of inputs
Christian Heimesfe337bf2008-03-23 21:54:12 +00002075using the unary plus operation:
2076
2077.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00002078
2079 >>> getcontext().prec = 3
2080 >>> +Decimal('1.23456789') # unary plus triggers rounding
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002081 Decimal('1.23')
Georg Brandl116aa622007-08-15 14:28:22 +00002082
2083Alternatively, inputs can be rounded upon creation using the
Christian Heimesfe337bf2008-03-23 21:54:12 +00002084:meth:`Context.create_decimal` method:
Georg Brandl116aa622007-08-15 14:28:22 +00002085
2086 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002087 Decimal('1.2345')