blob: 1fc56ad10fdb4158c5a0e0eeb768fb4c360db9b5 [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
Christian Heimesfe337bf2008-03-23 21:54:12 +000015.. import modules for testing inline doctests with the Sphinx doctest builder
16.. testsetup:: *
17
18 import decimal
19 import math
20 from decimal import *
21 # make sure each group gets a fresh context
22 setcontext(Context())
Georg Brandl116aa622007-08-15 14:28:22 +000023
Stefan Krah1919b7e2012-03-21 18:25:23 +010024The :mod:`decimal` module provides support for fast correctly-rounded
25decimal floating point arithmetic. It offers several advantages over the
26:class:`float` datatype:
Georg Brandl116aa622007-08-15 14:28:22 +000027
Christian Heimes3feef612008-02-11 06:19:17 +000028* Decimal "is based on a floating-point model which was designed with people
29 in mind, and necessarily has a paramount guiding principle -- computers must
30 provide an arithmetic that works in the same way as the arithmetic that
31 people learn at school." -- excerpt from the decimal arithmetic specification.
32
Georg Brandl116aa622007-08-15 14:28:22 +000033* Decimal numbers can be represented exactly. In contrast, numbers like
Terry Jan Reedya9314632012-01-13 23:43:13 -050034 :const:`1.1` and :const:`2.2` do not have exact representations in binary
Raymond Hettingerd258d1e2009-04-23 22:06:12 +000035 floating point. End users typically would not expect ``1.1 + 2.2`` to display
36 as :const:`3.3000000000000003` as it does with binary floating point.
Georg Brandl116aa622007-08-15 14:28:22 +000037
38* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000039 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl116aa622007-08-15 14:28:22 +000040 is :const:`5.5511151231257827e-017`. While near to zero, the differences
41 prevent reliable equality testing and differences can accumulate. For this
Christian Heimes3feef612008-02-11 06:19:17 +000042 reason, decimal is preferred in accounting applications which have strict
Georg Brandl116aa622007-08-15 14:28:22 +000043 equality invariants.
44
45* The decimal module incorporates a notion of significant places so that ``1.30
46 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
47 This is the customary presentation for monetary applications. For
48 multiplication, the "schoolbook" approach uses all the figures in the
49 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
50 1.20`` gives :const:`1.5600`.
51
52* Unlike hardware based binary floating point, the decimal module has a user
Thomas Wouters1b7f8912007-09-19 03:06:30 +000053 alterable precision (defaulting to 28 places) which can be as large as needed for
Christian Heimesfe337bf2008-03-23 21:54:12 +000054 a given problem:
Georg Brandl116aa622007-08-15 14:28:22 +000055
Mark Dickinson43ef32a2010-11-07 11:24:44 +000056 >>> from decimal import *
Georg Brandl116aa622007-08-15 14:28:22 +000057 >>> getcontext().prec = 6
58 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000059 Decimal('0.142857')
Georg Brandl116aa622007-08-15 14:28:22 +000060 >>> getcontext().prec = 28
61 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000062 Decimal('0.1428571428571428571428571429')
Georg Brandl116aa622007-08-15 14:28:22 +000063
64* Both binary and decimal floating point are implemented in terms of published
65 standards. While the built-in float type exposes only a modest portion of its
66 capabilities, the decimal module exposes all required parts of the standard.
67 When needed, the programmer has full control over rounding and signal handling.
Christian Heimes3feef612008-02-11 06:19:17 +000068 This includes an option to enforce exact arithmetic by using exceptions
69 to block any inexact operations.
70
71* The decimal module was designed to support "without prejudice, both exact
72 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
73 and rounded floating-point arithmetic." -- excerpt from the decimal
74 arithmetic specification.
Georg Brandl116aa622007-08-15 14:28:22 +000075
76The module design is centered around three concepts: the decimal number, the
77context for arithmetic, and signals.
78
79A decimal number is immutable. It has a sign, coefficient digits, and an
80exponent. To preserve significance, the coefficient digits do not truncate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000081trailing zeros. Decimals also include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +000082:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
83differentiates :const:`-0` from :const:`+0`.
84
85The context for arithmetic is an environment specifying precision, rounding
86rules, limits on exponents, flags indicating the results of operations, and trap
87enablers which determine whether signals are treated as exceptions. Rounding
88options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
89:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +000090:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl116aa622007-08-15 14:28:22 +000091
92Signals are groups of exceptional conditions arising during the course of
93computation. Depending on the needs of the application, signals may be ignored,
94considered as informational, or treated as exceptions. The signals in the
95decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
96:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
Stefan Krah1919b7e2012-03-21 18:25:23 +010097:const:`Overflow`, :const:`Underflow` and :const:`FloatOperation`.
Georg Brandl116aa622007-08-15 14:28:22 +000098
99For each signal there is a flag and a trap enabler. When a signal is
Raymond Hettinger86173da2008-02-01 20:38:12 +0000100encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl116aa622007-08-15 14:28:22 +0000101set to one, an exception is raised. Flags are sticky, so the user needs to
102reset them before monitoring a calculation.
103
104
105.. seealso::
106
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000107 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
Raymond Hettinger960dc362009-04-21 03:43:15 +0000108 Specification <http://speleotrove.com/decimal/decarith.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000109
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000110 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Christian Heimes77c02eb2008-02-09 02:18:51 +0000111 <http://754r.ucbtest.org/standards/854.pdf>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000112
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000113.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000114
115
116.. _decimal-tutorial:
117
118Quick-start Tutorial
119--------------------
120
121The usual start to using decimals is importing the module, viewing the current
122context with :func:`getcontext` and, if necessary, setting new values for
123precision, rounding, or enabled traps::
124
125 >>> from decimal import *
126 >>> getcontext()
Stefan Krah1919b7e2012-03-21 18:25:23 +0100127 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000128 capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000129 InvalidOperation])
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131 >>> getcontext().prec = 7 # Set a new precision
132
Mark Dickinsone534a072010-04-04 22:13:14 +0000133Decimal instances can be constructed from integers, strings, floats, or tuples.
134Construction from an integer or a float performs an exact conversion of the
135value of that integer or float. Decimal numbers include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +0000136:const:`NaN` which stands for "Not a number", positive and negative
Stefan Krah1919b7e2012-03-21 18:25:23 +0100137:const:`Infinity`, and :const:`-0`::
Georg Brandl116aa622007-08-15 14:28:22 +0000138
Facundo Batista789bdf02008-06-21 17:29:41 +0000139 >>> getcontext().prec = 28
Georg Brandl116aa622007-08-15 14:28:22 +0000140 >>> Decimal(10)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000141 Decimal('10')
142 >>> Decimal('3.14')
143 Decimal('3.14')
Mark Dickinsone534a072010-04-04 22:13:14 +0000144 >>> Decimal(3.14)
145 Decimal('3.140000000000000124344978758017532527446746826171875')
Georg Brandl116aa622007-08-15 14:28:22 +0000146 >>> Decimal((0, (3, 1, 4), -2))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000147 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000148 >>> Decimal(str(2.0 ** 0.5))
Alexander Belopolsky287d1fd2011-01-12 16:37:14 +0000149 Decimal('1.4142135623730951')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000150 >>> Decimal(2) ** Decimal('0.5')
151 Decimal('1.414213562373095048801688724')
152 >>> Decimal('NaN')
153 Decimal('NaN')
154 >>> Decimal('-Infinity')
155 Decimal('-Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000156
Stefan Krah1919b7e2012-03-21 18:25:23 +0100157If the :exc:`FloatOperation` signal is trapped, accidental mixing of
158decimals and floats in constructors or ordering comparisons raises
159an exception::
160
161 >>> c = getcontext()
162 >>> c.traps[FloatOperation] = True
163 >>> Decimal(3.14)
164 Traceback (most recent call last):
165 File "<stdin>", line 1, in <module>
166 decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
167 >>> Decimal('3.5') < 3.7
168 Traceback (most recent call last):
169 File "<stdin>", line 1, in <module>
170 decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
171 >>> Decimal('3.5') == 3.5
172 True
173
174.. versionadded:: 3.3
175
Georg Brandl116aa622007-08-15 14:28:22 +0000176The significance of a new Decimal is determined solely by the number of digits
177input. Context precision and rounding only come into play during arithmetic
Christian Heimesfe337bf2008-03-23 21:54:12 +0000178operations.
179
180.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000181
182 >>> getcontext().prec = 6
183 >>> Decimal('3.0')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000184 Decimal('3.0')
Georg Brandl116aa622007-08-15 14:28:22 +0000185 >>> Decimal('3.1415926535')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000186 Decimal('3.1415926535')
Georg Brandl116aa622007-08-15 14:28:22 +0000187 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000188 Decimal('5.85987')
Georg Brandl116aa622007-08-15 14:28:22 +0000189 >>> getcontext().rounding = ROUND_UP
190 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000191 Decimal('5.85988')
Georg Brandl116aa622007-08-15 14:28:22 +0000192
Stefan Krah1919b7e2012-03-21 18:25:23 +0100193If the internal limits of the C version are exceeded, constructing
194a decimal raises :class:`InvalidOperation`::
195
196 >>> Decimal("1e9999999999999999999")
197 Traceback (most recent call last):
198 File "<stdin>", line 1, in <module>
199 decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]
200
201.. versionchanged:: 3.3
202
Georg Brandl116aa622007-08-15 14:28:22 +0000203Decimals interact well with much of the rest of Python. Here is a small decimal
Christian Heimesfe337bf2008-03-23 21:54:12 +0000204floating point flying circus:
205
206.. doctest::
207 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000208
Facundo Batista789bdf02008-06-21 17:29:41 +0000209 >>> 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 +0000210 >>> max(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000211 Decimal('9.25')
Georg Brandl116aa622007-08-15 14:28:22 +0000212 >>> min(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000213 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +0000214 >>> sorted(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000215 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
216 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl116aa622007-08-15 14:28:22 +0000217 >>> sum(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000218 Decimal('19.29')
Georg Brandl116aa622007-08-15 14:28:22 +0000219 >>> a,b,c = data[:3]
220 >>> str(a)
221 '1.34'
222 >>> float(a)
Mark Dickinson8dad7df2009-06-28 20:36:54 +0000223 1.34
224 >>> round(a, 1)
225 Decimal('1.3')
Georg Brandl116aa622007-08-15 14:28:22 +0000226 >>> int(a)
227 1
228 >>> a * 5
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000229 Decimal('6.70')
Georg Brandl116aa622007-08-15 14:28:22 +0000230 >>> a * b
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000231 Decimal('2.5058')
Georg Brandl116aa622007-08-15 14:28:22 +0000232 >>> c % a
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000233 Decimal('0.77')
Georg Brandl116aa622007-08-15 14:28:22 +0000234
Christian Heimesfe337bf2008-03-23 21:54:12 +0000235And some mathematical functions are also available to Decimal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000236
Facundo Batista789bdf02008-06-21 17:29:41 +0000237 >>> getcontext().prec = 28
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000238 >>> Decimal(2).sqrt()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000239 Decimal('1.414213562373095048801688724')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000240 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000241 Decimal('2.718281828459045235360287471')
242 >>> Decimal('10').ln()
243 Decimal('2.302585092994045684017991455')
244 >>> Decimal('10').log10()
245 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000246
Georg Brandl116aa622007-08-15 14:28:22 +0000247The :meth:`quantize` method rounds a number to a fixed exponent. This method is
248useful for monetary applications that often round results to a fixed number of
Christian Heimesfe337bf2008-03-23 21:54:12 +0000249places:
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000252 Decimal('7.32')
Georg Brandl116aa622007-08-15 14:28:22 +0000253 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000254 Decimal('8')
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256As shown above, the :func:`getcontext` function accesses the current context and
257allows the settings to be changed. This approach meets the needs of most
258applications.
259
260For more advanced work, it may be useful to create alternate contexts using the
261Context() constructor. To make an alternate active, use the :func:`setcontext`
262function.
263
264In accordance with the standard, the :mod:`Decimal` module provides two ready to
265use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
266former is especially useful for debugging because many of the traps are
Christian Heimesfe337bf2008-03-23 21:54:12 +0000267enabled:
268
269.. doctest:: newcontext
270 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
273 >>> setcontext(myothercontext)
274 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000275 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277 >>> ExtendedContext
Stefan Krah1919b7e2012-03-21 18:25:23 +0100278 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000279 capitals=1, clamp=0, flags=[], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000280 >>> setcontext(ExtendedContext)
281 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000282 Decimal('0.142857143')
Georg Brandl116aa622007-08-15 14:28:22 +0000283 >>> Decimal(42) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000284 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286 >>> setcontext(BasicContext)
287 >>> Decimal(42) / Decimal(0)
288 Traceback (most recent call last):
289 File "<pyshell#143>", line 1, in -toplevel-
290 Decimal(42) / Decimal(0)
291 DivisionByZero: x / 0
292
293Contexts also have signal flags for monitoring exceptional conditions
294encountered during computations. The flags remain set until explicitly cleared,
295so it is best to clear the flags before each set of monitored computations by
296using the :meth:`clear_flags` method. ::
297
298 >>> setcontext(ExtendedContext)
299 >>> getcontext().clear_flags()
300 >>> Decimal(355) / Decimal(113)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000301 Decimal('3.14159292')
Georg Brandl116aa622007-08-15 14:28:22 +0000302 >>> getcontext()
Stefan Krah1919b7e2012-03-21 18:25:23 +0100303 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000304 capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000305
306The *flags* entry shows that the rational approximation to :const:`Pi` was
307rounded (digits beyond the context precision were thrown away) and that the
308result is inexact (some of the discarded digits were non-zero).
309
310Individual traps are set using the dictionary in the :attr:`traps` field of a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000311context:
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Christian Heimesfe337bf2008-03-23 21:54:12 +0000313.. doctest:: newcontext
314
315 >>> setcontext(ExtendedContext)
Georg Brandl116aa622007-08-15 14:28:22 +0000316 >>> Decimal(1) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000317 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000318 >>> getcontext().traps[DivisionByZero] = 1
319 >>> Decimal(1) / Decimal(0)
320 Traceback (most recent call last):
321 File "<pyshell#112>", line 1, in -toplevel-
322 Decimal(1) / Decimal(0)
323 DivisionByZero: x / 0
324
325Most programs adjust the current context only once, at the beginning of the
326program. And, in many applications, data is converted to :class:`Decimal` with
327a single cast inside a loop. With context set and decimals created, the bulk of
328the program manipulates the data no differently than with other Python numeric
329types.
330
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000331.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000332
333
334.. _decimal-decimal:
335
336Decimal objects
337---------------
338
339
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000340.. class:: Decimal(value="0", context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000341
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000342 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl116aa622007-08-15 14:28:22 +0000343
Raymond Hettinger96798592010-04-02 16:58:27 +0000344 *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal`
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000345 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Christian Heimesa62da1d2008-01-12 19:39:10 +0000346 string, it should conform to the decimal numeric string syntax after leading
347 and trailing whitespace characters are removed::
Georg Brandl116aa622007-08-15 14:28:22 +0000348
349 sign ::= '+' | '-'
350 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
351 indicator ::= 'e' | 'E'
352 digits ::= digit [digit]...
353 decimal-part ::= digits '.' [digits] | ['.'] digits
354 exponent-part ::= indicator [sign] digits
355 infinity ::= 'Infinity' | 'Inf'
356 nan ::= 'NaN' [digits] | 'sNaN' [digits]
357 numeric-value ::= decimal-part [exponent-part] | infinity
Georg Brandl48310cd2009-01-03 21:18:54 +0000358 numeric-string ::= [sign] numeric-value | [sign] nan
Georg Brandl116aa622007-08-15 14:28:22 +0000359
Mark Dickinson345adc42009-08-02 10:14:23 +0000360 Other Unicode decimal digits are also permitted where ``digit``
361 appears above. These include decimal digits from various other
362 alphabets (for example, Arabic-Indic and Devanāgarī digits) along
363 with the fullwidth digits ``'\uff10'`` through ``'\uff19'``.
364
Georg Brandl116aa622007-08-15 14:28:22 +0000365 If *value* is a :class:`tuple`, it should have three components, a sign
366 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
367 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000368 returns ``Decimal('1.414')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Raymond Hettinger96798592010-04-02 16:58:27 +0000370 If *value* is a :class:`float`, the binary floating point value is losslessly
371 converted to its exact decimal equivalent. This conversion can often require
Mark Dickinsone534a072010-04-04 22:13:14 +0000372 53 or more digits of precision. For example, ``Decimal(float('1.1'))``
373 converts to
374 ``Decimal('1.100000000000000088817841970012523233890533447265625')``.
Raymond Hettinger96798592010-04-02 16:58:27 +0000375
Georg Brandl116aa622007-08-15 14:28:22 +0000376 The *context* precision does not affect how many digits are stored. That is
377 determined exclusively by the number of digits in *value*. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000378 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl116aa622007-08-15 14:28:22 +0000379 only three.
380
381 The purpose of the *context* argument is determining what to do if *value* is a
382 malformed string. If the context traps :const:`InvalidOperation`, an exception
383 is raised; otherwise, the constructor returns a new Decimal with the value of
384 :const:`NaN`.
385
386 Once constructed, :class:`Decimal` objects are immutable.
387
Mark Dickinsone534a072010-04-04 22:13:14 +0000388 .. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000389 The argument to the constructor is now permitted to be a :class:`float`
390 instance.
Mark Dickinsone534a072010-04-04 22:13:14 +0000391
Stefan Krah1919b7e2012-03-21 18:25:23 +0100392 .. versionchanged:: 3.3
393 :class:`float` arguments raise an exception if the :exc:`FloatOperation`
394 trap is set. By default the trap is off.
395
Benjamin Petersone41251e2008-04-25 01:59:09 +0000396 Decimal floating point objects share many properties with the other built-in
397 numeric types such as :class:`float` and :class:`int`. All of the usual math
398 operations and special methods apply. Likewise, decimal objects can be
399 copied, pickled, printed, used as dictionary keys, used as set elements,
400 compared, sorted, and coerced to another type (such as :class:`float` or
Mark Dickinson5d233fd2010-02-18 14:54:37 +0000401 :class:`int`).
Christian Heimesa62da1d2008-01-12 19:39:10 +0000402
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000403 Decimal objects cannot generally be combined with floats or
404 instances of :class:`fractions.Fraction` in arithmetic operations:
405 an attempt to add a :class:`Decimal` to a :class:`float`, for
406 example, will raise a :exc:`TypeError`. However, it is possible to
407 use Python's comparison operators to compare a :class:`Decimal`
408 instance ``x`` with another number ``y``. This avoids confusing results
409 when doing equality comparisons between numbers of different types.
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000410
Ezio Melotti993a5ee2010-04-04 06:30:08 +0000411 .. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000412 Mixed-type comparisons between :class:`Decimal` instances and other
413 numeric types are now fully supported.
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000414
Benjamin Petersone41251e2008-04-25 01:59:09 +0000415 In addition to the standard numeric properties, decimal floating point
416 objects also have a number of specialized methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000417
Georg Brandl116aa622007-08-15 14:28:22 +0000418
Benjamin Petersone41251e2008-04-25 01:59:09 +0000419 .. method:: adjusted()
Georg Brandl116aa622007-08-15 14:28:22 +0000420
Benjamin Petersone41251e2008-04-25 01:59:09 +0000421 Return the adjusted exponent after shifting out the coefficient's
422 rightmost digits until only the lead digit remains:
423 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
424 position of the most significant digit with respect to the decimal point.
Georg Brandl116aa622007-08-15 14:28:22 +0000425
Georg Brandl116aa622007-08-15 14:28:22 +0000426
Benjamin Petersone41251e2008-04-25 01:59:09 +0000427 .. method:: as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +0000428
Benjamin Petersone41251e2008-04-25 01:59:09 +0000429 Return a :term:`named tuple` representation of the number:
430 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000431
Christian Heimes25bb7832008-01-11 16:17:00 +0000432
Benjamin Petersone41251e2008-04-25 01:59:09 +0000433 .. method:: canonical()
Georg Brandl116aa622007-08-15 14:28:22 +0000434
Benjamin Petersone41251e2008-04-25 01:59:09 +0000435 Return the canonical encoding of the argument. Currently, the encoding of
436 a :class:`Decimal` instance is always canonical, so this operation returns
437 its argument unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000438
Benjamin Petersone41251e2008-04-25 01:59:09 +0000439 .. method:: compare(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000440
Georg Brandl05f5ab72008-09-24 09:11:47 +0000441 Compare the values of two Decimal instances. :meth:`compare` returns a
442 Decimal instance, and if either operand is a NaN then the result is a
443 NaN::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000444
Georg Brandl05f5ab72008-09-24 09:11:47 +0000445 a or b is a NaN ==> Decimal('NaN')
446 a < b ==> Decimal('-1')
447 a == b ==> Decimal('0')
448 a > b ==> Decimal('1')
Georg Brandl116aa622007-08-15 14:28:22 +0000449
Benjamin Petersone41251e2008-04-25 01:59:09 +0000450 .. method:: compare_signal(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000451
Benjamin Petersone41251e2008-04-25 01:59:09 +0000452 This operation is identical to the :meth:`compare` method, except that all
453 NaNs signal. That is, if neither operand is a signaling NaN then any
454 quiet NaN operand is treated as though it were a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000455
Benjamin Petersone41251e2008-04-25 01:59:09 +0000456 .. method:: compare_total(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000457
Benjamin Petersone41251e2008-04-25 01:59:09 +0000458 Compare two operands using their abstract representation rather than their
459 numerical value. Similar to the :meth:`compare` method, but the result
460 gives a total ordering on :class:`Decimal` instances. Two
461 :class:`Decimal` instances with the same numeric value but different
462 representations compare unequal in this ordering:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000463
Benjamin Petersone41251e2008-04-25 01:59:09 +0000464 >>> Decimal('12.0').compare_total(Decimal('12'))
465 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000466
Benjamin Petersone41251e2008-04-25 01:59:09 +0000467 Quiet and signaling NaNs are also included in the total ordering. The
468 result of this function is ``Decimal('0')`` if both operands have the same
469 representation, ``Decimal('-1')`` if the first operand is lower in the
470 total order than the second, and ``Decimal('1')`` if the first operand is
471 higher in the total order than the second operand. See the specification
472 for details of the total order.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000473
Benjamin Petersone41251e2008-04-25 01:59:09 +0000474 .. method:: compare_total_mag(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000475
Benjamin Petersone41251e2008-04-25 01:59:09 +0000476 Compare two operands using their abstract representation rather than their
477 value as in :meth:`compare_total`, but ignoring the sign of each operand.
478 ``x.compare_total_mag(y)`` is equivalent to
479 ``x.copy_abs().compare_total(y.copy_abs())``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000480
Facundo Batista789bdf02008-06-21 17:29:41 +0000481 .. method:: conjugate()
482
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000483 Just returns self, this method is only to comply with the Decimal
Facundo Batista789bdf02008-06-21 17:29:41 +0000484 Specification.
485
Benjamin Petersone41251e2008-04-25 01:59:09 +0000486 .. method:: copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000487
Benjamin Petersone41251e2008-04-25 01:59:09 +0000488 Return the absolute value of the argument. This operation is unaffected
489 by the context and is quiet: no flags are changed and no rounding is
490 performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000491
Benjamin Petersone41251e2008-04-25 01:59:09 +0000492 .. method:: copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000493
Benjamin Petersone41251e2008-04-25 01:59:09 +0000494 Return the negation of the argument. This operation is unaffected by the
495 context and is quiet: no flags are changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000496
Benjamin Petersone41251e2008-04-25 01:59:09 +0000497 .. method:: copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000498
Benjamin Petersone41251e2008-04-25 01:59:09 +0000499 Return a copy of the first operand with the sign set to be the same as the
500 sign of the second operand. For example:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000501
Benjamin Petersone41251e2008-04-25 01:59:09 +0000502 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
503 Decimal('-2.3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000504
Benjamin Petersone41251e2008-04-25 01:59:09 +0000505 This operation is unaffected by the context and is quiet: no flags are
506 changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000507
Benjamin Petersone41251e2008-04-25 01:59:09 +0000508 .. method:: exp([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000509
Benjamin Petersone41251e2008-04-25 01:59:09 +0000510 Return the value of the (natural) exponential function ``e**x`` at the
511 given number. The result is correctly rounded using the
512 :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000513
Benjamin Petersone41251e2008-04-25 01:59:09 +0000514 >>> Decimal(1).exp()
515 Decimal('2.718281828459045235360287471')
516 >>> Decimal(321).exp()
517 Decimal('2.561702493119680037517373933E+139')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000518
Raymond Hettinger771ed762009-01-03 19:20:32 +0000519 .. method:: from_float(f)
520
521 Classmethod that converts a float to a decimal number, exactly.
522
523 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
524 Since 0.1 is not exactly representable in binary floating point, the
525 value is stored as the nearest representable value which is
526 `0x1.999999999999ap-4`. That equivalent value in decimal is
527 `0.1000000000000000055511151231257827021181583404541015625`.
528
Mark Dickinsone534a072010-04-04 22:13:14 +0000529 .. note:: From Python 3.2 onwards, a :class:`Decimal` instance
530 can also be constructed directly from a :class:`float`.
531
Raymond Hettinger771ed762009-01-03 19:20:32 +0000532 .. doctest::
533
534 >>> Decimal.from_float(0.1)
535 Decimal('0.1000000000000000055511151231257827021181583404541015625')
536 >>> Decimal.from_float(float('nan'))
537 Decimal('NaN')
538 >>> Decimal.from_float(float('inf'))
539 Decimal('Infinity')
540 >>> Decimal.from_float(float('-inf'))
541 Decimal('-Infinity')
542
Georg Brandl45f53372009-01-03 21:15:20 +0000543 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000544
Benjamin Petersone41251e2008-04-25 01:59:09 +0000545 .. method:: fma(other, third[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546
Benjamin Petersone41251e2008-04-25 01:59:09 +0000547 Fused multiply-add. Return self*other+third with no rounding of the
548 intermediate product self*other.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000549
Benjamin Petersone41251e2008-04-25 01:59:09 +0000550 >>> Decimal(2).fma(3, 5)
551 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000552
Benjamin Petersone41251e2008-04-25 01:59:09 +0000553 .. method:: is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000554
Benjamin Petersone41251e2008-04-25 01:59:09 +0000555 Return :const:`True` if the argument is canonical and :const:`False`
556 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
557 this operation always returns :const:`True`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000558
Benjamin Petersone41251e2008-04-25 01:59:09 +0000559 .. method:: is_finite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000560
Benjamin Petersone41251e2008-04-25 01:59:09 +0000561 Return :const:`True` if the argument is a finite number, and
562 :const:`False` if the argument is an infinity or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563
Benjamin Petersone41251e2008-04-25 01:59:09 +0000564 .. method:: is_infinite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000565
Benjamin Petersone41251e2008-04-25 01:59:09 +0000566 Return :const:`True` if the argument is either positive or negative
567 infinity and :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568
Benjamin Petersone41251e2008-04-25 01:59:09 +0000569 .. method:: is_nan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570
Benjamin Petersone41251e2008-04-25 01:59:09 +0000571 Return :const:`True` if the argument is a (quiet or signaling) NaN and
572 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000573
Benjamin Petersone41251e2008-04-25 01:59:09 +0000574 .. method:: is_normal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000575
Benjamin Petersone41251e2008-04-25 01:59:09 +0000576 Return :const:`True` if the argument is a *normal* finite number. Return
577 :const:`False` if the argument is zero, subnormal, infinite or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000578
Benjamin Petersone41251e2008-04-25 01:59:09 +0000579 .. method:: is_qnan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000580
Benjamin Petersone41251e2008-04-25 01:59:09 +0000581 Return :const:`True` if the argument is a quiet NaN, and
582 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000583
Benjamin Petersone41251e2008-04-25 01:59:09 +0000584 .. method:: is_signed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000585
Benjamin Petersone41251e2008-04-25 01:59:09 +0000586 Return :const:`True` if the argument has a negative sign and
587 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000588
Benjamin Petersone41251e2008-04-25 01:59:09 +0000589 .. method:: is_snan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000590
Benjamin Petersone41251e2008-04-25 01:59:09 +0000591 Return :const:`True` if the argument is a signaling NaN and :const:`False`
592 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000593
Benjamin Petersone41251e2008-04-25 01:59:09 +0000594 .. method:: is_subnormal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000595
Benjamin Petersone41251e2008-04-25 01:59:09 +0000596 Return :const:`True` if the argument is subnormal, and :const:`False`
597 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000598
Benjamin Petersone41251e2008-04-25 01:59:09 +0000599 .. method:: is_zero()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000600
Benjamin Petersone41251e2008-04-25 01:59:09 +0000601 Return :const:`True` if the argument is a (positive or negative) zero and
602 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000603
Benjamin Petersone41251e2008-04-25 01:59:09 +0000604 .. method:: ln([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000605
Benjamin Petersone41251e2008-04-25 01:59:09 +0000606 Return the natural (base e) logarithm of the operand. The result is
607 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000608
Benjamin Petersone41251e2008-04-25 01:59:09 +0000609 .. method:: log10([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000610
Benjamin Petersone41251e2008-04-25 01:59:09 +0000611 Return the base ten logarithm of the operand. The result is correctly
612 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000613
Benjamin Petersone41251e2008-04-25 01:59:09 +0000614 .. method:: logb([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000615
Benjamin Petersone41251e2008-04-25 01:59:09 +0000616 For a nonzero number, return the adjusted exponent of its operand as a
617 :class:`Decimal` instance. If the operand is a zero then
618 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
619 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
620 returned.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000621
Benjamin Petersone41251e2008-04-25 01:59:09 +0000622 .. method:: logical_and(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000623
Benjamin Petersone41251e2008-04-25 01:59:09 +0000624 :meth:`logical_and` is a logical operation which takes two *logical
625 operands* (see :ref:`logical_operands_label`). The result is the
626 digit-wise ``and`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000627
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000628 .. method:: logical_invert([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000629
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000630 :meth:`logical_invert` is a logical operation. The
Benjamin Petersone41251e2008-04-25 01:59:09 +0000631 result is the digit-wise inversion of the operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000632
Benjamin Petersone41251e2008-04-25 01:59:09 +0000633 .. method:: logical_or(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634
Benjamin Petersone41251e2008-04-25 01:59:09 +0000635 :meth:`logical_or` is a logical operation which takes two *logical
636 operands* (see :ref:`logical_operands_label`). The result is the
637 digit-wise ``or`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000638
Benjamin Petersone41251e2008-04-25 01:59:09 +0000639 .. method:: logical_xor(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000640
Benjamin Petersone41251e2008-04-25 01:59:09 +0000641 :meth:`logical_xor` is a logical operation which takes two *logical
642 operands* (see :ref:`logical_operands_label`). The result is the
643 digit-wise exclusive or of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644
Benjamin Petersone41251e2008-04-25 01:59:09 +0000645 .. method:: max(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646
Benjamin Petersone41251e2008-04-25 01:59:09 +0000647 Like ``max(self, other)`` except that the context rounding rule is applied
648 before returning and that :const:`NaN` values are either signaled or
649 ignored (depending on the context and whether they are signaling or
650 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000651
Benjamin Petersone41251e2008-04-25 01:59:09 +0000652 .. method:: max_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653
Georg Brandl502d9a52009-07-26 15:02:41 +0000654 Similar to the :meth:`.max` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000655 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000656
Benjamin Petersone41251e2008-04-25 01:59:09 +0000657 .. method:: min(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658
Benjamin Petersone41251e2008-04-25 01:59:09 +0000659 Like ``min(self, other)`` except that the context rounding rule is applied
660 before returning and that :const:`NaN` values are either signaled or
661 ignored (depending on the context and whether they are signaling or
662 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663
Benjamin Petersone41251e2008-04-25 01:59:09 +0000664 .. method:: min_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665
Georg Brandl502d9a52009-07-26 15:02:41 +0000666 Similar to the :meth:`.min` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000667 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668
Benjamin Petersone41251e2008-04-25 01:59:09 +0000669 .. method:: next_minus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000670
Benjamin Petersone41251e2008-04-25 01:59:09 +0000671 Return the largest number representable in the given context (or in the
672 current thread's context if no context is given) that is smaller than the
673 given operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000674
Benjamin Petersone41251e2008-04-25 01:59:09 +0000675 .. method:: next_plus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676
Benjamin Petersone41251e2008-04-25 01:59:09 +0000677 Return the smallest number representable in the given context (or in the
678 current thread's context if no context is given) that is larger than the
679 given operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000680
Benjamin Petersone41251e2008-04-25 01:59:09 +0000681 .. method:: next_toward(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000682
Benjamin Petersone41251e2008-04-25 01:59:09 +0000683 If the two operands are unequal, return the number closest to the first
684 operand in the direction of the second operand. If both operands are
685 numerically equal, return a copy of the first operand with the sign set to
686 be the same as the sign of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000687
Benjamin Petersone41251e2008-04-25 01:59:09 +0000688 .. method:: normalize([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689
Benjamin Petersone41251e2008-04-25 01:59:09 +0000690 Normalize the number by stripping the rightmost trailing zeros and
691 converting any result equal to :const:`Decimal('0')` to
Senthil Kumarana6bac952011-07-04 11:28:30 -0700692 :const:`Decimal('0e0')`. Used for producing canonical values for attributes
Benjamin Petersone41251e2008-04-25 01:59:09 +0000693 of an equivalence class. For example, ``Decimal('32.100')`` and
694 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
695 ``Decimal('32.1')``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000696
Benjamin Petersone41251e2008-04-25 01:59:09 +0000697 .. method:: number_class([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000698
Benjamin Petersone41251e2008-04-25 01:59:09 +0000699 Return a string describing the *class* of the operand. The returned value
700 is one of the following ten strings.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000701
Benjamin Petersone41251e2008-04-25 01:59:09 +0000702 * ``"-Infinity"``, indicating that the operand is negative infinity.
703 * ``"-Normal"``, indicating that the operand is a negative normal number.
704 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
705 * ``"-Zero"``, indicating that the operand is a negative zero.
706 * ``"+Zero"``, indicating that the operand is a positive zero.
707 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
708 * ``"+Normal"``, indicating that the operand is a positive normal number.
709 * ``"+Infinity"``, indicating that the operand is positive infinity.
710 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
711 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000712
Benjamin Petersone41251e2008-04-25 01:59:09 +0000713 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000714
Benjamin Petersone41251e2008-04-25 01:59:09 +0000715 Return a value equal to the first operand after rounding and having the
716 exponent of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000717
Benjamin Petersone41251e2008-04-25 01:59:09 +0000718 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
719 Decimal('1.414')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000720
Benjamin Petersone41251e2008-04-25 01:59:09 +0000721 Unlike other operations, if the length of the coefficient after the
722 quantize operation would be greater than precision, then an
723 :const:`InvalidOperation` is signaled. This guarantees that, unless there
724 is an error condition, the quantized exponent is always equal to that of
725 the right-hand operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000726
Benjamin Petersone41251e2008-04-25 01:59:09 +0000727 Also unlike other operations, quantize never signals Underflow, even if
728 the result is subnormal and inexact.
Georg Brandl116aa622007-08-15 14:28:22 +0000729
Benjamin Petersone41251e2008-04-25 01:59:09 +0000730 If the exponent of the second operand is larger than that of the first
731 then rounding may be necessary. In this case, the rounding mode is
732 determined by the ``rounding`` argument if given, else by the given
733 ``context`` argument; if neither argument is given the rounding mode of
734 the current thread's context is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000735
Benjamin Petersone41251e2008-04-25 01:59:09 +0000736 If *watchexp* is set (default), then an error is returned whenever the
737 resulting exponent is greater than :attr:`Emax` or less than
738 :attr:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +0000739
Stefan Krahaf3f3a72012-08-30 12:33:55 +0200740 .. deprecated:: 3.3
741 *watchexp* is an implementation detail from the pure Python version
742 and is not present in the C version. It will be removed in version
743 3.4, where it defaults to ``True``.
744
Benjamin Petersone41251e2008-04-25 01:59:09 +0000745 .. method:: radix()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000746
Benjamin Petersone41251e2008-04-25 01:59:09 +0000747 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
748 class does all its arithmetic. Included for compatibility with the
749 specification.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000750
Benjamin Petersone41251e2008-04-25 01:59:09 +0000751 .. method:: remainder_near(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000752
Mark Dickinson6ae568b2012-10-31 19:44:36 +0000753 Return the remainder from dividing *self* by *other*. This differs from
754 ``self % other`` in that the sign of the remainder is chosen so as to
755 minimize its absolute value. More precisely, the return value is
756 ``self - n * other`` where ``n`` is the integer nearest to the exact
757 value of ``self / other``, and if two integers are equally near then the
758 even one is chosen.
Georg Brandl116aa622007-08-15 14:28:22 +0000759
Mark Dickinson6ae568b2012-10-31 19:44:36 +0000760 If the result is zero then its sign will be the sign of *self*.
761
762 >>> Decimal(18).remainder_near(Decimal(10))
763 Decimal('-2')
764 >>> Decimal(25).remainder_near(Decimal(10))
765 Decimal('5')
766 >>> Decimal(35).remainder_near(Decimal(10))
767 Decimal('-5')
Georg Brandl116aa622007-08-15 14:28:22 +0000768
Benjamin Petersone41251e2008-04-25 01:59:09 +0000769 .. method:: rotate(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000770
Benjamin Petersone41251e2008-04-25 01:59:09 +0000771 Return the result of rotating the digits of the first operand by an amount
772 specified by the second operand. The second operand must be an integer in
773 the range -precision through precision. The absolute value of the second
774 operand gives the number of places to rotate. If the second operand is
775 positive then rotation is to the left; otherwise rotation is to the right.
776 The coefficient of the first operand is padded on the left with zeros to
777 length precision if necessary. The sign and exponent of the first operand
778 are unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000779
Benjamin Petersone41251e2008-04-25 01:59:09 +0000780 .. method:: same_quantum(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000781
Benjamin Petersone41251e2008-04-25 01:59:09 +0000782 Test whether self and other have the same exponent or whether both are
783 :const:`NaN`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784
Benjamin Petersone41251e2008-04-25 01:59:09 +0000785 .. method:: scaleb(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000786
Benjamin Petersone41251e2008-04-25 01:59:09 +0000787 Return the first operand with exponent adjusted by the second.
788 Equivalently, return the first operand multiplied by ``10**other``. The
789 second operand must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +0000790
Benjamin Petersone41251e2008-04-25 01:59:09 +0000791 .. method:: shift(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000792
Benjamin Petersone41251e2008-04-25 01:59:09 +0000793 Return the result of shifting the digits of the first operand by an amount
794 specified by the second operand. The second operand must be an integer in
795 the range -precision through precision. The absolute value of the second
796 operand gives the number of places to shift. If the second operand is
797 positive then the shift is to the left; otherwise the shift is to the
798 right. Digits shifted into the coefficient are zeros. The sign and
799 exponent of the first operand are unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +0000800
Benjamin Petersone41251e2008-04-25 01:59:09 +0000801 .. method:: sqrt([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000802
Benjamin Petersone41251e2008-04-25 01:59:09 +0000803 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000804
Georg Brandl116aa622007-08-15 14:28:22 +0000805
Benjamin Petersone41251e2008-04-25 01:59:09 +0000806 .. method:: to_eng_string([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000807
Benjamin Petersone41251e2008-04-25 01:59:09 +0000808 Convert to an engineering-type string.
Georg Brandl116aa622007-08-15 14:28:22 +0000809
Benjamin Petersone41251e2008-04-25 01:59:09 +0000810 Engineering notation has an exponent which is a multiple of 3, so there
811 are up to 3 digits left of the decimal place. For example, converts
812 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813
Benjamin Petersone41251e2008-04-25 01:59:09 +0000814 .. method:: to_integral([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000815
Benjamin Petersone41251e2008-04-25 01:59:09 +0000816 Identical to the :meth:`to_integral_value` method. The ``to_integral``
817 name has been kept for compatibility with older versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000818
Benjamin Petersone41251e2008-04-25 01:59:09 +0000819 .. method:: to_integral_exact([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000820
Benjamin Petersone41251e2008-04-25 01:59:09 +0000821 Round to the nearest integer, signaling :const:`Inexact` or
822 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
823 determined by the ``rounding`` parameter if given, else by the given
824 ``context``. If neither parameter is given then the rounding mode of the
825 current context is used.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826
Benjamin Petersone41251e2008-04-25 01:59:09 +0000827 .. method:: to_integral_value([rounding[, context]])
Georg Brandl116aa622007-08-15 14:28:22 +0000828
Benjamin Petersone41251e2008-04-25 01:59:09 +0000829 Round to the nearest integer without signaling :const:`Inexact` or
830 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
831 rounding method in either the supplied *context* or the current context.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833
834.. _logical_operands_label:
835
836Logical operands
837^^^^^^^^^^^^^^^^
838
839The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
840and :meth:`logical_xor` methods expect their arguments to be *logical
841operands*. A *logical operand* is a :class:`Decimal` instance whose
842exponent and sign are both zero, and whose digits are all either
843:const:`0` or :const:`1`.
844
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000845.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000846
847
848.. _decimal-context:
849
850Context objects
851---------------
852
853Contexts are environments for arithmetic operations. They govern precision, set
854rules for rounding, determine which signals are treated as exceptions, and limit
855the range for exponents.
856
857Each thread has its own current context which is accessed or changed using the
858:func:`getcontext` and :func:`setcontext` functions:
859
860
861.. function:: getcontext()
862
863 Return the current context for the active thread.
864
865
866.. function:: setcontext(c)
867
868 Set the current context for the active thread to *c*.
869
Georg Brandle6bcc912008-05-12 18:05:20 +0000870You can also use the :keyword:`with` statement and the :func:`localcontext`
871function to temporarily change the active context.
Georg Brandl116aa622007-08-15 14:28:22 +0000872
873.. function:: localcontext([c])
874
875 Return a context manager that will set the current context for the active thread
876 to a copy of *c* on entry to the with-statement and restore the previous context
877 when exiting the with-statement. If no context is specified, a copy of the
878 current context is used.
879
Georg Brandl116aa622007-08-15 14:28:22 +0000880 For example, the following code sets the current decimal precision to 42 places,
881 performs a calculation, and then automatically restores the previous context::
882
Georg Brandl116aa622007-08-15 14:28:22 +0000883 from decimal import localcontext
884
885 with localcontext() as ctx:
886 ctx.prec = 42 # Perform a high precision calculation
887 s = calculate_something()
888 s = +s # Round the final result back to the default precision
889
890New contexts can also be created using the :class:`Context` constructor
891described below. In addition, the module provides three pre-made contexts:
892
893
894.. class:: BasicContext
895
896 This is a standard context defined by the General Decimal Arithmetic
897 Specification. Precision is set to nine. Rounding is set to
898 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
899 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
900 :const:`Subnormal`.
901
902 Because many of the traps are enabled, this context is useful for debugging.
903
904
905.. class:: ExtendedContext
906
907 This is a standard context defined by the General Decimal Arithmetic
908 Specification. Precision is set to nine. Rounding is set to
909 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
910 exceptions are not raised during computations).
911
Christian Heimes3feef612008-02-11 06:19:17 +0000912 Because the traps are disabled, this context is useful for applications that
Georg Brandl116aa622007-08-15 14:28:22 +0000913 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
914 raising exceptions. This allows an application to complete a run in the
915 presence of conditions that would otherwise halt the program.
916
917
918.. class:: DefaultContext
919
920 This context is used by the :class:`Context` constructor as a prototype for new
921 contexts. Changing a field (such a precision) has the effect of changing the
Stefan Kraha1193932010-05-29 12:59:18 +0000922 default for new contexts created by the :class:`Context` constructor.
Georg Brandl116aa622007-08-15 14:28:22 +0000923
924 This context is most useful in multi-threaded environments. Changing one of the
925 fields before threads are started has the effect of setting system-wide
926 defaults. Changing the fields after threads have started is not recommended as
927 it would require thread synchronization to prevent race conditions.
928
929 In single threaded environments, it is preferable to not use this context at
930 all. Instead, simply create contexts explicitly as described below.
931
Stefan Krah1919b7e2012-03-21 18:25:23 +0100932 The default values are :attr:`prec`\ =\ :const:`28`,
933 :attr:`rounding`\ =\ :const:`ROUND_HALF_EVEN`,
934 and enabled traps for :class:`Overflow`, :class:`InvalidOperation`, and
935 :class:`DivisionByZero`.
Georg Brandl116aa622007-08-15 14:28:22 +0000936
937In addition to the three supplied contexts, new contexts can be created with the
938:class:`Context` constructor.
939
940
Stefan Krah1919b7e2012-03-21 18:25:23 +0100941.. 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 +0000942
943 Creates a new context. If a field is not specified or is :const:`None`, the
944 default values are copied from the :const:`DefaultContext`. If the *flags*
945 field is not specified or is :const:`None`, all flags are cleared.
946
Stefan Krah1919b7e2012-03-21 18:25:23 +0100947 *prec* is an integer in the range [:const:`1`, :const:`MAX_PREC`] that sets
948 the precision for arithmetic operations in the context.
Georg Brandl116aa622007-08-15 14:28:22 +0000949
Stefan Krah1919b7e2012-03-21 18:25:23 +0100950 The *rounding* option is one of the constants listed in the section
951 `Rounding Modes`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000952
953 The *traps* and *flags* fields list any signals to be set. Generally, new
954 contexts should only set traps and leave the flags clear.
955
956 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
Stefan Krah1919b7e2012-03-21 18:25:23 +0100957 for exponents. *Emin* must be in the range [:const:`MIN_EMIN`, :const:`0`],
958 *Emax* in the range [:const:`0`, :const:`MAX_EMAX`].
Georg Brandl116aa622007-08-15 14:28:22 +0000959
960 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
961 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
962 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
963
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000964 The *clamp* field is either :const:`0` (the default) or :const:`1`.
965 If set to :const:`1`, the exponent ``e`` of a :class:`Decimal`
966 instance representable in this context is strictly limited to the
967 range ``Emin - prec + 1 <= e <= Emax - prec + 1``. If *clamp* is
968 :const:`0` then a weaker condition holds: the adjusted exponent of
969 the :class:`Decimal` instance is at most ``Emax``. When *clamp* is
970 :const:`1`, a large normal number will, where possible, have its
971 exponent reduced and a corresponding number of zeros added to its
972 coefficient, in order to fit the exponent constraints; this
973 preserves the value of the number but loses information about
974 significant trailing zeros. For example::
975
976 >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
977 Decimal('1.23000E+999')
978
979 A *clamp* value of :const:`1` allows compatibility with the
980 fixed-width decimal interchange formats specified in IEEE 754.
Georg Brandl116aa622007-08-15 14:28:22 +0000981
Benjamin Petersone41251e2008-04-25 01:59:09 +0000982 The :class:`Context` class defines several general purpose methods as well as
983 a large number of methods for doing arithmetic directly in a given context.
984 In addition, for each of the :class:`Decimal` methods described above (with
985 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
Mark Dickinson84230a12010-02-18 14:49:50 +0000986 a corresponding :class:`Context` method. For example, for a :class:`Context`
987 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
988 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a
Mark Dickinson5d233fd2010-02-18 14:54:37 +0000989 Python integer (an instance of :class:`int`) anywhere that a
Mark Dickinson84230a12010-02-18 14:49:50 +0000990 Decimal instance is accepted.
Georg Brandl116aa622007-08-15 14:28:22 +0000991
992
Benjamin Petersone41251e2008-04-25 01:59:09 +0000993 .. method:: clear_flags()
Georg Brandl116aa622007-08-15 14:28:22 +0000994
Benjamin Petersone41251e2008-04-25 01:59:09 +0000995 Resets all of the flags to :const:`0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000996
Stefan Krah1919b7e2012-03-21 18:25:23 +0100997 .. method:: clear_traps()
998
999 Resets all of the traps to :const:`0`.
1000
1001 .. versionadded:: 3.3
1002
Benjamin Petersone41251e2008-04-25 01:59:09 +00001003 .. method:: copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001004
Benjamin Petersone41251e2008-04-25 01:59:09 +00001005 Return a duplicate of the context.
Georg Brandl116aa622007-08-15 14:28:22 +00001006
Benjamin Petersone41251e2008-04-25 01:59:09 +00001007 .. method:: copy_decimal(num)
Georg Brandl116aa622007-08-15 14:28:22 +00001008
Benjamin Petersone41251e2008-04-25 01:59:09 +00001009 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +00001010
Benjamin Petersone41251e2008-04-25 01:59:09 +00001011 .. method:: create_decimal(num)
Christian Heimesfe337bf2008-03-23 21:54:12 +00001012
Benjamin Petersone41251e2008-04-25 01:59:09 +00001013 Creates a new Decimal instance from *num* but using *self* as
1014 context. Unlike the :class:`Decimal` constructor, the context precision,
1015 rounding method, flags, and traps are applied to the conversion.
Georg Brandl116aa622007-08-15 14:28:22 +00001016
Benjamin Petersone41251e2008-04-25 01:59:09 +00001017 This is useful because constants are often given to a greater precision
1018 than is needed by the application. Another benefit is that rounding
1019 immediately eliminates unintended effects from digits beyond the current
1020 precision. In the following example, using unrounded inputs means that
1021 adding zero to a sum can change the result:
Georg Brandl116aa622007-08-15 14:28:22 +00001022
Benjamin Petersone41251e2008-04-25 01:59:09 +00001023 .. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001024
Benjamin Petersone41251e2008-04-25 01:59:09 +00001025 >>> getcontext().prec = 3
1026 >>> Decimal('3.4445') + Decimal('1.0023')
1027 Decimal('4.45')
1028 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1029 Decimal('4.44')
Georg Brandl116aa622007-08-15 14:28:22 +00001030
Benjamin Petersone41251e2008-04-25 01:59:09 +00001031 This method implements the to-number operation of the IBM specification.
1032 If the argument is a string, no leading or trailing whitespace is
1033 permitted.
1034
Georg Brandl45f53372009-01-03 21:15:20 +00001035 .. method:: create_decimal_from_float(f)
Raymond Hettinger771ed762009-01-03 19:20:32 +00001036
1037 Creates a new Decimal instance from a float *f* but rounding using *self*
Georg Brandl45f53372009-01-03 21:15:20 +00001038 as the context. Unlike the :meth:`Decimal.from_float` class method,
Raymond Hettinger771ed762009-01-03 19:20:32 +00001039 the context precision, rounding method, flags, and traps are applied to
1040 the conversion.
1041
1042 .. doctest::
1043
Georg Brandl45f53372009-01-03 21:15:20 +00001044 >>> context = Context(prec=5, rounding=ROUND_DOWN)
1045 >>> context.create_decimal_from_float(math.pi)
1046 Decimal('3.1415')
1047 >>> context = Context(prec=5, traps=[Inexact])
1048 >>> context.create_decimal_from_float(math.pi)
1049 Traceback (most recent call last):
1050 ...
1051 decimal.Inexact: None
Raymond Hettinger771ed762009-01-03 19:20:32 +00001052
Georg Brandl45f53372009-01-03 21:15:20 +00001053 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +00001054
Benjamin Petersone41251e2008-04-25 01:59:09 +00001055 .. method:: Etiny()
1056
1057 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
1058 value for subnormal results. When underflow occurs, the exponent is set
1059 to :const:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +00001060
Benjamin Petersone41251e2008-04-25 01:59:09 +00001061 .. method:: Etop()
Georg Brandl116aa622007-08-15 14:28:22 +00001062
Benjamin Petersone41251e2008-04-25 01:59:09 +00001063 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001064
Benjamin Petersone41251e2008-04-25 01:59:09 +00001065 The usual approach to working with decimals is to create :class:`Decimal`
1066 instances and then apply arithmetic operations which take place within the
1067 current context for the active thread. An alternative approach is to use
1068 context methods for calculating within a specific context. The methods are
1069 similar to those for the :class:`Decimal` class and are only briefly
1070 recounted here.
Georg Brandl116aa622007-08-15 14:28:22 +00001071
1072
Benjamin Petersone41251e2008-04-25 01:59:09 +00001073 .. method:: abs(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001074
Benjamin Petersone41251e2008-04-25 01:59:09 +00001075 Returns the absolute value of *x*.
Georg Brandl116aa622007-08-15 14:28:22 +00001076
1077
Benjamin Petersone41251e2008-04-25 01:59:09 +00001078 .. method:: add(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001079
Benjamin Petersone41251e2008-04-25 01:59:09 +00001080 Return the sum of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001081
1082
Facundo Batista789bdf02008-06-21 17:29:41 +00001083 .. method:: canonical(x)
1084
1085 Returns the same Decimal object *x*.
1086
1087
1088 .. method:: compare(x, y)
1089
1090 Compares *x* and *y* numerically.
1091
1092
1093 .. method:: compare_signal(x, y)
1094
1095 Compares the values of the two operands numerically.
1096
1097
1098 .. method:: compare_total(x, y)
1099
1100 Compares two operands using their abstract representation.
1101
1102
1103 .. method:: compare_total_mag(x, y)
1104
1105 Compares two operands using their abstract representation, ignoring sign.
1106
1107
1108 .. method:: copy_abs(x)
1109
1110 Returns a copy of *x* with the sign set to 0.
1111
1112
1113 .. method:: copy_negate(x)
1114
1115 Returns a copy of *x* with the sign inverted.
1116
1117
1118 .. method:: copy_sign(x, y)
1119
1120 Copies the sign from *y* to *x*.
1121
1122
Benjamin Petersone41251e2008-04-25 01:59:09 +00001123 .. method:: divide(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001124
Benjamin Petersone41251e2008-04-25 01:59:09 +00001125 Return *x* divided by *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001126
1127
Benjamin Petersone41251e2008-04-25 01:59:09 +00001128 .. method:: divide_int(x, y)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001129
Benjamin Petersone41251e2008-04-25 01:59:09 +00001130 Return *x* divided by *y*, truncated to an integer.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001131
1132
Benjamin Petersone41251e2008-04-25 01:59:09 +00001133 .. method:: divmod(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001134
Benjamin Petersone41251e2008-04-25 01:59:09 +00001135 Divides two numbers and returns the integer part of the result.
Georg Brandl116aa622007-08-15 14:28:22 +00001136
1137
Facundo Batista789bdf02008-06-21 17:29:41 +00001138 .. method:: exp(x)
1139
1140 Returns `e ** x`.
1141
1142
1143 .. method:: fma(x, y, z)
1144
1145 Returns *x* multiplied by *y*, plus *z*.
1146
1147
1148 .. method:: is_canonical(x)
1149
1150 Returns True if *x* is canonical; otherwise returns False.
1151
1152
1153 .. method:: is_finite(x)
1154
1155 Returns True if *x* is finite; otherwise returns False.
1156
1157
1158 .. method:: is_infinite(x)
1159
1160 Returns True if *x* is infinite; otherwise returns False.
1161
1162
1163 .. method:: is_nan(x)
1164
1165 Returns True if *x* is a qNaN or sNaN; otherwise returns False.
1166
1167
1168 .. method:: is_normal(x)
1169
1170 Returns True if *x* is a normal number; otherwise returns False.
1171
1172
1173 .. method:: is_qnan(x)
1174
1175 Returns True if *x* is a quiet NaN; otherwise returns False.
1176
1177
1178 .. method:: is_signed(x)
1179
1180 Returns True if *x* is negative; otherwise returns False.
1181
1182
1183 .. method:: is_snan(x)
1184
1185 Returns True if *x* is a signaling NaN; otherwise returns False.
1186
1187
1188 .. method:: is_subnormal(x)
1189
1190 Returns True if *x* is subnormal; otherwise returns False.
1191
1192
1193 .. method:: is_zero(x)
1194
1195 Returns True if *x* is a zero; otherwise returns False.
1196
1197
1198 .. method:: ln(x)
1199
1200 Returns the natural (base e) logarithm of *x*.
1201
1202
1203 .. method:: log10(x)
1204
1205 Returns the base 10 logarithm of *x*.
1206
1207
1208 .. method:: logb(x)
1209
1210 Returns the exponent of the magnitude of the operand's MSD.
1211
1212
1213 .. method:: logical_and(x, y)
1214
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001215 Applies the logical operation *and* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001216
1217
1218 .. method:: logical_invert(x)
1219
1220 Invert all the digits in *x*.
1221
1222
1223 .. method:: logical_or(x, y)
1224
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001225 Applies the logical operation *or* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001226
1227
1228 .. method:: logical_xor(x, y)
1229
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001230 Applies the logical operation *xor* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001231
1232
1233 .. method:: max(x, y)
1234
1235 Compares two values numerically and returns the maximum.
1236
1237
1238 .. method:: max_mag(x, y)
1239
1240 Compares the values numerically with their sign ignored.
1241
1242
1243 .. method:: min(x, y)
1244
1245 Compares two values numerically and returns the minimum.
1246
1247
1248 .. method:: min_mag(x, y)
1249
1250 Compares the values numerically with their sign ignored.
1251
1252
Benjamin Petersone41251e2008-04-25 01:59:09 +00001253 .. method:: minus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001254
Benjamin Petersone41251e2008-04-25 01:59:09 +00001255 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001256
1257
Benjamin Petersone41251e2008-04-25 01:59:09 +00001258 .. method:: multiply(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001259
Benjamin Petersone41251e2008-04-25 01:59:09 +00001260 Return the product of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001261
1262
Facundo Batista789bdf02008-06-21 17:29:41 +00001263 .. method:: next_minus(x)
1264
1265 Returns the largest representable number smaller than *x*.
1266
1267
1268 .. method:: next_plus(x)
1269
1270 Returns the smallest representable number larger than *x*.
1271
1272
1273 .. method:: next_toward(x, y)
1274
1275 Returns the number closest to *x*, in direction towards *y*.
1276
1277
1278 .. method:: normalize(x)
1279
1280 Reduces *x* to its simplest form.
1281
1282
1283 .. method:: number_class(x)
1284
1285 Returns an indication of the class of *x*.
1286
1287
Benjamin Petersone41251e2008-04-25 01:59:09 +00001288 .. method:: plus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001289
Benjamin Petersone41251e2008-04-25 01:59:09 +00001290 Plus corresponds to the unary prefix plus operator in Python. This
1291 operation applies the context precision and rounding, so it is *not* an
1292 identity operation.
Georg Brandl116aa622007-08-15 14:28:22 +00001293
1294
Benjamin Petersone41251e2008-04-25 01:59:09 +00001295 .. method:: power(x, y[, modulo])
Georg Brandl116aa622007-08-15 14:28:22 +00001296
Benjamin Petersone41251e2008-04-25 01:59:09 +00001297 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl116aa622007-08-15 14:28:22 +00001298
Benjamin Petersone41251e2008-04-25 01:59:09 +00001299 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1300 must be integral. The result will be inexact unless ``y`` is integral and
1301 the result is finite and can be expressed exactly in 'precision' digits.
Stefan Krah1919b7e2012-03-21 18:25:23 +01001302 The rounding mode of the context is used. Results are always correctly-rounded
1303 in the Python version.
1304
1305 .. versionchanged:: 3.3
1306 The C module computes :meth:`power` in terms of the correctly-rounded
1307 :meth:`exp` and :meth:`ln` functions. The result is well-defined but
1308 only "almost always correctly-rounded".
Georg Brandl116aa622007-08-15 14:28:22 +00001309
Benjamin Petersone41251e2008-04-25 01:59:09 +00001310 With three arguments, compute ``(x**y) % modulo``. For the three argument
1311 form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +00001312
Benjamin Petersone41251e2008-04-25 01:59:09 +00001313 - all three arguments must be integral
1314 - ``y`` must be nonnegative
1315 - at least one of ``x`` or ``y`` must be nonzero
1316 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +00001317
Mark Dickinson5961b0e2010-02-22 15:41:48 +00001318 The value resulting from ``Context.power(x, y, modulo)`` is
1319 equal to the value that would be obtained by computing ``(x**y)
1320 % modulo`` with unbounded precision, but is computed more
1321 efficiently. The exponent of the result is zero, regardless of
1322 the exponents of ``x``, ``y`` and ``modulo``. The result is
1323 always exact.
Georg Brandl116aa622007-08-15 14:28:22 +00001324
Facundo Batista789bdf02008-06-21 17:29:41 +00001325
1326 .. method:: quantize(x, y)
1327
1328 Returns a value equal to *x* (rounded), having the exponent of *y*.
1329
1330
1331 .. method:: radix()
1332
1333 Just returns 10, as this is Decimal, :)
1334
1335
Benjamin Petersone41251e2008-04-25 01:59:09 +00001336 .. method:: remainder(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001337
Benjamin Petersone41251e2008-04-25 01:59:09 +00001338 Returns the remainder from integer division.
Georg Brandl116aa622007-08-15 14:28:22 +00001339
Benjamin Petersone41251e2008-04-25 01:59:09 +00001340 The sign of the result, if non-zero, is the same as that of the original
1341 dividend.
Georg Brandl116aa622007-08-15 14:28:22 +00001342
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001343
Facundo Batista789bdf02008-06-21 17:29:41 +00001344 .. method:: remainder_near(x, y)
1345
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001346 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1347 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
Facundo Batista789bdf02008-06-21 17:29:41 +00001348
1349
1350 .. method:: rotate(x, y)
1351
1352 Returns a rotated copy of *x*, *y* times.
1353
1354
1355 .. method:: same_quantum(x, y)
1356
1357 Returns True if the two operands have the same exponent.
1358
1359
1360 .. method:: scaleb (x, y)
1361
1362 Returns the first operand after adding the second value its exp.
1363
1364
1365 .. method:: shift(x, y)
1366
1367 Returns a shifted copy of *x*, *y* times.
1368
1369
1370 .. method:: sqrt(x)
1371
1372 Square root of a non-negative number to context precision.
1373
1374
Benjamin Petersone41251e2008-04-25 01:59:09 +00001375 .. method:: subtract(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001376
Benjamin Petersone41251e2008-04-25 01:59:09 +00001377 Return the difference between *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001378
Facundo Batista789bdf02008-06-21 17:29:41 +00001379
1380 .. method:: to_eng_string(x)
1381
1382 Converts a number to a string, using scientific notation.
1383
1384
1385 .. method:: to_integral_exact(x)
1386
1387 Rounds to an integer.
1388
1389
Benjamin Petersone41251e2008-04-25 01:59:09 +00001390 .. method:: to_sci_string(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001391
Benjamin Petersone41251e2008-04-25 01:59:09 +00001392 Converts a number to a string using scientific notation.
Georg Brandl116aa622007-08-15 14:28:22 +00001393
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001394.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001395
Stefan Krah1919b7e2012-03-21 18:25:23 +01001396.. _decimal-rounding-modes:
1397
1398Constants
1399---------
1400
1401The constants in this section are only relevant for the C module. They
1402are also included in the pure Python version for compatibility.
1403
Stefan Krah851a07e2012-03-21 18:47:20 +01001404+---------------------+---------------------+-------------------------------+
1405| | 32-bit | 64-bit |
1406+=====================+=====================+===============================+
1407| .. data:: MAX_PREC | :const:`425000000` | :const:`999999999999999999` |
1408+---------------------+---------------------+-------------------------------+
1409| .. data:: MAX_EMAX | :const:`425000000` | :const:`999999999999999999` |
1410+---------------------+---------------------+-------------------------------+
1411| .. data:: MIN_EMIN | :const:`-425000000` | :const:`-999999999999999999` |
1412+---------------------+---------------------+-------------------------------+
1413| .. data:: MIN_ETINY | :const:`-849999999` | :const:`-1999999999999999997` |
1414+---------------------+---------------------+-------------------------------+
1415
Stefan Krah1919b7e2012-03-21 18:25:23 +01001416
1417.. data:: HAVE_THREADS
1418
1419 The default value is True. If Python is compiled without threads, the
1420 C version automatically disables the expensive thread local context
1421 machinery. In this case, the value is False.
1422
1423Rounding modes
1424--------------
1425
1426.. data:: ROUND_CEILING
1427
1428 Round towards :const:`Infinity`.
1429
1430.. data:: ROUND_DOWN
1431
1432 Round towards zero.
1433
1434.. data:: ROUND_FLOOR
1435
1436 Round towards :const:`-Infinity`.
1437
1438.. data:: ROUND_HALF_DOWN
1439
1440 Round to nearest with ties going towards zero.
1441
1442.. data:: ROUND_HALF_EVEN
1443
1444 Round to nearest with ties going to nearest even integer.
1445
1446.. data:: ROUND_HALF_UP
1447
1448 Round to nearest with ties going away from zero.
1449
1450.. data:: ROUND_UP
1451
1452 Round away from zero.
1453
1454.. data:: ROUND_05UP
1455
1456 Round away from zero if last digit after rounding towards zero would have
1457 been 0 or 5; otherwise round towards zero.
1458
Georg Brandl116aa622007-08-15 14:28:22 +00001459
1460.. _decimal-signals:
1461
1462Signals
1463-------
1464
1465Signals represent conditions that arise during computation. Each corresponds to
1466one context flag and one context trap enabler.
1467
Raymond Hettinger86173da2008-02-01 20:38:12 +00001468The context flag is set whenever the condition is encountered. After the
Georg Brandl116aa622007-08-15 14:28:22 +00001469computation, flags may be checked for informational purposes (for instance, to
1470determine whether a computation was exact). After checking the flags, be sure to
1471clear all flags before starting the next computation.
1472
1473If the context's trap enabler is set for the signal, then the condition causes a
1474Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1475is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1476condition.
1477
1478
1479.. class:: Clamped
1480
1481 Altered an exponent to fit representation constraints.
1482
1483 Typically, clamping occurs when an exponent falls outside the context's
1484 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001485 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001486
1487
1488.. class:: DecimalException
1489
1490 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1491
1492
1493.. class:: DivisionByZero
1494
1495 Signals the division of a non-infinite number by zero.
1496
1497 Can occur with division, modulo division, or when raising a number to a negative
1498 power. If this signal is not trapped, returns :const:`Infinity` or
1499 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1500
1501
1502.. class:: Inexact
1503
1504 Indicates that rounding occurred and the result is not exact.
1505
1506 Signals when non-zero digits were discarded during rounding. The rounded result
1507 is returned. The signal flag or trap is used to detect when results are
1508 inexact.
1509
1510
1511.. class:: InvalidOperation
1512
1513 An invalid operation was performed.
1514
1515 Indicates that an operation was requested that does not make sense. If not
1516 trapped, returns :const:`NaN`. Possible causes include::
1517
1518 Infinity - Infinity
1519 0 * Infinity
1520 Infinity / Infinity
1521 x % 0
1522 Infinity % x
Georg Brandl116aa622007-08-15 14:28:22 +00001523 sqrt(-x) and x > 0
1524 0 ** 0
1525 x ** (non-integer)
Georg Brandl48310cd2009-01-03 21:18:54 +00001526 x ** Infinity
Georg Brandl116aa622007-08-15 14:28:22 +00001527
1528
1529.. class:: Overflow
1530
1531 Numerical overflow.
1532
Benjamin Petersone41251e2008-04-25 01:59:09 +00001533 Indicates the exponent is larger than :attr:`Emax` after rounding has
1534 occurred. If not trapped, the result depends on the rounding mode, either
1535 pulling inward to the largest representable finite number or rounding outward
1536 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1537 are also signaled.
Georg Brandl116aa622007-08-15 14:28:22 +00001538
1539
1540.. class:: Rounded
1541
1542 Rounding occurred though possibly no information was lost.
1543
Benjamin Petersone41251e2008-04-25 01:59:09 +00001544 Signaled whenever rounding discards digits; even if those digits are zero
1545 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1546 the result unchanged. This signal is used to detect loss of significant
1547 digits.
Georg Brandl116aa622007-08-15 14:28:22 +00001548
1549
1550.. class:: Subnormal
1551
1552 Exponent was lower than :attr:`Emin` prior to rounding.
1553
Benjamin Petersone41251e2008-04-25 01:59:09 +00001554 Occurs when an operation result is subnormal (the exponent is too small). If
1555 not trapped, returns the result unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +00001556
1557
1558.. class:: Underflow
1559
1560 Numerical underflow with result rounded to zero.
1561
1562 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1563 and :class:`Subnormal` are also signaled.
1564
Stefan Krah1919b7e2012-03-21 18:25:23 +01001565
1566.. class:: FloatOperation
1567
1568 Enable stricter semantics for mixing floats and Decimals.
1569
1570 If the signal is not trapped (default), mixing floats and Decimals is
1571 permitted in the :class:`~decimal.Decimal` constructor,
1572 :meth:`~decimal.Context.create_decimal` and all comparison operators.
1573 Both conversion and comparisons are exact. Any occurrence of a mixed
1574 operation is silently recorded by setting :exc:`FloatOperation` in the
1575 context flags. Explicit conversions with :meth:`~decimal.Decimal.from_float`
1576 or :meth:`~decimal.Context.create_decimal_from_float` do not set the flag.
1577
1578 Otherwise (the signal is trapped), only equality comparisons and explicit
1579 conversions are silent. All other mixed operations raise :exc:`FloatOperation`.
1580
1581
Georg Brandl116aa622007-08-15 14:28:22 +00001582The following table summarizes the hierarchy of signals::
1583
1584 exceptions.ArithmeticError(exceptions.Exception)
1585 DecimalException
1586 Clamped
1587 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1588 Inexact
1589 Overflow(Inexact, Rounded)
1590 Underflow(Inexact, Rounded, Subnormal)
1591 InvalidOperation
1592 Rounded
1593 Subnormal
Stefan Krahb6405ef2012-03-23 14:46:48 +01001594 FloatOperation(DecimalException, exceptions.TypeError)
Georg Brandl116aa622007-08-15 14:28:22 +00001595
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001596.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001597
1598
Stefan Krah1919b7e2012-03-21 18:25:23 +01001599
Georg Brandl116aa622007-08-15 14:28:22 +00001600.. _decimal-notes:
1601
1602Floating Point Notes
1603--------------------
1604
1605
1606Mitigating round-off error with increased precision
1607^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1608
1609The use of decimal floating point eliminates decimal representation error
1610(making it possible to represent :const:`0.1` exactly); however, some operations
1611can still incur round-off error when non-zero digits exceed the fixed precision.
1612
1613The effects of round-off error can be amplified by the addition or subtraction
1614of nearly offsetting quantities resulting in loss of significance. Knuth
1615provides two instructive examples where rounded floating point arithmetic with
1616insufficient precision causes the breakdown of the associative and distributive
Christian Heimesfe337bf2008-03-23 21:54:12 +00001617properties of addition:
1618
1619.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001620
1621 # Examples from Seminumerical Algorithms, Section 4.2.2.
1622 >>> from decimal import Decimal, getcontext
1623 >>> getcontext().prec = 8
1624
1625 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1626 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001627 Decimal('9.5111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001628 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001629 Decimal('10')
Georg Brandl116aa622007-08-15 14:28:22 +00001630
1631 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1632 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001633 Decimal('0.01')
Georg Brandl116aa622007-08-15 14:28:22 +00001634 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001635 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001636
1637The :mod:`decimal` module makes it possible to restore the identities by
Christian Heimesfe337bf2008-03-23 21:54:12 +00001638expanding the precision sufficiently to avoid loss of significance:
1639
1640.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001641
1642 >>> getcontext().prec = 20
1643 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1644 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001645 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001646 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001647 Decimal('9.51111111')
Georg Brandl48310cd2009-01-03 21:18:54 +00001648 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001649 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1650 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001651 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001652 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001653 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001654
1655
1656Special values
1657^^^^^^^^^^^^^^
1658
1659The number system for the :mod:`decimal` module provides special values
1660including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001661and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001662
1663Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1664they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1665not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1666can result from rounding beyond the limits of the largest representable number.
1667
1668The infinities are signed (affine) and can be used in arithmetic operations
1669where they get treated as very large, indeterminate numbers. For instance,
1670adding a constant to infinity gives another infinite result.
1671
1672Some operations are indeterminate and return :const:`NaN`, or if the
1673:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1674``0/0`` returns :const:`NaN` which means "not a number". This variety of
1675:const:`NaN` is quiet and, once created, will flow through other computations
1676always resulting in another :const:`NaN`. This behavior can be useful for a
1677series of computations that occasionally have missing inputs --- it allows the
1678calculation to proceed while flagging specific results as invalid.
1679
1680A variant is :const:`sNaN` which signals rather than remaining quiet after every
1681operation. This is a useful return value when an invalid result needs to
1682interrupt a calculation for special handling.
1683
Christian Heimes77c02eb2008-02-09 02:18:51 +00001684The behavior of Python's comparison operators can be a little surprising where a
1685:const:`NaN` is involved. A test for equality where one of the operands is a
1686quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1687``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1688:const:`True`. An attempt to compare two Decimals using any of the ``<``,
1689``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1690if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes3feef612008-02-11 06:19:17 +00001691not trapped. Note that the General Decimal Arithmetic specification does not
Christian Heimes77c02eb2008-02-09 02:18:51 +00001692specify the behavior of direct comparisons; these rules for comparisons
1693involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1694section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1695and :meth:`compare-signal` methods instead.
1696
Georg Brandl116aa622007-08-15 14:28:22 +00001697The signed zeros can result from calculations that underflow. They keep the sign
1698that would have resulted if the calculation had been carried out to greater
1699precision. Since their magnitude is zero, both positive and negative zeros are
1700treated as equal and their sign is informational.
1701
1702In addition to the two signed zeros which are distinct yet equal, there are
1703various representations of zero with differing precisions yet equivalent in
1704value. This takes a bit of getting used to. For an eye accustomed to
1705normalized floating point representations, it is not immediately obvious that
Christian Heimesfe337bf2008-03-23 21:54:12 +00001706the following calculation returns a value equal to zero:
Georg Brandl116aa622007-08-15 14:28:22 +00001707
1708 >>> 1 / Decimal('Infinity')
Stefan Krah1919b7e2012-03-21 18:25:23 +01001709 Decimal('0E-1000026')
Georg Brandl116aa622007-08-15 14:28:22 +00001710
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001711.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001712
1713
1714.. _decimal-threads:
1715
1716Working with threads
1717--------------------
1718
1719The :func:`getcontext` function accesses a different :class:`Context` object for
1720each thread. Having separate thread contexts means that threads may make
Stefan Krah1919b7e2012-03-21 18:25:23 +01001721changes (such as ``getcontext().prec=10``) without interfering with other threads.
Georg Brandl116aa622007-08-15 14:28:22 +00001722
1723Likewise, the :func:`setcontext` function automatically assigns its target to
1724the current thread.
1725
1726If :func:`setcontext` has not been called before :func:`getcontext`, then
1727:func:`getcontext` will automatically create a new context for use in the
1728current thread.
1729
1730The new context is copied from a prototype context called *DefaultContext*. To
1731control the defaults so that each thread will use the same values throughout the
1732application, directly modify the *DefaultContext* object. This should be done
1733*before* any threads are started so that there won't be a race condition between
1734threads calling :func:`getcontext`. For example::
1735
1736 # Set applicationwide defaults for all threads about to be launched
1737 DefaultContext.prec = 12
1738 DefaultContext.rounding = ROUND_DOWN
1739 DefaultContext.traps = ExtendedContext.traps.copy()
1740 DefaultContext.traps[InvalidOperation] = 1
1741 setcontext(DefaultContext)
1742
1743 # Afterwards, the threads can be started
1744 t1.start()
1745 t2.start()
1746 t3.start()
1747 . . .
1748
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001749.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001750
1751
1752.. _decimal-recipes:
1753
1754Recipes
1755-------
1756
1757Here are a few recipes that serve as utility functions and that demonstrate ways
1758to work with the :class:`Decimal` class::
1759
1760 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1761 pos='', neg='-', trailneg=''):
1762 """Convert Decimal to a money formatted string.
1763
1764 places: required number of places after the decimal point
1765 curr: optional currency symbol before the sign (may be blank)
1766 sep: optional grouping separator (comma, period, space, or blank)
1767 dp: decimal point indicator (comma or period)
1768 only specify as blank when places is zero
1769 pos: optional sign for positive numbers: '+', space or blank
1770 neg: optional sign for negative numbers: '-', '(', space or blank
1771 trailneg:optional trailing minus indicator: '-', ')', space or blank
1772
1773 >>> d = Decimal('-1234567.8901')
1774 >>> moneyfmt(d, curr='$')
1775 '-$1,234,567.89'
1776 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1777 '1.234.568-'
1778 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1779 '($1,234,567.89)'
1780 >>> moneyfmt(Decimal(123456789), sep=' ')
1781 '123 456 789.00'
1782 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Christian Heimesdae2a892008-04-19 00:55:37 +00001783 '<0.02>'
Georg Brandl116aa622007-08-15 14:28:22 +00001784
1785 """
Christian Heimesa156e092008-02-16 07:38:31 +00001786 q = Decimal(10) ** -places # 2 places --> '0.01'
Georg Brandl48310cd2009-01-03 21:18:54 +00001787 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +00001788 result = []
Facundo Batista789bdf02008-06-21 17:29:41 +00001789 digits = list(map(str, digits))
Georg Brandl116aa622007-08-15 14:28:22 +00001790 build, next = result.append, digits.pop
1791 if sign:
1792 build(trailneg)
1793 for i in range(places):
Christian Heimesa156e092008-02-16 07:38:31 +00001794 build(next() if digits else '0')
Raymond Hettinger0ab10e42011-01-08 09:03:11 +00001795 if places:
1796 build(dp)
Christian Heimesdae2a892008-04-19 00:55:37 +00001797 if not digits:
1798 build('0')
Georg Brandl116aa622007-08-15 14:28:22 +00001799 i = 0
1800 while digits:
1801 build(next())
1802 i += 1
1803 if i == 3 and digits:
1804 i = 0
1805 build(sep)
1806 build(curr)
Christian Heimesa156e092008-02-16 07:38:31 +00001807 build(neg if sign else pos)
1808 return ''.join(reversed(result))
Georg Brandl116aa622007-08-15 14:28:22 +00001809
1810 def pi():
1811 """Compute Pi to the current precision.
1812
Georg Brandl6911e3c2007-09-04 07:15:32 +00001813 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001814 3.141592653589793238462643383
1815
1816 """
1817 getcontext().prec += 2 # extra digits for intermediate steps
1818 three = Decimal(3) # substitute "three=3.0" for regular floats
1819 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1820 while s != lasts:
1821 lasts = s
1822 n, na = n+na, na+8
1823 d, da = d+da, da+32
1824 t = (t * n) / d
1825 s += t
1826 getcontext().prec -= 2
1827 return +s # unary plus applies the new precision
1828
1829 def exp(x):
1830 """Return e raised to the power of x. Result type matches input type.
1831
Georg Brandl6911e3c2007-09-04 07:15:32 +00001832 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001833 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001834 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001835 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001836 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001837 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001838 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001839 (7.38905609893+0j)
1840
1841 """
1842 getcontext().prec += 2
1843 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1844 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001845 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001846 i += 1
1847 fact *= i
Georg Brandl48310cd2009-01-03 21:18:54 +00001848 num *= x
1849 s += num / fact
1850 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001851 return +s
1852
1853 def cos(x):
1854 """Return the cosine of x as measured in radians.
1855
Mark Dickinsonb2b23822010-11-21 07:37:49 +00001856 The Taylor series approximation works best for a small value of x.
Raymond Hettinger2a1e3e22010-11-21 02:47:22 +00001857 For larger values, first compute x = x % (2 * pi).
1858
Georg Brandl6911e3c2007-09-04 07:15:32 +00001859 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001860 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001861 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001862 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001863 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001864 (0.87758256189+0j)
1865
1866 """
1867 getcontext().prec += 2
1868 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1869 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001870 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001871 i += 2
1872 fact *= i * (i-1)
1873 num *= x * x
1874 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001875 s += num / fact * sign
1876 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001877 return +s
1878
1879 def sin(x):
1880 """Return the sine of x as measured in radians.
1881
Mark Dickinsonb2b23822010-11-21 07:37:49 +00001882 The Taylor series approximation works best for a small value of x.
Raymond Hettinger2a1e3e22010-11-21 02:47:22 +00001883 For larger values, first compute x = x % (2 * pi).
1884
Georg Brandl6911e3c2007-09-04 07:15:32 +00001885 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001886 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001887 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001888 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001889 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001890 (0.479425538604+0j)
1891
1892 """
1893 getcontext().prec += 2
1894 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1895 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001896 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001897 i += 2
1898 fact *= i * (i-1)
1899 num *= x * x
1900 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001901 s += num / fact * sign
1902 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001903 return +s
1904
1905
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001906.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001907
1908
1909.. _decimal-faq:
1910
1911Decimal FAQ
1912-----------
1913
1914Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1915minimize typing when using the interactive interpreter?
1916
Christian Heimesfe337bf2008-03-23 21:54:12 +00001917A. Some users abbreviate the constructor to just a single letter:
Georg Brandl116aa622007-08-15 14:28:22 +00001918
1919 >>> D = decimal.Decimal
1920 >>> D('1.23') + D('3.45')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001921 Decimal('4.68')
Georg Brandl116aa622007-08-15 14:28:22 +00001922
1923Q. In a fixed-point application with two decimal places, some inputs have many
1924places and need to be rounded. Others are not supposed to have excess digits
1925and need to be validated. What methods should be used?
1926
1927A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Christian Heimesfe337bf2008-03-23 21:54:12 +00001928the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl116aa622007-08-15 14:28:22 +00001929
1930 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1931
1932 >>> # Round to two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001933 >>> Decimal('3.214').quantize(TWOPLACES)
1934 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001935
Georg Brandl48310cd2009-01-03 21:18:54 +00001936 >>> # Validate that a number does not exceed two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001937 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1938 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001939
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001940 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl116aa622007-08-15 14:28:22 +00001941 Traceback (most recent call last):
1942 ...
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001943 Inexact: None
Georg Brandl116aa622007-08-15 14:28:22 +00001944
1945Q. Once I have valid two place inputs, how do I maintain that invariant
1946throughout an application?
1947
Christian Heimesa156e092008-02-16 07:38:31 +00001948A. Some operations like addition, subtraction, and multiplication by an integer
1949will automatically preserve fixed point. Others operations, like division and
1950non-integer multiplication, will change the number of decimal places and need to
Christian Heimesfe337bf2008-03-23 21:54:12 +00001951be followed-up with a :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001952
1953 >>> a = Decimal('102.72') # Initial fixed-point values
1954 >>> b = Decimal('3.17')
1955 >>> a + b # Addition preserves fixed-point
1956 Decimal('105.89')
1957 >>> a - b
1958 Decimal('99.55')
1959 >>> a * 42 # So does integer multiplication
1960 Decimal('4314.24')
1961 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1962 Decimal('325.62')
1963 >>> (b / a).quantize(TWOPLACES) # And quantize division
1964 Decimal('0.03')
1965
1966In developing fixed-point applications, it is convenient to define functions
Christian Heimesfe337bf2008-03-23 21:54:12 +00001967to handle the :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001968
1969 >>> def mul(x, y, fp=TWOPLACES):
1970 ... return (x * y).quantize(fp)
1971 >>> def div(x, y, fp=TWOPLACES):
1972 ... return (x / y).quantize(fp)
1973
1974 >>> mul(a, b) # Automatically preserve fixed-point
1975 Decimal('325.62')
1976 >>> div(b, a)
1977 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +00001978
1979Q. There are many ways to express the same value. The numbers :const:`200`,
1980:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1981various precisions. Is there a way to transform them to a single recognizable
1982canonical value?
1983
1984A. The :meth:`normalize` method maps all equivalent values to a single
Christian Heimesfe337bf2008-03-23 21:54:12 +00001985representative:
Georg Brandl116aa622007-08-15 14:28:22 +00001986
1987 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1988 >>> [v.normalize() for v in values]
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001989 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl116aa622007-08-15 14:28:22 +00001990
1991Q. Some decimal values always print with exponential notation. Is there a way
1992to get a non-exponential representation?
1993
1994A. For some values, exponential notation is the only way to express the number
1995of significant places in the coefficient. For example, expressing
1996:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1997original's two-place significance.
1998
Christian Heimesa156e092008-02-16 07:38:31 +00001999If an application does not care about tracking significance, it is easy to
Christian Heimesc3f30c42008-02-22 16:37:40 +00002000remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimesfe337bf2008-03-23 21:54:12 +00002001value unchanged:
Christian Heimesa156e092008-02-16 07:38:31 +00002002
2003 >>> def remove_exponent(d):
2004 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
2005
2006 >>> remove_exponent(Decimal('5E+3'))
2007 Decimal('5000')
2008
Georg Brandl116aa622007-08-15 14:28:22 +00002009Q. Is there a way to convert a regular float to a :class:`Decimal`?
2010
Mark Dickinsone534a072010-04-04 22:13:14 +00002011A. Yes, any binary floating point number can be exactly expressed as a
Raymond Hettinger96798592010-04-02 16:58:27 +00002012Decimal though an exact conversion may take more precision than intuition would
2013suggest:
Georg Brandl116aa622007-08-15 14:28:22 +00002014
Christian Heimesfe337bf2008-03-23 21:54:12 +00002015.. doctest::
2016
Raymond Hettinger96798592010-04-02 16:58:27 +00002017 >>> Decimal(math.pi)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002018 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl116aa622007-08-15 14:28:22 +00002019
Georg Brandl116aa622007-08-15 14:28:22 +00002020Q. Within a complex calculation, how can I make sure that I haven't gotten a
2021spurious result because of insufficient precision or rounding anomalies.
2022
2023A. The decimal module makes it easy to test results. A best practice is to
2024re-run calculations using greater precision and with various rounding modes.
2025Widely differing results indicate insufficient precision, rounding mode issues,
2026ill-conditioned inputs, or a numerically unstable algorithm.
2027
2028Q. I noticed that context precision is applied to the results of operations but
2029not to the inputs. Is there anything to watch out for when mixing values of
2030different precisions?
2031
2032A. Yes. The principle is that all values are considered to be exact and so is
2033the arithmetic on those values. Only the results are rounded. The advantage
2034for inputs is that "what you type is what you get". A disadvantage is that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00002035results can look odd if you forget that the inputs haven't been rounded:
2036
2037.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00002038
2039 >>> getcontext().prec = 3
Christian Heimesfe337bf2008-03-23 21:54:12 +00002040 >>> Decimal('3.104') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002041 Decimal('5.21')
Christian Heimesfe337bf2008-03-23 21:54:12 +00002042 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002043 Decimal('5.20')
Georg Brandl116aa622007-08-15 14:28:22 +00002044
2045The solution is either to increase precision or to force rounding of inputs
Christian Heimesfe337bf2008-03-23 21:54:12 +00002046using the unary plus operation:
2047
2048.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00002049
2050 >>> getcontext().prec = 3
2051 >>> +Decimal('1.23456789') # unary plus triggers rounding
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002052 Decimal('1.23')
Georg Brandl116aa622007-08-15 14:28:22 +00002053
2054Alternatively, inputs can be rounded upon creation using the
Christian Heimesfe337bf2008-03-23 21:54:12 +00002055:meth:`Context.create_decimal` method:
Georg Brandl116aa622007-08-15 14:28:22 +00002056
2057 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002058 Decimal('1.2345')
Georg Brandl116aa622007-08-15 14:28:22 +00002059