blob: 30467c8e94d893354cd1174397247aa56d7ab813 [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>
Georg Brandl116aa622007-08-15 14:28:22 +000012.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
13
Christian Heimesfe337bf2008-03-23 21:54:12 +000014.. import modules for testing inline doctests with the Sphinx doctest builder
15.. testsetup:: *
16
17 import decimal
18 import math
19 from decimal import *
20 # make sure each group gets a fresh context
21 setcontext(Context())
Georg Brandl116aa622007-08-15 14:28:22 +000022
Georg Brandl116aa622007-08-15 14:28:22 +000023The :mod:`decimal` module provides support for decimal floating point
Thomas Wouters1b7f8912007-09-19 03:06:30 +000024arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl116aa622007-08-15 14:28:22 +000025
Christian Heimes3feef612008-02-11 06:19:17 +000026* Decimal "is based on a floating-point model which was designed with people
27 in mind, and necessarily has a paramount guiding principle -- computers must
28 provide an arithmetic that works in the same way as the arithmetic that
29 people learn at school." -- excerpt from the decimal arithmetic specification.
30
Georg Brandl116aa622007-08-15 14:28:22 +000031* Decimal numbers can be represented exactly. In contrast, numbers like
Terry Jan Reedya9314632012-01-13 23:43:13 -050032 :const:`1.1` and :const:`2.2` do not have exact representations in binary
Raymond Hettingerd258d1e2009-04-23 22:06:12 +000033 floating point. End users typically would not expect ``1.1 + 2.2`` to display
34 as :const:`3.3000000000000003` as it does with binary floating point.
Georg Brandl116aa622007-08-15 14:28:22 +000035
36* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000037 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl116aa622007-08-15 14:28:22 +000038 is :const:`5.5511151231257827e-017`. While near to zero, the differences
39 prevent reliable equality testing and differences can accumulate. For this
Christian Heimes3feef612008-02-11 06:19:17 +000040 reason, decimal is preferred in accounting applications which have strict
Georg Brandl116aa622007-08-15 14:28:22 +000041 equality invariants.
42
43* The decimal module incorporates a notion of significant places so that ``1.30
44 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
45 This is the customary presentation for monetary applications. For
46 multiplication, the "schoolbook" approach uses all the figures in the
47 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
48 1.20`` gives :const:`1.5600`.
49
50* Unlike hardware based binary floating point, the decimal module has a user
Thomas Wouters1b7f8912007-09-19 03:06:30 +000051 alterable precision (defaulting to 28 places) which can be as large as needed for
Christian Heimesfe337bf2008-03-23 21:54:12 +000052 a given problem:
Georg Brandl116aa622007-08-15 14:28:22 +000053
Mark Dickinson43ef32a2010-11-07 11:24:44 +000054 >>> from decimal import *
Georg Brandl116aa622007-08-15 14:28:22 +000055 >>> getcontext().prec = 6
56 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000057 Decimal('0.142857')
Georg Brandl116aa622007-08-15 14:28:22 +000058 >>> getcontext().prec = 28
59 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000060 Decimal('0.1428571428571428571428571429')
Georg Brandl116aa622007-08-15 14:28:22 +000061
62* Both binary and decimal floating point are implemented in terms of published
63 standards. While the built-in float type exposes only a modest portion of its
64 capabilities, the decimal module exposes all required parts of the standard.
65 When needed, the programmer has full control over rounding and signal handling.
Christian Heimes3feef612008-02-11 06:19:17 +000066 This includes an option to enforce exact arithmetic by using exceptions
67 to block any inexact operations.
68
69* The decimal module was designed to support "without prejudice, both exact
70 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
71 and rounded floating-point arithmetic." -- excerpt from the decimal
72 arithmetic specification.
Georg Brandl116aa622007-08-15 14:28:22 +000073
74The module design is centered around three concepts: the decimal number, the
75context for arithmetic, and signals.
76
77A decimal number is immutable. It has a sign, coefficient digits, and an
78exponent. To preserve significance, the coefficient digits do not truncate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000079trailing zeros. Decimals also include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +000080:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
81differentiates :const:`-0` from :const:`+0`.
82
83The context for arithmetic is an environment specifying precision, rounding
84rules, limits on exponents, flags indicating the results of operations, and trap
85enablers which determine whether signals are treated as exceptions. Rounding
86options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
87:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +000088:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl116aa622007-08-15 14:28:22 +000089
90Signals are groups of exceptional conditions arising during the course of
91computation. Depending on the needs of the application, signals may be ignored,
92considered as informational, or treated as exceptions. The signals in the
93decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
94:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
95:const:`Overflow`, and :const:`Underflow`.
96
97For each signal there is a flag and a trap enabler. When a signal is
Raymond Hettinger86173da2008-02-01 20:38:12 +000098encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl116aa622007-08-15 14:28:22 +000099set to one, an exception is raised. Flags are sticky, so the user needs to
100reset them before monitoring a calculation.
101
102
103.. seealso::
104
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000105 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
Raymond Hettinger960dc362009-04-21 03:43:15 +0000106 Specification <http://speleotrove.com/decimal/decarith.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000108 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Christian Heimes77c02eb2008-02-09 02:18:51 +0000109 <http://754r.ucbtest.org/standards/854.pdf>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000111.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113
114.. _decimal-tutorial:
115
116Quick-start Tutorial
117--------------------
118
119The usual start to using decimals is importing the module, viewing the current
120context with :func:`getcontext` and, if necessary, setting new values for
121precision, rounding, or enabled traps::
122
123 >>> from decimal import *
124 >>> getcontext()
125 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000126 capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000127 InvalidOperation])
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129 >>> getcontext().prec = 7 # Set a new precision
130
Mark Dickinsone534a072010-04-04 22:13:14 +0000131Decimal instances can be constructed from integers, strings, floats, or tuples.
132Construction from an integer or a float performs an exact conversion of the
133value of that integer or float. Decimal numbers include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +0000134:const:`NaN` which stands for "Not a number", positive and negative
Christian Heimesfe337bf2008-03-23 21:54:12 +0000135:const:`Infinity`, and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000136
Facundo Batista789bdf02008-06-21 17:29:41 +0000137 >>> getcontext().prec = 28
Georg Brandl116aa622007-08-15 14:28:22 +0000138 >>> Decimal(10)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000139 Decimal('10')
140 >>> Decimal('3.14')
141 Decimal('3.14')
Mark Dickinsone534a072010-04-04 22:13:14 +0000142 >>> Decimal(3.14)
143 Decimal('3.140000000000000124344978758017532527446746826171875')
Georg Brandl116aa622007-08-15 14:28:22 +0000144 >>> Decimal((0, (3, 1, 4), -2))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000145 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000146 >>> Decimal(str(2.0 ** 0.5))
Alexander Belopolsky287d1fd2011-01-12 16:37:14 +0000147 Decimal('1.4142135623730951')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000148 >>> Decimal(2) ** Decimal('0.5')
149 Decimal('1.414213562373095048801688724')
150 >>> Decimal('NaN')
151 Decimal('NaN')
152 >>> Decimal('-Infinity')
153 Decimal('-Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155The significance of a new Decimal is determined solely by the number of digits
156input. Context precision and rounding only come into play during arithmetic
Christian Heimesfe337bf2008-03-23 21:54:12 +0000157operations.
158
159.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161 >>> getcontext().prec = 6
162 >>> Decimal('3.0')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000163 Decimal('3.0')
Georg Brandl116aa622007-08-15 14:28:22 +0000164 >>> Decimal('3.1415926535')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000165 Decimal('3.1415926535')
Georg Brandl116aa622007-08-15 14:28:22 +0000166 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000167 Decimal('5.85987')
Georg Brandl116aa622007-08-15 14:28:22 +0000168 >>> getcontext().rounding = ROUND_UP
169 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000170 Decimal('5.85988')
Georg Brandl116aa622007-08-15 14:28:22 +0000171
172Decimals interact well with much of the rest of Python. Here is a small decimal
Christian Heimesfe337bf2008-03-23 21:54:12 +0000173floating point flying circus:
174
175.. doctest::
176 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000177
Facundo Batista789bdf02008-06-21 17:29:41 +0000178 >>> 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 +0000179 >>> max(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000180 Decimal('9.25')
Georg Brandl116aa622007-08-15 14:28:22 +0000181 >>> min(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000182 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +0000183 >>> sorted(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000184 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
185 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl116aa622007-08-15 14:28:22 +0000186 >>> sum(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000187 Decimal('19.29')
Georg Brandl116aa622007-08-15 14:28:22 +0000188 >>> a,b,c = data[:3]
189 >>> str(a)
190 '1.34'
191 >>> float(a)
Mark Dickinson8dad7df2009-06-28 20:36:54 +0000192 1.34
193 >>> round(a, 1)
194 Decimal('1.3')
Georg Brandl116aa622007-08-15 14:28:22 +0000195 >>> int(a)
196 1
197 >>> a * 5
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000198 Decimal('6.70')
Georg Brandl116aa622007-08-15 14:28:22 +0000199 >>> a * b
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000200 Decimal('2.5058')
Georg Brandl116aa622007-08-15 14:28:22 +0000201 >>> c % a
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000202 Decimal('0.77')
Georg Brandl116aa622007-08-15 14:28:22 +0000203
Christian Heimesfe337bf2008-03-23 21:54:12 +0000204And some mathematical functions are also available to Decimal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000205
Facundo Batista789bdf02008-06-21 17:29:41 +0000206 >>> getcontext().prec = 28
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000207 >>> Decimal(2).sqrt()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000208 Decimal('1.414213562373095048801688724')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000209 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000210 Decimal('2.718281828459045235360287471')
211 >>> Decimal('10').ln()
212 Decimal('2.302585092994045684017991455')
213 >>> Decimal('10').log10()
214 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000215
Georg Brandl116aa622007-08-15 14:28:22 +0000216The :meth:`quantize` method rounds a number to a fixed exponent. This method is
217useful for monetary applications that often round results to a fixed number of
Christian Heimesfe337bf2008-03-23 21:54:12 +0000218places:
Georg Brandl116aa622007-08-15 14:28:22 +0000219
220 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000221 Decimal('7.32')
Georg Brandl116aa622007-08-15 14:28:22 +0000222 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000223 Decimal('8')
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225As shown above, the :func:`getcontext` function accesses the current context and
226allows the settings to be changed. This approach meets the needs of most
227applications.
228
229For more advanced work, it may be useful to create alternate contexts using the
230Context() constructor. To make an alternate active, use the :func:`setcontext`
231function.
232
233In accordance with the standard, the :mod:`Decimal` module provides two ready to
234use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
235former is especially useful for debugging because many of the traps are
Christian Heimesfe337bf2008-03-23 21:54:12 +0000236enabled:
237
238.. doctest:: newcontext
239 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000240
241 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
242 >>> setcontext(myothercontext)
243 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000244 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl116aa622007-08-15 14:28:22 +0000245
246 >>> ExtendedContext
247 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000248 capitals=1, clamp=0, flags=[], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000249 >>> setcontext(ExtendedContext)
250 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000251 Decimal('0.142857143')
Georg Brandl116aa622007-08-15 14:28:22 +0000252 >>> Decimal(42) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000253 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255 >>> setcontext(BasicContext)
256 >>> Decimal(42) / Decimal(0)
257 Traceback (most recent call last):
258 File "<pyshell#143>", line 1, in -toplevel-
259 Decimal(42) / Decimal(0)
260 DivisionByZero: x / 0
261
262Contexts also have signal flags for monitoring exceptional conditions
263encountered during computations. The flags remain set until explicitly cleared,
264so it is best to clear the flags before each set of monitored computations by
265using the :meth:`clear_flags` method. ::
266
267 >>> setcontext(ExtendedContext)
268 >>> getcontext().clear_flags()
269 >>> Decimal(355) / Decimal(113)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000270 Decimal('3.14159292')
Georg Brandl116aa622007-08-15 14:28:22 +0000271 >>> getcontext()
272 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000273 capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000274
275The *flags* entry shows that the rational approximation to :const:`Pi` was
276rounded (digits beyond the context precision were thrown away) and that the
277result is inexact (some of the discarded digits were non-zero).
278
279Individual traps are set using the dictionary in the :attr:`traps` field of a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000280context:
Georg Brandl116aa622007-08-15 14:28:22 +0000281
Christian Heimesfe337bf2008-03-23 21:54:12 +0000282.. doctest:: newcontext
283
284 >>> setcontext(ExtendedContext)
Georg Brandl116aa622007-08-15 14:28:22 +0000285 >>> Decimal(1) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000286 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000287 >>> getcontext().traps[DivisionByZero] = 1
288 >>> Decimal(1) / Decimal(0)
289 Traceback (most recent call last):
290 File "<pyshell#112>", line 1, in -toplevel-
291 Decimal(1) / Decimal(0)
292 DivisionByZero: x / 0
293
294Most programs adjust the current context only once, at the beginning of the
295program. And, in many applications, data is converted to :class:`Decimal` with
296a single cast inside a loop. With context set and decimals created, the bulk of
297the program manipulates the data no differently than with other Python numeric
298types.
299
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000300.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000301
302
303.. _decimal-decimal:
304
305Decimal objects
306---------------
307
308
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000309.. class:: Decimal(value="0", context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000310
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000311 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Raymond Hettinger96798592010-04-02 16:58:27 +0000313 *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal`
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000314 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Christian Heimesa62da1d2008-01-12 19:39:10 +0000315 string, it should conform to the decimal numeric string syntax after leading
316 and trailing whitespace characters are removed::
Georg Brandl116aa622007-08-15 14:28:22 +0000317
318 sign ::= '+' | '-'
319 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
320 indicator ::= 'e' | 'E'
321 digits ::= digit [digit]...
322 decimal-part ::= digits '.' [digits] | ['.'] digits
323 exponent-part ::= indicator [sign] digits
324 infinity ::= 'Infinity' | 'Inf'
325 nan ::= 'NaN' [digits] | 'sNaN' [digits]
326 numeric-value ::= decimal-part [exponent-part] | infinity
Georg Brandl48310cd2009-01-03 21:18:54 +0000327 numeric-string ::= [sign] numeric-value | [sign] nan
Georg Brandl116aa622007-08-15 14:28:22 +0000328
Mark Dickinson345adc42009-08-02 10:14:23 +0000329 Other Unicode decimal digits are also permitted where ``digit``
330 appears above. These include decimal digits from various other
331 alphabets (for example, Arabic-Indic and Devanāgarī digits) along
332 with the fullwidth digits ``'\uff10'`` through ``'\uff19'``.
333
Georg Brandl116aa622007-08-15 14:28:22 +0000334 If *value* is a :class:`tuple`, it should have three components, a sign
335 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
336 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000337 returns ``Decimal('1.414')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000338
Raymond Hettinger96798592010-04-02 16:58:27 +0000339 If *value* is a :class:`float`, the binary floating point value is losslessly
340 converted to its exact decimal equivalent. This conversion can often require
Mark Dickinsone534a072010-04-04 22:13:14 +0000341 53 or more digits of precision. For example, ``Decimal(float('1.1'))``
342 converts to
343 ``Decimal('1.100000000000000088817841970012523233890533447265625')``.
Raymond Hettinger96798592010-04-02 16:58:27 +0000344
Georg Brandl116aa622007-08-15 14:28:22 +0000345 The *context* precision does not affect how many digits are stored. That is
346 determined exclusively by the number of digits in *value*. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000347 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl116aa622007-08-15 14:28:22 +0000348 only three.
349
350 The purpose of the *context* argument is determining what to do if *value* is a
351 malformed string. If the context traps :const:`InvalidOperation`, an exception
352 is raised; otherwise, the constructor returns a new Decimal with the value of
353 :const:`NaN`.
354
355 Once constructed, :class:`Decimal` objects are immutable.
356
Mark Dickinsone534a072010-04-04 22:13:14 +0000357 .. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000358 The argument to the constructor is now permitted to be a :class:`float`
359 instance.
Mark Dickinsone534a072010-04-04 22:13:14 +0000360
Benjamin Petersone41251e2008-04-25 01:59:09 +0000361 Decimal floating point objects share many properties with the other built-in
362 numeric types such as :class:`float` and :class:`int`. All of the usual math
363 operations and special methods apply. Likewise, decimal objects can be
364 copied, pickled, printed, used as dictionary keys, used as set elements,
365 compared, sorted, and coerced to another type (such as :class:`float` or
Mark Dickinson5d233fd2010-02-18 14:54:37 +0000366 :class:`int`).
Christian Heimesa62da1d2008-01-12 19:39:10 +0000367
Mark Dickinsona3f37402012-11-18 10:22:05 +0000368 There are some small differences between arithmetic on Decimal objects and
369 arithmetic on integers and floats. When the remainder operator ``%`` is
370 applied to Decimal objects, the sign of the result is the sign of the
371 *dividend* rather than the sign of the divisor::
372
373 >>> (-7) % 4
374 1
375 >>> Decimal(-7) % Decimal(4)
376 Decimal('-3')
377
378 The integer division operator ``//`` behaves analogously, returning the
379 integer part of the true quotient (truncating towards zero) rather than its
380 floor, so as to preseve the usual identity ``x == (x // y) * y + x % y``::
381
382 >>> -7 // 4
383 -2
384 >>> Decimal(-7) // Decimal(4)
385 Decimal('-1')
386
387 The ``%`` and ``//`` operators implement the ``remainder`` and
388 ``divide-integer`` operations (respectively) as described in the
389 specification.
390
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000391 Decimal objects cannot generally be combined with floats or
392 instances of :class:`fractions.Fraction` in arithmetic operations:
393 an attempt to add a :class:`Decimal` to a :class:`float`, for
394 example, will raise a :exc:`TypeError`. However, it is possible to
395 use Python's comparison operators to compare a :class:`Decimal`
396 instance ``x`` with another number ``y``. This avoids confusing results
397 when doing equality comparisons between numbers of different types.
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000398
Ezio Melotti993a5ee2010-04-04 06:30:08 +0000399 .. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000400 Mixed-type comparisons between :class:`Decimal` instances and other
401 numeric types are now fully supported.
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000402
Benjamin Petersone41251e2008-04-25 01:59:09 +0000403 In addition to the standard numeric properties, decimal floating point
404 objects also have a number of specialized methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000405
Georg Brandl116aa622007-08-15 14:28:22 +0000406
Benjamin Petersone41251e2008-04-25 01:59:09 +0000407 .. method:: adjusted()
Georg Brandl116aa622007-08-15 14:28:22 +0000408
Benjamin Petersone41251e2008-04-25 01:59:09 +0000409 Return the adjusted exponent after shifting out the coefficient's
410 rightmost digits until only the lead digit remains:
411 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
412 position of the most significant digit with respect to the decimal point.
Georg Brandl116aa622007-08-15 14:28:22 +0000413
Georg Brandl116aa622007-08-15 14:28:22 +0000414
Benjamin Petersone41251e2008-04-25 01:59:09 +0000415 .. method:: as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +0000416
Benjamin Petersone41251e2008-04-25 01:59:09 +0000417 Return a :term:`named tuple` representation of the number:
418 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Christian Heimes25bb7832008-01-11 16:17:00 +0000420
Benjamin Petersone41251e2008-04-25 01:59:09 +0000421 .. method:: canonical()
Georg Brandl116aa622007-08-15 14:28:22 +0000422
Benjamin Petersone41251e2008-04-25 01:59:09 +0000423 Return the canonical encoding of the argument. Currently, the encoding of
424 a :class:`Decimal` instance is always canonical, so this operation returns
425 its argument unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000426
Benjamin Petersone41251e2008-04-25 01:59:09 +0000427 .. method:: compare(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000428
Georg Brandl05f5ab72008-09-24 09:11:47 +0000429 Compare the values of two Decimal instances. :meth:`compare` returns a
430 Decimal instance, and if either operand is a NaN then the result is a
431 NaN::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000432
Georg Brandl05f5ab72008-09-24 09:11:47 +0000433 a or b is a NaN ==> Decimal('NaN')
434 a < b ==> Decimal('-1')
435 a == b ==> Decimal('0')
436 a > b ==> Decimal('1')
Georg Brandl116aa622007-08-15 14:28:22 +0000437
Benjamin Petersone41251e2008-04-25 01:59:09 +0000438 .. method:: compare_signal(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000439
Benjamin Petersone41251e2008-04-25 01:59:09 +0000440 This operation is identical to the :meth:`compare` method, except that all
441 NaNs signal. That is, if neither operand is a signaling NaN then any
442 quiet NaN operand is treated as though it were a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000443
Benjamin Petersone41251e2008-04-25 01:59:09 +0000444 .. method:: compare_total(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000445
Benjamin Petersone41251e2008-04-25 01:59:09 +0000446 Compare two operands using their abstract representation rather than their
447 numerical value. Similar to the :meth:`compare` method, but the result
448 gives a total ordering on :class:`Decimal` instances. Two
449 :class:`Decimal` instances with the same numeric value but different
450 representations compare unequal in this ordering:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000451
Benjamin Petersone41251e2008-04-25 01:59:09 +0000452 >>> Decimal('12.0').compare_total(Decimal('12'))
453 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000454
Benjamin Petersone41251e2008-04-25 01:59:09 +0000455 Quiet and signaling NaNs are also included in the total ordering. The
456 result of this function is ``Decimal('0')`` if both operands have the same
457 representation, ``Decimal('-1')`` if the first operand is lower in the
458 total order than the second, and ``Decimal('1')`` if the first operand is
459 higher in the total order than the second operand. See the specification
460 for details of the total order.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000461
Benjamin Petersone41251e2008-04-25 01:59:09 +0000462 .. method:: compare_total_mag(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000463
Benjamin Petersone41251e2008-04-25 01:59:09 +0000464 Compare two operands using their abstract representation rather than their
465 value as in :meth:`compare_total`, but ignoring the sign of each operand.
466 ``x.compare_total_mag(y)`` is equivalent to
467 ``x.copy_abs().compare_total(y.copy_abs())``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000468
Facundo Batista789bdf02008-06-21 17:29:41 +0000469 .. method:: conjugate()
470
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000471 Just returns self, this method is only to comply with the Decimal
Facundo Batista789bdf02008-06-21 17:29:41 +0000472 Specification.
473
Benjamin Petersone41251e2008-04-25 01:59:09 +0000474 .. method:: copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000475
Benjamin Petersone41251e2008-04-25 01:59:09 +0000476 Return the absolute value of the argument. This operation is unaffected
477 by the context and is quiet: no flags are changed and no rounding is
478 performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000479
Benjamin Petersone41251e2008-04-25 01:59:09 +0000480 .. method:: copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000481
Benjamin Petersone41251e2008-04-25 01:59:09 +0000482 Return the negation of the argument. This operation is unaffected by the
483 context and is quiet: no flags are changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000484
Benjamin Petersone41251e2008-04-25 01:59:09 +0000485 .. method:: copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000486
Benjamin Petersone41251e2008-04-25 01:59:09 +0000487 Return a copy of the first operand with the sign set to be the same as the
488 sign of the second operand. For example:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000489
Benjamin Petersone41251e2008-04-25 01:59:09 +0000490 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
491 Decimal('-2.3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000492
Benjamin Petersone41251e2008-04-25 01:59:09 +0000493 This operation is unaffected by the context and is quiet: no flags are
494 changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000495
Benjamin Petersone41251e2008-04-25 01:59:09 +0000496 .. method:: exp([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000497
Benjamin Petersone41251e2008-04-25 01:59:09 +0000498 Return the value of the (natural) exponential function ``e**x`` at the
499 given number. The result is correctly rounded using the
500 :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000501
Benjamin Petersone41251e2008-04-25 01:59:09 +0000502 >>> Decimal(1).exp()
503 Decimal('2.718281828459045235360287471')
504 >>> Decimal(321).exp()
505 Decimal('2.561702493119680037517373933E+139')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000506
Raymond Hettinger771ed762009-01-03 19:20:32 +0000507 .. method:: from_float(f)
508
509 Classmethod that converts a float to a decimal number, exactly.
510
511 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
512 Since 0.1 is not exactly representable in binary floating point, the
513 value is stored as the nearest representable value which is
514 `0x1.999999999999ap-4`. That equivalent value in decimal is
515 `0.1000000000000000055511151231257827021181583404541015625`.
516
Mark Dickinsone534a072010-04-04 22:13:14 +0000517 .. note:: From Python 3.2 onwards, a :class:`Decimal` instance
518 can also be constructed directly from a :class:`float`.
519
Raymond Hettinger771ed762009-01-03 19:20:32 +0000520 .. doctest::
521
522 >>> Decimal.from_float(0.1)
523 Decimal('0.1000000000000000055511151231257827021181583404541015625')
524 >>> Decimal.from_float(float('nan'))
525 Decimal('NaN')
526 >>> Decimal.from_float(float('inf'))
527 Decimal('Infinity')
528 >>> Decimal.from_float(float('-inf'))
529 Decimal('-Infinity')
530
Georg Brandl45f53372009-01-03 21:15:20 +0000531 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000532
Benjamin Petersone41251e2008-04-25 01:59:09 +0000533 .. method:: fma(other, third[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000534
Benjamin Petersone41251e2008-04-25 01:59:09 +0000535 Fused multiply-add. Return self*other+third with no rounding of the
536 intermediate product self*other.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537
Benjamin Petersone41251e2008-04-25 01:59:09 +0000538 >>> Decimal(2).fma(3, 5)
539 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000540
Benjamin Petersone41251e2008-04-25 01:59:09 +0000541 .. method:: is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000542
Benjamin Petersone41251e2008-04-25 01:59:09 +0000543 Return :const:`True` if the argument is canonical and :const:`False`
544 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
545 this operation always returns :const:`True`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546
Benjamin Petersone41251e2008-04-25 01:59:09 +0000547 .. method:: is_finite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000548
Benjamin Petersone41251e2008-04-25 01:59:09 +0000549 Return :const:`True` if the argument is a finite number, and
550 :const:`False` if the argument is an infinity or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000551
Benjamin Petersone41251e2008-04-25 01:59:09 +0000552 .. method:: is_infinite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000553
Benjamin Petersone41251e2008-04-25 01:59:09 +0000554 Return :const:`True` if the argument is either positive or negative
555 infinity and :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000556
Benjamin Petersone41251e2008-04-25 01:59:09 +0000557 .. method:: is_nan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000558
Benjamin Petersone41251e2008-04-25 01:59:09 +0000559 Return :const:`True` if the argument is a (quiet or signaling) NaN and
560 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000561
Benjamin Petersone41251e2008-04-25 01:59:09 +0000562 .. method:: is_normal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563
Benjamin Petersone41251e2008-04-25 01:59:09 +0000564 Return :const:`True` if the argument is a *normal* finite number. Return
565 :const:`False` if the argument is zero, subnormal, infinite or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000566
Benjamin Petersone41251e2008-04-25 01:59:09 +0000567 .. method:: is_qnan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568
Benjamin Petersone41251e2008-04-25 01:59:09 +0000569 Return :const:`True` if the argument is a quiet NaN, and
570 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000571
Benjamin Petersone41251e2008-04-25 01:59:09 +0000572 .. method:: is_signed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000573
Benjamin Petersone41251e2008-04-25 01:59:09 +0000574 Return :const:`True` if the argument has a negative sign and
575 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000576
Benjamin Petersone41251e2008-04-25 01:59:09 +0000577 .. method:: is_snan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000578
Benjamin Petersone41251e2008-04-25 01:59:09 +0000579 Return :const:`True` if the argument is a signaling NaN and :const:`False`
580 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000581
Benjamin Petersone41251e2008-04-25 01:59:09 +0000582 .. method:: is_subnormal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000583
Benjamin Petersone41251e2008-04-25 01:59:09 +0000584 Return :const:`True` if the argument is subnormal, and :const:`False`
585 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000586
Benjamin Petersone41251e2008-04-25 01:59:09 +0000587 .. method:: is_zero()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000588
Benjamin Petersone41251e2008-04-25 01:59:09 +0000589 Return :const:`True` if the argument is a (positive or negative) zero and
590 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000591
Benjamin Petersone41251e2008-04-25 01:59:09 +0000592 .. method:: ln([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000593
Benjamin Petersone41251e2008-04-25 01:59:09 +0000594 Return the natural (base e) logarithm of the operand. The result is
595 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000596
Benjamin Petersone41251e2008-04-25 01:59:09 +0000597 .. method:: log10([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000598
Benjamin Petersone41251e2008-04-25 01:59:09 +0000599 Return the base ten logarithm of the operand. The result is correctly
600 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000601
Benjamin Petersone41251e2008-04-25 01:59:09 +0000602 .. method:: logb([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000603
Benjamin Petersone41251e2008-04-25 01:59:09 +0000604 For a nonzero number, return the adjusted exponent of its operand as a
605 :class:`Decimal` instance. If the operand is a zero then
606 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
607 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
608 returned.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000609
Benjamin Petersone41251e2008-04-25 01:59:09 +0000610 .. method:: logical_and(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000611
Benjamin Petersone41251e2008-04-25 01:59:09 +0000612 :meth:`logical_and` is a logical operation which takes two *logical
613 operands* (see :ref:`logical_operands_label`). The result is the
614 digit-wise ``and`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000615
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000616 .. method:: logical_invert([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000617
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000618 :meth:`logical_invert` is a logical operation. The
Benjamin Petersone41251e2008-04-25 01:59:09 +0000619 result is the digit-wise inversion of the operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000620
Benjamin Petersone41251e2008-04-25 01:59:09 +0000621 .. method:: logical_or(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000622
Benjamin Petersone41251e2008-04-25 01:59:09 +0000623 :meth:`logical_or` is a logical operation which takes two *logical
624 operands* (see :ref:`logical_operands_label`). The result is the
625 digit-wise ``or`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626
Benjamin Petersone41251e2008-04-25 01:59:09 +0000627 .. method:: logical_xor(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000628
Benjamin Petersone41251e2008-04-25 01:59:09 +0000629 :meth:`logical_xor` is a logical operation which takes two *logical
630 operands* (see :ref:`logical_operands_label`). The result is the
631 digit-wise exclusive or of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000632
Benjamin Petersone41251e2008-04-25 01:59:09 +0000633 .. method:: max(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634
Benjamin Petersone41251e2008-04-25 01:59:09 +0000635 Like ``max(self, other)`` except that the context rounding rule is applied
636 before returning and that :const:`NaN` values are either signaled or
637 ignored (depending on the context and whether they are signaling or
638 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000639
Benjamin Petersone41251e2008-04-25 01:59:09 +0000640 .. method:: max_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000641
Georg Brandl502d9a52009-07-26 15:02:41 +0000642 Similar to the :meth:`.max` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000643 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644
Benjamin Petersone41251e2008-04-25 01:59:09 +0000645 .. method:: min(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646
Benjamin Petersone41251e2008-04-25 01:59:09 +0000647 Like ``min(self, other)`` except that the context rounding rule is applied
648 before returning and that :const:`NaN` values are either signaled or
649 ignored (depending on the context and whether they are signaling or
650 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000651
Benjamin Petersone41251e2008-04-25 01:59:09 +0000652 .. method:: min_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653
Georg Brandl502d9a52009-07-26 15:02:41 +0000654 Similar to the :meth:`.min` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000655 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000656
Benjamin Petersone41251e2008-04-25 01:59:09 +0000657 .. method:: next_minus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658
Benjamin Petersone41251e2008-04-25 01:59:09 +0000659 Return the largest number representable in the given context (or in the
660 current thread's context if no context is given) that is smaller than the
661 given operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662
Benjamin Petersone41251e2008-04-25 01:59:09 +0000663 .. method:: next_plus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000664
Benjamin Petersone41251e2008-04-25 01:59:09 +0000665 Return the smallest number representable in the given context (or in the
666 current thread's context if no context is given) that is larger than the
667 given operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000668
Benjamin Petersone41251e2008-04-25 01:59:09 +0000669 .. method:: next_toward(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000670
Benjamin Petersone41251e2008-04-25 01:59:09 +0000671 If the two operands are unequal, return the number closest to the first
672 operand in the direction of the second operand. If both operands are
673 numerically equal, return a copy of the first operand with the sign set to
674 be the same as the sign of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000675
Benjamin Petersone41251e2008-04-25 01:59:09 +0000676 .. method:: normalize([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000677
Benjamin Petersone41251e2008-04-25 01:59:09 +0000678 Normalize the number by stripping the rightmost trailing zeros and
679 converting any result equal to :const:`Decimal('0')` to
Senthil Kumarana6bac952011-07-04 11:28:30 -0700680 :const:`Decimal('0e0')`. Used for producing canonical values for attributes
Benjamin Petersone41251e2008-04-25 01:59:09 +0000681 of an equivalence class. For example, ``Decimal('32.100')`` and
682 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
683 ``Decimal('32.1')``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000684
Benjamin Petersone41251e2008-04-25 01:59:09 +0000685 .. method:: number_class([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000686
Benjamin Petersone41251e2008-04-25 01:59:09 +0000687 Return a string describing the *class* of the operand. The returned value
688 is one of the following ten strings.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689
Benjamin Petersone41251e2008-04-25 01:59:09 +0000690 * ``"-Infinity"``, indicating that the operand is negative infinity.
691 * ``"-Normal"``, indicating that the operand is a negative normal number.
692 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
693 * ``"-Zero"``, indicating that the operand is a negative zero.
694 * ``"+Zero"``, indicating that the operand is a positive zero.
695 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
696 * ``"+Normal"``, indicating that the operand is a positive normal number.
697 * ``"+Infinity"``, indicating that the operand is positive infinity.
698 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
699 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000700
Benjamin Petersone41251e2008-04-25 01:59:09 +0000701 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000702
Benjamin Petersone41251e2008-04-25 01:59:09 +0000703 Return a value equal to the first operand after rounding and having the
704 exponent of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705
Benjamin Petersone41251e2008-04-25 01:59:09 +0000706 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
707 Decimal('1.414')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000708
Benjamin Petersone41251e2008-04-25 01:59:09 +0000709 Unlike other operations, if the length of the coefficient after the
710 quantize operation would be greater than precision, then an
711 :const:`InvalidOperation` is signaled. This guarantees that, unless there
712 is an error condition, the quantized exponent is always equal to that of
713 the right-hand operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000714
Benjamin Petersone41251e2008-04-25 01:59:09 +0000715 Also unlike other operations, quantize never signals Underflow, even if
716 the result is subnormal and inexact.
Georg Brandl116aa622007-08-15 14:28:22 +0000717
Benjamin Petersone41251e2008-04-25 01:59:09 +0000718 If the exponent of the second operand is larger than that of the first
719 then rounding may be necessary. In this case, the rounding mode is
720 determined by the ``rounding`` argument if given, else by the given
721 ``context`` argument; if neither argument is given the rounding mode of
722 the current thread's context is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000723
Benjamin Petersone41251e2008-04-25 01:59:09 +0000724 If *watchexp* is set (default), then an error is returned whenever the
725 resulting exponent is greater than :attr:`Emax` or less than
726 :attr:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +0000727
Benjamin Petersone41251e2008-04-25 01:59:09 +0000728 .. method:: radix()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000729
Benjamin Petersone41251e2008-04-25 01:59:09 +0000730 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
731 class does all its arithmetic. Included for compatibility with the
732 specification.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000733
Benjamin Petersone41251e2008-04-25 01:59:09 +0000734 .. method:: remainder_near(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000735
Mark Dickinson6ae568b2012-10-31 19:44:36 +0000736 Return the remainder from dividing *self* by *other*. This differs from
737 ``self % other`` in that the sign of the remainder is chosen so as to
738 minimize its absolute value. More precisely, the return value is
739 ``self - n * other`` where ``n`` is the integer nearest to the exact
740 value of ``self / other``, and if two integers are equally near then the
741 even one is chosen.
Georg Brandl116aa622007-08-15 14:28:22 +0000742
Mark Dickinson6ae568b2012-10-31 19:44:36 +0000743 If the result is zero then its sign will be the sign of *self*.
744
745 >>> Decimal(18).remainder_near(Decimal(10))
746 Decimal('-2')
747 >>> Decimal(25).remainder_near(Decimal(10))
748 Decimal('5')
749 >>> Decimal(35).remainder_near(Decimal(10))
750 Decimal('-5')
Georg Brandl116aa622007-08-15 14:28:22 +0000751
Benjamin Petersone41251e2008-04-25 01:59:09 +0000752 .. method:: rotate(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000753
Benjamin Petersone41251e2008-04-25 01:59:09 +0000754 Return the result of rotating the digits of the first operand by an amount
755 specified by the second operand. The second operand must be an integer in
756 the range -precision through precision. The absolute value of the second
757 operand gives the number of places to rotate. If the second operand is
758 positive then rotation is to the left; otherwise rotation is to the right.
759 The coefficient of the first operand is padded on the left with zeros to
760 length precision if necessary. The sign and exponent of the first operand
761 are unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000762
Benjamin Petersone41251e2008-04-25 01:59:09 +0000763 .. method:: same_quantum(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000764
Benjamin Petersone41251e2008-04-25 01:59:09 +0000765 Test whether self and other have the same exponent or whether both are
766 :const:`NaN`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000767
Benjamin Petersone41251e2008-04-25 01:59:09 +0000768 .. method:: scaleb(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000769
Benjamin Petersone41251e2008-04-25 01:59:09 +0000770 Return the first operand with exponent adjusted by the second.
771 Equivalently, return the first operand multiplied by ``10**other``. The
772 second operand must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +0000773
Benjamin Petersone41251e2008-04-25 01:59:09 +0000774 .. method:: shift(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000775
Benjamin Petersone41251e2008-04-25 01:59:09 +0000776 Return the result of shifting the digits of the first operand by an amount
777 specified by the second operand. The second operand must be an integer in
778 the range -precision through precision. The absolute value of the second
779 operand gives the number of places to shift. If the second operand is
780 positive then the shift is to the left; otherwise the shift is to the
781 right. Digits shifted into the coefficient are zeros. The sign and
782 exponent of the first operand are unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +0000783
Benjamin Petersone41251e2008-04-25 01:59:09 +0000784 .. method:: sqrt([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000785
Benjamin Petersone41251e2008-04-25 01:59:09 +0000786 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000787
Georg Brandl116aa622007-08-15 14:28:22 +0000788
Benjamin Petersone41251e2008-04-25 01:59:09 +0000789 .. method:: to_eng_string([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000790
Benjamin Petersone41251e2008-04-25 01:59:09 +0000791 Convert to an engineering-type string.
Georg Brandl116aa622007-08-15 14:28:22 +0000792
Benjamin Petersone41251e2008-04-25 01:59:09 +0000793 Engineering notation has an exponent which is a multiple of 3, so there
794 are up to 3 digits left of the decimal place. For example, converts
795 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000796
Benjamin Petersone41251e2008-04-25 01:59:09 +0000797 .. method:: to_integral([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000798
Benjamin Petersone41251e2008-04-25 01:59:09 +0000799 Identical to the :meth:`to_integral_value` method. The ``to_integral``
800 name has been kept for compatibility with older versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000801
Benjamin Petersone41251e2008-04-25 01:59:09 +0000802 .. method:: to_integral_exact([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000803
Benjamin Petersone41251e2008-04-25 01:59:09 +0000804 Round to the nearest integer, signaling :const:`Inexact` or
805 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
806 determined by the ``rounding`` parameter if given, else by the given
807 ``context``. If neither parameter is given then the rounding mode of the
808 current context is used.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000809
Benjamin Petersone41251e2008-04-25 01:59:09 +0000810 .. method:: to_integral_value([rounding[, context]])
Georg Brandl116aa622007-08-15 14:28:22 +0000811
Benjamin Petersone41251e2008-04-25 01:59:09 +0000812 Round to the nearest integer without signaling :const:`Inexact` or
813 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
814 rounding method in either the supplied *context* or the current context.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000815
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000816
817.. _logical_operands_label:
818
819Logical operands
820^^^^^^^^^^^^^^^^
821
822The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
823and :meth:`logical_xor` methods expect their arguments to be *logical
824operands*. A *logical operand* is a :class:`Decimal` instance whose
825exponent and sign are both zero, and whose digits are all either
826:const:`0` or :const:`1`.
827
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000828.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000829
830
831.. _decimal-context:
832
833Context objects
834---------------
835
836Contexts are environments for arithmetic operations. They govern precision, set
837rules for rounding, determine which signals are treated as exceptions, and limit
838the range for exponents.
839
840Each thread has its own current context which is accessed or changed using the
841:func:`getcontext` and :func:`setcontext` functions:
842
843
844.. function:: getcontext()
845
846 Return the current context for the active thread.
847
848
849.. function:: setcontext(c)
850
851 Set the current context for the active thread to *c*.
852
Georg Brandle6bcc912008-05-12 18:05:20 +0000853You can also use the :keyword:`with` statement and the :func:`localcontext`
854function to temporarily change the active context.
Georg Brandl116aa622007-08-15 14:28:22 +0000855
856.. function:: localcontext([c])
857
858 Return a context manager that will set the current context for the active thread
859 to a copy of *c* on entry to the with-statement and restore the previous context
860 when exiting the with-statement. If no context is specified, a copy of the
861 current context is used.
862
Georg Brandl116aa622007-08-15 14:28:22 +0000863 For example, the following code sets the current decimal precision to 42 places,
864 performs a calculation, and then automatically restores the previous context::
865
Georg Brandl116aa622007-08-15 14:28:22 +0000866 from decimal import localcontext
867
868 with localcontext() as ctx:
869 ctx.prec = 42 # Perform a high precision calculation
870 s = calculate_something()
871 s = +s # Round the final result back to the default precision
872
873New contexts can also be created using the :class:`Context` constructor
874described below. In addition, the module provides three pre-made contexts:
875
876
877.. class:: BasicContext
878
879 This is a standard context defined by the General Decimal Arithmetic
880 Specification. Precision is set to nine. Rounding is set to
881 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
882 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
883 :const:`Subnormal`.
884
885 Because many of the traps are enabled, this context is useful for debugging.
886
887
888.. class:: ExtendedContext
889
890 This is a standard context defined by the General Decimal Arithmetic
891 Specification. Precision is set to nine. Rounding is set to
892 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
893 exceptions are not raised during computations).
894
Christian Heimes3feef612008-02-11 06:19:17 +0000895 Because the traps are disabled, this context is useful for applications that
Georg Brandl116aa622007-08-15 14:28:22 +0000896 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
897 raising exceptions. This allows an application to complete a run in the
898 presence of conditions that would otherwise halt the program.
899
900
901.. class:: DefaultContext
902
903 This context is used by the :class:`Context` constructor as a prototype for new
904 contexts. Changing a field (such a precision) has the effect of changing the
Stefan Kraha1193932010-05-29 12:59:18 +0000905 default for new contexts created by the :class:`Context` constructor.
Georg Brandl116aa622007-08-15 14:28:22 +0000906
907 This context is most useful in multi-threaded environments. Changing one of the
908 fields before threads are started has the effect of setting system-wide
909 defaults. Changing the fields after threads have started is not recommended as
910 it would require thread synchronization to prevent race conditions.
911
912 In single threaded environments, it is preferable to not use this context at
913 all. Instead, simply create contexts explicitly as described below.
914
915 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
916 for Overflow, InvalidOperation, and DivisionByZero.
917
918In addition to the three supplied contexts, new contexts can be created with the
919:class:`Context` constructor.
920
921
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000922.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=None, clamp=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000923
924 Creates a new context. If a field is not specified or is :const:`None`, the
925 default values are copied from the :const:`DefaultContext`. If the *flags*
926 field is not specified or is :const:`None`, all flags are cleared.
927
928 The *prec* field is a positive integer that sets the precision for arithmetic
929 operations in the context.
930
931 The *rounding* option is one of:
932
933 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
934 * :const:`ROUND_DOWN` (towards zero),
935 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
936 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
937 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
938 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
939 * :const:`ROUND_UP` (away from zero).
Georg Brandl48310cd2009-01-03 21:18:54 +0000940 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000941 would have been 0 or 5; otherwise towards zero)
Georg Brandl116aa622007-08-15 14:28:22 +0000942
943 The *traps* and *flags* fields list any signals to be set. Generally, new
944 contexts should only set traps and leave the flags clear.
945
946 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
947 for exponents.
948
949 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
950 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
951 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
952
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000953 The *clamp* field is either :const:`0` (the default) or :const:`1`.
954 If set to :const:`1`, the exponent ``e`` of a :class:`Decimal`
955 instance representable in this context is strictly limited to the
956 range ``Emin - prec + 1 <= e <= Emax - prec + 1``. If *clamp* is
957 :const:`0` then a weaker condition holds: the adjusted exponent of
958 the :class:`Decimal` instance is at most ``Emax``. When *clamp* is
959 :const:`1`, a large normal number will, where possible, have its
960 exponent reduced and a corresponding number of zeros added to its
961 coefficient, in order to fit the exponent constraints; this
962 preserves the value of the number but loses information about
963 significant trailing zeros. For example::
964
965 >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
966 Decimal('1.23000E+999')
967
968 A *clamp* value of :const:`1` allows compatibility with the
969 fixed-width decimal interchange formats specified in IEEE 754.
Georg Brandl116aa622007-08-15 14:28:22 +0000970
Benjamin Petersone41251e2008-04-25 01:59:09 +0000971 The :class:`Context` class defines several general purpose methods as well as
972 a large number of methods for doing arithmetic directly in a given context.
973 In addition, for each of the :class:`Decimal` methods described above (with
974 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
Mark Dickinson84230a12010-02-18 14:49:50 +0000975 a corresponding :class:`Context` method. For example, for a :class:`Context`
976 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
977 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a
Mark Dickinson5d233fd2010-02-18 14:54:37 +0000978 Python integer (an instance of :class:`int`) anywhere that a
Mark Dickinson84230a12010-02-18 14:49:50 +0000979 Decimal instance is accepted.
Georg Brandl116aa622007-08-15 14:28:22 +0000980
981
Benjamin Petersone41251e2008-04-25 01:59:09 +0000982 .. method:: clear_flags()
Georg Brandl116aa622007-08-15 14:28:22 +0000983
Benjamin Petersone41251e2008-04-25 01:59:09 +0000984 Resets all of the flags to :const:`0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000985
Benjamin Petersone41251e2008-04-25 01:59:09 +0000986 .. method:: copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000987
Benjamin Petersone41251e2008-04-25 01:59:09 +0000988 Return a duplicate of the context.
Georg Brandl116aa622007-08-15 14:28:22 +0000989
Benjamin Petersone41251e2008-04-25 01:59:09 +0000990 .. method:: copy_decimal(num)
Georg Brandl116aa622007-08-15 14:28:22 +0000991
Benjamin Petersone41251e2008-04-25 01:59:09 +0000992 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +0000993
Benjamin Petersone41251e2008-04-25 01:59:09 +0000994 .. method:: create_decimal(num)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000995
Benjamin Petersone41251e2008-04-25 01:59:09 +0000996 Creates a new Decimal instance from *num* but using *self* as
997 context. Unlike the :class:`Decimal` constructor, the context precision,
998 rounding method, flags, and traps are applied to the conversion.
Georg Brandl116aa622007-08-15 14:28:22 +0000999
Benjamin Petersone41251e2008-04-25 01:59:09 +00001000 This is useful because constants are often given to a greater precision
1001 than is needed by the application. Another benefit is that rounding
1002 immediately eliminates unintended effects from digits beyond the current
1003 precision. In the following example, using unrounded inputs means that
1004 adding zero to a sum can change the result:
Georg Brandl116aa622007-08-15 14:28:22 +00001005
Benjamin Petersone41251e2008-04-25 01:59:09 +00001006 .. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001007
Benjamin Petersone41251e2008-04-25 01:59:09 +00001008 >>> getcontext().prec = 3
1009 >>> Decimal('3.4445') + Decimal('1.0023')
1010 Decimal('4.45')
1011 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1012 Decimal('4.44')
Georg Brandl116aa622007-08-15 14:28:22 +00001013
Benjamin Petersone41251e2008-04-25 01:59:09 +00001014 This method implements the to-number operation of the IBM specification.
1015 If the argument is a string, no leading or trailing whitespace is
1016 permitted.
1017
Georg Brandl45f53372009-01-03 21:15:20 +00001018 .. method:: create_decimal_from_float(f)
Raymond Hettinger771ed762009-01-03 19:20:32 +00001019
1020 Creates a new Decimal instance from a float *f* but rounding using *self*
Georg Brandl45f53372009-01-03 21:15:20 +00001021 as the context. Unlike the :meth:`Decimal.from_float` class method,
Raymond Hettinger771ed762009-01-03 19:20:32 +00001022 the context precision, rounding method, flags, and traps are applied to
1023 the conversion.
1024
1025 .. doctest::
1026
Georg Brandl45f53372009-01-03 21:15:20 +00001027 >>> context = Context(prec=5, rounding=ROUND_DOWN)
1028 >>> context.create_decimal_from_float(math.pi)
1029 Decimal('3.1415')
1030 >>> context = Context(prec=5, traps=[Inexact])
1031 >>> context.create_decimal_from_float(math.pi)
1032 Traceback (most recent call last):
1033 ...
1034 decimal.Inexact: None
Raymond Hettinger771ed762009-01-03 19:20:32 +00001035
Georg Brandl45f53372009-01-03 21:15:20 +00001036 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +00001037
Benjamin Petersone41251e2008-04-25 01:59:09 +00001038 .. method:: Etiny()
1039
1040 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
1041 value for subnormal results. When underflow occurs, the exponent is set
1042 to :const:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +00001043
Benjamin Petersone41251e2008-04-25 01:59:09 +00001044 .. method:: Etop()
Georg Brandl116aa622007-08-15 14:28:22 +00001045
Benjamin Petersone41251e2008-04-25 01:59:09 +00001046 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001047
Benjamin Petersone41251e2008-04-25 01:59:09 +00001048 The usual approach to working with decimals is to create :class:`Decimal`
1049 instances and then apply arithmetic operations which take place within the
1050 current context for the active thread. An alternative approach is to use
1051 context methods for calculating within a specific context. The methods are
1052 similar to those for the :class:`Decimal` class and are only briefly
1053 recounted here.
Georg Brandl116aa622007-08-15 14:28:22 +00001054
1055
Benjamin Petersone41251e2008-04-25 01:59:09 +00001056 .. method:: abs(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001057
Benjamin Petersone41251e2008-04-25 01:59:09 +00001058 Returns the absolute value of *x*.
Georg Brandl116aa622007-08-15 14:28:22 +00001059
1060
Benjamin Petersone41251e2008-04-25 01:59:09 +00001061 .. method:: add(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001062
Benjamin Petersone41251e2008-04-25 01:59:09 +00001063 Return the sum of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001064
1065
Facundo Batista789bdf02008-06-21 17:29:41 +00001066 .. method:: canonical(x)
1067
1068 Returns the same Decimal object *x*.
1069
1070
1071 .. method:: compare(x, y)
1072
1073 Compares *x* and *y* numerically.
1074
1075
1076 .. method:: compare_signal(x, y)
1077
1078 Compares the values of the two operands numerically.
1079
1080
1081 .. method:: compare_total(x, y)
1082
1083 Compares two operands using their abstract representation.
1084
1085
1086 .. method:: compare_total_mag(x, y)
1087
1088 Compares two operands using their abstract representation, ignoring sign.
1089
1090
1091 .. method:: copy_abs(x)
1092
1093 Returns a copy of *x* with the sign set to 0.
1094
1095
1096 .. method:: copy_negate(x)
1097
1098 Returns a copy of *x* with the sign inverted.
1099
1100
1101 .. method:: copy_sign(x, y)
1102
1103 Copies the sign from *y* to *x*.
1104
1105
Benjamin Petersone41251e2008-04-25 01:59:09 +00001106 .. method:: divide(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001107
Benjamin Petersone41251e2008-04-25 01:59:09 +00001108 Return *x* divided by *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001109
1110
Benjamin Petersone41251e2008-04-25 01:59:09 +00001111 .. method:: divide_int(x, y)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001112
Benjamin Petersone41251e2008-04-25 01:59:09 +00001113 Return *x* divided by *y*, truncated to an integer.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001114
1115
Benjamin Petersone41251e2008-04-25 01:59:09 +00001116 .. method:: divmod(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001117
Benjamin Petersone41251e2008-04-25 01:59:09 +00001118 Divides two numbers and returns the integer part of the result.
Georg Brandl116aa622007-08-15 14:28:22 +00001119
1120
Facundo Batista789bdf02008-06-21 17:29:41 +00001121 .. method:: exp(x)
1122
1123 Returns `e ** x`.
1124
1125
1126 .. method:: fma(x, y, z)
1127
1128 Returns *x* multiplied by *y*, plus *z*.
1129
1130
1131 .. method:: is_canonical(x)
1132
1133 Returns True if *x* is canonical; otherwise returns False.
1134
1135
1136 .. method:: is_finite(x)
1137
1138 Returns True if *x* is finite; otherwise returns False.
1139
1140
1141 .. method:: is_infinite(x)
1142
1143 Returns True if *x* is infinite; otherwise returns False.
1144
1145
1146 .. method:: is_nan(x)
1147
1148 Returns True if *x* is a qNaN or sNaN; otherwise returns False.
1149
1150
1151 .. method:: is_normal(x)
1152
1153 Returns True if *x* is a normal number; otherwise returns False.
1154
1155
1156 .. method:: is_qnan(x)
1157
1158 Returns True if *x* is a quiet NaN; otherwise returns False.
1159
1160
1161 .. method:: is_signed(x)
1162
1163 Returns True if *x* is negative; otherwise returns False.
1164
1165
1166 .. method:: is_snan(x)
1167
1168 Returns True if *x* is a signaling NaN; otherwise returns False.
1169
1170
1171 .. method:: is_subnormal(x)
1172
1173 Returns True if *x* is subnormal; otherwise returns False.
1174
1175
1176 .. method:: is_zero(x)
1177
1178 Returns True if *x* is a zero; otherwise returns False.
1179
1180
1181 .. method:: ln(x)
1182
1183 Returns the natural (base e) logarithm of *x*.
1184
1185
1186 .. method:: log10(x)
1187
1188 Returns the base 10 logarithm of *x*.
1189
1190
1191 .. method:: logb(x)
1192
1193 Returns the exponent of the magnitude of the operand's MSD.
1194
1195
1196 .. method:: logical_and(x, y)
1197
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001198 Applies the logical operation *and* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001199
1200
1201 .. method:: logical_invert(x)
1202
1203 Invert all the digits in *x*.
1204
1205
1206 .. method:: logical_or(x, y)
1207
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001208 Applies the logical operation *or* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001209
1210
1211 .. method:: logical_xor(x, y)
1212
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001213 Applies the logical operation *xor* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001214
1215
1216 .. method:: max(x, y)
1217
1218 Compares two values numerically and returns the maximum.
1219
1220
1221 .. method:: max_mag(x, y)
1222
1223 Compares the values numerically with their sign ignored.
1224
1225
1226 .. method:: min(x, y)
1227
1228 Compares two values numerically and returns the minimum.
1229
1230
1231 .. method:: min_mag(x, y)
1232
1233 Compares the values numerically with their sign ignored.
1234
1235
Benjamin Petersone41251e2008-04-25 01:59:09 +00001236 .. method:: minus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001237
Benjamin Petersone41251e2008-04-25 01:59:09 +00001238 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001239
1240
Benjamin Petersone41251e2008-04-25 01:59:09 +00001241 .. method:: multiply(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001242
Benjamin Petersone41251e2008-04-25 01:59:09 +00001243 Return the product of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001244
1245
Facundo Batista789bdf02008-06-21 17:29:41 +00001246 .. method:: next_minus(x)
1247
1248 Returns the largest representable number smaller than *x*.
1249
1250
1251 .. method:: next_plus(x)
1252
1253 Returns the smallest representable number larger than *x*.
1254
1255
1256 .. method:: next_toward(x, y)
1257
1258 Returns the number closest to *x*, in direction towards *y*.
1259
1260
1261 .. method:: normalize(x)
1262
1263 Reduces *x* to its simplest form.
1264
1265
1266 .. method:: number_class(x)
1267
1268 Returns an indication of the class of *x*.
1269
1270
Benjamin Petersone41251e2008-04-25 01:59:09 +00001271 .. method:: plus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001272
Benjamin Petersone41251e2008-04-25 01:59:09 +00001273 Plus corresponds to the unary prefix plus operator in Python. This
1274 operation applies the context precision and rounding, so it is *not* an
1275 identity operation.
Georg Brandl116aa622007-08-15 14:28:22 +00001276
1277
Benjamin Petersone41251e2008-04-25 01:59:09 +00001278 .. method:: power(x, y[, modulo])
Georg Brandl116aa622007-08-15 14:28:22 +00001279
Benjamin Petersone41251e2008-04-25 01:59:09 +00001280 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl116aa622007-08-15 14:28:22 +00001281
Benjamin Petersone41251e2008-04-25 01:59:09 +00001282 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1283 must be integral. The result will be inexact unless ``y`` is integral and
1284 the result is finite and can be expressed exactly in 'precision' digits.
1285 The result should always be correctly rounded, using the rounding mode of
1286 the current thread's context.
Georg Brandl116aa622007-08-15 14:28:22 +00001287
Benjamin Petersone41251e2008-04-25 01:59:09 +00001288 With three arguments, compute ``(x**y) % modulo``. For the three argument
1289 form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +00001290
Benjamin Petersone41251e2008-04-25 01:59:09 +00001291 - all three arguments must be integral
1292 - ``y`` must be nonnegative
1293 - at least one of ``x`` or ``y`` must be nonzero
1294 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +00001295
Mark Dickinson5961b0e2010-02-22 15:41:48 +00001296 The value resulting from ``Context.power(x, y, modulo)`` is
1297 equal to the value that would be obtained by computing ``(x**y)
1298 % modulo`` with unbounded precision, but is computed more
1299 efficiently. The exponent of the result is zero, regardless of
1300 the exponents of ``x``, ``y`` and ``modulo``. The result is
1301 always exact.
Georg Brandl116aa622007-08-15 14:28:22 +00001302
Facundo Batista789bdf02008-06-21 17:29:41 +00001303
1304 .. method:: quantize(x, y)
1305
1306 Returns a value equal to *x* (rounded), having the exponent of *y*.
1307
1308
1309 .. method:: radix()
1310
1311 Just returns 10, as this is Decimal, :)
1312
1313
Benjamin Petersone41251e2008-04-25 01:59:09 +00001314 .. method:: remainder(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001315
Benjamin Petersone41251e2008-04-25 01:59:09 +00001316 Returns the remainder from integer division.
Georg Brandl116aa622007-08-15 14:28:22 +00001317
Benjamin Petersone41251e2008-04-25 01:59:09 +00001318 The sign of the result, if non-zero, is the same as that of the original
1319 dividend.
Georg Brandl116aa622007-08-15 14:28:22 +00001320
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001321
Facundo Batista789bdf02008-06-21 17:29:41 +00001322 .. method:: remainder_near(x, y)
1323
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001324 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1325 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
Facundo Batista789bdf02008-06-21 17:29:41 +00001326
1327
1328 .. method:: rotate(x, y)
1329
1330 Returns a rotated copy of *x*, *y* times.
1331
1332
1333 .. method:: same_quantum(x, y)
1334
1335 Returns True if the two operands have the same exponent.
1336
1337
1338 .. method:: scaleb (x, y)
1339
1340 Returns the first operand after adding the second value its exp.
1341
1342
1343 .. method:: shift(x, y)
1344
1345 Returns a shifted copy of *x*, *y* times.
1346
1347
1348 .. method:: sqrt(x)
1349
1350 Square root of a non-negative number to context precision.
1351
1352
Benjamin Petersone41251e2008-04-25 01:59:09 +00001353 .. method:: subtract(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001354
Benjamin Petersone41251e2008-04-25 01:59:09 +00001355 Return the difference between *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001356
Facundo Batista789bdf02008-06-21 17:29:41 +00001357
1358 .. method:: to_eng_string(x)
1359
1360 Converts a number to a string, using scientific notation.
1361
1362
1363 .. method:: to_integral_exact(x)
1364
1365 Rounds to an integer.
1366
1367
Benjamin Petersone41251e2008-04-25 01:59:09 +00001368 .. method:: to_sci_string(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001369
Benjamin Petersone41251e2008-04-25 01:59:09 +00001370 Converts a number to a string using scientific notation.
Georg Brandl116aa622007-08-15 14:28:22 +00001371
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001372.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001373
1374
1375.. _decimal-signals:
1376
1377Signals
1378-------
1379
1380Signals represent conditions that arise during computation. Each corresponds to
1381one context flag and one context trap enabler.
1382
Raymond Hettinger86173da2008-02-01 20:38:12 +00001383The context flag is set whenever the condition is encountered. After the
Georg Brandl116aa622007-08-15 14:28:22 +00001384computation, flags may be checked for informational purposes (for instance, to
1385determine whether a computation was exact). After checking the flags, be sure to
1386clear all flags before starting the next computation.
1387
1388If the context's trap enabler is set for the signal, then the condition causes a
1389Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1390is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1391condition.
1392
1393
1394.. class:: Clamped
1395
1396 Altered an exponent to fit representation constraints.
1397
1398 Typically, clamping occurs when an exponent falls outside the context's
1399 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001400 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001401
1402
1403.. class:: DecimalException
1404
1405 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1406
1407
1408.. class:: DivisionByZero
1409
1410 Signals the division of a non-infinite number by zero.
1411
1412 Can occur with division, modulo division, or when raising a number to a negative
1413 power. If this signal is not trapped, returns :const:`Infinity` or
1414 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1415
1416
1417.. class:: Inexact
1418
1419 Indicates that rounding occurred and the result is not exact.
1420
1421 Signals when non-zero digits were discarded during rounding. The rounded result
1422 is returned. The signal flag or trap is used to detect when results are
1423 inexact.
1424
1425
1426.. class:: InvalidOperation
1427
1428 An invalid operation was performed.
1429
1430 Indicates that an operation was requested that does not make sense. If not
1431 trapped, returns :const:`NaN`. Possible causes include::
1432
1433 Infinity - Infinity
1434 0 * Infinity
1435 Infinity / Infinity
1436 x % 0
1437 Infinity % x
1438 x._rescale( non-integer )
1439 sqrt(-x) and x > 0
1440 0 ** 0
1441 x ** (non-integer)
Georg Brandl48310cd2009-01-03 21:18:54 +00001442 x ** Infinity
Georg Brandl116aa622007-08-15 14:28:22 +00001443
1444
1445.. class:: Overflow
1446
1447 Numerical overflow.
1448
Benjamin Petersone41251e2008-04-25 01:59:09 +00001449 Indicates the exponent is larger than :attr:`Emax` after rounding has
1450 occurred. If not trapped, the result depends on the rounding mode, either
1451 pulling inward to the largest representable finite number or rounding outward
1452 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1453 are also signaled.
Georg Brandl116aa622007-08-15 14:28:22 +00001454
1455
1456.. class:: Rounded
1457
1458 Rounding occurred though possibly no information was lost.
1459
Benjamin Petersone41251e2008-04-25 01:59:09 +00001460 Signaled whenever rounding discards digits; even if those digits are zero
1461 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1462 the result unchanged. This signal is used to detect loss of significant
1463 digits.
Georg Brandl116aa622007-08-15 14:28:22 +00001464
1465
1466.. class:: Subnormal
1467
1468 Exponent was lower than :attr:`Emin` prior to rounding.
1469
Benjamin Petersone41251e2008-04-25 01:59:09 +00001470 Occurs when an operation result is subnormal (the exponent is too small). If
1471 not trapped, returns the result unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +00001472
1473
1474.. class:: Underflow
1475
1476 Numerical underflow with result rounded to zero.
1477
1478 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1479 and :class:`Subnormal` are also signaled.
1480
1481The following table summarizes the hierarchy of signals::
1482
1483 exceptions.ArithmeticError(exceptions.Exception)
1484 DecimalException
1485 Clamped
1486 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1487 Inexact
1488 Overflow(Inexact, Rounded)
1489 Underflow(Inexact, Rounded, Subnormal)
1490 InvalidOperation
1491 Rounded
1492 Subnormal
1493
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001494.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001495
1496
1497.. _decimal-notes:
1498
1499Floating Point Notes
1500--------------------
1501
1502
1503Mitigating round-off error with increased precision
1504^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1505
1506The use of decimal floating point eliminates decimal representation error
1507(making it possible to represent :const:`0.1` exactly); however, some operations
1508can still incur round-off error when non-zero digits exceed the fixed precision.
1509
1510The effects of round-off error can be amplified by the addition or subtraction
1511of nearly offsetting quantities resulting in loss of significance. Knuth
1512provides two instructive examples where rounded floating point arithmetic with
1513insufficient precision causes the breakdown of the associative and distributive
Christian Heimesfe337bf2008-03-23 21:54:12 +00001514properties of addition:
1515
1516.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001517
1518 # Examples from Seminumerical Algorithms, Section 4.2.2.
1519 >>> from decimal import Decimal, getcontext
1520 >>> getcontext().prec = 8
1521
1522 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1523 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001524 Decimal('9.5111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001525 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001526 Decimal('10')
Georg Brandl116aa622007-08-15 14:28:22 +00001527
1528 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1529 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001530 Decimal('0.01')
Georg Brandl116aa622007-08-15 14:28:22 +00001531 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001532 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001533
1534The :mod:`decimal` module makes it possible to restore the identities by
Christian Heimesfe337bf2008-03-23 21:54:12 +00001535expanding the precision sufficiently to avoid loss of significance:
1536
1537.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001538
1539 >>> getcontext().prec = 20
1540 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1541 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001542 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001543 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001544 Decimal('9.51111111')
Georg Brandl48310cd2009-01-03 21:18:54 +00001545 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001546 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1547 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001548 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001549 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001550 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001551
1552
1553Special values
1554^^^^^^^^^^^^^^
1555
1556The number system for the :mod:`decimal` module provides special values
1557including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001558and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001559
1560Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1561they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1562not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1563can result from rounding beyond the limits of the largest representable number.
1564
1565The infinities are signed (affine) and can be used in arithmetic operations
1566where they get treated as very large, indeterminate numbers. For instance,
1567adding a constant to infinity gives another infinite result.
1568
1569Some operations are indeterminate and return :const:`NaN`, or if the
1570:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1571``0/0`` returns :const:`NaN` which means "not a number". This variety of
1572:const:`NaN` is quiet and, once created, will flow through other computations
1573always resulting in another :const:`NaN`. This behavior can be useful for a
1574series of computations that occasionally have missing inputs --- it allows the
1575calculation to proceed while flagging specific results as invalid.
1576
1577A variant is :const:`sNaN` which signals rather than remaining quiet after every
1578operation. This is a useful return value when an invalid result needs to
1579interrupt a calculation for special handling.
1580
Christian Heimes77c02eb2008-02-09 02:18:51 +00001581The behavior of Python's comparison operators can be a little surprising where a
1582:const:`NaN` is involved. A test for equality where one of the operands is a
1583quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1584``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1585:const:`True`. An attempt to compare two Decimals using any of the ``<``,
1586``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1587if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes3feef612008-02-11 06:19:17 +00001588not trapped. Note that the General Decimal Arithmetic specification does not
Christian Heimes77c02eb2008-02-09 02:18:51 +00001589specify the behavior of direct comparisons; these rules for comparisons
1590involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1591section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1592and :meth:`compare-signal` methods instead.
1593
Georg Brandl116aa622007-08-15 14:28:22 +00001594The signed zeros can result from calculations that underflow. They keep the sign
1595that would have resulted if the calculation had been carried out to greater
1596precision. Since their magnitude is zero, both positive and negative zeros are
1597treated as equal and their sign is informational.
1598
1599In addition to the two signed zeros which are distinct yet equal, there are
1600various representations of zero with differing precisions yet equivalent in
1601value. This takes a bit of getting used to. For an eye accustomed to
1602normalized floating point representations, it is not immediately obvious that
Christian Heimesfe337bf2008-03-23 21:54:12 +00001603the following calculation returns a value equal to zero:
Georg Brandl116aa622007-08-15 14:28:22 +00001604
1605 >>> 1 / Decimal('Infinity')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001606 Decimal('0E-1000000026')
Georg Brandl116aa622007-08-15 14:28:22 +00001607
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001608.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001609
1610
1611.. _decimal-threads:
1612
1613Working with threads
1614--------------------
1615
1616The :func:`getcontext` function accesses a different :class:`Context` object for
1617each thread. Having separate thread contexts means that threads may make
1618changes (such as ``getcontext.prec=10``) without interfering with other threads.
1619
1620Likewise, the :func:`setcontext` function automatically assigns its target to
1621the current thread.
1622
1623If :func:`setcontext` has not been called before :func:`getcontext`, then
1624:func:`getcontext` will automatically create a new context for use in the
1625current thread.
1626
1627The new context is copied from a prototype context called *DefaultContext*. To
1628control the defaults so that each thread will use the same values throughout the
1629application, directly modify the *DefaultContext* object. This should be done
1630*before* any threads are started so that there won't be a race condition between
1631threads calling :func:`getcontext`. For example::
1632
1633 # Set applicationwide defaults for all threads about to be launched
1634 DefaultContext.prec = 12
1635 DefaultContext.rounding = ROUND_DOWN
1636 DefaultContext.traps = ExtendedContext.traps.copy()
1637 DefaultContext.traps[InvalidOperation] = 1
1638 setcontext(DefaultContext)
1639
1640 # Afterwards, the threads can be started
1641 t1.start()
1642 t2.start()
1643 t3.start()
1644 . . .
1645
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001646.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001647
1648
1649.. _decimal-recipes:
1650
1651Recipes
1652-------
1653
1654Here are a few recipes that serve as utility functions and that demonstrate ways
1655to work with the :class:`Decimal` class::
1656
1657 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1658 pos='', neg='-', trailneg=''):
1659 """Convert Decimal to a money formatted string.
1660
1661 places: required number of places after the decimal point
1662 curr: optional currency symbol before the sign (may be blank)
1663 sep: optional grouping separator (comma, period, space, or blank)
1664 dp: decimal point indicator (comma or period)
1665 only specify as blank when places is zero
1666 pos: optional sign for positive numbers: '+', space or blank
1667 neg: optional sign for negative numbers: '-', '(', space or blank
1668 trailneg:optional trailing minus indicator: '-', ')', space or blank
1669
1670 >>> d = Decimal('-1234567.8901')
1671 >>> moneyfmt(d, curr='$')
1672 '-$1,234,567.89'
1673 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1674 '1.234.568-'
1675 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1676 '($1,234,567.89)'
1677 >>> moneyfmt(Decimal(123456789), sep=' ')
1678 '123 456 789.00'
1679 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Christian Heimesdae2a892008-04-19 00:55:37 +00001680 '<0.02>'
Georg Brandl116aa622007-08-15 14:28:22 +00001681
1682 """
Christian Heimesa156e092008-02-16 07:38:31 +00001683 q = Decimal(10) ** -places # 2 places --> '0.01'
Georg Brandl48310cd2009-01-03 21:18:54 +00001684 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +00001685 result = []
Facundo Batista789bdf02008-06-21 17:29:41 +00001686 digits = list(map(str, digits))
Georg Brandl116aa622007-08-15 14:28:22 +00001687 build, next = result.append, digits.pop
1688 if sign:
1689 build(trailneg)
1690 for i in range(places):
Christian Heimesa156e092008-02-16 07:38:31 +00001691 build(next() if digits else '0')
Raymond Hettinger0ab10e42011-01-08 09:03:11 +00001692 if places:
1693 build(dp)
Christian Heimesdae2a892008-04-19 00:55:37 +00001694 if not digits:
1695 build('0')
Georg Brandl116aa622007-08-15 14:28:22 +00001696 i = 0
1697 while digits:
1698 build(next())
1699 i += 1
1700 if i == 3 and digits:
1701 i = 0
1702 build(sep)
1703 build(curr)
Christian Heimesa156e092008-02-16 07:38:31 +00001704 build(neg if sign else pos)
1705 return ''.join(reversed(result))
Georg Brandl116aa622007-08-15 14:28:22 +00001706
1707 def pi():
1708 """Compute Pi to the current precision.
1709
Georg Brandl6911e3c2007-09-04 07:15:32 +00001710 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001711 3.141592653589793238462643383
1712
1713 """
1714 getcontext().prec += 2 # extra digits for intermediate steps
1715 three = Decimal(3) # substitute "three=3.0" for regular floats
1716 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1717 while s != lasts:
1718 lasts = s
1719 n, na = n+na, na+8
1720 d, da = d+da, da+32
1721 t = (t * n) / d
1722 s += t
1723 getcontext().prec -= 2
1724 return +s # unary plus applies the new precision
1725
1726 def exp(x):
1727 """Return e raised to the power of x. Result type matches input type.
1728
Georg Brandl6911e3c2007-09-04 07:15:32 +00001729 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001730 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001731 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001732 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001733 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001734 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001735 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001736 (7.38905609893+0j)
1737
1738 """
1739 getcontext().prec += 2
1740 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1741 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001742 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001743 i += 1
1744 fact *= i
Georg Brandl48310cd2009-01-03 21:18:54 +00001745 num *= x
1746 s += num / fact
1747 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001748 return +s
1749
1750 def cos(x):
1751 """Return the cosine of x as measured in radians.
1752
Mark Dickinsonb2b23822010-11-21 07:37:49 +00001753 The Taylor series approximation works best for a small value of x.
Raymond Hettinger2a1e3e22010-11-21 02:47:22 +00001754 For larger values, first compute x = x % (2 * pi).
1755
Georg Brandl6911e3c2007-09-04 07:15:32 +00001756 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001757 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001758 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001759 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001760 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001761 (0.87758256189+0j)
1762
1763 """
1764 getcontext().prec += 2
1765 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1766 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001767 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001768 i += 2
1769 fact *= i * (i-1)
1770 num *= x * x
1771 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001772 s += num / fact * sign
1773 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001774 return +s
1775
1776 def sin(x):
1777 """Return the sine of x as measured in radians.
1778
Mark Dickinsonb2b23822010-11-21 07:37:49 +00001779 The Taylor series approximation works best for a small value of x.
Raymond Hettinger2a1e3e22010-11-21 02:47:22 +00001780 For larger values, first compute x = x % (2 * pi).
1781
Georg Brandl6911e3c2007-09-04 07:15:32 +00001782 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001783 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001784 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001785 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001786 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001787 (0.479425538604+0j)
1788
1789 """
1790 getcontext().prec += 2
1791 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1792 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001793 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001794 i += 2
1795 fact *= i * (i-1)
1796 num *= x * x
1797 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001798 s += num / fact * sign
1799 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001800 return +s
1801
1802
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001803.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001804
1805
1806.. _decimal-faq:
1807
1808Decimal FAQ
1809-----------
1810
1811Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1812minimize typing when using the interactive interpreter?
1813
Christian Heimesfe337bf2008-03-23 21:54:12 +00001814A. Some users abbreviate the constructor to just a single letter:
Georg Brandl116aa622007-08-15 14:28:22 +00001815
1816 >>> D = decimal.Decimal
1817 >>> D('1.23') + D('3.45')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001818 Decimal('4.68')
Georg Brandl116aa622007-08-15 14:28:22 +00001819
1820Q. In a fixed-point application with two decimal places, some inputs have many
1821places and need to be rounded. Others are not supposed to have excess digits
1822and need to be validated. What methods should be used?
1823
1824A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Christian Heimesfe337bf2008-03-23 21:54:12 +00001825the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl116aa622007-08-15 14:28:22 +00001826
1827 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1828
1829 >>> # Round to two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001830 >>> Decimal('3.214').quantize(TWOPLACES)
1831 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001832
Georg Brandl48310cd2009-01-03 21:18:54 +00001833 >>> # Validate that a number does not exceed two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001834 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1835 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001836
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001837 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl116aa622007-08-15 14:28:22 +00001838 Traceback (most recent call last):
1839 ...
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001840 Inexact: None
Georg Brandl116aa622007-08-15 14:28:22 +00001841
1842Q. Once I have valid two place inputs, how do I maintain that invariant
1843throughout an application?
1844
Christian Heimesa156e092008-02-16 07:38:31 +00001845A. Some operations like addition, subtraction, and multiplication by an integer
1846will automatically preserve fixed point. Others operations, like division and
1847non-integer multiplication, will change the number of decimal places and need to
Christian Heimesfe337bf2008-03-23 21:54:12 +00001848be followed-up with a :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001849
1850 >>> a = Decimal('102.72') # Initial fixed-point values
1851 >>> b = Decimal('3.17')
1852 >>> a + b # Addition preserves fixed-point
1853 Decimal('105.89')
1854 >>> a - b
1855 Decimal('99.55')
1856 >>> a * 42 # So does integer multiplication
1857 Decimal('4314.24')
1858 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1859 Decimal('325.62')
1860 >>> (b / a).quantize(TWOPLACES) # And quantize division
1861 Decimal('0.03')
1862
1863In developing fixed-point applications, it is convenient to define functions
Christian Heimesfe337bf2008-03-23 21:54:12 +00001864to handle the :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001865
1866 >>> def mul(x, y, fp=TWOPLACES):
1867 ... return (x * y).quantize(fp)
1868 >>> def div(x, y, fp=TWOPLACES):
1869 ... return (x / y).quantize(fp)
1870
1871 >>> mul(a, b) # Automatically preserve fixed-point
1872 Decimal('325.62')
1873 >>> div(b, a)
1874 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +00001875
1876Q. There are many ways to express the same value. The numbers :const:`200`,
1877:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1878various precisions. Is there a way to transform them to a single recognizable
1879canonical value?
1880
1881A. The :meth:`normalize` method maps all equivalent values to a single
Christian Heimesfe337bf2008-03-23 21:54:12 +00001882representative:
Georg Brandl116aa622007-08-15 14:28:22 +00001883
1884 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1885 >>> [v.normalize() for v in values]
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001886 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl116aa622007-08-15 14:28:22 +00001887
1888Q. Some decimal values always print with exponential notation. Is there a way
1889to get a non-exponential representation?
1890
1891A. For some values, exponential notation is the only way to express the number
1892of significant places in the coefficient. For example, expressing
1893:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1894original's two-place significance.
1895
Christian Heimesa156e092008-02-16 07:38:31 +00001896If an application does not care about tracking significance, it is easy to
Christian Heimesc3f30c42008-02-22 16:37:40 +00001897remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001898value unchanged:
Christian Heimesa156e092008-02-16 07:38:31 +00001899
1900 >>> def remove_exponent(d):
1901 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1902
1903 >>> remove_exponent(Decimal('5E+3'))
1904 Decimal('5000')
1905
Georg Brandl116aa622007-08-15 14:28:22 +00001906Q. Is there a way to convert a regular float to a :class:`Decimal`?
1907
Mark Dickinsone534a072010-04-04 22:13:14 +00001908A. Yes, any binary floating point number can be exactly expressed as a
Raymond Hettinger96798592010-04-02 16:58:27 +00001909Decimal though an exact conversion may take more precision than intuition would
1910suggest:
Georg Brandl116aa622007-08-15 14:28:22 +00001911
Christian Heimesfe337bf2008-03-23 21:54:12 +00001912.. doctest::
1913
Raymond Hettinger96798592010-04-02 16:58:27 +00001914 >>> Decimal(math.pi)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001915 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl116aa622007-08-15 14:28:22 +00001916
Georg Brandl116aa622007-08-15 14:28:22 +00001917Q. Within a complex calculation, how can I make sure that I haven't gotten a
1918spurious result because of insufficient precision or rounding anomalies.
1919
1920A. The decimal module makes it easy to test results. A best practice is to
1921re-run calculations using greater precision and with various rounding modes.
1922Widely differing results indicate insufficient precision, rounding mode issues,
1923ill-conditioned inputs, or a numerically unstable algorithm.
1924
1925Q. I noticed that context precision is applied to the results of operations but
1926not to the inputs. Is there anything to watch out for when mixing values of
1927different precisions?
1928
1929A. Yes. The principle is that all values are considered to be exact and so is
1930the arithmetic on those values. Only the results are rounded. The advantage
1931for inputs is that "what you type is what you get". A disadvantage is that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001932results can look odd if you forget that the inputs haven't been rounded:
1933
1934.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001935
1936 >>> getcontext().prec = 3
Christian Heimesfe337bf2008-03-23 21:54:12 +00001937 >>> Decimal('3.104') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001938 Decimal('5.21')
Christian Heimesfe337bf2008-03-23 21:54:12 +00001939 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001940 Decimal('5.20')
Georg Brandl116aa622007-08-15 14:28:22 +00001941
1942The solution is either to increase precision or to force rounding of inputs
Christian Heimesfe337bf2008-03-23 21:54:12 +00001943using the unary plus operation:
1944
1945.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001946
1947 >>> getcontext().prec = 3
1948 >>> +Decimal('1.23456789') # unary plus triggers rounding
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001949 Decimal('1.23')
Georg Brandl116aa622007-08-15 14:28:22 +00001950
1951Alternatively, inputs can be rounded upon creation using the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001952:meth:`Context.create_decimal` method:
Georg Brandl116aa622007-08-15 14:28:22 +00001953
1954 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001955 Decimal('1.2345')
Georg Brandl116aa622007-08-15 14:28:22 +00001956