blob: e759c5cf23b9e74fe77d92f7211565d67e29c46f [file] [log] [blame]
Christian Heimes3feef612008-02-11 06:19:17 +00001:mod:`decimal` --- Decimal fixed point and floating point arithmetic
2====================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: decimal
5 :synopsis: Implementation of the General Decimal Arithmetic Specification.
6
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
8.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
9.. moduleauthor:: Raymond Hettinger <python at rcn.com>
10.. moduleauthor:: Aahz <aahz at pobox.com>
11.. moduleauthor:: Tim Peters <tim.one at comcast.net>
Stefan Krah1919b7e2012-03-21 18:25:23 +010012.. moduleauthor:: Stefan Krah <skrah at bytereef.org>
Georg Brandl116aa622007-08-15 14:28:22 +000013.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
14
Andrew Kuchling2e3743c2014-03-19 16:23:01 -040015**Source code:** :source:`Lib/decimal.py`
16
Christian Heimesfe337bf2008-03-23 21:54:12 +000017.. import modules for testing inline doctests with the Sphinx doctest builder
18.. testsetup:: *
19
20 import decimal
21 import math
22 from decimal import *
23 # make sure each group gets a fresh context
24 setcontext(Context())
Georg Brandl116aa622007-08-15 14:28:22 +000025
Marco Buttu2c0b5c62017-04-13 13:30:25 +020026.. testcleanup:: *
27
28 # make sure other tests (outside this file) get a fresh context
29 setcontext(Context())
30
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040031--------------
32
Stefan Krah1919b7e2012-03-21 18:25:23 +010033The :mod:`decimal` module provides support for fast correctly-rounded
34decimal floating point arithmetic. It offers several advantages over the
35:class:`float` datatype:
Georg Brandl116aa622007-08-15 14:28:22 +000036
Christian Heimes3feef612008-02-11 06:19:17 +000037* Decimal "is based on a floating-point model which was designed with people
38 in mind, and necessarily has a paramount guiding principle -- computers must
39 provide an arithmetic that works in the same way as the arithmetic that
40 people learn at school." -- excerpt from the decimal arithmetic specification.
41
Georg Brandl116aa622007-08-15 14:28:22 +000042* Decimal numbers can be represented exactly. In contrast, numbers like
Terry Jan Reedya9314632012-01-13 23:43:13 -050043 :const:`1.1` and :const:`2.2` do not have exact representations in binary
Raymond Hettingerd258d1e2009-04-23 22:06:12 +000044 floating point. End users typically would not expect ``1.1 + 2.2`` to display
45 as :const:`3.3000000000000003` as it does with binary floating point.
Georg Brandl116aa622007-08-15 14:28:22 +000046
47* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000048 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl116aa622007-08-15 14:28:22 +000049 is :const:`5.5511151231257827e-017`. While near to zero, the differences
50 prevent reliable equality testing and differences can accumulate. For this
Christian Heimes3feef612008-02-11 06:19:17 +000051 reason, decimal is preferred in accounting applications which have strict
Georg Brandl116aa622007-08-15 14:28:22 +000052 equality invariants.
53
54* The decimal module incorporates a notion of significant places so that ``1.30
55 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
56 This is the customary presentation for monetary applications. For
57 multiplication, the "schoolbook" approach uses all the figures in the
58 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
59 1.20`` gives :const:`1.5600`.
60
61* Unlike hardware based binary floating point, the decimal module has a user
Thomas Wouters1b7f8912007-09-19 03:06:30 +000062 alterable precision (defaulting to 28 places) which can be as large as needed for
Christian Heimesfe337bf2008-03-23 21:54:12 +000063 a given problem:
Georg Brandl116aa622007-08-15 14:28:22 +000064
Mark Dickinson43ef32a2010-11-07 11:24:44 +000065 >>> from decimal import *
Georg Brandl116aa622007-08-15 14:28:22 +000066 >>> getcontext().prec = 6
67 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000068 Decimal('0.142857')
Georg Brandl116aa622007-08-15 14:28:22 +000069 >>> getcontext().prec = 28
70 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000071 Decimal('0.1428571428571428571428571429')
Georg Brandl116aa622007-08-15 14:28:22 +000072
73* Both binary and decimal floating point are implemented in terms of published
74 standards. While the built-in float type exposes only a modest portion of its
75 capabilities, the decimal module exposes all required parts of the standard.
76 When needed, the programmer has full control over rounding and signal handling.
Christian Heimes3feef612008-02-11 06:19:17 +000077 This includes an option to enforce exact arithmetic by using exceptions
78 to block any inexact operations.
79
80* The decimal module was designed to support "without prejudice, both exact
81 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
82 and rounded floating-point arithmetic." -- excerpt from the decimal
83 arithmetic specification.
Georg Brandl116aa622007-08-15 14:28:22 +000084
85The module design is centered around three concepts: the decimal number, the
86context for arithmetic, and signals.
87
88A decimal number is immutable. It has a sign, coefficient digits, and an
89exponent. To preserve significance, the coefficient digits do not truncate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000090trailing zeros. Decimals also include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +000091:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
92differentiates :const:`-0` from :const:`+0`.
93
94The context for arithmetic is an environment specifying precision, rounding
95rules, limits on exponents, flags indicating the results of operations, and trap
96enablers which determine whether signals are treated as exceptions. Rounding
97options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
98:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +000099:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101Signals are groups of exceptional conditions arising during the course of
102computation. Depending on the needs of the application, signals may be ignored,
103considered as informational, or treated as exceptions. The signals in the
104decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
105:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
Stefan Krah1919b7e2012-03-21 18:25:23 +0100106:const:`Overflow`, :const:`Underflow` and :const:`FloatOperation`.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108For each signal there is a flag and a trap enabler. When a signal is
Raymond Hettinger86173da2008-02-01 20:38:12 +0000109encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl116aa622007-08-15 14:28:22 +0000110set to one, an exception is raised. Flags are sticky, so the user needs to
111reset them before monitoring a calculation.
112
113
114.. seealso::
115
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000116 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
Raymond Hettinger960dc362009-04-21 03:43:15 +0000117 Specification <http://speleotrove.com/decimal/decarith.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000118
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000119.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121
122.. _decimal-tutorial:
123
124Quick-start Tutorial
125--------------------
126
127The usual start to using decimals is importing the module, viewing the current
128context with :func:`getcontext` and, if necessary, setting new values for
129precision, rounding, or enabled traps::
130
131 >>> from decimal import *
132 >>> getcontext()
Stefan Krah1919b7e2012-03-21 18:25:23 +0100133 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000134 capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000135 InvalidOperation])
Georg Brandl116aa622007-08-15 14:28:22 +0000136
137 >>> getcontext().prec = 7 # Set a new precision
138
Mark Dickinsone534a072010-04-04 22:13:14 +0000139Decimal instances can be constructed from integers, strings, floats, or tuples.
140Construction from an integer or a float performs an exact conversion of the
141value of that integer or float. Decimal numbers include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +0000142:const:`NaN` which stands for "Not a number", positive and negative
Stefan Krah1919b7e2012-03-21 18:25:23 +0100143:const:`Infinity`, and :const:`-0`::
Georg Brandl116aa622007-08-15 14:28:22 +0000144
Facundo Batista789bdf02008-06-21 17:29:41 +0000145 >>> getcontext().prec = 28
Georg Brandl116aa622007-08-15 14:28:22 +0000146 >>> Decimal(10)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000147 Decimal('10')
148 >>> Decimal('3.14')
149 Decimal('3.14')
Mark Dickinsone534a072010-04-04 22:13:14 +0000150 >>> Decimal(3.14)
151 Decimal('3.140000000000000124344978758017532527446746826171875')
Georg Brandl116aa622007-08-15 14:28:22 +0000152 >>> Decimal((0, (3, 1, 4), -2))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000153 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000154 >>> Decimal(str(2.0 ** 0.5))
Alexander Belopolsky287d1fd2011-01-12 16:37:14 +0000155 Decimal('1.4142135623730951')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000156 >>> Decimal(2) ** Decimal('0.5')
157 Decimal('1.414213562373095048801688724')
158 >>> Decimal('NaN')
159 Decimal('NaN')
160 >>> Decimal('-Infinity')
161 Decimal('-Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000162
Stefan Krah1919b7e2012-03-21 18:25:23 +0100163If the :exc:`FloatOperation` signal is trapped, accidental mixing of
164decimals and floats in constructors or ordering comparisons raises
165an exception::
166
167 >>> c = getcontext()
168 >>> c.traps[FloatOperation] = True
169 >>> Decimal(3.14)
170 Traceback (most recent call last):
Martin Panter1050d2d2016-07-26 11:18:21 +0200171 File "<stdin>", line 1, in <module>
Stefan Krah1919b7e2012-03-21 18:25:23 +0100172 decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
173 >>> Decimal('3.5') < 3.7
174 Traceback (most recent call last):
175 File "<stdin>", line 1, in <module>
176 decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
177 >>> Decimal('3.5') == 3.5
178 True
179
180.. versionadded:: 3.3
181
Georg Brandl116aa622007-08-15 14:28:22 +0000182The significance of a new Decimal is determined solely by the number of digits
183input. Context precision and rounding only come into play during arithmetic
Christian Heimesfe337bf2008-03-23 21:54:12 +0000184operations.
185
186.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000187
188 >>> getcontext().prec = 6
189 >>> Decimal('3.0')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000190 Decimal('3.0')
Georg Brandl116aa622007-08-15 14:28:22 +0000191 >>> Decimal('3.1415926535')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000192 Decimal('3.1415926535')
Georg Brandl116aa622007-08-15 14:28:22 +0000193 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000194 Decimal('5.85987')
Georg Brandl116aa622007-08-15 14:28:22 +0000195 >>> getcontext().rounding = ROUND_UP
196 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000197 Decimal('5.85988')
Georg Brandl116aa622007-08-15 14:28:22 +0000198
Stefan Krah1919b7e2012-03-21 18:25:23 +0100199If the internal limits of the C version are exceeded, constructing
200a decimal raises :class:`InvalidOperation`::
201
202 >>> Decimal("1e9999999999999999999")
203 Traceback (most recent call last):
204 File "<stdin>", line 1, in <module>
205 decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]
206
207.. versionchanged:: 3.3
208
Georg Brandl116aa622007-08-15 14:28:22 +0000209Decimals interact well with much of the rest of Python. Here is a small decimal
Christian Heimesfe337bf2008-03-23 21:54:12 +0000210floating point flying circus:
211
212.. doctest::
213 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000214
Facundo Batista789bdf02008-06-21 17:29:41 +0000215 >>> 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 +0000216 >>> max(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000217 Decimal('9.25')
Georg Brandl116aa622007-08-15 14:28:22 +0000218 >>> min(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000219 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +0000220 >>> sorted(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000221 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
222 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl116aa622007-08-15 14:28:22 +0000223 >>> sum(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000224 Decimal('19.29')
Georg Brandl116aa622007-08-15 14:28:22 +0000225 >>> a,b,c = data[:3]
226 >>> str(a)
227 '1.34'
228 >>> float(a)
Mark Dickinson8dad7df2009-06-28 20:36:54 +0000229 1.34
230 >>> round(a, 1)
231 Decimal('1.3')
Georg Brandl116aa622007-08-15 14:28:22 +0000232 >>> int(a)
233 1
234 >>> a * 5
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000235 Decimal('6.70')
Georg Brandl116aa622007-08-15 14:28:22 +0000236 >>> a * b
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000237 Decimal('2.5058')
Georg Brandl116aa622007-08-15 14:28:22 +0000238 >>> c % a
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000239 Decimal('0.77')
Georg Brandl116aa622007-08-15 14:28:22 +0000240
Christian Heimesfe337bf2008-03-23 21:54:12 +0000241And some mathematical functions are also available to Decimal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000242
Facundo Batista789bdf02008-06-21 17:29:41 +0000243 >>> getcontext().prec = 28
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000244 >>> Decimal(2).sqrt()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000245 Decimal('1.414213562373095048801688724')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000246 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000247 Decimal('2.718281828459045235360287471')
248 >>> Decimal('10').ln()
249 Decimal('2.302585092994045684017991455')
250 >>> Decimal('10').log10()
251 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000252
Georg Brandl116aa622007-08-15 14:28:22 +0000253The :meth:`quantize` method rounds a number to a fixed exponent. This method is
254useful for monetary applications that often round results to a fixed number of
Christian Heimesfe337bf2008-03-23 21:54:12 +0000255places:
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000258 Decimal('7.32')
Georg Brandl116aa622007-08-15 14:28:22 +0000259 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000260 Decimal('8')
Georg Brandl116aa622007-08-15 14:28:22 +0000261
262As shown above, the :func:`getcontext` function accesses the current context and
263allows the settings to be changed. This approach meets the needs of most
264applications.
265
266For more advanced work, it may be useful to create alternate contexts using the
267Context() constructor. To make an alternate active, use the :func:`setcontext`
268function.
269
Serhiy Storchakab19542d2015-03-14 21:32:57 +0200270In accordance with the standard, the :mod:`decimal` module provides two ready to
Georg Brandl116aa622007-08-15 14:28:22 +0000271use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
272former is especially useful for debugging because many of the traps are
Christian Heimesfe337bf2008-03-23 21:54:12 +0000273enabled:
274
275.. doctest:: newcontext
276 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
279 >>> setcontext(myothercontext)
280 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000281 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283 >>> ExtendedContext
Stefan Krah1919b7e2012-03-21 18:25:23 +0100284 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000285 capitals=1, clamp=0, flags=[], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000286 >>> setcontext(ExtendedContext)
287 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000288 Decimal('0.142857143')
Georg Brandl116aa622007-08-15 14:28:22 +0000289 >>> Decimal(42) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000290 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000291
292 >>> setcontext(BasicContext)
293 >>> Decimal(42) / Decimal(0)
294 Traceback (most recent call last):
295 File "<pyshell#143>", line 1, in -toplevel-
296 Decimal(42) / Decimal(0)
297 DivisionByZero: x / 0
298
299Contexts also have signal flags for monitoring exceptional conditions
300encountered during computations. The flags remain set until explicitly cleared,
301so it is best to clear the flags before each set of monitored computations by
302using the :meth:`clear_flags` method. ::
303
304 >>> setcontext(ExtendedContext)
305 >>> getcontext().clear_flags()
306 >>> Decimal(355) / Decimal(113)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000307 Decimal('3.14159292')
Georg Brandl116aa622007-08-15 14:28:22 +0000308 >>> getcontext()
Stefan Krah1919b7e2012-03-21 18:25:23 +0100309 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000310 capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312The *flags* entry shows that the rational approximation to :const:`Pi` was
313rounded (digits beyond the context precision were thrown away) and that the
314result is inexact (some of the discarded digits were non-zero).
315
316Individual traps are set using the dictionary in the :attr:`traps` field of a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000317context:
Georg Brandl116aa622007-08-15 14:28:22 +0000318
Christian Heimesfe337bf2008-03-23 21:54:12 +0000319.. doctest:: newcontext
320
321 >>> setcontext(ExtendedContext)
Georg Brandl116aa622007-08-15 14:28:22 +0000322 >>> Decimal(1) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000323 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000324 >>> getcontext().traps[DivisionByZero] = 1
325 >>> Decimal(1) / Decimal(0)
326 Traceback (most recent call last):
327 File "<pyshell#112>", line 1, in -toplevel-
328 Decimal(1) / Decimal(0)
329 DivisionByZero: x / 0
330
331Most programs adjust the current context only once, at the beginning of the
332program. And, in many applications, data is converted to :class:`Decimal` with
333a single cast inside a loop. With context set and decimals created, the bulk of
334the program manipulates the data no differently than with other Python numeric
335types.
336
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000337.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000338
339
340.. _decimal-decimal:
341
342Decimal objects
343---------------
344
345
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000346.. class:: Decimal(value="0", context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000347
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000348 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl116aa622007-08-15 14:28:22 +0000349
Raymond Hettinger96798592010-04-02 16:58:27 +0000350 *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal`
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000351 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Christian Heimesa62da1d2008-01-12 19:39:10 +0000352 string, it should conform to the decimal numeric string syntax after leading
Brett Cannona721aba2016-09-09 14:57:09 -0700353 and trailing whitespace characters, as well as underscores throughout, are removed::
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355 sign ::= '+' | '-'
356 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
357 indicator ::= 'e' | 'E'
358 digits ::= digit [digit]...
359 decimal-part ::= digits '.' [digits] | ['.'] digits
360 exponent-part ::= indicator [sign] digits
361 infinity ::= 'Infinity' | 'Inf'
362 nan ::= 'NaN' [digits] | 'sNaN' [digits]
363 numeric-value ::= decimal-part [exponent-part] | infinity
Georg Brandl48310cd2009-01-03 21:18:54 +0000364 numeric-string ::= [sign] numeric-value | [sign] nan
Georg Brandl116aa622007-08-15 14:28:22 +0000365
Mark Dickinson345adc42009-08-02 10:14:23 +0000366 Other Unicode decimal digits are also permitted where ``digit``
367 appears above. These include decimal digits from various other
368 alphabets (for example, Arabic-Indic and Devanāgarī digits) along
369 with the fullwidth digits ``'\uff10'`` through ``'\uff19'``.
370
Georg Brandl116aa622007-08-15 14:28:22 +0000371 If *value* is a :class:`tuple`, it should have three components, a sign
372 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
373 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000374 returns ``Decimal('1.414')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000375
Raymond Hettinger96798592010-04-02 16:58:27 +0000376 If *value* is a :class:`float`, the binary floating point value is losslessly
377 converted to its exact decimal equivalent. This conversion can often require
Mark Dickinsone534a072010-04-04 22:13:14 +0000378 53 or more digits of precision. For example, ``Decimal(float('1.1'))``
379 converts to
380 ``Decimal('1.100000000000000088817841970012523233890533447265625')``.
Raymond Hettinger96798592010-04-02 16:58:27 +0000381
Georg Brandl116aa622007-08-15 14:28:22 +0000382 The *context* precision does not affect how many digits are stored. That is
383 determined exclusively by the number of digits in *value*. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000384 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl116aa622007-08-15 14:28:22 +0000385 only three.
386
387 The purpose of the *context* argument is determining what to do if *value* is a
388 malformed string. If the context traps :const:`InvalidOperation`, an exception
389 is raised; otherwise, the constructor returns a new Decimal with the value of
390 :const:`NaN`.
391
392 Once constructed, :class:`Decimal` objects are immutable.
393
Mark Dickinsone534a072010-04-04 22:13:14 +0000394 .. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000395 The argument to the constructor is now permitted to be a :class:`float`
396 instance.
Mark Dickinsone534a072010-04-04 22:13:14 +0000397
Stefan Krah1919b7e2012-03-21 18:25:23 +0100398 .. versionchanged:: 3.3
399 :class:`float` arguments raise an exception if the :exc:`FloatOperation`
400 trap is set. By default the trap is off.
401
Brett Cannona721aba2016-09-09 14:57:09 -0700402 .. versionchanged:: 3.6
403 Underscores are allowed for grouping, as with integral and floating-point
404 literals in code.
405
Benjamin Petersone41251e2008-04-25 01:59:09 +0000406 Decimal floating point objects share many properties with the other built-in
407 numeric types such as :class:`float` and :class:`int`. All of the usual math
408 operations and special methods apply. Likewise, decimal objects can be
409 copied, pickled, printed, used as dictionary keys, used as set elements,
410 compared, sorted, and coerced to another type (such as :class:`float` or
Mark Dickinson5d233fd2010-02-18 14:54:37 +0000411 :class:`int`).
Christian Heimesa62da1d2008-01-12 19:39:10 +0000412
Mark Dickinsona3f37402012-11-18 10:22:05 +0000413 There are some small differences between arithmetic on Decimal objects and
414 arithmetic on integers and floats. When the remainder operator ``%`` is
415 applied to Decimal objects, the sign of the result is the sign of the
416 *dividend* rather than the sign of the divisor::
417
418 >>> (-7) % 4
419 1
420 >>> Decimal(-7) % Decimal(4)
421 Decimal('-3')
422
423 The integer division operator ``//`` behaves analogously, returning the
424 integer part of the true quotient (truncating towards zero) rather than its
Mark Dickinsonec967242012-11-18 10:42:07 +0000425 floor, so as to preserve the usual identity ``x == (x // y) * y + x % y``::
Mark Dickinsona3f37402012-11-18 10:22:05 +0000426
427 >>> -7 // 4
428 -2
429 >>> Decimal(-7) // Decimal(4)
430 Decimal('-1')
431
432 The ``%`` and ``//`` operators implement the ``remainder`` and
433 ``divide-integer`` operations (respectively) as described in the
434 specification.
435
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000436 Decimal objects cannot generally be combined with floats or
437 instances of :class:`fractions.Fraction` in arithmetic operations:
438 an attempt to add a :class:`Decimal` to a :class:`float`, for
439 example, will raise a :exc:`TypeError`. However, it is possible to
440 use Python's comparison operators to compare a :class:`Decimal`
441 instance ``x`` with another number ``y``. This avoids confusing results
442 when doing equality comparisons between numbers of different types.
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000443
Ezio Melotti993a5ee2010-04-04 06:30:08 +0000444 .. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000445 Mixed-type comparisons between :class:`Decimal` instances and other
446 numeric types are now fully supported.
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000447
Benjamin Petersone41251e2008-04-25 01:59:09 +0000448 In addition to the standard numeric properties, decimal floating point
449 objects also have a number of specialized methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000450
Georg Brandl116aa622007-08-15 14:28:22 +0000451
Benjamin Petersone41251e2008-04-25 01:59:09 +0000452 .. method:: adjusted()
Georg Brandl116aa622007-08-15 14:28:22 +0000453
Benjamin Petersone41251e2008-04-25 01:59:09 +0000454 Return the adjusted exponent after shifting out the coefficient's
455 rightmost digits until only the lead digit remains:
456 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
457 position of the most significant digit with respect to the decimal point.
Georg Brandl116aa622007-08-15 14:28:22 +0000458
Stefan Krah53f2e0a2015-12-28 23:02:02 +0100459 .. method:: as_integer_ratio()
460
461 Return a pair ``(n, d)`` of integers that represent the given
462 :class:`Decimal` instance as a fraction, in lowest terms and
463 with a positive denominator::
464
465 >>> Decimal('-3.14').as_integer_ratio()
466 (-157, 50)
467
468 The conversion is exact. Raise OverflowError on infinities and ValueError
469 on NaNs.
470
471 .. versionadded:: 3.6
Georg Brandl116aa622007-08-15 14:28:22 +0000472
Benjamin Petersone41251e2008-04-25 01:59:09 +0000473 .. method:: as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +0000474
Benjamin Petersone41251e2008-04-25 01:59:09 +0000475 Return a :term:`named tuple` representation of the number:
476 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000477
Christian Heimes25bb7832008-01-11 16:17:00 +0000478
Benjamin Petersone41251e2008-04-25 01:59:09 +0000479 .. method:: canonical()
Georg Brandl116aa622007-08-15 14:28:22 +0000480
Benjamin Petersone41251e2008-04-25 01:59:09 +0000481 Return the canonical encoding of the argument. Currently, the encoding of
482 a :class:`Decimal` instance is always canonical, so this operation returns
483 its argument unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000484
Stefan Krah040e3112012-12-15 22:33:33 +0100485 .. method:: compare(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000486
Georg Brandl05f5ab72008-09-24 09:11:47 +0000487 Compare the values of two Decimal instances. :meth:`compare` returns a
488 Decimal instance, and if either operand is a NaN then the result is a
489 NaN::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000490
Georg Brandl05f5ab72008-09-24 09:11:47 +0000491 a or b is a NaN ==> Decimal('NaN')
492 a < b ==> Decimal('-1')
493 a == b ==> Decimal('0')
494 a > b ==> Decimal('1')
Georg Brandl116aa622007-08-15 14:28:22 +0000495
Stefan Krah040e3112012-12-15 22:33:33 +0100496 .. method:: compare_signal(other, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000497
Benjamin Petersone41251e2008-04-25 01:59:09 +0000498 This operation is identical to the :meth:`compare` method, except that all
499 NaNs signal. That is, if neither operand is a signaling NaN then any
500 quiet NaN operand is treated as though it were a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000501
Stefan Krah040e3112012-12-15 22:33:33 +0100502 .. method:: compare_total(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503
Benjamin Petersone41251e2008-04-25 01:59:09 +0000504 Compare two operands using their abstract representation rather than their
505 numerical value. Similar to the :meth:`compare` method, but the result
506 gives a total ordering on :class:`Decimal` instances. Two
507 :class:`Decimal` instances with the same numeric value but different
508 representations compare unequal in this ordering:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000509
Benjamin Petersone41251e2008-04-25 01:59:09 +0000510 >>> Decimal('12.0').compare_total(Decimal('12'))
511 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000512
Benjamin Petersone41251e2008-04-25 01:59:09 +0000513 Quiet and signaling NaNs are also included in the total ordering. The
514 result of this function is ``Decimal('0')`` if both operands have the same
515 representation, ``Decimal('-1')`` if the first operand is lower in the
516 total order than the second, and ``Decimal('1')`` if the first operand is
517 higher in the total order than the second operand. See the specification
518 for details of the total order.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000519
Stefan Krah040e3112012-12-15 22:33:33 +0100520 This operation is unaffected by context and is quiet: no flags are changed
521 and no rounding is performed. As an exception, the C version may raise
522 InvalidOperation if the second operand cannot be converted exactly.
523
524 .. method:: compare_total_mag(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000525
Benjamin Petersone41251e2008-04-25 01:59:09 +0000526 Compare two operands using their abstract representation rather than their
527 value as in :meth:`compare_total`, but ignoring the sign of each operand.
528 ``x.compare_total_mag(y)`` is equivalent to
529 ``x.copy_abs().compare_total(y.copy_abs())``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000530
Stefan Krah040e3112012-12-15 22:33:33 +0100531 This operation is unaffected by context and is quiet: no flags are changed
532 and no rounding is performed. As an exception, the C version may raise
533 InvalidOperation if the second operand cannot be converted exactly.
534
Facundo Batista789bdf02008-06-21 17:29:41 +0000535 .. method:: conjugate()
536
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000537 Just returns self, this method is only to comply with the Decimal
Facundo Batista789bdf02008-06-21 17:29:41 +0000538 Specification.
539
Benjamin Petersone41251e2008-04-25 01:59:09 +0000540 .. method:: copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000541
Benjamin Petersone41251e2008-04-25 01:59:09 +0000542 Return the absolute value of the argument. This operation is unaffected
543 by the context and is quiet: no flags are changed and no rounding is
544 performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000545
Benjamin Petersone41251e2008-04-25 01:59:09 +0000546 .. method:: copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000547
Benjamin Petersone41251e2008-04-25 01:59:09 +0000548 Return the negation of the argument. This operation is unaffected by the
549 context and is quiet: no flags are changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000550
Stefan Krah040e3112012-12-15 22:33:33 +0100551 .. method:: copy_sign(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000552
Benjamin Petersone41251e2008-04-25 01:59:09 +0000553 Return a copy of the first operand with the sign set to be the same as the
554 sign of the second operand. For example:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000555
Benjamin Petersone41251e2008-04-25 01:59:09 +0000556 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
557 Decimal('-2.3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000558
Stefan Krah040e3112012-12-15 22:33:33 +0100559 This operation is unaffected by context and is quiet: no flags are changed
560 and no rounding is performed. As an exception, the C version may raise
561 InvalidOperation if the second operand cannot be converted exactly.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000562
Stefan Krah040e3112012-12-15 22:33:33 +0100563 .. method:: exp(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000564
Benjamin Petersone41251e2008-04-25 01:59:09 +0000565 Return the value of the (natural) exponential function ``e**x`` at the
566 given number. The result is correctly rounded using the
567 :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568
Benjamin Petersone41251e2008-04-25 01:59:09 +0000569 >>> Decimal(1).exp()
570 Decimal('2.718281828459045235360287471')
571 >>> Decimal(321).exp()
572 Decimal('2.561702493119680037517373933E+139')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000573
Raymond Hettinger771ed762009-01-03 19:20:32 +0000574 .. method:: from_float(f)
575
576 Classmethod that converts a float to a decimal number, exactly.
577
578 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
579 Since 0.1 is not exactly representable in binary floating point, the
580 value is stored as the nearest representable value which is
581 `0x1.999999999999ap-4`. That equivalent value in decimal is
582 `0.1000000000000000055511151231257827021181583404541015625`.
583
Mark Dickinsone534a072010-04-04 22:13:14 +0000584 .. note:: From Python 3.2 onwards, a :class:`Decimal` instance
585 can also be constructed directly from a :class:`float`.
586
Raymond Hettinger771ed762009-01-03 19:20:32 +0000587 .. doctest::
588
589 >>> Decimal.from_float(0.1)
590 Decimal('0.1000000000000000055511151231257827021181583404541015625')
591 >>> Decimal.from_float(float('nan'))
592 Decimal('NaN')
593 >>> Decimal.from_float(float('inf'))
594 Decimal('Infinity')
595 >>> Decimal.from_float(float('-inf'))
596 Decimal('-Infinity')
597
Georg Brandl45f53372009-01-03 21:15:20 +0000598 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000599
Stefan Krah040e3112012-12-15 22:33:33 +0100600 .. method:: fma(other, third, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000601
Benjamin Petersone41251e2008-04-25 01:59:09 +0000602 Fused multiply-add. Return self*other+third with no rounding of the
603 intermediate product self*other.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
Benjamin Petersone41251e2008-04-25 01:59:09 +0000605 >>> Decimal(2).fma(3, 5)
606 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000607
Benjamin Petersone41251e2008-04-25 01:59:09 +0000608 .. method:: is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000609
Benjamin Petersone41251e2008-04-25 01:59:09 +0000610 Return :const:`True` if the argument is canonical and :const:`False`
611 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
612 this operation always returns :const:`True`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000613
Benjamin Petersone41251e2008-04-25 01:59:09 +0000614 .. method:: is_finite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000615
Benjamin Petersone41251e2008-04-25 01:59:09 +0000616 Return :const:`True` if the argument is a finite number, and
617 :const:`False` if the argument is an infinity or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000618
Benjamin Petersone41251e2008-04-25 01:59:09 +0000619 .. method:: is_infinite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000620
Benjamin Petersone41251e2008-04-25 01:59:09 +0000621 Return :const:`True` if the argument is either positive or negative
622 infinity and :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000623
Benjamin Petersone41251e2008-04-25 01:59:09 +0000624 .. method:: is_nan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000625
Benjamin Petersone41251e2008-04-25 01:59:09 +0000626 Return :const:`True` if the argument is a (quiet or signaling) NaN and
627 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000628
Stefan Krah040e3112012-12-15 22:33:33 +0100629 .. method:: is_normal(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000630
Benjamin Petersone41251e2008-04-25 01:59:09 +0000631 Return :const:`True` if the argument is a *normal* finite number. Return
632 :const:`False` if the argument is zero, subnormal, infinite or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000633
Benjamin Petersone41251e2008-04-25 01:59:09 +0000634 .. method:: is_qnan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000635
Benjamin Petersone41251e2008-04-25 01:59:09 +0000636 Return :const:`True` if the argument is a quiet NaN, and
637 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000638
Benjamin Petersone41251e2008-04-25 01:59:09 +0000639 .. method:: is_signed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000640
Benjamin Petersone41251e2008-04-25 01:59:09 +0000641 Return :const:`True` if the argument has a negative sign and
642 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000643
Benjamin Petersone41251e2008-04-25 01:59:09 +0000644 .. method:: is_snan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000645
Benjamin Petersone41251e2008-04-25 01:59:09 +0000646 Return :const:`True` if the argument is a signaling NaN and :const:`False`
647 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000648
Stefan Krah040e3112012-12-15 22:33:33 +0100649 .. method:: is_subnormal(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000650
Benjamin Petersone41251e2008-04-25 01:59:09 +0000651 Return :const:`True` if the argument is subnormal, and :const:`False`
652 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653
Benjamin Petersone41251e2008-04-25 01:59:09 +0000654 .. method:: is_zero()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000655
Benjamin Petersone41251e2008-04-25 01:59:09 +0000656 Return :const:`True` if the argument is a (positive or negative) zero and
657 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658
Stefan Krah040e3112012-12-15 22:33:33 +0100659 .. method:: ln(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000660
Benjamin Petersone41251e2008-04-25 01:59:09 +0000661 Return the natural (base e) logarithm of the operand. The result is
662 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663
Stefan Krah040e3112012-12-15 22:33:33 +0100664 .. method:: log10(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665
Benjamin Petersone41251e2008-04-25 01:59:09 +0000666 Return the base ten logarithm of the operand. The result is correctly
667 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668
Stefan Krah040e3112012-12-15 22:33:33 +0100669 .. method:: logb(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000670
Benjamin Petersone41251e2008-04-25 01:59:09 +0000671 For a nonzero number, return the adjusted exponent of its operand as a
672 :class:`Decimal` instance. If the operand is a zero then
673 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
674 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
675 returned.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676
Stefan Krah040e3112012-12-15 22:33:33 +0100677 .. method:: logical_and(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000678
Benjamin Petersone41251e2008-04-25 01:59:09 +0000679 :meth:`logical_and` is a logical operation which takes two *logical
680 operands* (see :ref:`logical_operands_label`). The result is the
681 digit-wise ``and`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000682
Stefan Krah040e3112012-12-15 22:33:33 +0100683 .. method:: logical_invert(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000684
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000685 :meth:`logical_invert` is a logical operation. The
Benjamin Petersone41251e2008-04-25 01:59:09 +0000686 result is the digit-wise inversion of the operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000687
Stefan Krah040e3112012-12-15 22:33:33 +0100688 .. method:: logical_or(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689
Benjamin Petersone41251e2008-04-25 01:59:09 +0000690 :meth:`logical_or` is a logical operation which takes two *logical
691 operands* (see :ref:`logical_operands_label`). The result is the
692 digit-wise ``or`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000693
Stefan Krah040e3112012-12-15 22:33:33 +0100694 .. method:: logical_xor(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000695
Benjamin Petersone41251e2008-04-25 01:59:09 +0000696 :meth:`logical_xor` is a logical operation which takes two *logical
697 operands* (see :ref:`logical_operands_label`). The result is the
698 digit-wise exclusive or of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000699
Stefan Krah040e3112012-12-15 22:33:33 +0100700 .. method:: max(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000701
Benjamin Petersone41251e2008-04-25 01:59:09 +0000702 Like ``max(self, other)`` except that the context rounding rule is applied
703 before returning and that :const:`NaN` values are either signaled or
704 ignored (depending on the context and whether they are signaling or
705 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000706
Stefan Krah040e3112012-12-15 22:33:33 +0100707 .. method:: max_mag(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000708
Georg Brandl502d9a52009-07-26 15:02:41 +0000709 Similar to the :meth:`.max` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000710 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000711
Stefan Krah040e3112012-12-15 22:33:33 +0100712 .. method:: min(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000713
Benjamin Petersone41251e2008-04-25 01:59:09 +0000714 Like ``min(self, other)`` except that the context rounding rule is applied
715 before returning and that :const:`NaN` values are either signaled or
716 ignored (depending on the context and whether they are signaling or
717 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000718
Stefan Krah040e3112012-12-15 22:33:33 +0100719 .. method:: min_mag(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000720
Georg Brandl502d9a52009-07-26 15:02:41 +0000721 Similar to the :meth:`.min` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000722 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000723
Stefan Krah040e3112012-12-15 22:33:33 +0100724 .. method:: next_minus(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000725
Benjamin Petersone41251e2008-04-25 01:59:09 +0000726 Return the largest number representable in the given context (or in the
727 current thread's context if no context is given) that is smaller than the
728 given operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000729
Stefan Krah040e3112012-12-15 22:33:33 +0100730 .. method:: next_plus(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000731
Benjamin Petersone41251e2008-04-25 01:59:09 +0000732 Return the smallest number representable in the given context (or in the
733 current thread's context if no context is given) that is larger than the
734 given operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000735
Stefan Krah040e3112012-12-15 22:33:33 +0100736 .. method:: next_toward(other, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000737
Benjamin Petersone41251e2008-04-25 01:59:09 +0000738 If the two operands are unequal, return the number closest to the first
739 operand in the direction of the second operand. If both operands are
740 numerically equal, return a copy of the first operand with the sign set to
741 be the same as the sign of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000742
Stefan Krah040e3112012-12-15 22:33:33 +0100743 .. method:: normalize(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000744
Benjamin Petersone41251e2008-04-25 01:59:09 +0000745 Normalize the number by stripping the rightmost trailing zeros and
746 converting any result equal to :const:`Decimal('0')` to
Senthil Kumarana6bac952011-07-04 11:28:30 -0700747 :const:`Decimal('0e0')`. Used for producing canonical values for attributes
Benjamin Petersone41251e2008-04-25 01:59:09 +0000748 of an equivalence class. For example, ``Decimal('32.100')`` and
749 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
750 ``Decimal('32.1')``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751
Stefan Krah040e3112012-12-15 22:33:33 +0100752 .. method:: number_class(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000753
Benjamin Petersone41251e2008-04-25 01:59:09 +0000754 Return a string describing the *class* of the operand. The returned value
755 is one of the following ten strings.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000756
Benjamin Petersone41251e2008-04-25 01:59:09 +0000757 * ``"-Infinity"``, indicating that the operand is negative infinity.
758 * ``"-Normal"``, indicating that the operand is a negative normal number.
759 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
760 * ``"-Zero"``, indicating that the operand is a negative zero.
761 * ``"+Zero"``, indicating that the operand is a positive zero.
762 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
763 * ``"+Normal"``, indicating that the operand is a positive normal number.
764 * ``"+Infinity"``, indicating that the operand is positive infinity.
765 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
766 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000767
Stefan Krahb151f8f2014-04-30 19:15:38 +0200768 .. method:: quantize(exp, rounding=None, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000769
Benjamin Petersone41251e2008-04-25 01:59:09 +0000770 Return a value equal to the first operand after rounding and having the
771 exponent of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000772
Benjamin Petersone41251e2008-04-25 01:59:09 +0000773 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
774 Decimal('1.414')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000775
Benjamin Petersone41251e2008-04-25 01:59:09 +0000776 Unlike other operations, if the length of the coefficient after the
777 quantize operation would be greater than precision, then an
778 :const:`InvalidOperation` is signaled. This guarantees that, unless there
779 is an error condition, the quantized exponent is always equal to that of
780 the right-hand operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000781
Benjamin Petersone41251e2008-04-25 01:59:09 +0000782 Also unlike other operations, quantize never signals Underflow, even if
783 the result is subnormal and inexact.
Georg Brandl116aa622007-08-15 14:28:22 +0000784
Benjamin Petersone41251e2008-04-25 01:59:09 +0000785 If the exponent of the second operand is larger than that of the first
786 then rounding may be necessary. In this case, the rounding mode is
787 determined by the ``rounding`` argument if given, else by the given
788 ``context`` argument; if neither argument is given the rounding mode of
789 the current thread's context is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000790
Stefan Krahb151f8f2014-04-30 19:15:38 +0200791 An error is returned whenever the resulting exponent is greater than
792 :attr:`Emax` or less than :attr:`Etiny`.
Stefan Krahaf3f3a72012-08-30 12:33:55 +0200793
Benjamin Petersone41251e2008-04-25 01:59:09 +0000794 .. method:: radix()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795
Benjamin Petersone41251e2008-04-25 01:59:09 +0000796 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
797 class does all its arithmetic. Included for compatibility with the
798 specification.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000799
Stefan Krah040e3112012-12-15 22:33:33 +0100800 .. method:: remainder_near(other, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000801
Mark Dickinson6ae568b2012-10-31 19:44:36 +0000802 Return the remainder from dividing *self* by *other*. This differs from
803 ``self % other`` in that the sign of the remainder is chosen so as to
804 minimize its absolute value. More precisely, the return value is
805 ``self - n * other`` where ``n`` is the integer nearest to the exact
806 value of ``self / other``, and if two integers are equally near then the
807 even one is chosen.
Georg Brandl116aa622007-08-15 14:28:22 +0000808
Mark Dickinson6ae568b2012-10-31 19:44:36 +0000809 If the result is zero then its sign will be the sign of *self*.
810
811 >>> Decimal(18).remainder_near(Decimal(10))
812 Decimal('-2')
813 >>> Decimal(25).remainder_near(Decimal(10))
814 Decimal('5')
815 >>> Decimal(35).remainder_near(Decimal(10))
816 Decimal('-5')
Georg Brandl116aa622007-08-15 14:28:22 +0000817
Stefan Krah040e3112012-12-15 22:33:33 +0100818 .. method:: rotate(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000819
Benjamin Petersone41251e2008-04-25 01:59:09 +0000820 Return the result of rotating the digits of the first operand by an amount
821 specified by the second operand. The second operand must be an integer in
822 the range -precision through precision. The absolute value of the second
823 operand gives the number of places to rotate. If the second operand is
824 positive then rotation is to the left; otherwise rotation is to the right.
825 The coefficient of the first operand is padded on the left with zeros to
826 length precision if necessary. The sign and exponent of the first operand
827 are unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Stefan Krah040e3112012-12-15 22:33:33 +0100829 .. method:: same_quantum(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000830
Benjamin Petersone41251e2008-04-25 01:59:09 +0000831 Test whether self and other have the same exponent or whether both are
832 :const:`NaN`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833
Stefan Krah040e3112012-12-15 22:33:33 +0100834 This operation is unaffected by context and is quiet: no flags are changed
835 and no rounding is performed. As an exception, the C version may raise
836 InvalidOperation if the second operand cannot be converted exactly.
837
838 .. method:: scaleb(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839
Benjamin Petersone41251e2008-04-25 01:59:09 +0000840 Return the first operand with exponent adjusted by the second.
841 Equivalently, return the first operand multiplied by ``10**other``. The
842 second operand must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +0000843
Stefan Krah040e3112012-12-15 22:33:33 +0100844 .. method:: shift(other, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000845
Benjamin Petersone41251e2008-04-25 01:59:09 +0000846 Return the result of shifting the digits of the first operand by an amount
847 specified by the second operand. The second operand must be an integer in
848 the range -precision through precision. The absolute value of the second
849 operand gives the number of places to shift. If the second operand is
850 positive then the shift is to the left; otherwise the shift is to the
851 right. Digits shifted into the coefficient are zeros. The sign and
852 exponent of the first operand are unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +0000853
Stefan Krah040e3112012-12-15 22:33:33 +0100854 .. method:: sqrt(context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000855
Benjamin Petersone41251e2008-04-25 01:59:09 +0000856 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000857
Georg Brandl116aa622007-08-15 14:28:22 +0000858
Stefan Krah040e3112012-12-15 22:33:33 +0100859 .. method:: to_eng_string(context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000860
Raymond Hettingerf6ffa982016-08-13 11:15:34 -0700861 Convert to a string, using engineering notation if an exponent is needed.
Georg Brandl116aa622007-08-15 14:28:22 +0000862
Raymond Hettingerf6ffa982016-08-13 11:15:34 -0700863 Engineering notation has an exponent which is a multiple of 3. This
864 can leave up to 3 digits to the left of the decimal place and may
865 require the addition of either one or two trailing zeros.
866
867 For example, this converts ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000868
Stefan Krah040e3112012-12-15 22:33:33 +0100869 .. method:: to_integral(rounding=None, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000870
Benjamin Petersone41251e2008-04-25 01:59:09 +0000871 Identical to the :meth:`to_integral_value` method. The ``to_integral``
872 name has been kept for compatibility with older versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000873
Stefan Krah040e3112012-12-15 22:33:33 +0100874 .. method:: to_integral_exact(rounding=None, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000875
Benjamin Petersone41251e2008-04-25 01:59:09 +0000876 Round to the nearest integer, signaling :const:`Inexact` or
877 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
878 determined by the ``rounding`` parameter if given, else by the given
879 ``context``. If neither parameter is given then the rounding mode of the
880 current context is used.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881
Stefan Krah040e3112012-12-15 22:33:33 +0100882 .. method:: to_integral_value(rounding=None, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000883
Benjamin Petersone41251e2008-04-25 01:59:09 +0000884 Round to the nearest integer without signaling :const:`Inexact` or
885 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
886 rounding method in either the supplied *context* or the current context.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000887
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888
889.. _logical_operands_label:
890
891Logical operands
892^^^^^^^^^^^^^^^^
893
894The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
895and :meth:`logical_xor` methods expect their arguments to be *logical
896operands*. A *logical operand* is a :class:`Decimal` instance whose
897exponent and sign are both zero, and whose digits are all either
898:const:`0` or :const:`1`.
899
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000900.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000901
902
903.. _decimal-context:
904
905Context objects
906---------------
907
908Contexts are environments for arithmetic operations. They govern precision, set
909rules for rounding, determine which signals are treated as exceptions, and limit
910the range for exponents.
911
912Each thread has its own current context which is accessed or changed using the
913:func:`getcontext` and :func:`setcontext` functions:
914
915
916.. function:: getcontext()
917
918 Return the current context for the active thread.
919
920
921.. function:: setcontext(c)
922
923 Set the current context for the active thread to *c*.
924
Georg Brandle6bcc912008-05-12 18:05:20 +0000925You can also use the :keyword:`with` statement and the :func:`localcontext`
926function to temporarily change the active context.
Georg Brandl116aa622007-08-15 14:28:22 +0000927
Stefan Krah040e3112012-12-15 22:33:33 +0100928.. function:: localcontext(ctx=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000929
930 Return a context manager that will set the current context for the active thread
Stefan Krah040e3112012-12-15 22:33:33 +0100931 to a copy of *ctx* on entry to the with-statement and restore the previous context
Georg Brandl116aa622007-08-15 14:28:22 +0000932 when exiting the with-statement. If no context is specified, a copy of the
933 current context is used.
934
Georg Brandl116aa622007-08-15 14:28:22 +0000935 For example, the following code sets the current decimal precision to 42 places,
936 performs a calculation, and then automatically restores the previous context::
937
Georg Brandl116aa622007-08-15 14:28:22 +0000938 from decimal import localcontext
939
940 with localcontext() as ctx:
941 ctx.prec = 42 # Perform a high precision calculation
942 s = calculate_something()
943 s = +s # Round the final result back to the default precision
944
945New contexts can also be created using the :class:`Context` constructor
946described below. In addition, the module provides three pre-made contexts:
947
948
949.. class:: BasicContext
950
951 This is a standard context defined by the General Decimal Arithmetic
952 Specification. Precision is set to nine. Rounding is set to
953 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
954 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
955 :const:`Subnormal`.
956
957 Because many of the traps are enabled, this context is useful for debugging.
958
959
960.. class:: ExtendedContext
961
962 This is a standard context defined by the General Decimal Arithmetic
963 Specification. Precision is set to nine. Rounding is set to
964 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
965 exceptions are not raised during computations).
966
Christian Heimes3feef612008-02-11 06:19:17 +0000967 Because the traps are disabled, this context is useful for applications that
Georg Brandl116aa622007-08-15 14:28:22 +0000968 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
969 raising exceptions. This allows an application to complete a run in the
970 presence of conditions that would otherwise halt the program.
971
972
973.. class:: DefaultContext
974
975 This context is used by the :class:`Context` constructor as a prototype for new
976 contexts. Changing a field (such a precision) has the effect of changing the
Stefan Kraha1193932010-05-29 12:59:18 +0000977 default for new contexts created by the :class:`Context` constructor.
Georg Brandl116aa622007-08-15 14:28:22 +0000978
979 This context is most useful in multi-threaded environments. Changing one of the
980 fields before threads are started has the effect of setting system-wide
981 defaults. Changing the fields after threads have started is not recommended as
982 it would require thread synchronization to prevent race conditions.
983
984 In single threaded environments, it is preferable to not use this context at
985 all. Instead, simply create contexts explicitly as described below.
986
Stefan Krah1919b7e2012-03-21 18:25:23 +0100987 The default values are :attr:`prec`\ =\ :const:`28`,
988 :attr:`rounding`\ =\ :const:`ROUND_HALF_EVEN`,
989 and enabled traps for :class:`Overflow`, :class:`InvalidOperation`, and
990 :class:`DivisionByZero`.
Georg Brandl116aa622007-08-15 14:28:22 +0000991
992In addition to the three supplied contexts, new contexts can be created with the
993:class:`Context` constructor.
994
995
Stefan Krah1919b7e2012-03-21 18:25:23 +0100996.. 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 +0000997
998 Creates a new context. If a field is not specified or is :const:`None`, the
999 default values are copied from the :const:`DefaultContext`. If the *flags*
1000 field is not specified or is :const:`None`, all flags are cleared.
1001
Stefan Krah1919b7e2012-03-21 18:25:23 +01001002 *prec* is an integer in the range [:const:`1`, :const:`MAX_PREC`] that sets
1003 the precision for arithmetic operations in the context.
Georg Brandl116aa622007-08-15 14:28:22 +00001004
Stefan Krah1919b7e2012-03-21 18:25:23 +01001005 The *rounding* option is one of the constants listed in the section
1006 `Rounding Modes`_.
Georg Brandl116aa622007-08-15 14:28:22 +00001007
1008 The *traps* and *flags* fields list any signals to be set. Generally, new
1009 contexts should only set traps and leave the flags clear.
1010
1011 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
Stefan Krah1919b7e2012-03-21 18:25:23 +01001012 for exponents. *Emin* must be in the range [:const:`MIN_EMIN`, :const:`0`],
1013 *Emax* in the range [:const:`0`, :const:`MAX_EMAX`].
Georg Brandl116aa622007-08-15 14:28:22 +00001014
1015 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
1016 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
1017 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
1018
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001019 The *clamp* field is either :const:`0` (the default) or :const:`1`.
1020 If set to :const:`1`, the exponent ``e`` of a :class:`Decimal`
1021 instance representable in this context is strictly limited to the
1022 range ``Emin - prec + 1 <= e <= Emax - prec + 1``. If *clamp* is
1023 :const:`0` then a weaker condition holds: the adjusted exponent of
1024 the :class:`Decimal` instance is at most ``Emax``. When *clamp* is
1025 :const:`1`, a large normal number will, where possible, have its
1026 exponent reduced and a corresponding number of zeros added to its
1027 coefficient, in order to fit the exponent constraints; this
1028 preserves the value of the number but loses information about
1029 significant trailing zeros. For example::
1030
1031 >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
1032 Decimal('1.23000E+999')
1033
1034 A *clamp* value of :const:`1` allows compatibility with the
1035 fixed-width decimal interchange formats specified in IEEE 754.
Georg Brandl116aa622007-08-15 14:28:22 +00001036
Benjamin Petersone41251e2008-04-25 01:59:09 +00001037 The :class:`Context` class defines several general purpose methods as well as
1038 a large number of methods for doing arithmetic directly in a given context.
1039 In addition, for each of the :class:`Decimal` methods described above (with
1040 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
Mark Dickinson84230a12010-02-18 14:49:50 +00001041 a corresponding :class:`Context` method. For example, for a :class:`Context`
1042 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
1043 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a
Mark Dickinson5d233fd2010-02-18 14:54:37 +00001044 Python integer (an instance of :class:`int`) anywhere that a
Mark Dickinson84230a12010-02-18 14:49:50 +00001045 Decimal instance is accepted.
Georg Brandl116aa622007-08-15 14:28:22 +00001046
1047
Benjamin Petersone41251e2008-04-25 01:59:09 +00001048 .. method:: clear_flags()
Georg Brandl116aa622007-08-15 14:28:22 +00001049
Benjamin Petersone41251e2008-04-25 01:59:09 +00001050 Resets all of the flags to :const:`0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001051
Stefan Krah1919b7e2012-03-21 18:25:23 +01001052 .. method:: clear_traps()
1053
1054 Resets all of the traps to :const:`0`.
1055
1056 .. versionadded:: 3.3
1057
Benjamin Petersone41251e2008-04-25 01:59:09 +00001058 .. method:: copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001059
Benjamin Petersone41251e2008-04-25 01:59:09 +00001060 Return a duplicate of the context.
Georg Brandl116aa622007-08-15 14:28:22 +00001061
Benjamin Petersone41251e2008-04-25 01:59:09 +00001062 .. method:: copy_decimal(num)
Georg Brandl116aa622007-08-15 14:28:22 +00001063
Benjamin Petersone41251e2008-04-25 01:59:09 +00001064 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +00001065
Benjamin Petersone41251e2008-04-25 01:59:09 +00001066 .. method:: create_decimal(num)
Christian Heimesfe337bf2008-03-23 21:54:12 +00001067
Benjamin Petersone41251e2008-04-25 01:59:09 +00001068 Creates a new Decimal instance from *num* but using *self* as
1069 context. Unlike the :class:`Decimal` constructor, the context precision,
1070 rounding method, flags, and traps are applied to the conversion.
Georg Brandl116aa622007-08-15 14:28:22 +00001071
Benjamin Petersone41251e2008-04-25 01:59:09 +00001072 This is useful because constants are often given to a greater precision
1073 than is needed by the application. Another benefit is that rounding
1074 immediately eliminates unintended effects from digits beyond the current
1075 precision. In the following example, using unrounded inputs means that
1076 adding zero to a sum can change the result:
Georg Brandl116aa622007-08-15 14:28:22 +00001077
Benjamin Petersone41251e2008-04-25 01:59:09 +00001078 .. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001079
Benjamin Petersone41251e2008-04-25 01:59:09 +00001080 >>> getcontext().prec = 3
1081 >>> Decimal('3.4445') + Decimal('1.0023')
1082 Decimal('4.45')
1083 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1084 Decimal('4.44')
Georg Brandl116aa622007-08-15 14:28:22 +00001085
Benjamin Petersone41251e2008-04-25 01:59:09 +00001086 This method implements the to-number operation of the IBM specification.
Brett Cannona721aba2016-09-09 14:57:09 -07001087 If the argument is a string, no leading or trailing whitespace or
1088 underscores are permitted.
Benjamin Petersone41251e2008-04-25 01:59:09 +00001089
Georg Brandl45f53372009-01-03 21:15:20 +00001090 .. method:: create_decimal_from_float(f)
Raymond Hettinger771ed762009-01-03 19:20:32 +00001091
1092 Creates a new Decimal instance from a float *f* but rounding using *self*
Georg Brandl45f53372009-01-03 21:15:20 +00001093 as the context. Unlike the :meth:`Decimal.from_float` class method,
Raymond Hettinger771ed762009-01-03 19:20:32 +00001094 the context precision, rounding method, flags, and traps are applied to
1095 the conversion.
1096
1097 .. doctest::
1098
Georg Brandl45f53372009-01-03 21:15:20 +00001099 >>> context = Context(prec=5, rounding=ROUND_DOWN)
1100 >>> context.create_decimal_from_float(math.pi)
1101 Decimal('3.1415')
1102 >>> context = Context(prec=5, traps=[Inexact])
1103 >>> context.create_decimal_from_float(math.pi)
1104 Traceback (most recent call last):
1105 ...
1106 decimal.Inexact: None
Raymond Hettinger771ed762009-01-03 19:20:32 +00001107
Georg Brandl45f53372009-01-03 21:15:20 +00001108 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +00001109
Benjamin Petersone41251e2008-04-25 01:59:09 +00001110 .. method:: Etiny()
1111
1112 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
1113 value for subnormal results. When underflow occurs, the exponent is set
1114 to :const:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +00001115
Benjamin Petersone41251e2008-04-25 01:59:09 +00001116 .. method:: Etop()
Georg Brandl116aa622007-08-15 14:28:22 +00001117
Benjamin Petersone41251e2008-04-25 01:59:09 +00001118 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001119
Benjamin Petersone41251e2008-04-25 01:59:09 +00001120 The usual approach to working with decimals is to create :class:`Decimal`
1121 instances and then apply arithmetic operations which take place within the
1122 current context for the active thread. An alternative approach is to use
1123 context methods for calculating within a specific context. The methods are
1124 similar to those for the :class:`Decimal` class and are only briefly
1125 recounted here.
Georg Brandl116aa622007-08-15 14:28:22 +00001126
1127
Benjamin Petersone41251e2008-04-25 01:59:09 +00001128 .. method:: abs(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001129
Benjamin Petersone41251e2008-04-25 01:59:09 +00001130 Returns the absolute value of *x*.
Georg Brandl116aa622007-08-15 14:28:22 +00001131
1132
Benjamin Petersone41251e2008-04-25 01:59:09 +00001133 .. method:: add(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001134
Benjamin Petersone41251e2008-04-25 01:59:09 +00001135 Return the sum of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001136
1137
Facundo Batista789bdf02008-06-21 17:29:41 +00001138 .. method:: canonical(x)
1139
1140 Returns the same Decimal object *x*.
1141
1142
1143 .. method:: compare(x, y)
1144
1145 Compares *x* and *y* numerically.
1146
1147
1148 .. method:: compare_signal(x, y)
1149
1150 Compares the values of the two operands numerically.
1151
1152
1153 .. method:: compare_total(x, y)
1154
1155 Compares two operands using their abstract representation.
1156
1157
1158 .. method:: compare_total_mag(x, y)
1159
1160 Compares two operands using their abstract representation, ignoring sign.
1161
1162
1163 .. method:: copy_abs(x)
1164
1165 Returns a copy of *x* with the sign set to 0.
1166
1167
1168 .. method:: copy_negate(x)
1169
1170 Returns a copy of *x* with the sign inverted.
1171
1172
1173 .. method:: copy_sign(x, y)
1174
1175 Copies the sign from *y* to *x*.
1176
1177
Benjamin Petersone41251e2008-04-25 01:59:09 +00001178 .. method:: divide(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001179
Benjamin Petersone41251e2008-04-25 01:59:09 +00001180 Return *x* divided by *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001181
1182
Benjamin Petersone41251e2008-04-25 01:59:09 +00001183 .. method:: divide_int(x, y)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001184
Benjamin Petersone41251e2008-04-25 01:59:09 +00001185 Return *x* divided by *y*, truncated to an integer.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001186
1187
Benjamin Petersone41251e2008-04-25 01:59:09 +00001188 .. method:: divmod(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001189
Benjamin Petersone41251e2008-04-25 01:59:09 +00001190 Divides two numbers and returns the integer part of the result.
Georg Brandl116aa622007-08-15 14:28:22 +00001191
1192
Facundo Batista789bdf02008-06-21 17:29:41 +00001193 .. method:: exp(x)
1194
1195 Returns `e ** x`.
1196
1197
1198 .. method:: fma(x, y, z)
1199
1200 Returns *x* multiplied by *y*, plus *z*.
1201
1202
1203 .. method:: is_canonical(x)
1204
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001205 Returns ``True`` if *x* is canonical; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001206
1207
1208 .. method:: is_finite(x)
1209
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001210 Returns ``True`` if *x* is finite; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001211
1212
1213 .. method:: is_infinite(x)
1214
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001215 Returns ``True`` if *x* is infinite; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001216
1217
1218 .. method:: is_nan(x)
1219
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001220 Returns ``True`` if *x* is a qNaN or sNaN; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001221
1222
1223 .. method:: is_normal(x)
1224
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001225 Returns ``True`` if *x* is a normal number; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001226
1227
1228 .. method:: is_qnan(x)
1229
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001230 Returns ``True`` if *x* is a quiet NaN; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001231
1232
1233 .. method:: is_signed(x)
1234
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001235 Returns ``True`` if *x* is negative; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001236
1237
1238 .. method:: is_snan(x)
1239
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001240 Returns ``True`` if *x* is a signaling NaN; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001241
1242
1243 .. method:: is_subnormal(x)
1244
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001245 Returns ``True`` if *x* is subnormal; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001246
1247
1248 .. method:: is_zero(x)
1249
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001250 Returns ``True`` if *x* is a zero; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001251
1252
1253 .. method:: ln(x)
1254
1255 Returns the natural (base e) logarithm of *x*.
1256
1257
1258 .. method:: log10(x)
1259
1260 Returns the base 10 logarithm of *x*.
1261
1262
1263 .. method:: logb(x)
1264
1265 Returns the exponent of the magnitude of the operand's MSD.
1266
1267
1268 .. method:: logical_and(x, y)
1269
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001270 Applies the logical operation *and* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001271
1272
1273 .. method:: logical_invert(x)
1274
1275 Invert all the digits in *x*.
1276
1277
1278 .. method:: logical_or(x, y)
1279
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001280 Applies the logical operation *or* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001281
1282
1283 .. method:: logical_xor(x, y)
1284
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001285 Applies the logical operation *xor* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001286
1287
1288 .. method:: max(x, y)
1289
1290 Compares two values numerically and returns the maximum.
1291
1292
1293 .. method:: max_mag(x, y)
1294
1295 Compares the values numerically with their sign ignored.
1296
1297
1298 .. method:: min(x, y)
1299
1300 Compares two values numerically and returns the minimum.
1301
1302
1303 .. method:: min_mag(x, y)
1304
1305 Compares the values numerically with their sign ignored.
1306
1307
Benjamin Petersone41251e2008-04-25 01:59:09 +00001308 .. method:: minus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001309
Benjamin Petersone41251e2008-04-25 01:59:09 +00001310 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001311
1312
Benjamin Petersone41251e2008-04-25 01:59:09 +00001313 .. method:: multiply(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001314
Benjamin Petersone41251e2008-04-25 01:59:09 +00001315 Return the product of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001316
1317
Facundo Batista789bdf02008-06-21 17:29:41 +00001318 .. method:: next_minus(x)
1319
1320 Returns the largest representable number smaller than *x*.
1321
1322
1323 .. method:: next_plus(x)
1324
1325 Returns the smallest representable number larger than *x*.
1326
1327
1328 .. method:: next_toward(x, y)
1329
1330 Returns the number closest to *x*, in direction towards *y*.
1331
1332
1333 .. method:: normalize(x)
1334
1335 Reduces *x* to its simplest form.
1336
1337
1338 .. method:: number_class(x)
1339
1340 Returns an indication of the class of *x*.
1341
1342
Benjamin Petersone41251e2008-04-25 01:59:09 +00001343 .. method:: plus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001344
Benjamin Petersone41251e2008-04-25 01:59:09 +00001345 Plus corresponds to the unary prefix plus operator in Python. This
1346 operation applies the context precision and rounding, so it is *not* an
1347 identity operation.
Georg Brandl116aa622007-08-15 14:28:22 +00001348
1349
Stefan Krah040e3112012-12-15 22:33:33 +01001350 .. method:: power(x, y, modulo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001351
Benjamin Petersone41251e2008-04-25 01:59:09 +00001352 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl116aa622007-08-15 14:28:22 +00001353
Benjamin Petersone41251e2008-04-25 01:59:09 +00001354 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1355 must be integral. The result will be inexact unless ``y`` is integral and
1356 the result is finite and can be expressed exactly in 'precision' digits.
Stefan Krah1919b7e2012-03-21 18:25:23 +01001357 The rounding mode of the context is used. Results are always correctly-rounded
1358 in the Python version.
1359
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)10e46642020-07-19 16:33:43 +05301360 ``Decimal(0) ** Decimal(0)`` results in ``InvalidOperation``, and if ``InvalidOperation``
1361 is not trapped, then results in ``Decimal('NaN')``.
1362
Stefan Krah1919b7e2012-03-21 18:25:23 +01001363 .. versionchanged:: 3.3
1364 The C module computes :meth:`power` in terms of the correctly-rounded
1365 :meth:`exp` and :meth:`ln` functions. The result is well-defined but
1366 only "almost always correctly-rounded".
Georg Brandl116aa622007-08-15 14:28:22 +00001367
Benjamin Petersone41251e2008-04-25 01:59:09 +00001368 With three arguments, compute ``(x**y) % modulo``. For the three argument
1369 form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +00001370
Benjamin Petersone41251e2008-04-25 01:59:09 +00001371 - all three arguments must be integral
1372 - ``y`` must be nonnegative
1373 - at least one of ``x`` or ``y`` must be nonzero
1374 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +00001375
Mark Dickinson5961b0e2010-02-22 15:41:48 +00001376 The value resulting from ``Context.power(x, y, modulo)`` is
1377 equal to the value that would be obtained by computing ``(x**y)
1378 % modulo`` with unbounded precision, but is computed more
1379 efficiently. The exponent of the result is zero, regardless of
1380 the exponents of ``x``, ``y`` and ``modulo``. The result is
1381 always exact.
Georg Brandl116aa622007-08-15 14:28:22 +00001382
Facundo Batista789bdf02008-06-21 17:29:41 +00001383
1384 .. method:: quantize(x, y)
1385
1386 Returns a value equal to *x* (rounded), having the exponent of *y*.
1387
1388
1389 .. method:: radix()
1390
1391 Just returns 10, as this is Decimal, :)
1392
1393
Benjamin Petersone41251e2008-04-25 01:59:09 +00001394 .. method:: remainder(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001395
Benjamin Petersone41251e2008-04-25 01:59:09 +00001396 Returns the remainder from integer division.
Georg Brandl116aa622007-08-15 14:28:22 +00001397
Benjamin Petersone41251e2008-04-25 01:59:09 +00001398 The sign of the result, if non-zero, is the same as that of the original
1399 dividend.
Georg Brandl116aa622007-08-15 14:28:22 +00001400
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001401
Facundo Batista789bdf02008-06-21 17:29:41 +00001402 .. method:: remainder_near(x, y)
1403
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001404 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1405 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
Facundo Batista789bdf02008-06-21 17:29:41 +00001406
1407
1408 .. method:: rotate(x, y)
1409
1410 Returns a rotated copy of *x*, *y* times.
1411
1412
1413 .. method:: same_quantum(x, y)
1414
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001415 Returns ``True`` if the two operands have the same exponent.
Facundo Batista789bdf02008-06-21 17:29:41 +00001416
1417
1418 .. method:: scaleb (x, y)
1419
1420 Returns the first operand after adding the second value its exp.
1421
1422
1423 .. method:: shift(x, y)
1424
1425 Returns a shifted copy of *x*, *y* times.
1426
1427
1428 .. method:: sqrt(x)
1429
1430 Square root of a non-negative number to context precision.
1431
1432
Benjamin Petersone41251e2008-04-25 01:59:09 +00001433 .. method:: subtract(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001434
Benjamin Petersone41251e2008-04-25 01:59:09 +00001435 Return the difference between *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001436
Facundo Batista789bdf02008-06-21 17:29:41 +00001437
1438 .. method:: to_eng_string(x)
1439
Raymond Hettingerf6ffa982016-08-13 11:15:34 -07001440 Convert to a string, using engineering notation if an exponent is needed.
1441
1442 Engineering notation has an exponent which is a multiple of 3. This
1443 can leave up to 3 digits to the left of the decimal place and may
1444 require the addition of either one or two trailing zeros.
Facundo Batista789bdf02008-06-21 17:29:41 +00001445
1446
1447 .. method:: to_integral_exact(x)
1448
1449 Rounds to an integer.
1450
1451
Benjamin Petersone41251e2008-04-25 01:59:09 +00001452 .. method:: to_sci_string(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001453
Benjamin Petersone41251e2008-04-25 01:59:09 +00001454 Converts a number to a string using scientific notation.
Georg Brandl116aa622007-08-15 14:28:22 +00001455
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001456.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001457
Stefan Krah1919b7e2012-03-21 18:25:23 +01001458.. _decimal-rounding-modes:
1459
1460Constants
1461---------
1462
1463The constants in this section are only relevant for the C module. They
1464are also included in the pure Python version for compatibility.
1465
Stefan Krah851a07e2012-03-21 18:47:20 +01001466+---------------------+---------------------+-------------------------------+
1467| | 32-bit | 64-bit |
1468+=====================+=====================+===============================+
1469| .. data:: MAX_PREC | :const:`425000000` | :const:`999999999999999999` |
1470+---------------------+---------------------+-------------------------------+
1471| .. data:: MAX_EMAX | :const:`425000000` | :const:`999999999999999999` |
1472+---------------------+---------------------+-------------------------------+
1473| .. data:: MIN_EMIN | :const:`-425000000` | :const:`-999999999999999999` |
1474+---------------------+---------------------+-------------------------------+
1475| .. data:: MIN_ETINY | :const:`-849999999` | :const:`-1999999999999999997` |
1476+---------------------+---------------------+-------------------------------+
1477
Stefan Krah1919b7e2012-03-21 18:25:23 +01001478
1479.. data:: HAVE_THREADS
1480
Stefan Krah815280e2020-02-29 19:43:42 +01001481 The value is ``True``. Deprecated, because Python now always has threads.
1482
1483.. deprecated:: 3.9
1484
1485.. data:: HAVE_CONTEXTVAR
1486
Victor Stinner85918e42021-04-12 23:27:35 +02001487 The default value is ``True``. If Python is :option:`configured using
1488 the --without-decimal-contextvar option <--without-decimal-contextvar>`,
Stefan Krah815280e2020-02-29 19:43:42 +01001489 the C version uses a thread-local rather than a coroutine-local context and the value
1490 is ``False``. This is slightly faster in some nested context scenarios.
1491
Stefan Krah0b0d29f2020-02-29 22:39:23 +01001492.. versionadded:: 3.9 backported to 3.7 and 3.8.
Stefan Krah815280e2020-02-29 19:43:42 +01001493
Stefan Krah1919b7e2012-03-21 18:25:23 +01001494
1495Rounding modes
1496--------------
1497
1498.. data:: ROUND_CEILING
1499
1500 Round towards :const:`Infinity`.
1501
1502.. data:: ROUND_DOWN
1503
1504 Round towards zero.
1505
1506.. data:: ROUND_FLOOR
1507
1508 Round towards :const:`-Infinity`.
1509
1510.. data:: ROUND_HALF_DOWN
1511
1512 Round to nearest with ties going towards zero.
1513
1514.. data:: ROUND_HALF_EVEN
1515
1516 Round to nearest with ties going to nearest even integer.
1517
1518.. data:: ROUND_HALF_UP
1519
1520 Round to nearest with ties going away from zero.
1521
1522.. data:: ROUND_UP
1523
1524 Round away from zero.
1525
1526.. data:: ROUND_05UP
1527
1528 Round away from zero if last digit after rounding towards zero would have
1529 been 0 or 5; otherwise round towards zero.
1530
Georg Brandl116aa622007-08-15 14:28:22 +00001531
1532.. _decimal-signals:
1533
1534Signals
1535-------
1536
1537Signals represent conditions that arise during computation. Each corresponds to
1538one context flag and one context trap enabler.
1539
Raymond Hettinger86173da2008-02-01 20:38:12 +00001540The context flag is set whenever the condition is encountered. After the
Georg Brandl116aa622007-08-15 14:28:22 +00001541computation, flags may be checked for informational purposes (for instance, to
1542determine whether a computation was exact). After checking the flags, be sure to
1543clear all flags before starting the next computation.
1544
1545If the context's trap enabler is set for the signal, then the condition causes a
1546Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1547is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1548condition.
1549
1550
1551.. class:: Clamped
1552
1553 Altered an exponent to fit representation constraints.
1554
1555 Typically, clamping occurs when an exponent falls outside the context's
1556 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001557 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001558
1559
1560.. class:: DecimalException
1561
1562 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1563
1564
1565.. class:: DivisionByZero
1566
1567 Signals the division of a non-infinite number by zero.
1568
1569 Can occur with division, modulo division, or when raising a number to a negative
1570 power. If this signal is not trapped, returns :const:`Infinity` or
1571 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1572
1573
1574.. class:: Inexact
1575
1576 Indicates that rounding occurred and the result is not exact.
1577
1578 Signals when non-zero digits were discarded during rounding. The rounded result
1579 is returned. The signal flag or trap is used to detect when results are
1580 inexact.
1581
1582
1583.. class:: InvalidOperation
1584
1585 An invalid operation was performed.
1586
1587 Indicates that an operation was requested that does not make sense. If not
1588 trapped, returns :const:`NaN`. Possible causes include::
1589
1590 Infinity - Infinity
1591 0 * Infinity
1592 Infinity / Infinity
1593 x % 0
1594 Infinity % x
Georg Brandl116aa622007-08-15 14:28:22 +00001595 sqrt(-x) and x > 0
1596 0 ** 0
1597 x ** (non-integer)
Georg Brandl48310cd2009-01-03 21:18:54 +00001598 x ** Infinity
Georg Brandl116aa622007-08-15 14:28:22 +00001599
1600
1601.. class:: Overflow
1602
1603 Numerical overflow.
1604
Benjamin Petersone41251e2008-04-25 01:59:09 +00001605 Indicates the exponent is larger than :attr:`Emax` after rounding has
1606 occurred. If not trapped, the result depends on the rounding mode, either
1607 pulling inward to the largest representable finite number or rounding outward
1608 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1609 are also signaled.
Georg Brandl116aa622007-08-15 14:28:22 +00001610
1611
1612.. class:: Rounded
1613
1614 Rounding occurred though possibly no information was lost.
1615
Benjamin Petersone41251e2008-04-25 01:59:09 +00001616 Signaled whenever rounding discards digits; even if those digits are zero
1617 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1618 the result unchanged. This signal is used to detect loss of significant
1619 digits.
Georg Brandl116aa622007-08-15 14:28:22 +00001620
1621
1622.. class:: Subnormal
1623
1624 Exponent was lower than :attr:`Emin` prior to rounding.
1625
Benjamin Petersone41251e2008-04-25 01:59:09 +00001626 Occurs when an operation result is subnormal (the exponent is too small). If
1627 not trapped, returns the result unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +00001628
1629
1630.. class:: Underflow
1631
1632 Numerical underflow with result rounded to zero.
1633
1634 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1635 and :class:`Subnormal` are also signaled.
1636
Stefan Krah1919b7e2012-03-21 18:25:23 +01001637
1638.. class:: FloatOperation
1639
1640 Enable stricter semantics for mixing floats and Decimals.
1641
1642 If the signal is not trapped (default), mixing floats and Decimals is
1643 permitted in the :class:`~decimal.Decimal` constructor,
1644 :meth:`~decimal.Context.create_decimal` and all comparison operators.
1645 Both conversion and comparisons are exact. Any occurrence of a mixed
1646 operation is silently recorded by setting :exc:`FloatOperation` in the
1647 context flags. Explicit conversions with :meth:`~decimal.Decimal.from_float`
1648 or :meth:`~decimal.Context.create_decimal_from_float` do not set the flag.
1649
1650 Otherwise (the signal is trapped), only equality comparisons and explicit
1651 conversions are silent. All other mixed operations raise :exc:`FloatOperation`.
1652
1653
Georg Brandl116aa622007-08-15 14:28:22 +00001654The following table summarizes the hierarchy of signals::
1655
1656 exceptions.ArithmeticError(exceptions.Exception)
1657 DecimalException
1658 Clamped
1659 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1660 Inexact
1661 Overflow(Inexact, Rounded)
1662 Underflow(Inexact, Rounded, Subnormal)
1663 InvalidOperation
1664 Rounded
1665 Subnormal
Stefan Krahb6405ef2012-03-23 14:46:48 +01001666 FloatOperation(DecimalException, exceptions.TypeError)
Georg Brandl116aa622007-08-15 14:28:22 +00001667
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001668.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001669
1670
Stefan Krah1919b7e2012-03-21 18:25:23 +01001671
Georg Brandl116aa622007-08-15 14:28:22 +00001672.. _decimal-notes:
1673
1674Floating Point Notes
1675--------------------
1676
1677
1678Mitigating round-off error with increased precision
1679^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1680
1681The use of decimal floating point eliminates decimal representation error
1682(making it possible to represent :const:`0.1` exactly); however, some operations
1683can still incur round-off error when non-zero digits exceed the fixed precision.
1684
1685The effects of round-off error can be amplified by the addition or subtraction
1686of nearly offsetting quantities resulting in loss of significance. Knuth
1687provides two instructive examples where rounded floating point arithmetic with
1688insufficient precision causes the breakdown of the associative and distributive
Christian Heimesfe337bf2008-03-23 21:54:12 +00001689properties of addition:
1690
1691.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001692
1693 # Examples from Seminumerical Algorithms, Section 4.2.2.
1694 >>> from decimal import Decimal, getcontext
1695 >>> getcontext().prec = 8
1696
1697 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1698 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001699 Decimal('9.5111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001700 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001701 Decimal('10')
Georg Brandl116aa622007-08-15 14:28:22 +00001702
1703 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1704 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001705 Decimal('0.01')
Georg Brandl116aa622007-08-15 14:28:22 +00001706 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001707 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001708
1709The :mod:`decimal` module makes it possible to restore the identities by
Christian Heimesfe337bf2008-03-23 21:54:12 +00001710expanding the precision sufficiently to avoid loss of significance:
1711
1712.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001713
1714 >>> getcontext().prec = 20
1715 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1716 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001717 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001718 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001719 Decimal('9.51111111')
Georg Brandl48310cd2009-01-03 21:18:54 +00001720 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001721 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1722 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001723 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001724 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001725 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001726
1727
1728Special values
1729^^^^^^^^^^^^^^
1730
1731The number system for the :mod:`decimal` module provides special values
1732including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001733and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001734
1735Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1736they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1737not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1738can result from rounding beyond the limits of the largest representable number.
1739
1740The infinities are signed (affine) and can be used in arithmetic operations
1741where they get treated as very large, indeterminate numbers. For instance,
1742adding a constant to infinity gives another infinite result.
1743
1744Some operations are indeterminate and return :const:`NaN`, or if the
1745:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1746``0/0`` returns :const:`NaN` which means "not a number". This variety of
1747:const:`NaN` is quiet and, once created, will flow through other computations
1748always resulting in another :const:`NaN`. This behavior can be useful for a
1749series of computations that occasionally have missing inputs --- it allows the
1750calculation to proceed while flagging specific results as invalid.
1751
1752A variant is :const:`sNaN` which signals rather than remaining quiet after every
1753operation. This is a useful return value when an invalid result needs to
1754interrupt a calculation for special handling.
1755
Christian Heimes77c02eb2008-02-09 02:18:51 +00001756The behavior of Python's comparison operators can be a little surprising where a
1757:const:`NaN` is involved. A test for equality where one of the operands is a
1758quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1759``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1760:const:`True`. An attempt to compare two Decimals using any of the ``<``,
1761``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1762if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes3feef612008-02-11 06:19:17 +00001763not trapped. Note that the General Decimal Arithmetic specification does not
Christian Heimes77c02eb2008-02-09 02:18:51 +00001764specify the behavior of direct comparisons; these rules for comparisons
1765involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1766section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1767and :meth:`compare-signal` methods instead.
1768
Georg Brandl116aa622007-08-15 14:28:22 +00001769The signed zeros can result from calculations that underflow. They keep the sign
1770that would have resulted if the calculation had been carried out to greater
1771precision. Since their magnitude is zero, both positive and negative zeros are
1772treated as equal and their sign is informational.
1773
1774In addition to the two signed zeros which are distinct yet equal, there are
1775various representations of zero with differing precisions yet equivalent in
1776value. This takes a bit of getting used to. For an eye accustomed to
1777normalized floating point representations, it is not immediately obvious that
Christian Heimesfe337bf2008-03-23 21:54:12 +00001778the following calculation returns a value equal to zero:
Georg Brandl116aa622007-08-15 14:28:22 +00001779
1780 >>> 1 / Decimal('Infinity')
Stefan Krah1919b7e2012-03-21 18:25:23 +01001781 Decimal('0E-1000026')
Georg Brandl116aa622007-08-15 14:28:22 +00001782
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001783.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001784
1785
1786.. _decimal-threads:
1787
1788Working with threads
1789--------------------
1790
1791The :func:`getcontext` function accesses a different :class:`Context` object for
1792each thread. Having separate thread contexts means that threads may make
Stefan Krah1919b7e2012-03-21 18:25:23 +01001793changes (such as ``getcontext().prec=10``) without interfering with other threads.
Georg Brandl116aa622007-08-15 14:28:22 +00001794
1795Likewise, the :func:`setcontext` function automatically assigns its target to
1796the current thread.
1797
1798If :func:`setcontext` has not been called before :func:`getcontext`, then
1799:func:`getcontext` will automatically create a new context for use in the
1800current thread.
1801
1802The new context is copied from a prototype context called *DefaultContext*. To
1803control the defaults so that each thread will use the same values throughout the
1804application, directly modify the *DefaultContext* object. This should be done
1805*before* any threads are started so that there won't be a race condition between
1806threads calling :func:`getcontext`. For example::
1807
1808 # Set applicationwide defaults for all threads about to be launched
1809 DefaultContext.prec = 12
1810 DefaultContext.rounding = ROUND_DOWN
1811 DefaultContext.traps = ExtendedContext.traps.copy()
1812 DefaultContext.traps[InvalidOperation] = 1
1813 setcontext(DefaultContext)
1814
1815 # Afterwards, the threads can be started
1816 t1.start()
1817 t2.start()
1818 t3.start()
1819 . . .
1820
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001821.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001822
1823
1824.. _decimal-recipes:
1825
1826Recipes
1827-------
1828
1829Here are a few recipes that serve as utility functions and that demonstrate ways
1830to work with the :class:`Decimal` class::
1831
1832 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1833 pos='', neg='-', trailneg=''):
1834 """Convert Decimal to a money formatted string.
1835
1836 places: required number of places after the decimal point
1837 curr: optional currency symbol before the sign (may be blank)
1838 sep: optional grouping separator (comma, period, space, or blank)
1839 dp: decimal point indicator (comma or period)
1840 only specify as blank when places is zero
1841 pos: optional sign for positive numbers: '+', space or blank
1842 neg: optional sign for negative numbers: '-', '(', space or blank
1843 trailneg:optional trailing minus indicator: '-', ')', space or blank
1844
1845 >>> d = Decimal('-1234567.8901')
1846 >>> moneyfmt(d, curr='$')
1847 '-$1,234,567.89'
1848 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1849 '1.234.568-'
1850 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1851 '($1,234,567.89)'
1852 >>> moneyfmt(Decimal(123456789), sep=' ')
1853 '123 456 789.00'
1854 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Christian Heimesdae2a892008-04-19 00:55:37 +00001855 '<0.02>'
Georg Brandl116aa622007-08-15 14:28:22 +00001856
1857 """
Christian Heimesa156e092008-02-16 07:38:31 +00001858 q = Decimal(10) ** -places # 2 places --> '0.01'
Georg Brandl48310cd2009-01-03 21:18:54 +00001859 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +00001860 result = []
Facundo Batista789bdf02008-06-21 17:29:41 +00001861 digits = list(map(str, digits))
Georg Brandl116aa622007-08-15 14:28:22 +00001862 build, next = result.append, digits.pop
1863 if sign:
1864 build(trailneg)
1865 for i in range(places):
Christian Heimesa156e092008-02-16 07:38:31 +00001866 build(next() if digits else '0')
Raymond Hettinger0ab10e42011-01-08 09:03:11 +00001867 if places:
1868 build(dp)
Christian Heimesdae2a892008-04-19 00:55:37 +00001869 if not digits:
1870 build('0')
Georg Brandl116aa622007-08-15 14:28:22 +00001871 i = 0
1872 while digits:
1873 build(next())
1874 i += 1
1875 if i == 3 and digits:
1876 i = 0
1877 build(sep)
1878 build(curr)
Christian Heimesa156e092008-02-16 07:38:31 +00001879 build(neg if sign else pos)
1880 return ''.join(reversed(result))
Georg Brandl116aa622007-08-15 14:28:22 +00001881
1882 def pi():
1883 """Compute Pi to the current precision.
1884
Georg Brandl6911e3c2007-09-04 07:15:32 +00001885 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001886 3.141592653589793238462643383
1887
1888 """
1889 getcontext().prec += 2 # extra digits for intermediate steps
1890 three = Decimal(3) # substitute "three=3.0" for regular floats
1891 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1892 while s != lasts:
1893 lasts = s
1894 n, na = n+na, na+8
1895 d, da = d+da, da+32
1896 t = (t * n) / d
1897 s += t
1898 getcontext().prec -= 2
1899 return +s # unary plus applies the new precision
1900
1901 def exp(x):
1902 """Return e raised to the power of x. Result type matches input type.
1903
Georg Brandl6911e3c2007-09-04 07:15:32 +00001904 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001905 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001906 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001907 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001908 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001909 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001910 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001911 (7.38905609893+0j)
1912
1913 """
1914 getcontext().prec += 2
1915 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1916 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001917 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001918 i += 1
1919 fact *= i
Georg Brandl48310cd2009-01-03 21:18:54 +00001920 num *= x
1921 s += num / fact
1922 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001923 return +s
1924
1925 def cos(x):
1926 """Return the cosine of x as measured in radians.
1927
Mark Dickinsonb2b23822010-11-21 07:37:49 +00001928 The Taylor series approximation works best for a small value of x.
Raymond Hettinger2a1e3e22010-11-21 02:47:22 +00001929 For larger values, first compute x = x % (2 * pi).
1930
Georg Brandl6911e3c2007-09-04 07:15:32 +00001931 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001932 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001933 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001934 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001935 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001936 (0.87758256189+0j)
1937
1938 """
1939 getcontext().prec += 2
1940 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1941 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001942 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001943 i += 2
1944 fact *= i * (i-1)
1945 num *= x * x
1946 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001947 s += num / fact * sign
1948 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001949 return +s
1950
1951 def sin(x):
1952 """Return the sine of x as measured in radians.
1953
Mark Dickinsonb2b23822010-11-21 07:37:49 +00001954 The Taylor series approximation works best for a small value of x.
Raymond Hettinger2a1e3e22010-11-21 02:47:22 +00001955 For larger values, first compute x = x % (2 * pi).
1956
Georg Brandl6911e3c2007-09-04 07:15:32 +00001957 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001958 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001959 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001960 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001961 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001962 (0.479425538604+0j)
1963
1964 """
1965 getcontext().prec += 2
1966 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1967 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001968 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001969 i += 2
1970 fact *= i * (i-1)
1971 num *= x * x
1972 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001973 s += num / fact * sign
1974 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001975 return +s
1976
1977
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001978.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001979
1980
1981.. _decimal-faq:
1982
1983Decimal FAQ
1984-----------
1985
1986Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1987minimize typing when using the interactive interpreter?
1988
Christian Heimesfe337bf2008-03-23 21:54:12 +00001989A. Some users abbreviate the constructor to just a single letter:
Georg Brandl116aa622007-08-15 14:28:22 +00001990
1991 >>> D = decimal.Decimal
1992 >>> D('1.23') + D('3.45')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001993 Decimal('4.68')
Georg Brandl116aa622007-08-15 14:28:22 +00001994
1995Q. In a fixed-point application with two decimal places, some inputs have many
1996places and need to be rounded. Others are not supposed to have excess digits
1997and need to be validated. What methods should be used?
1998
1999A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Christian Heimesfe337bf2008-03-23 21:54:12 +00002000the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl116aa622007-08-15 14:28:22 +00002001
2002 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
2003
2004 >>> # Round to two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002005 >>> Decimal('3.214').quantize(TWOPLACES)
2006 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00002007
Georg Brandl48310cd2009-01-03 21:18:54 +00002008 >>> # Validate that a number does not exceed two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002009 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
2010 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00002011
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002012 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl116aa622007-08-15 14:28:22 +00002013 Traceback (most recent call last):
2014 ...
Benjamin Peterson25c95f12009-05-08 20:42:26 +00002015 Inexact: None
Georg Brandl116aa622007-08-15 14:28:22 +00002016
2017Q. Once I have valid two place inputs, how do I maintain that invariant
2018throughout an application?
2019
Christian Heimesa156e092008-02-16 07:38:31 +00002020A. Some operations like addition, subtraction, and multiplication by an integer
2021will automatically preserve fixed point. Others operations, like division and
2022non-integer multiplication, will change the number of decimal places and need to
Christian Heimesfe337bf2008-03-23 21:54:12 +00002023be followed-up with a :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00002024
2025 >>> a = Decimal('102.72') # Initial fixed-point values
2026 >>> b = Decimal('3.17')
2027 >>> a + b # Addition preserves fixed-point
2028 Decimal('105.89')
2029 >>> a - b
2030 Decimal('99.55')
2031 >>> a * 42 # So does integer multiplication
2032 Decimal('4314.24')
2033 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
2034 Decimal('325.62')
2035 >>> (b / a).quantize(TWOPLACES) # And quantize division
2036 Decimal('0.03')
2037
2038In developing fixed-point applications, it is convenient to define functions
Christian Heimesfe337bf2008-03-23 21:54:12 +00002039to handle the :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00002040
2041 >>> def mul(x, y, fp=TWOPLACES):
2042 ... return (x * y).quantize(fp)
2043 >>> def div(x, y, fp=TWOPLACES):
2044 ... return (x / y).quantize(fp)
2045
2046 >>> mul(a, b) # Automatically preserve fixed-point
2047 Decimal('325.62')
2048 >>> div(b, a)
2049 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +00002050
2051Q. There are many ways to express the same value. The numbers :const:`200`,
2052:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
2053various precisions. Is there a way to transform them to a single recognizable
2054canonical value?
2055
2056A. The :meth:`normalize` method maps all equivalent values to a single
Christian Heimesfe337bf2008-03-23 21:54:12 +00002057representative:
Georg Brandl116aa622007-08-15 14:28:22 +00002058
2059 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
2060 >>> [v.normalize() for v in values]
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002061 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl116aa622007-08-15 14:28:22 +00002062
2063Q. Some decimal values always print with exponential notation. Is there a way
2064to get a non-exponential representation?
2065
2066A. For some values, exponential notation is the only way to express the number
2067of significant places in the coefficient. For example, expressing
2068:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
2069original's two-place significance.
2070
Christian Heimesa156e092008-02-16 07:38:31 +00002071If an application does not care about tracking significance, it is easy to
Christian Heimesc3f30c42008-02-22 16:37:40 +00002072remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimesfe337bf2008-03-23 21:54:12 +00002073value unchanged:
Christian Heimesa156e092008-02-16 07:38:31 +00002074
2075 >>> def remove_exponent(d):
2076 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
2077
2078 >>> remove_exponent(Decimal('5E+3'))
2079 Decimal('5000')
2080
Georg Brandl116aa622007-08-15 14:28:22 +00002081Q. Is there a way to convert a regular float to a :class:`Decimal`?
2082
Mark Dickinsone534a072010-04-04 22:13:14 +00002083A. Yes, any binary floating point number can be exactly expressed as a
Raymond Hettinger96798592010-04-02 16:58:27 +00002084Decimal though an exact conversion may take more precision than intuition would
2085suggest:
Georg Brandl116aa622007-08-15 14:28:22 +00002086
Christian Heimesfe337bf2008-03-23 21:54:12 +00002087.. doctest::
2088
Raymond Hettinger96798592010-04-02 16:58:27 +00002089 >>> Decimal(math.pi)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002090 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl116aa622007-08-15 14:28:22 +00002091
Georg Brandl116aa622007-08-15 14:28:22 +00002092Q. Within a complex calculation, how can I make sure that I haven't gotten a
2093spurious result because of insufficient precision or rounding anomalies.
2094
2095A. The decimal module makes it easy to test results. A best practice is to
2096re-run calculations using greater precision and with various rounding modes.
2097Widely differing results indicate insufficient precision, rounding mode issues,
2098ill-conditioned inputs, or a numerically unstable algorithm.
2099
2100Q. I noticed that context precision is applied to the results of operations but
2101not to the inputs. Is there anything to watch out for when mixing values of
2102different precisions?
2103
2104A. Yes. The principle is that all values are considered to be exact and so is
2105the arithmetic on those values. Only the results are rounded. The advantage
2106for inputs is that "what you type is what you get". A disadvantage is that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00002107results can look odd if you forget that the inputs haven't been rounded:
2108
2109.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00002110
2111 >>> getcontext().prec = 3
Christian Heimesfe337bf2008-03-23 21:54:12 +00002112 >>> Decimal('3.104') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002113 Decimal('5.21')
Christian Heimesfe337bf2008-03-23 21:54:12 +00002114 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002115 Decimal('5.20')
Georg Brandl116aa622007-08-15 14:28:22 +00002116
2117The solution is either to increase precision or to force rounding of inputs
Christian Heimesfe337bf2008-03-23 21:54:12 +00002118using the unary plus operation:
2119
2120.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00002121
2122 >>> getcontext().prec = 3
2123 >>> +Decimal('1.23456789') # unary plus triggers rounding
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002124 Decimal('1.23')
Georg Brandl116aa622007-08-15 14:28:22 +00002125
2126Alternatively, inputs can be rounded upon creation using the
Christian Heimesfe337bf2008-03-23 21:54:12 +00002127:meth:`Context.create_decimal` method:
Georg Brandl116aa622007-08-15 14:28:22 +00002128
2129 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002130 Decimal('1.2345')
Cheryl Sabella00e9c552019-02-02 09:37:39 -05002131
2132Q. Is the CPython implementation fast for large numbers?
2133
2134A. Yes. In the CPython and PyPy3 implementations, the C/CFFI versions of
2135the decimal module integrate the high speed `libmpdec
2136<https://www.bytereef.org/mpdecimal/doc/libmpdec/index.html>`_ library for
Stefan Kraha025d4c2020-02-21 21:27:37 +01002137arbitrary precision correctly-rounded decimal floating point arithmetic [#]_.
Cheryl Sabella00e9c552019-02-02 09:37:39 -05002138``libmpdec`` uses `Karatsuba multiplication
2139<https://en.wikipedia.org/wiki/Karatsuba_algorithm>`_
2140for medium-sized numbers and the `Number Theoretic Transform
2141<https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform>`_
Stefan Kraha025d4c2020-02-21 21:27:37 +01002142for very large numbers.
Cheryl Sabella00e9c552019-02-02 09:37:39 -05002143
Stefan Kraha025d4c2020-02-21 21:27:37 +01002144The context must be adapted for exact arbitrary precision arithmetic. :attr:`Emin`
2145and :attr:`Emax` should always be set to the maximum values, :attr:`clamp`
2146should always be 0 (the default). Setting :attr:`prec` requires some care.
Cheryl Sabella00e9c552019-02-02 09:37:39 -05002147
Stefan Kraha025d4c2020-02-21 21:27:37 +01002148The easiest approach for trying out bignum arithmetic is to use the maximum
2149value for :attr:`prec` as well [#]_::
2150
2151 >>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN))
2152 >>> x = Decimal(2) ** 256
2153 >>> x / 128
2154 Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')
2155
2156
2157For inexact results, :attr:`MAX_PREC` is far too large on 64-bit platforms and
2158the available memory will be insufficient::
2159
2160 >>> Decimal(1) / 3
2161 Traceback (most recent call last):
2162 File "<stdin>", line 1, in <module>
2163 MemoryError
2164
2165On systems with overallocation (e.g. Linux), a more sophisticated approach is to
2166adjust :attr:`prec` to the amount of available RAM. Suppose that you have 8GB of
2167RAM and expect 10 simultaneous operands using a maximum of 500MB each::
2168
2169 >>> import sys
2170 >>>
Stefan Krahb76518d2020-02-23 14:36:54 +01002171 >>> # Maximum number of digits for a single operand using 500MB in 8-byte words
2172 >>> # with 19 digits per word (4-byte and 9 digits for the 32-bit build):
Stefan Kraha025d4c2020-02-21 21:27:37 +01002173 >>> maxdigits = 19 * ((500 * 1024**2) // 8)
2174 >>>
2175 >>> # Check that this works:
2176 >>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN)
2177 >>> c.traps[Inexact] = True
2178 >>> setcontext(c)
2179 >>>
2180 >>> # Fill the available precision with nines:
2181 >>> x = Decimal(0).logical_invert() * 9
2182 >>> sys.getsizeof(x)
2183 524288112
2184 >>> x + 2
2185 Traceback (most recent call last):
2186 File "<stdin>", line 1, in <module>
2187 decimal.Inexact: [<class 'decimal.Inexact'>]
2188
2189In general (and especially on systems without overallocation), it is recommended
2190to estimate even tighter bounds and set the :attr:`Inexact` trap if all calculations
2191are expected to be exact.
2192
2193
2194.. [#]
2195 .. versionadded:: 3.3
2196
2197.. [#]
2198 .. versionchanged:: 3.9
2199 This approach now works for all exact results except for non-integer powers.