blob: 9edc696b79d665fb9642f56059c14751a974deaf [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
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040026--------------
27
Stefan Krah1919b7e2012-03-21 18:25:23 +010028The :mod:`decimal` module provides support for fast correctly-rounded
29decimal floating point arithmetic. It offers several advantages over the
30:class:`float` datatype:
Georg Brandl116aa622007-08-15 14:28:22 +000031
Christian Heimes3feef612008-02-11 06:19:17 +000032* Decimal "is based on a floating-point model which was designed with people
33 in mind, and necessarily has a paramount guiding principle -- computers must
34 provide an arithmetic that works in the same way as the arithmetic that
35 people learn at school." -- excerpt from the decimal arithmetic specification.
36
Georg Brandl116aa622007-08-15 14:28:22 +000037* Decimal numbers can be represented exactly. In contrast, numbers like
Terry Jan Reedya9314632012-01-13 23:43:13 -050038 :const:`1.1` and :const:`2.2` do not have exact representations in binary
Raymond Hettingerd258d1e2009-04-23 22:06:12 +000039 floating point. End users typically would not expect ``1.1 + 2.2`` to display
40 as :const:`3.3000000000000003` as it does with binary floating point.
Georg Brandl116aa622007-08-15 14:28:22 +000041
42* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000043 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl116aa622007-08-15 14:28:22 +000044 is :const:`5.5511151231257827e-017`. While near to zero, the differences
45 prevent reliable equality testing and differences can accumulate. For this
Christian Heimes3feef612008-02-11 06:19:17 +000046 reason, decimal is preferred in accounting applications which have strict
Georg Brandl116aa622007-08-15 14:28:22 +000047 equality invariants.
48
49* The decimal module incorporates a notion of significant places so that ``1.30
50 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
51 This is the customary presentation for monetary applications. For
52 multiplication, the "schoolbook" approach uses all the figures in the
53 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
54 1.20`` gives :const:`1.5600`.
55
56* Unlike hardware based binary floating point, the decimal module has a user
Thomas Wouters1b7f8912007-09-19 03:06:30 +000057 alterable precision (defaulting to 28 places) which can be as large as needed for
Christian Heimesfe337bf2008-03-23 21:54:12 +000058 a given problem:
Georg Brandl116aa622007-08-15 14:28:22 +000059
Mark Dickinson43ef32a2010-11-07 11:24:44 +000060 >>> from decimal import *
Georg Brandl116aa622007-08-15 14:28:22 +000061 >>> getcontext().prec = 6
62 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000063 Decimal('0.142857')
Georg Brandl116aa622007-08-15 14:28:22 +000064 >>> getcontext().prec = 28
65 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000066 Decimal('0.1428571428571428571428571429')
Georg Brandl116aa622007-08-15 14:28:22 +000067
68* Both binary and decimal floating point are implemented in terms of published
69 standards. While the built-in float type exposes only a modest portion of its
70 capabilities, the decimal module exposes all required parts of the standard.
71 When needed, the programmer has full control over rounding and signal handling.
Christian Heimes3feef612008-02-11 06:19:17 +000072 This includes an option to enforce exact arithmetic by using exceptions
73 to block any inexact operations.
74
75* The decimal module was designed to support "without prejudice, both exact
76 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
77 and rounded floating-point arithmetic." -- excerpt from the decimal
78 arithmetic specification.
Georg Brandl116aa622007-08-15 14:28:22 +000079
80The module design is centered around three concepts: the decimal number, the
81context for arithmetic, and signals.
82
83A decimal number is immutable. It has a sign, coefficient digits, and an
84exponent. To preserve significance, the coefficient digits do not truncate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000085trailing zeros. Decimals also include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +000086:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
87differentiates :const:`-0` from :const:`+0`.
88
89The context for arithmetic is an environment specifying precision, rounding
90rules, limits on exponents, flags indicating the results of operations, and trap
91enablers which determine whether signals are treated as exceptions. Rounding
92options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
93:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +000094:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl116aa622007-08-15 14:28:22 +000095
96Signals are groups of exceptional conditions arising during the course of
97computation. Depending on the needs of the application, signals may be ignored,
98considered as informational, or treated as exceptions. The signals in the
99decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
100:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
Stefan Krah1919b7e2012-03-21 18:25:23 +0100101:const:`Overflow`, :const:`Underflow` and :const:`FloatOperation`.
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103For each signal there is a flag and a trap enabler. When a signal is
Raymond Hettinger86173da2008-02-01 20:38:12 +0000104encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl116aa622007-08-15 14:28:22 +0000105set to one, an exception is raised. Flags are sticky, so the user needs to
106reset them before monitoring a calculation.
107
108
109.. seealso::
110
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000111 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
Raymond Hettinger960dc362009-04-21 03:43:15 +0000112 Specification <http://speleotrove.com/decimal/decarith.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000113
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000114.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000115
116
117.. _decimal-tutorial:
118
119Quick-start Tutorial
120--------------------
121
122The usual start to using decimals is importing the module, viewing the current
123context with :func:`getcontext` and, if necessary, setting new values for
124precision, rounding, or enabled traps::
125
126 >>> from decimal import *
127 >>> getcontext()
Stefan Krah1919b7e2012-03-21 18:25:23 +0100128 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000129 capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000130 InvalidOperation])
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132 >>> getcontext().prec = 7 # Set a new precision
133
Mark Dickinsone534a072010-04-04 22:13:14 +0000134Decimal instances can be constructed from integers, strings, floats, or tuples.
135Construction from an integer or a float performs an exact conversion of the
136value of that integer or float. Decimal numbers include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +0000137:const:`NaN` which stands for "Not a number", positive and negative
Stefan Krah1919b7e2012-03-21 18:25:23 +0100138:const:`Infinity`, and :const:`-0`::
Georg Brandl116aa622007-08-15 14:28:22 +0000139
Facundo Batista789bdf02008-06-21 17:29:41 +0000140 >>> getcontext().prec = 28
Georg Brandl116aa622007-08-15 14:28:22 +0000141 >>> Decimal(10)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000142 Decimal('10')
143 >>> Decimal('3.14')
144 Decimal('3.14')
Mark Dickinsone534a072010-04-04 22:13:14 +0000145 >>> Decimal(3.14)
146 Decimal('3.140000000000000124344978758017532527446746826171875')
Georg Brandl116aa622007-08-15 14:28:22 +0000147 >>> Decimal((0, (3, 1, 4), -2))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000148 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000149 >>> Decimal(str(2.0 ** 0.5))
Alexander Belopolsky287d1fd2011-01-12 16:37:14 +0000150 Decimal('1.4142135623730951')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000151 >>> Decimal(2) ** Decimal('0.5')
152 Decimal('1.414213562373095048801688724')
153 >>> Decimal('NaN')
154 Decimal('NaN')
155 >>> Decimal('-Infinity')
156 Decimal('-Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000157
Stefan Krah1919b7e2012-03-21 18:25:23 +0100158If the :exc:`FloatOperation` signal is trapped, accidental mixing of
159decimals and floats in constructors or ordering comparisons raises
160an exception::
161
162 >>> c = getcontext()
163 >>> c.traps[FloatOperation] = True
164 >>> Decimal(3.14)
165 Traceback (most recent call last):
166 File "<stdin>", line 1, in <module>
167 decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
168 >>> Decimal('3.5') < 3.7
169 Traceback (most recent call last):
170 File "<stdin>", line 1, in <module>
171 decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
172 >>> Decimal('3.5') == 3.5
173 True
174
175.. versionadded:: 3.3
176
Georg Brandl116aa622007-08-15 14:28:22 +0000177The significance of a new Decimal is determined solely by the number of digits
178input. Context precision and rounding only come into play during arithmetic
Christian Heimesfe337bf2008-03-23 21:54:12 +0000179operations.
180
181.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183 >>> getcontext().prec = 6
184 >>> Decimal('3.0')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000185 Decimal('3.0')
Georg Brandl116aa622007-08-15 14:28:22 +0000186 >>> Decimal('3.1415926535')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000187 Decimal('3.1415926535')
Georg Brandl116aa622007-08-15 14:28:22 +0000188 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000189 Decimal('5.85987')
Georg Brandl116aa622007-08-15 14:28:22 +0000190 >>> getcontext().rounding = ROUND_UP
191 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000192 Decimal('5.85988')
Georg Brandl116aa622007-08-15 14:28:22 +0000193
Stefan Krah1919b7e2012-03-21 18:25:23 +0100194If the internal limits of the C version are exceeded, constructing
195a decimal raises :class:`InvalidOperation`::
196
197 >>> Decimal("1e9999999999999999999")
198 Traceback (most recent call last):
199 File "<stdin>", line 1, in <module>
200 decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]
201
202.. versionchanged:: 3.3
203
Georg Brandl116aa622007-08-15 14:28:22 +0000204Decimals interact well with much of the rest of Python. Here is a small decimal
Christian Heimesfe337bf2008-03-23 21:54:12 +0000205floating point flying circus:
206
207.. doctest::
208 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000209
Facundo Batista789bdf02008-06-21 17:29:41 +0000210 >>> 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 +0000211 >>> max(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000212 Decimal('9.25')
Georg Brandl116aa622007-08-15 14:28:22 +0000213 >>> min(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000214 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +0000215 >>> sorted(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000216 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
217 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl116aa622007-08-15 14:28:22 +0000218 >>> sum(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000219 Decimal('19.29')
Georg Brandl116aa622007-08-15 14:28:22 +0000220 >>> a,b,c = data[:3]
221 >>> str(a)
222 '1.34'
223 >>> float(a)
Mark Dickinson8dad7df2009-06-28 20:36:54 +0000224 1.34
225 >>> round(a, 1)
226 Decimal('1.3')
Georg Brandl116aa622007-08-15 14:28:22 +0000227 >>> int(a)
228 1
229 >>> a * 5
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000230 Decimal('6.70')
Georg Brandl116aa622007-08-15 14:28:22 +0000231 >>> a * b
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000232 Decimal('2.5058')
Georg Brandl116aa622007-08-15 14:28:22 +0000233 >>> c % a
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000234 Decimal('0.77')
Georg Brandl116aa622007-08-15 14:28:22 +0000235
Christian Heimesfe337bf2008-03-23 21:54:12 +0000236And some mathematical functions are also available to Decimal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000237
Facundo Batista789bdf02008-06-21 17:29:41 +0000238 >>> getcontext().prec = 28
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000239 >>> Decimal(2).sqrt()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000240 Decimal('1.414213562373095048801688724')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000241 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000242 Decimal('2.718281828459045235360287471')
243 >>> Decimal('10').ln()
244 Decimal('2.302585092994045684017991455')
245 >>> Decimal('10').log10()
246 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000247
Georg Brandl116aa622007-08-15 14:28:22 +0000248The :meth:`quantize` method rounds a number to a fixed exponent. This method is
249useful for monetary applications that often round results to a fixed number of
Christian Heimesfe337bf2008-03-23 21:54:12 +0000250places:
Georg Brandl116aa622007-08-15 14:28:22 +0000251
252 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000253 Decimal('7.32')
Georg Brandl116aa622007-08-15 14:28:22 +0000254 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000255 Decimal('8')
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257As shown above, the :func:`getcontext` function accesses the current context and
258allows the settings to be changed. This approach meets the needs of most
259applications.
260
261For more advanced work, it may be useful to create alternate contexts using the
262Context() constructor. To make an alternate active, use the :func:`setcontext`
263function.
264
Serhiy Storchakab19542d2015-03-14 21:32:57 +0200265In accordance with the standard, the :mod:`decimal` module provides two ready to
Georg Brandl116aa622007-08-15 14:28:22 +0000266use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
267former is especially useful for debugging because many of the traps are
Christian Heimesfe337bf2008-03-23 21:54:12 +0000268enabled:
269
270.. doctest:: newcontext
271 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000272
273 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
274 >>> setcontext(myothercontext)
275 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000276 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278 >>> ExtendedContext
Stefan Krah1919b7e2012-03-21 18:25:23 +0100279 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000280 capitals=1, clamp=0, flags=[], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000281 >>> setcontext(ExtendedContext)
282 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000283 Decimal('0.142857143')
Georg Brandl116aa622007-08-15 14:28:22 +0000284 >>> Decimal(42) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000285 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287 >>> setcontext(BasicContext)
288 >>> Decimal(42) / Decimal(0)
289 Traceback (most recent call last):
290 File "<pyshell#143>", line 1, in -toplevel-
291 Decimal(42) / Decimal(0)
292 DivisionByZero: x / 0
293
294Contexts also have signal flags for monitoring exceptional conditions
295encountered during computations. The flags remain set until explicitly cleared,
296so it is best to clear the flags before each set of monitored computations by
297using the :meth:`clear_flags` method. ::
298
299 >>> setcontext(ExtendedContext)
300 >>> getcontext().clear_flags()
301 >>> Decimal(355) / Decimal(113)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000302 Decimal('3.14159292')
Georg Brandl116aa622007-08-15 14:28:22 +0000303 >>> getcontext()
Stefan Krah1919b7e2012-03-21 18:25:23 +0100304 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000305 capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000306
307The *flags* entry shows that the rational approximation to :const:`Pi` was
308rounded (digits beyond the context precision were thrown away) and that the
309result is inexact (some of the discarded digits were non-zero).
310
311Individual traps are set using the dictionary in the :attr:`traps` field of a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000312context:
Georg Brandl116aa622007-08-15 14:28:22 +0000313
Christian Heimesfe337bf2008-03-23 21:54:12 +0000314.. doctest:: newcontext
315
316 >>> setcontext(ExtendedContext)
Georg Brandl116aa622007-08-15 14:28:22 +0000317 >>> Decimal(1) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000318 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000319 >>> getcontext().traps[DivisionByZero] = 1
320 >>> Decimal(1) / Decimal(0)
321 Traceback (most recent call last):
322 File "<pyshell#112>", line 1, in -toplevel-
323 Decimal(1) / Decimal(0)
324 DivisionByZero: x / 0
325
326Most programs adjust the current context only once, at the beginning of the
327program. And, in many applications, data is converted to :class:`Decimal` with
328a single cast inside a loop. With context set and decimals created, the bulk of
329the program manipulates the data no differently than with other Python numeric
330types.
331
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000332.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000333
334
335.. _decimal-decimal:
336
337Decimal objects
338---------------
339
340
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000341.. class:: Decimal(value="0", context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000342
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000343 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl116aa622007-08-15 14:28:22 +0000344
Raymond Hettinger96798592010-04-02 16:58:27 +0000345 *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal`
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000346 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Christian Heimesa62da1d2008-01-12 19:39:10 +0000347 string, it should conform to the decimal numeric string syntax after leading
348 and trailing whitespace characters are removed::
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350 sign ::= '+' | '-'
351 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
352 indicator ::= 'e' | 'E'
353 digits ::= digit [digit]...
354 decimal-part ::= digits '.' [digits] | ['.'] digits
355 exponent-part ::= indicator [sign] digits
356 infinity ::= 'Infinity' | 'Inf'
357 nan ::= 'NaN' [digits] | 'sNaN' [digits]
358 numeric-value ::= decimal-part [exponent-part] | infinity
Georg Brandl48310cd2009-01-03 21:18:54 +0000359 numeric-string ::= [sign] numeric-value | [sign] nan
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Mark Dickinson345adc42009-08-02 10:14:23 +0000361 Other Unicode decimal digits are also permitted where ``digit``
362 appears above. These include decimal digits from various other
363 alphabets (for example, Arabic-Indic and Devanāgarī digits) along
364 with the fullwidth digits ``'\uff10'`` through ``'\uff19'``.
365
Georg Brandl116aa622007-08-15 14:28:22 +0000366 If *value* is a :class:`tuple`, it should have three components, a sign
367 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
368 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000369 returns ``Decimal('1.414')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000370
Raymond Hettinger96798592010-04-02 16:58:27 +0000371 If *value* is a :class:`float`, the binary floating point value is losslessly
372 converted to its exact decimal equivalent. This conversion can often require
Mark Dickinsone534a072010-04-04 22:13:14 +0000373 53 or more digits of precision. For example, ``Decimal(float('1.1'))``
374 converts to
375 ``Decimal('1.100000000000000088817841970012523233890533447265625')``.
Raymond Hettinger96798592010-04-02 16:58:27 +0000376
Georg Brandl116aa622007-08-15 14:28:22 +0000377 The *context* precision does not affect how many digits are stored. That is
378 determined exclusively by the number of digits in *value*. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000379 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl116aa622007-08-15 14:28:22 +0000380 only three.
381
382 The purpose of the *context* argument is determining what to do if *value* is a
383 malformed string. If the context traps :const:`InvalidOperation`, an exception
384 is raised; otherwise, the constructor returns a new Decimal with the value of
385 :const:`NaN`.
386
387 Once constructed, :class:`Decimal` objects are immutable.
388
Mark Dickinsone534a072010-04-04 22:13:14 +0000389 .. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000390 The argument to the constructor is now permitted to be a :class:`float`
391 instance.
Mark Dickinsone534a072010-04-04 22:13:14 +0000392
Stefan Krah1919b7e2012-03-21 18:25:23 +0100393 .. versionchanged:: 3.3
394 :class:`float` arguments raise an exception if the :exc:`FloatOperation`
395 trap is set. By default the trap is off.
396
Benjamin Petersone41251e2008-04-25 01:59:09 +0000397 Decimal floating point objects share many properties with the other built-in
398 numeric types such as :class:`float` and :class:`int`. All of the usual math
399 operations and special methods apply. Likewise, decimal objects can be
400 copied, pickled, printed, used as dictionary keys, used as set elements,
401 compared, sorted, and coerced to another type (such as :class:`float` or
Mark Dickinson5d233fd2010-02-18 14:54:37 +0000402 :class:`int`).
Christian Heimesa62da1d2008-01-12 19:39:10 +0000403
Mark Dickinsona3f37402012-11-18 10:22:05 +0000404 There are some small differences between arithmetic on Decimal objects and
405 arithmetic on integers and floats. When the remainder operator ``%`` is
406 applied to Decimal objects, the sign of the result is the sign of the
407 *dividend* rather than the sign of the divisor::
408
409 >>> (-7) % 4
410 1
411 >>> Decimal(-7) % Decimal(4)
412 Decimal('-3')
413
414 The integer division operator ``//`` behaves analogously, returning the
415 integer part of the true quotient (truncating towards zero) rather than its
Mark Dickinsonec967242012-11-18 10:42:07 +0000416 floor, so as to preserve the usual identity ``x == (x // y) * y + x % y``::
Mark Dickinsona3f37402012-11-18 10:22:05 +0000417
418 >>> -7 // 4
419 -2
420 >>> Decimal(-7) // Decimal(4)
421 Decimal('-1')
422
423 The ``%`` and ``//`` operators implement the ``remainder`` and
424 ``divide-integer`` operations (respectively) as described in the
425 specification.
426
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000427 Decimal objects cannot generally be combined with floats or
428 instances of :class:`fractions.Fraction` in arithmetic operations:
429 an attempt to add a :class:`Decimal` to a :class:`float`, for
430 example, will raise a :exc:`TypeError`. However, it is possible to
431 use Python's comparison operators to compare a :class:`Decimal`
432 instance ``x`` with another number ``y``. This avoids confusing results
433 when doing equality comparisons between numbers of different types.
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000434
Ezio Melotti993a5ee2010-04-04 06:30:08 +0000435 .. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000436 Mixed-type comparisons between :class:`Decimal` instances and other
437 numeric types are now fully supported.
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000438
Benjamin Petersone41251e2008-04-25 01:59:09 +0000439 In addition to the standard numeric properties, decimal floating point
440 objects also have a number of specialized methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000441
Georg Brandl116aa622007-08-15 14:28:22 +0000442
Benjamin Petersone41251e2008-04-25 01:59:09 +0000443 .. method:: adjusted()
Georg Brandl116aa622007-08-15 14:28:22 +0000444
Benjamin Petersone41251e2008-04-25 01:59:09 +0000445 Return the adjusted exponent after shifting out the coefficient's
446 rightmost digits until only the lead digit remains:
447 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
448 position of the most significant digit with respect to the decimal point.
Georg Brandl116aa622007-08-15 14:28:22 +0000449
Stefan Krah53f2e0a2015-12-28 23:02:02 +0100450 .. method:: as_integer_ratio()
451
452 Return a pair ``(n, d)`` of integers that represent the given
453 :class:`Decimal` instance as a fraction, in lowest terms and
454 with a positive denominator::
455
456 >>> Decimal('-3.14').as_integer_ratio()
457 (-157, 50)
458
459 The conversion is exact. Raise OverflowError on infinities and ValueError
460 on NaNs.
461
462 .. versionadded:: 3.6
Georg Brandl116aa622007-08-15 14:28:22 +0000463
Benjamin Petersone41251e2008-04-25 01:59:09 +0000464 .. method:: as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +0000465
Benjamin Petersone41251e2008-04-25 01:59:09 +0000466 Return a :term:`named tuple` representation of the number:
467 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000468
Christian Heimes25bb7832008-01-11 16:17:00 +0000469
Benjamin Petersone41251e2008-04-25 01:59:09 +0000470 .. method:: canonical()
Georg Brandl116aa622007-08-15 14:28:22 +0000471
Benjamin Petersone41251e2008-04-25 01:59:09 +0000472 Return the canonical encoding of the argument. Currently, the encoding of
473 a :class:`Decimal` instance is always canonical, so this operation returns
474 its argument unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000475
Stefan Krah040e3112012-12-15 22:33:33 +0100476 .. method:: compare(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000477
Georg Brandl05f5ab72008-09-24 09:11:47 +0000478 Compare the values of two Decimal instances. :meth:`compare` returns a
479 Decimal instance, and if either operand is a NaN then the result is a
480 NaN::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000481
Georg Brandl05f5ab72008-09-24 09:11:47 +0000482 a or b is a NaN ==> Decimal('NaN')
483 a < b ==> Decimal('-1')
484 a == b ==> Decimal('0')
485 a > b ==> Decimal('1')
Georg Brandl116aa622007-08-15 14:28:22 +0000486
Stefan Krah040e3112012-12-15 22:33:33 +0100487 .. method:: compare_signal(other, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000488
Benjamin Petersone41251e2008-04-25 01:59:09 +0000489 This operation is identical to the :meth:`compare` method, except that all
490 NaNs signal. That is, if neither operand is a signaling NaN then any
491 quiet NaN operand is treated as though it were a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000492
Stefan Krah040e3112012-12-15 22:33:33 +0100493 .. method:: compare_total(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000494
Benjamin Petersone41251e2008-04-25 01:59:09 +0000495 Compare two operands using their abstract representation rather than their
496 numerical value. Similar to the :meth:`compare` method, but the result
497 gives a total ordering on :class:`Decimal` instances. Two
498 :class:`Decimal` instances with the same numeric value but different
499 representations compare unequal in this ordering:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000500
Benjamin Petersone41251e2008-04-25 01:59:09 +0000501 >>> Decimal('12.0').compare_total(Decimal('12'))
502 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503
Benjamin Petersone41251e2008-04-25 01:59:09 +0000504 Quiet and signaling NaNs are also included in the total ordering. The
505 result of this function is ``Decimal('0')`` if both operands have the same
506 representation, ``Decimal('-1')`` if the first operand is lower in the
507 total order than the second, and ``Decimal('1')`` if the first operand is
508 higher in the total order than the second operand. See the specification
509 for details of the total order.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510
Stefan Krah040e3112012-12-15 22:33:33 +0100511 This operation is unaffected by context and is quiet: no flags are changed
512 and no rounding is performed. As an exception, the C version may raise
513 InvalidOperation if the second operand cannot be converted exactly.
514
515 .. method:: compare_total_mag(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000516
Benjamin Petersone41251e2008-04-25 01:59:09 +0000517 Compare two operands using their abstract representation rather than their
518 value as in :meth:`compare_total`, but ignoring the sign of each operand.
519 ``x.compare_total_mag(y)`` is equivalent to
520 ``x.copy_abs().compare_total(y.copy_abs())``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000521
Stefan Krah040e3112012-12-15 22:33:33 +0100522 This operation is unaffected by context and is quiet: no flags are changed
523 and no rounding is performed. As an exception, the C version may raise
524 InvalidOperation if the second operand cannot be converted exactly.
525
Facundo Batista789bdf02008-06-21 17:29:41 +0000526 .. method:: conjugate()
527
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000528 Just returns self, this method is only to comply with the Decimal
Facundo Batista789bdf02008-06-21 17:29:41 +0000529 Specification.
530
Benjamin Petersone41251e2008-04-25 01:59:09 +0000531 .. method:: copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000532
Benjamin Petersone41251e2008-04-25 01:59:09 +0000533 Return the absolute value of the argument. This operation is unaffected
534 by the context and is quiet: no flags are changed and no rounding is
535 performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000536
Benjamin Petersone41251e2008-04-25 01:59:09 +0000537 .. method:: copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000538
Benjamin Petersone41251e2008-04-25 01:59:09 +0000539 Return the negation of the argument. This operation is unaffected by the
540 context and is quiet: no flags are changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000541
Stefan Krah040e3112012-12-15 22:33:33 +0100542 .. method:: copy_sign(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000543
Benjamin Petersone41251e2008-04-25 01:59:09 +0000544 Return a copy of the first operand with the sign set to be the same as the
545 sign of the second operand. For example:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546
Benjamin Petersone41251e2008-04-25 01:59:09 +0000547 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
548 Decimal('-2.3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000549
Stefan Krah040e3112012-12-15 22:33:33 +0100550 This operation is unaffected by context and is quiet: no flags are changed
551 and no rounding is performed. As an exception, the C version may raise
552 InvalidOperation if the second operand cannot be converted exactly.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000553
Stefan Krah040e3112012-12-15 22:33:33 +0100554 .. method:: exp(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000555
Benjamin Petersone41251e2008-04-25 01:59:09 +0000556 Return the value of the (natural) exponential function ``e**x`` at the
557 given number. The result is correctly rounded using the
558 :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000559
Benjamin Petersone41251e2008-04-25 01:59:09 +0000560 >>> Decimal(1).exp()
561 Decimal('2.718281828459045235360287471')
562 >>> Decimal(321).exp()
563 Decimal('2.561702493119680037517373933E+139')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000564
Raymond Hettinger771ed762009-01-03 19:20:32 +0000565 .. method:: from_float(f)
566
567 Classmethod that converts a float to a decimal number, exactly.
568
569 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
570 Since 0.1 is not exactly representable in binary floating point, the
571 value is stored as the nearest representable value which is
572 `0x1.999999999999ap-4`. That equivalent value in decimal is
573 `0.1000000000000000055511151231257827021181583404541015625`.
574
Mark Dickinsone534a072010-04-04 22:13:14 +0000575 .. note:: From Python 3.2 onwards, a :class:`Decimal` instance
576 can also be constructed directly from a :class:`float`.
577
Raymond Hettinger771ed762009-01-03 19:20:32 +0000578 .. doctest::
579
580 >>> Decimal.from_float(0.1)
581 Decimal('0.1000000000000000055511151231257827021181583404541015625')
582 >>> Decimal.from_float(float('nan'))
583 Decimal('NaN')
584 >>> Decimal.from_float(float('inf'))
585 Decimal('Infinity')
586 >>> Decimal.from_float(float('-inf'))
587 Decimal('-Infinity')
588
Georg Brandl45f53372009-01-03 21:15:20 +0000589 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000590
Stefan Krah040e3112012-12-15 22:33:33 +0100591 .. method:: fma(other, third, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000592
Benjamin Petersone41251e2008-04-25 01:59:09 +0000593 Fused multiply-add. Return self*other+third with no rounding of the
594 intermediate product self*other.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000595
Benjamin Petersone41251e2008-04-25 01:59:09 +0000596 >>> Decimal(2).fma(3, 5)
597 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000598
Benjamin Petersone41251e2008-04-25 01:59:09 +0000599 .. method:: is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000600
Benjamin Petersone41251e2008-04-25 01:59:09 +0000601 Return :const:`True` if the argument is canonical and :const:`False`
602 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
603 this operation always returns :const:`True`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
Benjamin Petersone41251e2008-04-25 01:59:09 +0000605 .. method:: is_finite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000606
Benjamin Petersone41251e2008-04-25 01:59:09 +0000607 Return :const:`True` if the argument is a finite number, and
608 :const:`False` if the argument is an infinity or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000609
Benjamin Petersone41251e2008-04-25 01:59:09 +0000610 .. method:: is_infinite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000611
Benjamin Petersone41251e2008-04-25 01:59:09 +0000612 Return :const:`True` if the argument is either positive or negative
613 infinity and :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000614
Benjamin Petersone41251e2008-04-25 01:59:09 +0000615 .. method:: is_nan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616
Benjamin Petersone41251e2008-04-25 01:59:09 +0000617 Return :const:`True` if the argument is a (quiet or signaling) NaN and
618 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000619
Stefan Krah040e3112012-12-15 22:33:33 +0100620 .. method:: is_normal(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000621
Benjamin Petersone41251e2008-04-25 01:59:09 +0000622 Return :const:`True` if the argument is a *normal* finite number. Return
623 :const:`False` if the argument is zero, subnormal, infinite or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624
Benjamin Petersone41251e2008-04-25 01:59:09 +0000625 .. method:: is_qnan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626
Benjamin Petersone41251e2008-04-25 01:59:09 +0000627 Return :const:`True` if the argument is a quiet NaN, and
628 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000629
Benjamin Petersone41251e2008-04-25 01:59:09 +0000630 .. method:: is_signed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000631
Benjamin Petersone41251e2008-04-25 01:59:09 +0000632 Return :const:`True` if the argument has a negative sign and
633 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634
Benjamin Petersone41251e2008-04-25 01:59:09 +0000635 .. method:: is_snan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000636
Benjamin Petersone41251e2008-04-25 01:59:09 +0000637 Return :const:`True` if the argument is a signaling NaN and :const:`False`
638 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000639
Stefan Krah040e3112012-12-15 22:33:33 +0100640 .. method:: is_subnormal(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000641
Benjamin Petersone41251e2008-04-25 01:59:09 +0000642 Return :const:`True` if the argument is subnormal, and :const:`False`
643 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644
Benjamin Petersone41251e2008-04-25 01:59:09 +0000645 .. method:: is_zero()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646
Benjamin Petersone41251e2008-04-25 01:59:09 +0000647 Return :const:`True` if the argument is a (positive or negative) zero and
648 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000649
Stefan Krah040e3112012-12-15 22:33:33 +0100650 .. method:: ln(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000651
Benjamin Petersone41251e2008-04-25 01:59:09 +0000652 Return the natural (base e) logarithm of the operand. The result is
653 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000654
Stefan Krah040e3112012-12-15 22:33:33 +0100655 .. method:: log10(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000656
Benjamin Petersone41251e2008-04-25 01:59:09 +0000657 Return the base ten logarithm of the operand. The result is correctly
658 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000659
Stefan Krah040e3112012-12-15 22:33:33 +0100660 .. method:: logb(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000661
Benjamin Petersone41251e2008-04-25 01:59:09 +0000662 For a nonzero number, return the adjusted exponent of its operand as a
663 :class:`Decimal` instance. If the operand is a zero then
664 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
665 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
666 returned.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000667
Stefan Krah040e3112012-12-15 22:33:33 +0100668 .. method:: logical_and(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000669
Benjamin Petersone41251e2008-04-25 01:59:09 +0000670 :meth:`logical_and` is a logical operation which takes two *logical
671 operands* (see :ref:`logical_operands_label`). The result is the
672 digit-wise ``and`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000673
Stefan Krah040e3112012-12-15 22:33:33 +0100674 .. method:: logical_invert(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000675
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000676 :meth:`logical_invert` is a logical operation. The
Benjamin Petersone41251e2008-04-25 01:59:09 +0000677 result is the digit-wise inversion of the operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000678
Stefan Krah040e3112012-12-15 22:33:33 +0100679 .. method:: logical_or(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000680
Benjamin Petersone41251e2008-04-25 01:59:09 +0000681 :meth:`logical_or` is a logical operation which takes two *logical
682 operands* (see :ref:`logical_operands_label`). The result is the
683 digit-wise ``or`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000684
Stefan Krah040e3112012-12-15 22:33:33 +0100685 .. method:: logical_xor(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000686
Benjamin Petersone41251e2008-04-25 01:59:09 +0000687 :meth:`logical_xor` is a logical operation which takes two *logical
688 operands* (see :ref:`logical_operands_label`). The result is the
689 digit-wise exclusive or of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000690
Stefan Krah040e3112012-12-15 22:33:33 +0100691 .. method:: max(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692
Benjamin Petersone41251e2008-04-25 01:59:09 +0000693 Like ``max(self, other)`` except that the context rounding rule is applied
694 before returning and that :const:`NaN` values are either signaled or
695 ignored (depending on the context and whether they are signaling or
696 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000697
Stefan Krah040e3112012-12-15 22:33:33 +0100698 .. method:: max_mag(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000699
Georg Brandl502d9a52009-07-26 15:02:41 +0000700 Similar to the :meth:`.max` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000701 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000702
Stefan Krah040e3112012-12-15 22:33:33 +0100703 .. method:: min(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000704
Benjamin Petersone41251e2008-04-25 01:59:09 +0000705 Like ``min(self, other)`` except that the context rounding rule is applied
706 before returning and that :const:`NaN` values are either signaled or
707 ignored (depending on the context and whether they are signaling or
708 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000709
Stefan Krah040e3112012-12-15 22:33:33 +0100710 .. method:: min_mag(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000711
Georg Brandl502d9a52009-07-26 15:02:41 +0000712 Similar to the :meth:`.min` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000713 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000714
Stefan Krah040e3112012-12-15 22:33:33 +0100715 .. method:: next_minus(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000716
Benjamin Petersone41251e2008-04-25 01:59:09 +0000717 Return the largest number representable in the given context (or in the
718 current thread's context if no context is given) that is smaller than the
719 given operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000720
Stefan Krah040e3112012-12-15 22:33:33 +0100721 .. method:: next_plus(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000722
Benjamin Petersone41251e2008-04-25 01:59:09 +0000723 Return the smallest number representable in the given context (or in the
724 current thread's context if no context is given) that is larger than the
725 given operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000726
Stefan Krah040e3112012-12-15 22:33:33 +0100727 .. method:: next_toward(other, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000728
Benjamin Petersone41251e2008-04-25 01:59:09 +0000729 If the two operands are unequal, return the number closest to the first
730 operand in the direction of the second operand. If both operands are
731 numerically equal, return a copy of the first operand with the sign set to
732 be the same as the sign of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000733
Stefan Krah040e3112012-12-15 22:33:33 +0100734 .. method:: normalize(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000735
Benjamin Petersone41251e2008-04-25 01:59:09 +0000736 Normalize the number by stripping the rightmost trailing zeros and
737 converting any result equal to :const:`Decimal('0')` to
Senthil Kumarana6bac952011-07-04 11:28:30 -0700738 :const:`Decimal('0e0')`. Used for producing canonical values for attributes
Benjamin Petersone41251e2008-04-25 01:59:09 +0000739 of an equivalence class. For example, ``Decimal('32.100')`` and
740 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
741 ``Decimal('32.1')``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000742
Stefan Krah040e3112012-12-15 22:33:33 +0100743 .. method:: number_class(context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000744
Benjamin Petersone41251e2008-04-25 01:59:09 +0000745 Return a string describing the *class* of the operand. The returned value
746 is one of the following ten strings.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000747
Benjamin Petersone41251e2008-04-25 01:59:09 +0000748 * ``"-Infinity"``, indicating that the operand is negative infinity.
749 * ``"-Normal"``, indicating that the operand is a negative normal number.
750 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
751 * ``"-Zero"``, indicating that the operand is a negative zero.
752 * ``"+Zero"``, indicating that the operand is a positive zero.
753 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
754 * ``"+Normal"``, indicating that the operand is a positive normal number.
755 * ``"+Infinity"``, indicating that the operand is positive infinity.
756 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
757 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000758
Stefan Krahb151f8f2014-04-30 19:15:38 +0200759 .. method:: quantize(exp, rounding=None, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000760
Benjamin Petersone41251e2008-04-25 01:59:09 +0000761 Return a value equal to the first operand after rounding and having the
762 exponent of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000763
Benjamin Petersone41251e2008-04-25 01:59:09 +0000764 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
765 Decimal('1.414')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000766
Benjamin Petersone41251e2008-04-25 01:59:09 +0000767 Unlike other operations, if the length of the coefficient after the
768 quantize operation would be greater than precision, then an
769 :const:`InvalidOperation` is signaled. This guarantees that, unless there
770 is an error condition, the quantized exponent is always equal to that of
771 the right-hand operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000772
Benjamin Petersone41251e2008-04-25 01:59:09 +0000773 Also unlike other operations, quantize never signals Underflow, even if
774 the result is subnormal and inexact.
Georg Brandl116aa622007-08-15 14:28:22 +0000775
Benjamin Petersone41251e2008-04-25 01:59:09 +0000776 If the exponent of the second operand is larger than that of the first
777 then rounding may be necessary. In this case, the rounding mode is
778 determined by the ``rounding`` argument if given, else by the given
779 ``context`` argument; if neither argument is given the rounding mode of
780 the current thread's context is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000781
Stefan Krahb151f8f2014-04-30 19:15:38 +0200782 An error is returned whenever the resulting exponent is greater than
783 :attr:`Emax` or less than :attr:`Etiny`.
Stefan Krahaf3f3a72012-08-30 12:33:55 +0200784
Benjamin Petersone41251e2008-04-25 01:59:09 +0000785 .. method:: radix()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000786
Benjamin Petersone41251e2008-04-25 01:59:09 +0000787 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
788 class does all its arithmetic. Included for compatibility with the
789 specification.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000790
Stefan Krah040e3112012-12-15 22:33:33 +0100791 .. method:: remainder_near(other, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000792
Mark Dickinson6ae568b2012-10-31 19:44:36 +0000793 Return the remainder from dividing *self* by *other*. This differs from
794 ``self % other`` in that the sign of the remainder is chosen so as to
795 minimize its absolute value. More precisely, the return value is
796 ``self - n * other`` where ``n`` is the integer nearest to the exact
797 value of ``self / other``, and if two integers are equally near then the
798 even one is chosen.
Georg Brandl116aa622007-08-15 14:28:22 +0000799
Mark Dickinson6ae568b2012-10-31 19:44:36 +0000800 If the result is zero then its sign will be the sign of *self*.
801
802 >>> Decimal(18).remainder_near(Decimal(10))
803 Decimal('-2')
804 >>> Decimal(25).remainder_near(Decimal(10))
805 Decimal('5')
806 >>> Decimal(35).remainder_near(Decimal(10))
807 Decimal('-5')
Georg Brandl116aa622007-08-15 14:28:22 +0000808
Stefan Krah040e3112012-12-15 22:33:33 +0100809 .. method:: rotate(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810
Benjamin Petersone41251e2008-04-25 01:59:09 +0000811 Return the result of rotating the digits of the first operand by an amount
812 specified by the second operand. The second operand must be an integer in
813 the range -precision through precision. The absolute value of the second
814 operand gives the number of places to rotate. If the second operand is
815 positive then rotation is to the left; otherwise rotation is to the right.
816 The coefficient of the first operand is padded on the left with zeros to
817 length precision if necessary. The sign and exponent of the first operand
818 are unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000819
Stefan Krah040e3112012-12-15 22:33:33 +0100820 .. method:: same_quantum(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000821
Benjamin Petersone41251e2008-04-25 01:59:09 +0000822 Test whether self and other have the same exponent or whether both are
823 :const:`NaN`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824
Stefan Krah040e3112012-12-15 22:33:33 +0100825 This operation is unaffected by context and is quiet: no flags are changed
826 and no rounding is performed. As an exception, the C version may raise
827 InvalidOperation if the second operand cannot be converted exactly.
828
829 .. method:: scaleb(other, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000830
Benjamin Petersone41251e2008-04-25 01:59:09 +0000831 Return the first operand with exponent adjusted by the second.
832 Equivalently, return the first operand multiplied by ``10**other``. The
833 second operand must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +0000834
Stefan Krah040e3112012-12-15 22:33:33 +0100835 .. method:: shift(other, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000836
Benjamin Petersone41251e2008-04-25 01:59:09 +0000837 Return the result of shifting the digits of the first operand by an amount
838 specified by the second operand. The second operand must be an integer in
839 the range -precision through precision. The absolute value of the second
840 operand gives the number of places to shift. If the second operand is
841 positive then the shift is to the left; otherwise the shift is to the
842 right. Digits shifted into the coefficient are zeros. The sign and
843 exponent of the first operand are unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +0000844
Stefan Krah040e3112012-12-15 22:33:33 +0100845 .. method:: sqrt(context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000846
Benjamin Petersone41251e2008-04-25 01:59:09 +0000847 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000848
Georg Brandl116aa622007-08-15 14:28:22 +0000849
Stefan Krah040e3112012-12-15 22:33:33 +0100850 .. method:: to_eng_string(context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000851
Benjamin Petersone41251e2008-04-25 01:59:09 +0000852 Convert to an engineering-type string.
Georg Brandl116aa622007-08-15 14:28:22 +0000853
Benjamin Petersone41251e2008-04-25 01:59:09 +0000854 Engineering notation has an exponent which is a multiple of 3, so there
855 are up to 3 digits left of the decimal place. For example, converts
Martin Panterd21e0b52015-10-10 10:36:22 +0000856 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000857
Stefan Krah040e3112012-12-15 22:33:33 +0100858 .. method:: to_integral(rounding=None, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000859
Benjamin Petersone41251e2008-04-25 01:59:09 +0000860 Identical to the :meth:`to_integral_value` method. The ``to_integral``
861 name has been kept for compatibility with older versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000862
Stefan Krah040e3112012-12-15 22:33:33 +0100863 .. method:: to_integral_exact(rounding=None, context=None)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000864
Benjamin Petersone41251e2008-04-25 01:59:09 +0000865 Round to the nearest integer, signaling :const:`Inexact` or
866 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
867 determined by the ``rounding`` parameter if given, else by the given
868 ``context``. If neither parameter is given then the rounding mode of the
869 current context is used.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000870
Stefan Krah040e3112012-12-15 22:33:33 +0100871 .. method:: to_integral_value(rounding=None, context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000872
Benjamin Petersone41251e2008-04-25 01:59:09 +0000873 Round to the nearest integer without signaling :const:`Inexact` or
874 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
875 rounding method in either the supplied *context* or the current context.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000876
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000877
878.. _logical_operands_label:
879
880Logical operands
881^^^^^^^^^^^^^^^^
882
883The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
884and :meth:`logical_xor` methods expect their arguments to be *logical
885operands*. A *logical operand* is a :class:`Decimal` instance whose
886exponent and sign are both zero, and whose digits are all either
887:const:`0` or :const:`1`.
888
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000889.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000890
891
892.. _decimal-context:
893
894Context objects
895---------------
896
897Contexts are environments for arithmetic operations. They govern precision, set
898rules for rounding, determine which signals are treated as exceptions, and limit
899the range for exponents.
900
901Each thread has its own current context which is accessed or changed using the
902:func:`getcontext` and :func:`setcontext` functions:
903
904
905.. function:: getcontext()
906
907 Return the current context for the active thread.
908
909
910.. function:: setcontext(c)
911
912 Set the current context for the active thread to *c*.
913
Georg Brandle6bcc912008-05-12 18:05:20 +0000914You can also use the :keyword:`with` statement and the :func:`localcontext`
915function to temporarily change the active context.
Georg Brandl116aa622007-08-15 14:28:22 +0000916
Stefan Krah040e3112012-12-15 22:33:33 +0100917.. function:: localcontext(ctx=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000918
919 Return a context manager that will set the current context for the active thread
Stefan Krah040e3112012-12-15 22:33:33 +0100920 to a copy of *ctx* on entry to the with-statement and restore the previous context
Georg Brandl116aa622007-08-15 14:28:22 +0000921 when exiting the with-statement. If no context is specified, a copy of the
922 current context is used.
923
Georg Brandl116aa622007-08-15 14:28:22 +0000924 For example, the following code sets the current decimal precision to 42 places,
925 performs a calculation, and then automatically restores the previous context::
926
Georg Brandl116aa622007-08-15 14:28:22 +0000927 from decimal import localcontext
928
929 with localcontext() as ctx:
930 ctx.prec = 42 # Perform a high precision calculation
931 s = calculate_something()
932 s = +s # Round the final result back to the default precision
933
934New contexts can also be created using the :class:`Context` constructor
935described below. In addition, the module provides three pre-made contexts:
936
937
938.. class:: BasicContext
939
940 This is a standard context defined by the General Decimal Arithmetic
941 Specification. Precision is set to nine. Rounding is set to
942 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
943 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
944 :const:`Subnormal`.
945
946 Because many of the traps are enabled, this context is useful for debugging.
947
948
949.. class:: ExtendedContext
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_EVEN`. All flags are cleared. No traps are enabled (so that
954 exceptions are not raised during computations).
955
Christian Heimes3feef612008-02-11 06:19:17 +0000956 Because the traps are disabled, this context is useful for applications that
Georg Brandl116aa622007-08-15 14:28:22 +0000957 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
958 raising exceptions. This allows an application to complete a run in the
959 presence of conditions that would otherwise halt the program.
960
961
962.. class:: DefaultContext
963
964 This context is used by the :class:`Context` constructor as a prototype for new
965 contexts. Changing a field (such a precision) has the effect of changing the
Stefan Kraha1193932010-05-29 12:59:18 +0000966 default for new contexts created by the :class:`Context` constructor.
Georg Brandl116aa622007-08-15 14:28:22 +0000967
968 This context is most useful in multi-threaded environments. Changing one of the
969 fields before threads are started has the effect of setting system-wide
970 defaults. Changing the fields after threads have started is not recommended as
971 it would require thread synchronization to prevent race conditions.
972
973 In single threaded environments, it is preferable to not use this context at
974 all. Instead, simply create contexts explicitly as described below.
975
Stefan Krah1919b7e2012-03-21 18:25:23 +0100976 The default values are :attr:`prec`\ =\ :const:`28`,
977 :attr:`rounding`\ =\ :const:`ROUND_HALF_EVEN`,
978 and enabled traps for :class:`Overflow`, :class:`InvalidOperation`, and
979 :class:`DivisionByZero`.
Georg Brandl116aa622007-08-15 14:28:22 +0000980
981In addition to the three supplied contexts, new contexts can be created with the
982:class:`Context` constructor.
983
984
Stefan Krah1919b7e2012-03-21 18:25:23 +0100985.. 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 +0000986
987 Creates a new context. If a field is not specified or is :const:`None`, the
988 default values are copied from the :const:`DefaultContext`. If the *flags*
989 field is not specified or is :const:`None`, all flags are cleared.
990
Stefan Krah1919b7e2012-03-21 18:25:23 +0100991 *prec* is an integer in the range [:const:`1`, :const:`MAX_PREC`] that sets
992 the precision for arithmetic operations in the context.
Georg Brandl116aa622007-08-15 14:28:22 +0000993
Stefan Krah1919b7e2012-03-21 18:25:23 +0100994 The *rounding* option is one of the constants listed in the section
995 `Rounding Modes`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000996
997 The *traps* and *flags* fields list any signals to be set. Generally, new
998 contexts should only set traps and leave the flags clear.
999
1000 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
Stefan Krah1919b7e2012-03-21 18:25:23 +01001001 for exponents. *Emin* must be in the range [:const:`MIN_EMIN`, :const:`0`],
1002 *Emax* in the range [:const:`0`, :const:`MAX_EMAX`].
Georg Brandl116aa622007-08-15 14:28:22 +00001003
1004 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
1005 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
1006 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
1007
Mark Dickinsonb1d8e322010-05-22 18:35:36 +00001008 The *clamp* field is either :const:`0` (the default) or :const:`1`.
1009 If set to :const:`1`, the exponent ``e`` of a :class:`Decimal`
1010 instance representable in this context is strictly limited to the
1011 range ``Emin - prec + 1 <= e <= Emax - prec + 1``. If *clamp* is
1012 :const:`0` then a weaker condition holds: the adjusted exponent of
1013 the :class:`Decimal` instance is at most ``Emax``. When *clamp* is
1014 :const:`1`, a large normal number will, where possible, have its
1015 exponent reduced and a corresponding number of zeros added to its
1016 coefficient, in order to fit the exponent constraints; this
1017 preserves the value of the number but loses information about
1018 significant trailing zeros. For example::
1019
1020 >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
1021 Decimal('1.23000E+999')
1022
1023 A *clamp* value of :const:`1` allows compatibility with the
1024 fixed-width decimal interchange formats specified in IEEE 754.
Georg Brandl116aa622007-08-15 14:28:22 +00001025
Benjamin Petersone41251e2008-04-25 01:59:09 +00001026 The :class:`Context` class defines several general purpose methods as well as
1027 a large number of methods for doing arithmetic directly in a given context.
1028 In addition, for each of the :class:`Decimal` methods described above (with
1029 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
Mark Dickinson84230a12010-02-18 14:49:50 +00001030 a corresponding :class:`Context` method. For example, for a :class:`Context`
1031 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
1032 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a
Mark Dickinson5d233fd2010-02-18 14:54:37 +00001033 Python integer (an instance of :class:`int`) anywhere that a
Mark Dickinson84230a12010-02-18 14:49:50 +00001034 Decimal instance is accepted.
Georg Brandl116aa622007-08-15 14:28:22 +00001035
1036
Benjamin Petersone41251e2008-04-25 01:59:09 +00001037 .. method:: clear_flags()
Georg Brandl116aa622007-08-15 14:28:22 +00001038
Benjamin Petersone41251e2008-04-25 01:59:09 +00001039 Resets all of the flags to :const:`0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001040
Stefan Krah1919b7e2012-03-21 18:25:23 +01001041 .. method:: clear_traps()
1042
1043 Resets all of the traps to :const:`0`.
1044
1045 .. versionadded:: 3.3
1046
Benjamin Petersone41251e2008-04-25 01:59:09 +00001047 .. method:: copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001048
Benjamin Petersone41251e2008-04-25 01:59:09 +00001049 Return a duplicate of the context.
Georg Brandl116aa622007-08-15 14:28:22 +00001050
Benjamin Petersone41251e2008-04-25 01:59:09 +00001051 .. method:: copy_decimal(num)
Georg Brandl116aa622007-08-15 14:28:22 +00001052
Benjamin Petersone41251e2008-04-25 01:59:09 +00001053 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +00001054
Benjamin Petersone41251e2008-04-25 01:59:09 +00001055 .. method:: create_decimal(num)
Christian Heimesfe337bf2008-03-23 21:54:12 +00001056
Benjamin Petersone41251e2008-04-25 01:59:09 +00001057 Creates a new Decimal instance from *num* but using *self* as
1058 context. Unlike the :class:`Decimal` constructor, the context precision,
1059 rounding method, flags, and traps are applied to the conversion.
Georg Brandl116aa622007-08-15 14:28:22 +00001060
Benjamin Petersone41251e2008-04-25 01:59:09 +00001061 This is useful because constants are often given to a greater precision
1062 than is needed by the application. Another benefit is that rounding
1063 immediately eliminates unintended effects from digits beyond the current
1064 precision. In the following example, using unrounded inputs means that
1065 adding zero to a sum can change the result:
Georg Brandl116aa622007-08-15 14:28:22 +00001066
Benjamin Petersone41251e2008-04-25 01:59:09 +00001067 .. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001068
Benjamin Petersone41251e2008-04-25 01:59:09 +00001069 >>> getcontext().prec = 3
1070 >>> Decimal('3.4445') + Decimal('1.0023')
1071 Decimal('4.45')
1072 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1073 Decimal('4.44')
Georg Brandl116aa622007-08-15 14:28:22 +00001074
Benjamin Petersone41251e2008-04-25 01:59:09 +00001075 This method implements the to-number operation of the IBM specification.
1076 If the argument is a string, no leading or trailing whitespace is
1077 permitted.
1078
Georg Brandl45f53372009-01-03 21:15:20 +00001079 .. method:: create_decimal_from_float(f)
Raymond Hettinger771ed762009-01-03 19:20:32 +00001080
1081 Creates a new Decimal instance from a float *f* but rounding using *self*
Georg Brandl45f53372009-01-03 21:15:20 +00001082 as the context. Unlike the :meth:`Decimal.from_float` class method,
Raymond Hettinger771ed762009-01-03 19:20:32 +00001083 the context precision, rounding method, flags, and traps are applied to
1084 the conversion.
1085
1086 .. doctest::
1087
Georg Brandl45f53372009-01-03 21:15:20 +00001088 >>> context = Context(prec=5, rounding=ROUND_DOWN)
1089 >>> context.create_decimal_from_float(math.pi)
1090 Decimal('3.1415')
1091 >>> context = Context(prec=5, traps=[Inexact])
1092 >>> context.create_decimal_from_float(math.pi)
1093 Traceback (most recent call last):
1094 ...
1095 decimal.Inexact: None
Raymond Hettinger771ed762009-01-03 19:20:32 +00001096
Georg Brandl45f53372009-01-03 21:15:20 +00001097 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +00001098
Benjamin Petersone41251e2008-04-25 01:59:09 +00001099 .. method:: Etiny()
1100
1101 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
1102 value for subnormal results. When underflow occurs, the exponent is set
1103 to :const:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +00001104
Benjamin Petersone41251e2008-04-25 01:59:09 +00001105 .. method:: Etop()
Georg Brandl116aa622007-08-15 14:28:22 +00001106
Benjamin Petersone41251e2008-04-25 01:59:09 +00001107 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001108
Benjamin Petersone41251e2008-04-25 01:59:09 +00001109 The usual approach to working with decimals is to create :class:`Decimal`
1110 instances and then apply arithmetic operations which take place within the
1111 current context for the active thread. An alternative approach is to use
1112 context methods for calculating within a specific context. The methods are
1113 similar to those for the :class:`Decimal` class and are only briefly
1114 recounted here.
Georg Brandl116aa622007-08-15 14:28:22 +00001115
1116
Benjamin Petersone41251e2008-04-25 01:59:09 +00001117 .. method:: abs(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001118
Benjamin Petersone41251e2008-04-25 01:59:09 +00001119 Returns the absolute value of *x*.
Georg Brandl116aa622007-08-15 14:28:22 +00001120
1121
Benjamin Petersone41251e2008-04-25 01:59:09 +00001122 .. method:: add(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001123
Benjamin Petersone41251e2008-04-25 01:59:09 +00001124 Return the sum of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001125
1126
Facundo Batista789bdf02008-06-21 17:29:41 +00001127 .. method:: canonical(x)
1128
1129 Returns the same Decimal object *x*.
1130
1131
1132 .. method:: compare(x, y)
1133
1134 Compares *x* and *y* numerically.
1135
1136
1137 .. method:: compare_signal(x, y)
1138
1139 Compares the values of the two operands numerically.
1140
1141
1142 .. method:: compare_total(x, y)
1143
1144 Compares two operands using their abstract representation.
1145
1146
1147 .. method:: compare_total_mag(x, y)
1148
1149 Compares two operands using their abstract representation, ignoring sign.
1150
1151
1152 .. method:: copy_abs(x)
1153
1154 Returns a copy of *x* with the sign set to 0.
1155
1156
1157 .. method:: copy_negate(x)
1158
1159 Returns a copy of *x* with the sign inverted.
1160
1161
1162 .. method:: copy_sign(x, y)
1163
1164 Copies the sign from *y* to *x*.
1165
1166
Benjamin Petersone41251e2008-04-25 01:59:09 +00001167 .. method:: divide(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001168
Benjamin Petersone41251e2008-04-25 01:59:09 +00001169 Return *x* divided by *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001170
1171
Benjamin Petersone41251e2008-04-25 01:59:09 +00001172 .. method:: divide_int(x, y)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001173
Benjamin Petersone41251e2008-04-25 01:59:09 +00001174 Return *x* divided by *y*, truncated to an integer.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001175
1176
Benjamin Petersone41251e2008-04-25 01:59:09 +00001177 .. method:: divmod(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001178
Benjamin Petersone41251e2008-04-25 01:59:09 +00001179 Divides two numbers and returns the integer part of the result.
Georg Brandl116aa622007-08-15 14:28:22 +00001180
1181
Facundo Batista789bdf02008-06-21 17:29:41 +00001182 .. method:: exp(x)
1183
1184 Returns `e ** x`.
1185
1186
1187 .. method:: fma(x, y, z)
1188
1189 Returns *x* multiplied by *y*, plus *z*.
1190
1191
1192 .. method:: is_canonical(x)
1193
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001194 Returns ``True`` if *x* is canonical; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001195
1196
1197 .. method:: is_finite(x)
1198
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001199 Returns ``True`` if *x* is finite; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001200
1201
1202 .. method:: is_infinite(x)
1203
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001204 Returns ``True`` if *x* is infinite; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001205
1206
1207 .. method:: is_nan(x)
1208
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001209 Returns ``True`` if *x* is a qNaN or sNaN; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001210
1211
1212 .. method:: is_normal(x)
1213
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001214 Returns ``True`` if *x* is a normal number; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001215
1216
1217 .. method:: is_qnan(x)
1218
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001219 Returns ``True`` if *x* is a quiet NaN; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001220
1221
1222 .. method:: is_signed(x)
1223
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001224 Returns ``True`` if *x* is negative; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001225
1226
1227 .. method:: is_snan(x)
1228
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001229 Returns ``True`` if *x* is a signaling NaN; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001230
1231
1232 .. method:: is_subnormal(x)
1233
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001234 Returns ``True`` if *x* is subnormal; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001235
1236
1237 .. method:: is_zero(x)
1238
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001239 Returns ``True`` if *x* is a zero; otherwise returns ``False``.
Facundo Batista789bdf02008-06-21 17:29:41 +00001240
1241
1242 .. method:: ln(x)
1243
1244 Returns the natural (base e) logarithm of *x*.
1245
1246
1247 .. method:: log10(x)
1248
1249 Returns the base 10 logarithm of *x*.
1250
1251
1252 .. method:: logb(x)
1253
1254 Returns the exponent of the magnitude of the operand's MSD.
1255
1256
1257 .. method:: logical_and(x, y)
1258
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001259 Applies the logical operation *and* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001260
1261
1262 .. method:: logical_invert(x)
1263
1264 Invert all the digits in *x*.
1265
1266
1267 .. method:: logical_or(x, y)
1268
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001269 Applies the logical operation *or* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001270
1271
1272 .. method:: logical_xor(x, y)
1273
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001274 Applies the logical operation *xor* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001275
1276
1277 .. method:: max(x, y)
1278
1279 Compares two values numerically and returns the maximum.
1280
1281
1282 .. method:: max_mag(x, y)
1283
1284 Compares the values numerically with their sign ignored.
1285
1286
1287 .. method:: min(x, y)
1288
1289 Compares two values numerically and returns the minimum.
1290
1291
1292 .. method:: min_mag(x, y)
1293
1294 Compares the values numerically with their sign ignored.
1295
1296
Benjamin Petersone41251e2008-04-25 01:59:09 +00001297 .. method:: minus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001298
Benjamin Petersone41251e2008-04-25 01:59:09 +00001299 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001300
1301
Benjamin Petersone41251e2008-04-25 01:59:09 +00001302 .. method:: multiply(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001303
Benjamin Petersone41251e2008-04-25 01:59:09 +00001304 Return the product of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001305
1306
Facundo Batista789bdf02008-06-21 17:29:41 +00001307 .. method:: next_minus(x)
1308
1309 Returns the largest representable number smaller than *x*.
1310
1311
1312 .. method:: next_plus(x)
1313
1314 Returns the smallest representable number larger than *x*.
1315
1316
1317 .. method:: next_toward(x, y)
1318
1319 Returns the number closest to *x*, in direction towards *y*.
1320
1321
1322 .. method:: normalize(x)
1323
1324 Reduces *x* to its simplest form.
1325
1326
1327 .. method:: number_class(x)
1328
1329 Returns an indication of the class of *x*.
1330
1331
Benjamin Petersone41251e2008-04-25 01:59:09 +00001332 .. method:: plus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001333
Benjamin Petersone41251e2008-04-25 01:59:09 +00001334 Plus corresponds to the unary prefix plus operator in Python. This
1335 operation applies the context precision and rounding, so it is *not* an
1336 identity operation.
Georg Brandl116aa622007-08-15 14:28:22 +00001337
1338
Stefan Krah040e3112012-12-15 22:33:33 +01001339 .. method:: power(x, y, modulo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001340
Benjamin Petersone41251e2008-04-25 01:59:09 +00001341 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl116aa622007-08-15 14:28:22 +00001342
Benjamin Petersone41251e2008-04-25 01:59:09 +00001343 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1344 must be integral. The result will be inexact unless ``y`` is integral and
1345 the result is finite and can be expressed exactly in 'precision' digits.
Stefan Krah1919b7e2012-03-21 18:25:23 +01001346 The rounding mode of the context is used. Results are always correctly-rounded
1347 in the Python version.
1348
1349 .. versionchanged:: 3.3
1350 The C module computes :meth:`power` in terms of the correctly-rounded
1351 :meth:`exp` and :meth:`ln` functions. The result is well-defined but
1352 only "almost always correctly-rounded".
Georg Brandl116aa622007-08-15 14:28:22 +00001353
Benjamin Petersone41251e2008-04-25 01:59:09 +00001354 With three arguments, compute ``(x**y) % modulo``. For the three argument
1355 form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +00001356
Benjamin Petersone41251e2008-04-25 01:59:09 +00001357 - all three arguments must be integral
1358 - ``y`` must be nonnegative
1359 - at least one of ``x`` or ``y`` must be nonzero
1360 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +00001361
Mark Dickinson5961b0e2010-02-22 15:41:48 +00001362 The value resulting from ``Context.power(x, y, modulo)`` is
1363 equal to the value that would be obtained by computing ``(x**y)
1364 % modulo`` with unbounded precision, but is computed more
1365 efficiently. The exponent of the result is zero, regardless of
1366 the exponents of ``x``, ``y`` and ``modulo``. The result is
1367 always exact.
Georg Brandl116aa622007-08-15 14:28:22 +00001368
Facundo Batista789bdf02008-06-21 17:29:41 +00001369
1370 .. method:: quantize(x, y)
1371
1372 Returns a value equal to *x* (rounded), having the exponent of *y*.
1373
1374
1375 .. method:: radix()
1376
1377 Just returns 10, as this is Decimal, :)
1378
1379
Benjamin Petersone41251e2008-04-25 01:59:09 +00001380 .. method:: remainder(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001381
Benjamin Petersone41251e2008-04-25 01:59:09 +00001382 Returns the remainder from integer division.
Georg Brandl116aa622007-08-15 14:28:22 +00001383
Benjamin Petersone41251e2008-04-25 01:59:09 +00001384 The sign of the result, if non-zero, is the same as that of the original
1385 dividend.
Georg Brandl116aa622007-08-15 14:28:22 +00001386
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001387
Facundo Batista789bdf02008-06-21 17:29:41 +00001388 .. method:: remainder_near(x, y)
1389
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001390 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1391 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
Facundo Batista789bdf02008-06-21 17:29:41 +00001392
1393
1394 .. method:: rotate(x, y)
1395
1396 Returns a rotated copy of *x*, *y* times.
1397
1398
1399 .. method:: same_quantum(x, y)
1400
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001401 Returns ``True`` if the two operands have the same exponent.
Facundo Batista789bdf02008-06-21 17:29:41 +00001402
1403
1404 .. method:: scaleb (x, y)
1405
1406 Returns the first operand after adding the second value its exp.
1407
1408
1409 .. method:: shift(x, y)
1410
1411 Returns a shifted copy of *x*, *y* times.
1412
1413
1414 .. method:: sqrt(x)
1415
1416 Square root of a non-negative number to context precision.
1417
1418
Benjamin Petersone41251e2008-04-25 01:59:09 +00001419 .. method:: subtract(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001420
Benjamin Petersone41251e2008-04-25 01:59:09 +00001421 Return the difference between *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001422
Facundo Batista789bdf02008-06-21 17:29:41 +00001423
1424 .. method:: to_eng_string(x)
1425
1426 Converts a number to a string, using scientific notation.
1427
1428
1429 .. method:: to_integral_exact(x)
1430
1431 Rounds to an integer.
1432
1433
Benjamin Petersone41251e2008-04-25 01:59:09 +00001434 .. method:: to_sci_string(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001435
Benjamin Petersone41251e2008-04-25 01:59:09 +00001436 Converts a number to a string using scientific notation.
Georg Brandl116aa622007-08-15 14:28:22 +00001437
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001438.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001439
Stefan Krah1919b7e2012-03-21 18:25:23 +01001440.. _decimal-rounding-modes:
1441
1442Constants
1443---------
1444
1445The constants in this section are only relevant for the C module. They
1446are also included in the pure Python version for compatibility.
1447
Stefan Krah851a07e2012-03-21 18:47:20 +01001448+---------------------+---------------------+-------------------------------+
1449| | 32-bit | 64-bit |
1450+=====================+=====================+===============================+
1451| .. data:: MAX_PREC | :const:`425000000` | :const:`999999999999999999` |
1452+---------------------+---------------------+-------------------------------+
1453| .. data:: MAX_EMAX | :const:`425000000` | :const:`999999999999999999` |
1454+---------------------+---------------------+-------------------------------+
1455| .. data:: MIN_EMIN | :const:`-425000000` | :const:`-999999999999999999` |
1456+---------------------+---------------------+-------------------------------+
1457| .. data:: MIN_ETINY | :const:`-849999999` | :const:`-1999999999999999997` |
1458+---------------------+---------------------+-------------------------------+
1459
Stefan Krah1919b7e2012-03-21 18:25:23 +01001460
1461.. data:: HAVE_THREADS
1462
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001463 The default value is ``True``. If Python is compiled without threads, the
Stefan Krah1919b7e2012-03-21 18:25:23 +01001464 C version automatically disables the expensive thread local context
Serhiy Storchaka22dc4d52013-11-26 17:32:16 +02001465 machinery. In this case, the value is ``False``.
Stefan Krah1919b7e2012-03-21 18:25:23 +01001466
1467Rounding modes
1468--------------
1469
1470.. data:: ROUND_CEILING
1471
1472 Round towards :const:`Infinity`.
1473
1474.. data:: ROUND_DOWN
1475
1476 Round towards zero.
1477
1478.. data:: ROUND_FLOOR
1479
1480 Round towards :const:`-Infinity`.
1481
1482.. data:: ROUND_HALF_DOWN
1483
1484 Round to nearest with ties going towards zero.
1485
1486.. data:: ROUND_HALF_EVEN
1487
1488 Round to nearest with ties going to nearest even integer.
1489
1490.. data:: ROUND_HALF_UP
1491
1492 Round to nearest with ties going away from zero.
1493
1494.. data:: ROUND_UP
1495
1496 Round away from zero.
1497
1498.. data:: ROUND_05UP
1499
1500 Round away from zero if last digit after rounding towards zero would have
1501 been 0 or 5; otherwise round towards zero.
1502
Georg Brandl116aa622007-08-15 14:28:22 +00001503
1504.. _decimal-signals:
1505
1506Signals
1507-------
1508
1509Signals represent conditions that arise during computation. Each corresponds to
1510one context flag and one context trap enabler.
1511
Raymond Hettinger86173da2008-02-01 20:38:12 +00001512The context flag is set whenever the condition is encountered. After the
Georg Brandl116aa622007-08-15 14:28:22 +00001513computation, flags may be checked for informational purposes (for instance, to
1514determine whether a computation was exact). After checking the flags, be sure to
1515clear all flags before starting the next computation.
1516
1517If the context's trap enabler is set for the signal, then the condition causes a
1518Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1519is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1520condition.
1521
1522
1523.. class:: Clamped
1524
1525 Altered an exponent to fit representation constraints.
1526
1527 Typically, clamping occurs when an exponent falls outside the context's
1528 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001529 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001530
1531
1532.. class:: DecimalException
1533
1534 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1535
1536
1537.. class:: DivisionByZero
1538
1539 Signals the division of a non-infinite number by zero.
1540
1541 Can occur with division, modulo division, or when raising a number to a negative
1542 power. If this signal is not trapped, returns :const:`Infinity` or
1543 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1544
1545
1546.. class:: Inexact
1547
1548 Indicates that rounding occurred and the result is not exact.
1549
1550 Signals when non-zero digits were discarded during rounding. The rounded result
1551 is returned. The signal flag or trap is used to detect when results are
1552 inexact.
1553
1554
1555.. class:: InvalidOperation
1556
1557 An invalid operation was performed.
1558
1559 Indicates that an operation was requested that does not make sense. If not
1560 trapped, returns :const:`NaN`. Possible causes include::
1561
1562 Infinity - Infinity
1563 0 * Infinity
1564 Infinity / Infinity
1565 x % 0
1566 Infinity % x
Georg Brandl116aa622007-08-15 14:28:22 +00001567 sqrt(-x) and x > 0
1568 0 ** 0
1569 x ** (non-integer)
Georg Brandl48310cd2009-01-03 21:18:54 +00001570 x ** Infinity
Georg Brandl116aa622007-08-15 14:28:22 +00001571
1572
1573.. class:: Overflow
1574
1575 Numerical overflow.
1576
Benjamin Petersone41251e2008-04-25 01:59:09 +00001577 Indicates the exponent is larger than :attr:`Emax` after rounding has
1578 occurred. If not trapped, the result depends on the rounding mode, either
1579 pulling inward to the largest representable finite number or rounding outward
1580 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1581 are also signaled.
Georg Brandl116aa622007-08-15 14:28:22 +00001582
1583
1584.. class:: Rounded
1585
1586 Rounding occurred though possibly no information was lost.
1587
Benjamin Petersone41251e2008-04-25 01:59:09 +00001588 Signaled whenever rounding discards digits; even if those digits are zero
1589 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1590 the result unchanged. This signal is used to detect loss of significant
1591 digits.
Georg Brandl116aa622007-08-15 14:28:22 +00001592
1593
1594.. class:: Subnormal
1595
1596 Exponent was lower than :attr:`Emin` prior to rounding.
1597
Benjamin Petersone41251e2008-04-25 01:59:09 +00001598 Occurs when an operation result is subnormal (the exponent is too small). If
1599 not trapped, returns the result unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +00001600
1601
1602.. class:: Underflow
1603
1604 Numerical underflow with result rounded to zero.
1605
1606 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1607 and :class:`Subnormal` are also signaled.
1608
Stefan Krah1919b7e2012-03-21 18:25:23 +01001609
1610.. class:: FloatOperation
1611
1612 Enable stricter semantics for mixing floats and Decimals.
1613
1614 If the signal is not trapped (default), mixing floats and Decimals is
1615 permitted in the :class:`~decimal.Decimal` constructor,
1616 :meth:`~decimal.Context.create_decimal` and all comparison operators.
1617 Both conversion and comparisons are exact. Any occurrence of a mixed
1618 operation is silently recorded by setting :exc:`FloatOperation` in the
1619 context flags. Explicit conversions with :meth:`~decimal.Decimal.from_float`
1620 or :meth:`~decimal.Context.create_decimal_from_float` do not set the flag.
1621
1622 Otherwise (the signal is trapped), only equality comparisons and explicit
1623 conversions are silent. All other mixed operations raise :exc:`FloatOperation`.
1624
1625
Georg Brandl116aa622007-08-15 14:28:22 +00001626The following table summarizes the hierarchy of signals::
1627
1628 exceptions.ArithmeticError(exceptions.Exception)
1629 DecimalException
1630 Clamped
1631 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1632 Inexact
1633 Overflow(Inexact, Rounded)
1634 Underflow(Inexact, Rounded, Subnormal)
1635 InvalidOperation
1636 Rounded
1637 Subnormal
Stefan Krahb6405ef2012-03-23 14:46:48 +01001638 FloatOperation(DecimalException, exceptions.TypeError)
Georg Brandl116aa622007-08-15 14:28:22 +00001639
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001640.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001641
1642
Stefan Krah1919b7e2012-03-21 18:25:23 +01001643
Georg Brandl116aa622007-08-15 14:28:22 +00001644.. _decimal-notes:
1645
1646Floating Point Notes
1647--------------------
1648
1649
1650Mitigating round-off error with increased precision
1651^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1652
1653The use of decimal floating point eliminates decimal representation error
1654(making it possible to represent :const:`0.1` exactly); however, some operations
1655can still incur round-off error when non-zero digits exceed the fixed precision.
1656
1657The effects of round-off error can be amplified by the addition or subtraction
1658of nearly offsetting quantities resulting in loss of significance. Knuth
1659provides two instructive examples where rounded floating point arithmetic with
1660insufficient precision causes the breakdown of the associative and distributive
Christian Heimesfe337bf2008-03-23 21:54:12 +00001661properties of addition:
1662
1663.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001664
1665 # Examples from Seminumerical Algorithms, Section 4.2.2.
1666 >>> from decimal import Decimal, getcontext
1667 >>> getcontext().prec = 8
1668
1669 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1670 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001671 Decimal('9.5111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001672 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001673 Decimal('10')
Georg Brandl116aa622007-08-15 14:28:22 +00001674
1675 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1676 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001677 Decimal('0.01')
Georg Brandl116aa622007-08-15 14:28:22 +00001678 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001679 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001680
1681The :mod:`decimal` module makes it possible to restore the identities by
Christian Heimesfe337bf2008-03-23 21:54:12 +00001682expanding the precision sufficiently to avoid loss of significance:
1683
1684.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001685
1686 >>> getcontext().prec = 20
1687 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1688 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001689 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001690 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001691 Decimal('9.51111111')
Georg Brandl48310cd2009-01-03 21:18:54 +00001692 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001693 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1694 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001695 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001696 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001697 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001698
1699
1700Special values
1701^^^^^^^^^^^^^^
1702
1703The number system for the :mod:`decimal` module provides special values
1704including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001705and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001706
1707Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1708they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1709not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1710can result from rounding beyond the limits of the largest representable number.
1711
1712The infinities are signed (affine) and can be used in arithmetic operations
1713where they get treated as very large, indeterminate numbers. For instance,
1714adding a constant to infinity gives another infinite result.
1715
1716Some operations are indeterminate and return :const:`NaN`, or if the
1717:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1718``0/0`` returns :const:`NaN` which means "not a number". This variety of
1719:const:`NaN` is quiet and, once created, will flow through other computations
1720always resulting in another :const:`NaN`. This behavior can be useful for a
1721series of computations that occasionally have missing inputs --- it allows the
1722calculation to proceed while flagging specific results as invalid.
1723
1724A variant is :const:`sNaN` which signals rather than remaining quiet after every
1725operation. This is a useful return value when an invalid result needs to
1726interrupt a calculation for special handling.
1727
Christian Heimes77c02eb2008-02-09 02:18:51 +00001728The behavior of Python's comparison operators can be a little surprising where a
1729:const:`NaN` is involved. A test for equality where one of the operands is a
1730quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1731``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1732:const:`True`. An attempt to compare two Decimals using any of the ``<``,
1733``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1734if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes3feef612008-02-11 06:19:17 +00001735not trapped. Note that the General Decimal Arithmetic specification does not
Christian Heimes77c02eb2008-02-09 02:18:51 +00001736specify the behavior of direct comparisons; these rules for comparisons
1737involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1738section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1739and :meth:`compare-signal` methods instead.
1740
Georg Brandl116aa622007-08-15 14:28:22 +00001741The signed zeros can result from calculations that underflow. They keep the sign
1742that would have resulted if the calculation had been carried out to greater
1743precision. Since their magnitude is zero, both positive and negative zeros are
1744treated as equal and their sign is informational.
1745
1746In addition to the two signed zeros which are distinct yet equal, there are
1747various representations of zero with differing precisions yet equivalent in
1748value. This takes a bit of getting used to. For an eye accustomed to
1749normalized floating point representations, it is not immediately obvious that
Christian Heimesfe337bf2008-03-23 21:54:12 +00001750the following calculation returns a value equal to zero:
Georg Brandl116aa622007-08-15 14:28:22 +00001751
1752 >>> 1 / Decimal('Infinity')
Stefan Krah1919b7e2012-03-21 18:25:23 +01001753 Decimal('0E-1000026')
Georg Brandl116aa622007-08-15 14:28:22 +00001754
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001755.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001756
1757
1758.. _decimal-threads:
1759
1760Working with threads
1761--------------------
1762
1763The :func:`getcontext` function accesses a different :class:`Context` object for
1764each thread. Having separate thread contexts means that threads may make
Stefan Krah1919b7e2012-03-21 18:25:23 +01001765changes (such as ``getcontext().prec=10``) without interfering with other threads.
Georg Brandl116aa622007-08-15 14:28:22 +00001766
1767Likewise, the :func:`setcontext` function automatically assigns its target to
1768the current thread.
1769
1770If :func:`setcontext` has not been called before :func:`getcontext`, then
1771:func:`getcontext` will automatically create a new context for use in the
1772current thread.
1773
1774The new context is copied from a prototype context called *DefaultContext*. To
1775control the defaults so that each thread will use the same values throughout the
1776application, directly modify the *DefaultContext* object. This should be done
1777*before* any threads are started so that there won't be a race condition between
1778threads calling :func:`getcontext`. For example::
1779
1780 # Set applicationwide defaults for all threads about to be launched
1781 DefaultContext.prec = 12
1782 DefaultContext.rounding = ROUND_DOWN
1783 DefaultContext.traps = ExtendedContext.traps.copy()
1784 DefaultContext.traps[InvalidOperation] = 1
1785 setcontext(DefaultContext)
1786
1787 # Afterwards, the threads can be started
1788 t1.start()
1789 t2.start()
1790 t3.start()
1791 . . .
1792
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001793.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001794
1795
1796.. _decimal-recipes:
1797
1798Recipes
1799-------
1800
1801Here are a few recipes that serve as utility functions and that demonstrate ways
1802to work with the :class:`Decimal` class::
1803
1804 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1805 pos='', neg='-', trailneg=''):
1806 """Convert Decimal to a money formatted string.
1807
1808 places: required number of places after the decimal point
1809 curr: optional currency symbol before the sign (may be blank)
1810 sep: optional grouping separator (comma, period, space, or blank)
1811 dp: decimal point indicator (comma or period)
1812 only specify as blank when places is zero
1813 pos: optional sign for positive numbers: '+', space or blank
1814 neg: optional sign for negative numbers: '-', '(', space or blank
1815 trailneg:optional trailing minus indicator: '-', ')', space or blank
1816
1817 >>> d = Decimal('-1234567.8901')
1818 >>> moneyfmt(d, curr='$')
1819 '-$1,234,567.89'
1820 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1821 '1.234.568-'
1822 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1823 '($1,234,567.89)'
1824 >>> moneyfmt(Decimal(123456789), sep=' ')
1825 '123 456 789.00'
1826 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Christian Heimesdae2a892008-04-19 00:55:37 +00001827 '<0.02>'
Georg Brandl116aa622007-08-15 14:28:22 +00001828
1829 """
Christian Heimesa156e092008-02-16 07:38:31 +00001830 q = Decimal(10) ** -places # 2 places --> '0.01'
Georg Brandl48310cd2009-01-03 21:18:54 +00001831 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +00001832 result = []
Facundo Batista789bdf02008-06-21 17:29:41 +00001833 digits = list(map(str, digits))
Georg Brandl116aa622007-08-15 14:28:22 +00001834 build, next = result.append, digits.pop
1835 if sign:
1836 build(trailneg)
1837 for i in range(places):
Christian Heimesa156e092008-02-16 07:38:31 +00001838 build(next() if digits else '0')
Raymond Hettinger0ab10e42011-01-08 09:03:11 +00001839 if places:
1840 build(dp)
Christian Heimesdae2a892008-04-19 00:55:37 +00001841 if not digits:
1842 build('0')
Georg Brandl116aa622007-08-15 14:28:22 +00001843 i = 0
1844 while digits:
1845 build(next())
1846 i += 1
1847 if i == 3 and digits:
1848 i = 0
1849 build(sep)
1850 build(curr)
Christian Heimesa156e092008-02-16 07:38:31 +00001851 build(neg if sign else pos)
1852 return ''.join(reversed(result))
Georg Brandl116aa622007-08-15 14:28:22 +00001853
1854 def pi():
1855 """Compute Pi to the current precision.
1856
Georg Brandl6911e3c2007-09-04 07:15:32 +00001857 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001858 3.141592653589793238462643383
1859
1860 """
1861 getcontext().prec += 2 # extra digits for intermediate steps
1862 three = Decimal(3) # substitute "three=3.0" for regular floats
1863 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1864 while s != lasts:
1865 lasts = s
1866 n, na = n+na, na+8
1867 d, da = d+da, da+32
1868 t = (t * n) / d
1869 s += t
1870 getcontext().prec -= 2
1871 return +s # unary plus applies the new precision
1872
1873 def exp(x):
1874 """Return e raised to the power of x. Result type matches input type.
1875
Georg Brandl6911e3c2007-09-04 07:15:32 +00001876 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001877 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001878 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001879 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001880 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001881 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001882 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001883 (7.38905609893+0j)
1884
1885 """
1886 getcontext().prec += 2
1887 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1888 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001889 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001890 i += 1
1891 fact *= i
Georg Brandl48310cd2009-01-03 21:18:54 +00001892 num *= x
1893 s += num / fact
1894 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001895 return +s
1896
1897 def cos(x):
1898 """Return the cosine of x as measured in radians.
1899
Mark Dickinsonb2b23822010-11-21 07:37:49 +00001900 The Taylor series approximation works best for a small value of x.
Raymond Hettinger2a1e3e22010-11-21 02:47:22 +00001901 For larger values, first compute x = x % (2 * pi).
1902
Georg Brandl6911e3c2007-09-04 07:15:32 +00001903 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001904 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001905 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001906 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001907 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001908 (0.87758256189+0j)
1909
1910 """
1911 getcontext().prec += 2
1912 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1913 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001914 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001915 i += 2
1916 fact *= i * (i-1)
1917 num *= x * x
1918 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001919 s += num / fact * sign
1920 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001921 return +s
1922
1923 def sin(x):
1924 """Return the sine of x as measured in radians.
1925
Mark Dickinsonb2b23822010-11-21 07:37:49 +00001926 The Taylor series approximation works best for a small value of x.
Raymond Hettinger2a1e3e22010-11-21 02:47:22 +00001927 For larger values, first compute x = x % (2 * pi).
1928
Georg Brandl6911e3c2007-09-04 07:15:32 +00001929 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001930 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001931 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001932 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001933 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001934 (0.479425538604+0j)
1935
1936 """
1937 getcontext().prec += 2
1938 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1939 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001940 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001941 i += 2
1942 fact *= i * (i-1)
1943 num *= x * x
1944 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001945 s += num / fact * sign
1946 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001947 return +s
1948
1949
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001950.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001951
1952
1953.. _decimal-faq:
1954
1955Decimal FAQ
1956-----------
1957
1958Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1959minimize typing when using the interactive interpreter?
1960
Christian Heimesfe337bf2008-03-23 21:54:12 +00001961A. Some users abbreviate the constructor to just a single letter:
Georg Brandl116aa622007-08-15 14:28:22 +00001962
1963 >>> D = decimal.Decimal
1964 >>> D('1.23') + D('3.45')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001965 Decimal('4.68')
Georg Brandl116aa622007-08-15 14:28:22 +00001966
1967Q. In a fixed-point application with two decimal places, some inputs have many
1968places and need to be rounded. Others are not supposed to have excess digits
1969and need to be validated. What methods should be used?
1970
1971A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Christian Heimesfe337bf2008-03-23 21:54:12 +00001972the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl116aa622007-08-15 14:28:22 +00001973
1974 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1975
1976 >>> # Round to two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001977 >>> Decimal('3.214').quantize(TWOPLACES)
1978 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001979
Georg Brandl48310cd2009-01-03 21:18:54 +00001980 >>> # Validate that a number does not exceed two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001981 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1982 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001983
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001984 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl116aa622007-08-15 14:28:22 +00001985 Traceback (most recent call last):
1986 ...
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001987 Inexact: None
Georg Brandl116aa622007-08-15 14:28:22 +00001988
1989Q. Once I have valid two place inputs, how do I maintain that invariant
1990throughout an application?
1991
Christian Heimesa156e092008-02-16 07:38:31 +00001992A. Some operations like addition, subtraction, and multiplication by an integer
1993will automatically preserve fixed point. Others operations, like division and
1994non-integer multiplication, will change the number of decimal places and need to
Christian Heimesfe337bf2008-03-23 21:54:12 +00001995be followed-up with a :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001996
1997 >>> a = Decimal('102.72') # Initial fixed-point values
1998 >>> b = Decimal('3.17')
1999 >>> a + b # Addition preserves fixed-point
2000 Decimal('105.89')
2001 >>> a - b
2002 Decimal('99.55')
2003 >>> a * 42 # So does integer multiplication
2004 Decimal('4314.24')
2005 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
2006 Decimal('325.62')
2007 >>> (b / a).quantize(TWOPLACES) # And quantize division
2008 Decimal('0.03')
2009
2010In developing fixed-point applications, it is convenient to define functions
Christian Heimesfe337bf2008-03-23 21:54:12 +00002011to handle the :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00002012
2013 >>> def mul(x, y, fp=TWOPLACES):
2014 ... return (x * y).quantize(fp)
2015 >>> def div(x, y, fp=TWOPLACES):
2016 ... return (x / y).quantize(fp)
2017
2018 >>> mul(a, b) # Automatically preserve fixed-point
2019 Decimal('325.62')
2020 >>> div(b, a)
2021 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +00002022
2023Q. There are many ways to express the same value. The numbers :const:`200`,
2024:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
2025various precisions. Is there a way to transform them to a single recognizable
2026canonical value?
2027
2028A. The :meth:`normalize` method maps all equivalent values to a single
Christian Heimesfe337bf2008-03-23 21:54:12 +00002029representative:
Georg Brandl116aa622007-08-15 14:28:22 +00002030
2031 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
2032 >>> [v.normalize() for v in values]
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002033 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl116aa622007-08-15 14:28:22 +00002034
2035Q. Some decimal values always print with exponential notation. Is there a way
2036to get a non-exponential representation?
2037
2038A. For some values, exponential notation is the only way to express the number
2039of significant places in the coefficient. For example, expressing
2040:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
2041original's two-place significance.
2042
Christian Heimesa156e092008-02-16 07:38:31 +00002043If an application does not care about tracking significance, it is easy to
Christian Heimesc3f30c42008-02-22 16:37:40 +00002044remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimesfe337bf2008-03-23 21:54:12 +00002045value unchanged:
Christian Heimesa156e092008-02-16 07:38:31 +00002046
2047 >>> def remove_exponent(d):
2048 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
2049
2050 >>> remove_exponent(Decimal('5E+3'))
2051 Decimal('5000')
2052
Georg Brandl116aa622007-08-15 14:28:22 +00002053Q. Is there a way to convert a regular float to a :class:`Decimal`?
2054
Mark Dickinsone534a072010-04-04 22:13:14 +00002055A. Yes, any binary floating point number can be exactly expressed as a
Raymond Hettinger96798592010-04-02 16:58:27 +00002056Decimal though an exact conversion may take more precision than intuition would
2057suggest:
Georg Brandl116aa622007-08-15 14:28:22 +00002058
Christian Heimesfe337bf2008-03-23 21:54:12 +00002059.. doctest::
2060
Raymond Hettinger96798592010-04-02 16:58:27 +00002061 >>> Decimal(math.pi)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002062 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl116aa622007-08-15 14:28:22 +00002063
Georg Brandl116aa622007-08-15 14:28:22 +00002064Q. Within a complex calculation, how can I make sure that I haven't gotten a
2065spurious result because of insufficient precision or rounding anomalies.
2066
2067A. The decimal module makes it easy to test results. A best practice is to
2068re-run calculations using greater precision and with various rounding modes.
2069Widely differing results indicate insufficient precision, rounding mode issues,
2070ill-conditioned inputs, or a numerically unstable algorithm.
2071
2072Q. I noticed that context precision is applied to the results of operations but
2073not to the inputs. Is there anything to watch out for when mixing values of
2074different precisions?
2075
2076A. Yes. The principle is that all values are considered to be exact and so is
2077the arithmetic on those values. Only the results are rounded. The advantage
2078for inputs is that "what you type is what you get". A disadvantage is that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00002079results can look odd if you forget that the inputs haven't been rounded:
2080
2081.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00002082
2083 >>> getcontext().prec = 3
Christian Heimesfe337bf2008-03-23 21:54:12 +00002084 >>> Decimal('3.104') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002085 Decimal('5.21')
Christian Heimesfe337bf2008-03-23 21:54:12 +00002086 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002087 Decimal('5.20')
Georg Brandl116aa622007-08-15 14:28:22 +00002088
2089The solution is either to increase precision or to force rounding of inputs
Christian Heimesfe337bf2008-03-23 21:54:12 +00002090using the unary plus operation:
2091
2092.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00002093
2094 >>> getcontext().prec = 3
2095 >>> +Decimal('1.23456789') # unary plus triggers rounding
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002096 Decimal('1.23')
Georg Brandl116aa622007-08-15 14:28:22 +00002097
2098Alternatively, inputs can be rounded upon creation using the
Christian Heimesfe337bf2008-03-23 21:54:12 +00002099:meth:`Context.create_decimal` method:
Georg Brandl116aa622007-08-15 14:28:22 +00002100
2101 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00002102 Decimal('1.2345')