blob: cbd3950cf677cc8ed378e479434fd6f0c9380a1d [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
Raymond Hettinger13a70752008-02-10 07:21:09 +00002:mod:`decimal` --- Decimal fixed point and floating point arithmetic
3====================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00004
5.. module:: decimal
6 :synopsis: Implementation of the General Decimal Arithmetic Specification.
7
8
9.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
10.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
11.. moduleauthor:: Raymond Hettinger <python at rcn.com>
12.. moduleauthor:: Aahz <aahz at pobox.com>
13.. moduleauthor:: Tim Peters <tim.one at comcast.net>
14
15
16.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
17
Georg Brandl8ec7f652007-08-15 14:28:01 +000018.. versionadded:: 2.4
19
Georg Brandl17baef02008-03-22 10:56:23 +000020.. testsetup:: *
21
22 from decimal import *
23
Georg Brandl8ec7f652007-08-15 14:28:01 +000024The :mod:`decimal` module provides support for decimal floating point
Facundo Batista7c82a3e92007-09-14 18:58:34 +000025arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl8ec7f652007-08-15 14:28:01 +000026
Raymond Hettinger13a70752008-02-10 07:21:09 +000027* Decimal "is based on a floating-point model which was designed with people
28 in mind, and necessarily has a paramount guiding principle -- computers must
29 provide an arithmetic that works in the same way as the arithmetic that
30 people learn at school." -- excerpt from the decimal arithmetic specification.
31
Georg Brandl8ec7f652007-08-15 14:28:01 +000032* Decimal numbers can be represented exactly. In contrast, numbers like
33 :const:`1.1` do not have an exact representation in binary floating point. End
34 users typically would not expect :const:`1.1` to display as
35 :const:`1.1000000000000001` as it does with binary floating point.
36
37* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Facundo Batista7c82a3e92007-09-14 18:58:34 +000038 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl8ec7f652007-08-15 14:28:01 +000039 is :const:`5.5511151231257827e-017`. While near to zero, the differences
40 prevent reliable equality testing and differences can accumulate. For this
Raymond Hettinger13a70752008-02-10 07:21:09 +000041 reason, decimal is preferred in accounting applications which have strict
Georg Brandl8ec7f652007-08-15 14:28:01 +000042 equality invariants.
43
44* The decimal module incorporates a notion of significant places so that ``1.30
45 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
46 This is the customary presentation for monetary applications. For
47 multiplication, the "schoolbook" approach uses all the figures in the
48 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
49 1.20`` gives :const:`1.5600`.
50
51* Unlike hardware based binary floating point, the decimal module has a user
Facundo Batista7c82a3e92007-09-14 18:58:34 +000052 alterable precision (defaulting to 28 places) which can be as large as needed for
Georg Brandl17baef02008-03-22 10:56:23 +000053 a given problem:
Georg Brandl8ec7f652007-08-15 14:28:01 +000054
55 >>> getcontext().prec = 6
56 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +000057 Decimal('0.142857')
Georg Brandl8ec7f652007-08-15 14:28:01 +000058 >>> getcontext().prec = 28
59 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +000060 Decimal('0.1428571428571428571428571429')
Georg Brandl8ec7f652007-08-15 14:28:01 +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.
Raymond Hettinger13a70752008-02-10 07:21:09 +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 Brandl8ec7f652007-08-15 14:28:01 +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
Facundo Batista7c82a3e92007-09-14 18:58:34 +000079trailing zeros. Decimals also include special values such as
Georg Brandl8ec7f652007-08-15 14:28:01 +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`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +000088:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl8ec7f652007-08-15 14:28:01 +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
98encountered, its flag is incremented from zero and, then, if the trap enabler is
99set 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
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000105 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
106 Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000107
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000108 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Mark Dickinsonff6672f2008-02-07 01:14:23 +0000109 <http://754r.ucbtest.org/standards/854.pdf>`_.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000110
Georg Brandlb19be572007-12-29 10:57:00 +0000111.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandl17baef02008-03-22 10:56:23 +0000121precision, rounding, or enabled traps:
122
123.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +0000124
125 >>> from decimal import *
126 >>> getcontext()
127 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
128 capitals=1, flags=[], traps=[Overflow, InvalidOperation,
129 DivisionByZero])
130
131 >>> getcontext().prec = 7 # Set a new precision
132
133Decimal instances can be constructed from integers, strings, or tuples. To
134create a Decimal from a :class:`float`, first convert it to a string. This
135serves as an explicit reminder of the details of the conversion (including
136representation error). Decimal numbers include special values such as
137:const:`NaN` which stands for "Not a number", positive and negative
Georg Brandl17baef02008-03-22 10:56:23 +0000138:const:`Infinity`, and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000139
140 >>> Decimal(10)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000141 Decimal('10')
142 >>> Decimal('3.14')
143 Decimal('3.14')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000144 >>> Decimal((0, (3, 1, 4), -2))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000145 Decimal('3.14')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000146 >>> Decimal(str(2.0 ** 0.5))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000147 Decimal('1.41421356237')
148 >>> Decimal(2) ** Decimal('0.5')
149 Decimal('1.414213562373095048801688724')
150 >>> Decimal('NaN')
151 Decimal('NaN')
152 >>> Decimal('-Infinity')
153 Decimal('-Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandl17baef02008-03-22 10:56:23 +0000157operations.
158
159.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +0000160
161 >>> getcontext().prec = 6
162 >>> Decimal('3.0')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000163 Decimal('3.0')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000164 >>> Decimal('3.1415926535')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000165 Decimal('3.1415926535')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000166 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000167 Decimal('5.85987')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000168 >>> getcontext().rounding = ROUND_UP
169 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000170 Decimal('5.85988')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000171
172Decimals interact well with much of the rest of Python. Here is a small decimal
173floating point flying circus::
174
175 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
176 >>> max(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000177 Decimal('9.25')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000178 >>> min(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000179 Decimal('0.03')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000180 >>> sorted(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000181 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
182 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000183 >>> sum(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000184 Decimal('19.29')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000185 >>> a,b,c = data[:3]
186 >>> str(a)
187 '1.34'
188 >>> float(a)
189 1.3400000000000001
190 >>> round(a, 1) # round() first converts to binary floating point
191 1.3
192 >>> int(a)
193 1
194 >>> a * 5
Raymond Hettingerabe32372008-02-14 02:41:22 +0000195 Decimal('6.70')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000196 >>> a * b
Raymond Hettingerabe32372008-02-14 02:41:22 +0000197 Decimal('2.5058')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000198 >>> c % a
Raymond Hettingerabe32372008-02-14 02:41:22 +0000199 Decimal('0.77')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000200
Andrew M. Kuchling6d407e42007-09-24 23:46:28 +0000201And some mathematical functions are also available to Decimal::
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000202
203 >>> Decimal(2).sqrt()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000204 Decimal('1.414213562373095048801688724')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000205 >>> Decimal(1).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000206 Decimal('2.718281828459045235360287471')
207 >>> Decimal('10').ln()
208 Decimal('2.302585092994045684017991455')
209 >>> Decimal('10').log10()
210 Decimal('1')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000211
Georg Brandl8ec7f652007-08-15 14:28:01 +0000212The :meth:`quantize` method rounds a number to a fixed exponent. This method is
213useful for monetary applications that often round results to a fixed number of
214places::
215
216 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000217 Decimal('7.32')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000218 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000219 Decimal('8')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000220
221As shown above, the :func:`getcontext` function accesses the current context and
222allows the settings to be changed. This approach meets the needs of most
223applications.
224
225For more advanced work, it may be useful to create alternate contexts using the
226Context() constructor. To make an alternate active, use the :func:`setcontext`
227function.
228
229In accordance with the standard, the :mod:`Decimal` module provides two ready to
230use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
231former is especially useful for debugging because many of the traps are
232enabled::
233
234 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
235 >>> setcontext(myothercontext)
236 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000237 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000238
239 >>> ExtendedContext
240 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
241 capitals=1, flags=[], traps=[])
242 >>> setcontext(ExtendedContext)
243 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000244 Decimal('0.142857143')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000245 >>> Decimal(42) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000246 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000247
248 >>> setcontext(BasicContext)
249 >>> Decimal(42) / Decimal(0)
250 Traceback (most recent call last):
251 File "<pyshell#143>", line 1, in -toplevel-
252 Decimal(42) / Decimal(0)
253 DivisionByZero: x / 0
254
255Contexts also have signal flags for monitoring exceptional conditions
256encountered during computations. The flags remain set until explicitly cleared,
257so it is best to clear the flags before each set of monitored computations by
258using the :meth:`clear_flags` method. ::
259
260 >>> setcontext(ExtendedContext)
261 >>> getcontext().clear_flags()
262 >>> Decimal(355) / Decimal(113)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000263 Decimal('3.14159292')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000264 >>> getcontext()
265 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
266 capitals=1, flags=[Inexact, Rounded], traps=[])
267
268The *flags* entry shows that the rational approximation to :const:`Pi` was
269rounded (digits beyond the context precision were thrown away) and that the
270result is inexact (some of the discarded digits were non-zero).
271
272Individual traps are set using the dictionary in the :attr:`traps` field of a
273context::
274
275 >>> Decimal(1) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000276 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277 >>> getcontext().traps[DivisionByZero] = 1
278 >>> Decimal(1) / Decimal(0)
279 Traceback (most recent call last):
280 File "<pyshell#112>", line 1, in -toplevel-
281 Decimal(1) / Decimal(0)
282 DivisionByZero: x / 0
283
284Most programs adjust the current context only once, at the beginning of the
285program. And, in many applications, data is converted to :class:`Decimal` with
286a single cast inside a loop. With context set and decimals created, the bulk of
287the program manipulates the data no differently than with other Python numeric
288types.
289
Georg Brandlb19be572007-12-29 10:57:00 +0000290.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000291
292
293.. _decimal-decimal:
294
295Decimal objects
296---------------
297
298
299.. class:: Decimal([value [, context]])
300
Georg Brandlb19be572007-12-29 10:57:00 +0000301 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000302
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000303 *value* can be an integer, string, tuple, or another :class:`Decimal`
Raymond Hettingerabe32372008-02-14 02:41:22 +0000304 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000305 string, it should conform to the decimal numeric string syntax after leading
306 and trailing whitespace characters are removed::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000307
308 sign ::= '+' | '-'
309 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
310 indicator ::= 'e' | 'E'
311 digits ::= digit [digit]...
312 decimal-part ::= digits '.' [digits] | ['.'] digits
313 exponent-part ::= indicator [sign] digits
314 infinity ::= 'Infinity' | 'Inf'
315 nan ::= 'NaN' [digits] | 'sNaN' [digits]
316 numeric-value ::= decimal-part [exponent-part] | infinity
317 numeric-string ::= [sign] numeric-value | [sign] nan
318
319 If *value* is a :class:`tuple`, it should have three components, a sign
320 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
321 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Raymond Hettingerabe32372008-02-14 02:41:22 +0000322 returns ``Decimal('1.414')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000323
324 The *context* precision does not affect how many digits are stored. That is
325 determined exclusively by the number of digits in *value*. For example,
Raymond Hettingerabe32372008-02-14 02:41:22 +0000326 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000327 only three.
328
329 The purpose of the *context* argument is determining what to do if *value* is a
330 malformed string. If the context traps :const:`InvalidOperation`, an exception
331 is raised; otherwise, the constructor returns a new Decimal with the value of
332 :const:`NaN`.
333
334 Once constructed, :class:`Decimal` objects are immutable.
335
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000336 .. versionchanged:: 2.6
337 leading and trailing whitespace characters are permitted when
338 creating a Decimal instance from a string.
339
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000340Decimal floating point objects share many properties with the other built-in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000341numeric types such as :class:`float` and :class:`int`. All of the usual math
342operations and special methods apply. Likewise, decimal objects can be copied,
343pickled, printed, used as dictionary keys, used as set elements, compared,
344sorted, and coerced to another type (such as :class:`float` or :class:`long`).
345
346In addition to the standard numeric properties, decimal floating point objects
347also have a number of specialized methods:
348
349
350.. method:: Decimal.adjusted()
351
352 Return the adjusted exponent after shifting out the coefficient's rightmost
Raymond Hettingerabe32372008-02-14 02:41:22 +0000353 digits until only the lead digit remains: ``Decimal('321e+5').adjusted()``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000354 returns seven. Used for determining the position of the most significant digit
355 with respect to the decimal point.
356
357
358.. method:: Decimal.as_tuple()
359
Georg Brandle3c3db52008-01-11 09:55:53 +0000360 Return a :term:`named tuple` representation of the number:
361 ``DecimalTuple(sign, digits, exponent)``.
362
363 .. versionchanged:: 2.6
364 Use a named tuple.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000365
366
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000367.. method:: Decimal.canonical()
368
369 Return the canonical encoding of the argument. Currently, the
370 encoding of a :class:`Decimal` instance is always canonical, so
371 this operation returns its argument unchanged.
372
373 .. versionadded:: 2.6
374
Georg Brandl8ec7f652007-08-15 14:28:01 +0000375.. method:: Decimal.compare(other[, context])
376
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000377 Compare the values of two Decimal instances. This operation
378 behaves in the same way as the usual comparison method
379 :meth:`__cmp__`, except that :meth:`compare` returns a Decimal
380 instance rather than an integer, and if either operand is a NaN
381 then the result is a NaN::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000382
Raymond Hettingerabe32372008-02-14 02:41:22 +0000383 a or b is a NaN ==> Decimal('NaN')
384 a < b ==> Decimal('-1')
385 a == b ==> Decimal('0')
386 a > b ==> Decimal('1')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000387
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000388.. method:: Decimal.compare_signal(other[, context])
389
390 This operation is identical to the :meth:`compare` method, except
391 that all NaNs signal. That is, if neither operand is a signaling
392 NaN then any quiet NaN operand is treated as though it were a
393 signaling NaN.
394
395 .. versionadded:: 2.6
396
397.. method:: Decimal.compare_total(other)
398
399 Compare two operands using their abstract representation rather
400 than their numerical value. Similar to the :meth:`compare` method,
401 but the result gives a total ordering on :class:`Decimal`
402 instances. Two :class:`Decimal` instances with the same numeric
403 value but different representations compare unequal in this
404 ordering::
405
Raymond Hettingerabe32372008-02-14 02:41:22 +0000406 >>> Decimal('12.0').compare_total(Decimal('12'))
407 Decimal('-1')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000408
409 Quiet and signaling NaNs are also included in the total ordering.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000410 The result of this function is ``Decimal('0')`` if both operands
411 have the same representation, ``Decimal('-1')`` if the first
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000412 operand is lower in the total order than the second, and
Raymond Hettingerabe32372008-02-14 02:41:22 +0000413 ``Decimal('1')`` if the first operand is higher in the total order
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000414 than the second operand. See the specification for details of the
415 total order.
416
417 .. versionadded:: 2.6
418
419.. method:: Decimal.compare_total_mag(other)
420
421 Compare two operands using their abstract representation rather
422 than their value as in :meth:`compare_total`, but ignoring the sign
423 of each operand. ``x.compare_total_mag(y)`` is equivalent to
424 ``x.copy_abs().compare_total(y.copy_abs())``.
425
426 .. versionadded:: 2.6
427
428.. method:: Decimal.copy_abs()
429
430 Return the absolute value of the argument. This operation is
431 unaffected by the context and is quiet: no flags are changed and no
432 rounding is performed.
433
434 .. versionadded:: 2.6
435
436.. method:: Decimal.copy_negate()
437
438 Return the negation of the argument. This operation is unaffected
439 by the context and is quiet: no flags are changed and no rounding
440 is performed.
441
442 .. versionadded:: 2.6
443
444.. method:: Decimal.copy_sign(other)
445
446 Return a copy of the first operand with the sign set to be the
447 same as the sign of the second operand. For example::
448
Raymond Hettingerabe32372008-02-14 02:41:22 +0000449 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
450 Decimal('-2.3')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000451
452 This operation is unaffected by the context and is quiet: no flags
453 are changed and no rounding is performed.
454
455 .. versionadded:: 2.6
456
457.. method:: Decimal.exp([context])
458
459 Return the value of the (natural) exponential function ``e**x`` at the
460 given number. The result is correctly rounded using the
461 :const:`ROUND_HALF_EVEN` rounding mode.
462
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000463 >>> Decimal(1).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000464 Decimal('2.718281828459045235360287471')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000465 >>> Decimal(321).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000466 Decimal('2.561702493119680037517373933E+139')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000467
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000468 .. versionadded:: 2.6
469
470.. method:: Decimal.fma(other, third[, context])
471
472 Fused multiply-add. Return self*other+third with no rounding of
473 the intermediate product self*other.
474
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000475 >>> Decimal(2).fma(3, 5)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000476 Decimal('11')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000477
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000478 .. versionadded:: 2.6
479
480.. method:: Decimal.is_canonical()
481
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000482 Return :const:`True` if the argument is canonical and
483 :const:`False` otherwise. Currently, a :class:`Decimal` instance
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000484 is always canonical, so this operation always returns
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000485 :const:`True`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000486
487 .. versionadded:: 2.6
488
489.. method:: is_finite()
490
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000491 Return :const:`True` if the argument is a finite number, and
492 :const:`False` if the argument is an infinity or a NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000493
494 .. versionadded:: 2.6
495
496.. method:: is_infinite()
497
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000498 Return :const:`True` if the argument is either positive or
499 negative infinity and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000500
501 .. versionadded:: 2.6
502
503.. method:: is_nan()
504
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000505 Return :const:`True` if the argument is a (quiet or signaling)
506 NaN and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000507
508 .. versionadded:: 2.6
509
510.. method:: is_normal()
511
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000512 Return :const:`True` if the argument is a *normal* finite number.
513 Return :const:`False` if the argument is zero, subnormal, infinite
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000514 or a NaN.
515
516 .. versionadded:: 2.6
517
518.. method:: is_qnan()
519
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000520 Return :const:`True` if the argument is a quiet NaN, and
521 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000522
523 .. versionadded:: 2.6
524
525.. method:: is_signed()
526
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000527 Return :const:`True` if the argument has a negative sign and
528 :const:`False` otherwise. Note that zeros and NaNs can both carry
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000529 signs.
530
531 .. versionadded:: 2.6
532
533.. method:: is_snan()
534
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000535 Return :const:`True` if the argument is a signaling NaN and
536 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000537
538 .. versionadded:: 2.6
539
540.. method:: is_subnormal()
541
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000542 Return :const:`True` if the argument is subnormal, and
543 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000544
545 .. versionadded:: 2.6
546
547.. method:: is_zero()
548
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000549 Return :const:`True` if the argument is a (positive or negative)
550 zero and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000551
552 .. versionadded:: 2.6
553
554.. method:: Decimal.ln([context])
555
556 Return the natural (base e) logarithm of the operand. The result
557 is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
558 mode.
559
560 .. versionadded:: 2.6
561
562.. method:: Decimal.log10([context])
563
564 Return the base ten logarithm of the operand. The result is
565 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
566
567 .. versionadded:: 2.6
568
Georg Brandlb19be572007-12-29 10:57:00 +0000569.. method:: Decimal.logb([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000570
571 For a nonzero number, return the adjusted exponent of its operand
572 as a :class:`Decimal` instance. If the operand is a zero then
Raymond Hettingerabe32372008-02-14 02:41:22 +0000573 ``Decimal('-Infinity')`` is returned and the
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000574 :const:`DivisionByZero` flag is raised. If the operand is an
Raymond Hettingerabe32372008-02-14 02:41:22 +0000575 infinity then ``Decimal('Infinity')`` is returned.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000576
577 .. versionadded:: 2.6
578
579.. method:: Decimal.logical_and(other[, context])
580
581 :meth:`logical_and` is a logical operation which takes two
582 *logical operands* (see :ref:`logical_operands_label`). The result
583 is the digit-wise ``and`` of the two operands.
584
585 .. versionadded:: 2.6
586
587.. method:: Decimal.logical_invert(other[, context])
588
589 :meth:`logical_invert` is a logical operation. The argument must
590 be a *logical operand* (see :ref:`logical_operands_label`). The
591 result is the digit-wise inversion of the operand.
592
593 .. versionadded:: 2.6
594
595.. method:: Decimal.logical_or(other[, context])
596
597 :meth:`logical_or` is a logical operation which takes two *logical
598 operands* (see :ref:`logical_operands_label`). The result is the
599 digit-wise ``or`` of the two operands.
600
601 .. versionadded:: 2.6
602
603.. method:: Decimal.logical_xor(other[, context])
604
605 :meth:`logical_xor` is a logical operation which takes two
606 *logical operands* (see :ref:`logical_operands_label`). The result
607 is the digit-wise exclusive or of the two operands.
608
609 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000610
611.. method:: Decimal.max(other[, context])
612
613 Like ``max(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000614 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000615 (depending on the context and whether they are signaling or quiet).
616
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000617.. method:: Decimal.max_mag(other[, context])
618
619 Similar to the :meth:`max` method, but the comparison is done using
620 the absolute values of the operands.
621
622 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000623
624.. method:: Decimal.min(other[, context])
625
626 Like ``min(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000627 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000628 (depending on the context and whether they are signaling or quiet).
629
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000630.. method:: Decimal.min_mag(other[, context])
631
632 Similar to the :meth:`min` method, but the comparison is done using
633 the absolute values of the operands.
634
635 .. versionadded:: 2.6
636
637.. method:: Decimal.next_minus([context])
638
639 Return the largest number representable in the given context (or
640 in the current thread's context if no context is given) that is smaller
641 than the given operand.
642
643 .. versionadded:: 2.6
644
645.. method:: Decimal.next_plus([context])
646
647 Return the smallest number representable in the given context (or
648 in the current thread's context if no context is given) that is
649 larger than the given operand.
650
651 .. versionadded:: 2.6
652
653.. method:: Decimal.next_toward(other[, context])
654
655 If the two operands are unequal, return the number closest to the
656 first operand in the direction of the second operand. If both
657 operands are numerically equal, return a copy of the first operand
658 with the sign set to be the same as the sign of the second operand.
659
660 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000661
662.. method:: Decimal.normalize([context])
663
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000664 Normalize the number by stripping the rightmost trailing zeros and converting
Raymond Hettingerabe32372008-02-14 02:41:22 +0000665 any result equal to :const:`Decimal('0')` to :const:`Decimal('0e0')`. Used for
Georg Brandl8ec7f652007-08-15 14:28:01 +0000666 producing canonical values for members of an equivalence class. For example,
Raymond Hettingerabe32372008-02-14 02:41:22 +0000667 ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both normalize to the
668 equivalent value ``Decimal('32.1')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000669
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000670.. method:: Decimal.number_class([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000671
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000672 Return a string describing the *class* of the operand. The
673 returned value is one of the following ten strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000674
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000675 * ``"-Infinity"``, indicating that the operand is negative infinity.
676 * ``"-Normal"``, indicating that the operand is a negative normal number.
677 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
678 * ``"-Zero"``, indicating that the operand is a negative zero.
679 * ``"+Zero"``, indicating that the operand is a positive zero.
680 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
681 * ``"+Normal"``, indicating that the operand is a positive normal number.
682 * ``"+Infinity"``, indicating that the operand is positive infinity.
683 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
684 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000685
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000686 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000687
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000688.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]])
689
Georg Brandlb19be572007-12-29 10:57:00 +0000690 Return a value equal to the first operand after rounding and
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000691 having the exponent of the second operand.
692
Raymond Hettingerabe32372008-02-14 02:41:22 +0000693 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
694 Decimal('1.414')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000695
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000696 Unlike other operations, if the length of the coefficient after the
697 quantize operation would be greater than precision, then an
698 :const:`InvalidOperation` is signaled. This guarantees that, unless
699 there is an error condition, the quantized exponent is always equal
700 to that of the right-hand operand.
701
702 Also unlike other operations, quantize never signals Underflow,
703 even if the result is subnormal and inexact.
704
705 If the exponent of the second operand is larger than that of the
706 first then rounding may be necessary. In this case, the rounding
707 mode is determined by the ``rounding`` argument if given, else by
708 the given ``context`` argument; if neither argument is given the
709 rounding mode of the current thread's context is used.
710
Georg Brandlb19be572007-12-29 10:57:00 +0000711 If *watchexp* is set (default), then an error is returned whenever the
712 resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000713
714.. method:: Decimal.radix()
715
716 Return ``Decimal(10)``, the radix (base) in which the
717 :class:`Decimal` class does all its arithmetic. Included for
718 compatibility with the specification.
719
720 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000721
722.. method:: Decimal.remainder_near(other[, context])
723
Georg Brandlb19be572007-12-29 10:57:00 +0000724 Compute the modulo as either a positive or negative value depending on which is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000725 closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
Raymond Hettingerabe32372008-02-14 02:41:22 +0000726 ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000727
728 If both are equally close, the one chosen will have the same sign as *self*.
729
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000730.. method:: Decimal.rotate(other[, context])
731
732 Return the result of rotating the digits of the first operand by
733 an amount specified by the second operand. The second operand
734 must be an integer in the range -precision through precision. The
735 absolute value of the second operand gives the number of places to
736 rotate. If the second operand is positive then rotation is to the
737 left; otherwise rotation is to the right. The coefficient of the
738 first operand is padded on the left with zeros to length precision
739 if necessary. The sign and exponent of the first operand are
740 unchanged.
741
742 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000743
744.. method:: Decimal.same_quantum(other[, context])
745
746 Test whether self and other have the same exponent or whether both are
747 :const:`NaN`.
748
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000749.. method:: Decimal.scaleb(other[, context])
750
751 Return the first operand with exponent adjusted by the second.
752 Equivalently, return the first operand multiplied by ``10**other``.
753 The second operand must be an integer.
754
755 .. versionadded:: 2.6
756
757.. method:: Decimal.shift(other[, context])
758
759 Return the result of shifting the digits of the first operand by
760 an amount specified by the second operand. The second operand must
761 be an integer in the range -precision through precision. The
762 absolute value of the second operand gives the number of places to
763 shift. If the second operand is positive then the shift is to the
764 left; otherwise the shift is to the right. Digits shifted into the
765 coefficient are zeros. The sign and exponent of the first operand
766 are unchanged.
767
768 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000769
770.. method:: Decimal.sqrt([context])
771
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000772 Return the square root of the argument to full precision.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000773
774
775.. method:: Decimal.to_eng_string([context])
776
777 Convert to an engineering-type string.
778
779 Engineering notation has an exponent which is a multiple of 3, so there are up
780 to 3 digits left of the decimal place. For example, converts
Raymond Hettingerabe32372008-02-14 02:41:22 +0000781 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000782
Georg Brandl8ec7f652007-08-15 14:28:01 +0000783.. method:: Decimal.to_integral([rounding[, context]])
784
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000785 Identical to the :meth:`to_integral_value` method. The ``to_integral``
786 name has been kept for compatibility with older versions.
787
788.. method:: Decimal.to_integral_exact([rounding[, context]])
789
Georg Brandlb19be572007-12-29 10:57:00 +0000790 Round to the nearest integer, signaling
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000791 :const:`Inexact` or :const:`Rounded` as appropriate if rounding
792 occurs. The rounding mode is determined by the ``rounding``
793 parameter if given, else by the given ``context``. If neither
794 parameter is given then the rounding mode of the current context is
795 used.
796
797 .. versionadded:: 2.6
798
799.. method:: Decimal.to_integral_value([rounding[, context]])
800
Georg Brandlb19be572007-12-29 10:57:00 +0000801 Round to the nearest integer without signaling :const:`Inexact` or
Georg Brandl8ec7f652007-08-15 14:28:01 +0000802 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding
803 method in either the supplied *context* or the current context.
804
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000805 .. versionchanged:: 2.6
806 renamed from ``to_integral`` to ``to_integral_value``. The old name
807 remains valid for compatibility.
808
809.. method:: Decimal.trim()
810
Georg Brandlb19be572007-12-29 10:57:00 +0000811 Return the decimal with *insignificant* trailing zeros removed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000812 Here, a trailing zero is considered insignificant either if it
813 follows the decimal point, or if the exponent of the argument (that
814 is, the last element of the :meth:`as_tuple` representation) is
815 positive.
816
817 .. versionadded:: 2.6
818
819.. _logical_operands_label:
820
821Logical operands
822^^^^^^^^^^^^^^^^
823
824The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
825and :meth:`logical_xor` methods expect their arguments to be *logical
826operands*. A *logical operand* is a :class:`Decimal` instance whose
827exponent and sign are both zero, and whose digits are all either
828:const:`0` or :const:`1`.
829
Georg Brandlb19be572007-12-29 10:57:00 +0000830.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000831
832
833.. _decimal-context:
834
835Context objects
836---------------
837
838Contexts are environments for arithmetic operations. They govern precision, set
839rules for rounding, determine which signals are treated as exceptions, and limit
840the range for exponents.
841
842Each thread has its own current context which is accessed or changed using the
843:func:`getcontext` and :func:`setcontext` functions:
844
845
846.. function:: getcontext()
847
848 Return the current context for the active thread.
849
850
851.. function:: setcontext(c)
852
853 Set the current context for the active thread to *c*.
854
855Beginning with Python 2.5, you can also use the :keyword:`with` statement and
856the :func:`localcontext` function to temporarily change the active context.
857
858
859.. function:: localcontext([c])
860
861 Return a context manager that will set the current context for the active thread
862 to a copy of *c* on entry to the with-statement and restore the previous context
863 when exiting the with-statement. If no context is specified, a copy of the
864 current context is used.
865
866 .. versionadded:: 2.5
867
868 For example, the following code sets the current decimal precision to 42 places,
869 performs a calculation, and then automatically restores the previous context::
870
Georg Brandl8ec7f652007-08-15 14:28:01 +0000871 from decimal import localcontext
872
873 with localcontext() as ctx:
874 ctx.prec = 42 # Perform a high precision calculation
875 s = calculate_something()
876 s = +s # Round the final result back to the default precision
877
878New contexts can also be created using the :class:`Context` constructor
879described below. In addition, the module provides three pre-made contexts:
880
881
882.. class:: BasicContext
883
884 This is a standard context defined by the General Decimal Arithmetic
885 Specification. Precision is set to nine. Rounding is set to
886 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
887 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
888 :const:`Subnormal`.
889
890 Because many of the traps are enabled, this context is useful for debugging.
891
892
893.. class:: ExtendedContext
894
895 This is a standard context defined by the General Decimal Arithmetic
896 Specification. Precision is set to nine. Rounding is set to
897 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
898 exceptions are not raised during computations).
899
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000900 Because the traps are disabled, this context is useful for applications that
Georg Brandl8ec7f652007-08-15 14:28:01 +0000901 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
902 raising exceptions. This allows an application to complete a run in the
903 presence of conditions that would otherwise halt the program.
904
905
906.. class:: DefaultContext
907
908 This context is used by the :class:`Context` constructor as a prototype for new
909 contexts. Changing a field (such a precision) has the effect of changing the
910 default for new contexts creating by the :class:`Context` constructor.
911
912 This context is most useful in multi-threaded environments. Changing one of the
913 fields before threads are started has the effect of setting system-wide
914 defaults. Changing the fields after threads have started is not recommended as
915 it would require thread synchronization to prevent race conditions.
916
917 In single threaded environments, it is preferable to not use this context at
918 all. Instead, simply create contexts explicitly as described below.
919
920 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
921 for Overflow, InvalidOperation, and DivisionByZero.
922
923In addition to the three supplied contexts, new contexts can be created with the
924:class:`Context` constructor.
925
926
927.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
928
929 Creates a new context. If a field is not specified or is :const:`None`, the
930 default values are copied from the :const:`DefaultContext`. If the *flags*
931 field is not specified or is :const:`None`, all flags are cleared.
932
933 The *prec* field is a positive integer that sets the precision for arithmetic
934 operations in the context.
935
936 The *rounding* option is one of:
937
938 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
939 * :const:`ROUND_DOWN` (towards zero),
940 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
941 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
942 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
943 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
944 * :const:`ROUND_UP` (away from zero).
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000945 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
946 would have been 0 or 5; otherwise towards zero)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000947
948 The *traps* and *flags* fields list any signals to be set. Generally, new
949 contexts should only set traps and leave the flags clear.
950
951 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
952 for exponents.
953
954 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
955 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
956 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
957
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000958 .. versionchanged:: 2.6
959 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000960
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000961The :class:`Context` class defines several general purpose methods as
962well as a large number of methods for doing arithmetic directly in a
963given context. In addition, for each of the :class:`Decimal` methods
964described above (with the exception of the :meth:`adjusted` and
965:meth:`as_tuple` methods) there is a corresponding :class:`Context`
966method. For example, ``C.exp(x)`` is equivalent to
967``x.exp(context=C)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000968
969.. method:: Context.clear_flags()
970
971 Resets all of the flags to :const:`0`.
972
973
974.. method:: Context.copy()
975
976 Return a duplicate of the context.
977
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000978.. method:: Context.copy_decimal(num)
979
980 Return a copy of the Decimal instance num.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000981
982.. method:: Context.create_decimal(num)
983
984 Creates a new Decimal instance from *num* but using *self* as context. Unlike
985 the :class:`Decimal` constructor, the context precision, rounding method, flags,
986 and traps are applied to the conversion.
987
988 This is useful because constants are often given to a greater precision than is
989 needed by the application. Another benefit is that rounding immediately
990 eliminates unintended effects from digits beyond the current precision. In the
991 following example, using unrounded inputs means that adding zero to a sum can
992 change the result::
993
994 >>> getcontext().prec = 3
Raymond Hettingerabe32372008-02-14 02:41:22 +0000995 >>> Decimal('3.4445') + Decimal('1.0023')
996 Decimal('4.45')
997 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
998 Decimal('4.44')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000999
Mark Dickinson59bc20b2008-01-12 01:56:00 +00001000 This method implements the to-number operation of the IBM
1001 specification. If the argument is a string, no leading or trailing
1002 whitespace is permitted.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001003
1004.. method:: Context.Etiny()
1005
1006 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
1007 for subnormal results. When underflow occurs, the exponent is set to
1008 :const:`Etiny`.
1009
1010
1011.. method:: Context.Etop()
1012
1013 Returns a value equal to ``Emax - prec + 1``.
1014
1015The usual approach to working with decimals is to create :class:`Decimal`
1016instances and then apply arithmetic operations which take place within the
Georg Brandl5d242ee2007-09-20 08:44:59 +00001017current context for the active thread. An alternative approach is to use context
Georg Brandl8ec7f652007-08-15 14:28:01 +00001018methods for calculating within a specific context. The methods are similar to
1019those for the :class:`Decimal` class and are only briefly recounted here.
1020
1021
1022.. method:: Context.abs(x)
1023
1024 Returns the absolute value of *x*.
1025
1026
1027.. method:: Context.add(x, y)
1028
1029 Return the sum of *x* and *y*.
1030
1031
Georg Brandl8ec7f652007-08-15 14:28:01 +00001032.. method:: Context.divide(x, y)
1033
1034 Return *x* divided by *y*.
1035
1036
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001037.. method:: Context.divide_int(x, y)
1038
1039 Return *x* divided by *y*, truncated to an integer.
1040
1041
Georg Brandl8ec7f652007-08-15 14:28:01 +00001042.. method:: Context.divmod(x, y)
1043
1044 Divides two numbers and returns the integer part of the result.
1045
1046
Georg Brandl8ec7f652007-08-15 14:28:01 +00001047.. method:: Context.minus(x)
1048
1049 Minus corresponds to the unary prefix minus operator in Python.
1050
1051
1052.. method:: Context.multiply(x, y)
1053
1054 Return the product of *x* and *y*.
1055
1056
Georg Brandl8ec7f652007-08-15 14:28:01 +00001057.. method:: Context.plus(x)
1058
1059 Plus corresponds to the unary prefix plus operator in Python. This operation
1060 applies the context precision and rounding, so it is *not* an identity
1061 operation.
1062
1063
1064.. method:: Context.power(x, y[, modulo])
1065
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001066 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if
1067 given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001068
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001069 With two arguments, compute ``x**y``. If ``x`` is negative then
1070 ``y`` must be integral. The result will be inexact unless ``y`` is
1071 integral and the result is finite and can be expressed exactly in
1072 'precision' digits. The result should always be correctly rounded,
1073 using the rounding mode of the current thread's context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001074
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001075 With three arguments, compute ``(x**y) % modulo``. For the three
1076 argument form, the following restrictions on the arguments hold:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001077
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001078 - all three arguments must be integral
1079 - ``y`` must be nonnegative
1080 - at least one of ``x`` or ``y`` must be nonzero
1081 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl8ec7f652007-08-15 14:28:01 +00001082
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001083 The result of ``Context.power(x, y, modulo)`` is identical to
1084 the result that would be obtained by computing ``(x**y) %
1085 modulo`` with unbounded precision, but is computed more
1086 efficiently. It is always exact.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001087
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001088 .. versionchanged:: 2.6
1089 ``y`` may now be nonintegral in ``x**y``.
1090 Stricter requirements for the three-argument version.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001091
1092
1093.. method:: Context.remainder(x, y)
1094
1095 Returns the remainder from integer division.
1096
1097 The sign of the result, if non-zero, is the same as that of the original
1098 dividend.
1099
Georg Brandl8ec7f652007-08-15 14:28:01 +00001100.. method:: Context.subtract(x, y)
1101
1102 Return the difference between *x* and *y*.
1103
Georg Brandl8ec7f652007-08-15 14:28:01 +00001104.. method:: Context.to_sci_string(x)
1105
1106 Converts a number to a string using scientific notation.
1107
Georg Brandlb19be572007-12-29 10:57:00 +00001108.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001109
1110
1111.. _decimal-signals:
1112
1113Signals
1114-------
1115
1116Signals represent conditions that arise during computation. Each corresponds to
1117one context flag and one context trap enabler.
1118
1119The context flag is incremented whenever the condition is encountered. After the
1120computation, flags may be checked for informational purposes (for instance, to
1121determine whether a computation was exact). After checking the flags, be sure to
1122clear all flags before starting the next computation.
1123
1124If the context's trap enabler is set for the signal, then the condition causes a
1125Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1126is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1127condition.
1128
1129
1130.. class:: Clamped
1131
1132 Altered an exponent to fit representation constraints.
1133
1134 Typically, clamping occurs when an exponent falls outside the context's
1135 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001136 fit by adding zeros to the coefficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001137
1138
1139.. class:: DecimalException
1140
1141 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1142
1143
1144.. class:: DivisionByZero
1145
1146 Signals the division of a non-infinite number by zero.
1147
1148 Can occur with division, modulo division, or when raising a number to a negative
1149 power. If this signal is not trapped, returns :const:`Infinity` or
1150 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1151
1152
1153.. class:: Inexact
1154
1155 Indicates that rounding occurred and the result is not exact.
1156
1157 Signals when non-zero digits were discarded during rounding. The rounded result
1158 is returned. The signal flag or trap is used to detect when results are
1159 inexact.
1160
1161
1162.. class:: InvalidOperation
1163
1164 An invalid operation was performed.
1165
1166 Indicates that an operation was requested that does not make sense. If not
1167 trapped, returns :const:`NaN`. Possible causes include::
1168
1169 Infinity - Infinity
1170 0 * Infinity
1171 Infinity / Infinity
1172 x % 0
1173 Infinity % x
1174 x._rescale( non-integer )
1175 sqrt(-x) and x > 0
1176 0 ** 0
1177 x ** (non-integer)
1178 x ** Infinity
1179
1180
1181.. class:: Overflow
1182
1183 Numerical overflow.
1184
1185 Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
1186 If not trapped, the result depends on the rounding mode, either pulling inward
1187 to the largest representable finite number or rounding outward to
1188 :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are
1189 also signaled.
1190
1191
1192.. class:: Rounded
1193
1194 Rounding occurred though possibly no information was lost.
1195
1196 Signaled whenever rounding discards digits; even if those digits are zero (such
1197 as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result
1198 unchanged. This signal is used to detect loss of significant digits.
1199
1200
1201.. class:: Subnormal
1202
1203 Exponent was lower than :attr:`Emin` prior to rounding.
1204
1205 Occurs when an operation result is subnormal (the exponent is too small). If not
1206 trapped, returns the result unchanged.
1207
1208
1209.. class:: Underflow
1210
1211 Numerical underflow with result rounded to zero.
1212
1213 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1214 and :class:`Subnormal` are also signaled.
1215
1216The following table summarizes the hierarchy of signals::
1217
1218 exceptions.ArithmeticError(exceptions.StandardError)
1219 DecimalException
1220 Clamped
1221 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1222 Inexact
1223 Overflow(Inexact, Rounded)
1224 Underflow(Inexact, Rounded, Subnormal)
1225 InvalidOperation
1226 Rounded
1227 Subnormal
1228
Georg Brandlb19be572007-12-29 10:57:00 +00001229.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001230
1231
1232.. _decimal-notes:
1233
1234Floating Point Notes
1235--------------------
1236
1237
1238Mitigating round-off error with increased precision
1239^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1240
1241The use of decimal floating point eliminates decimal representation error
1242(making it possible to represent :const:`0.1` exactly); however, some operations
1243can still incur round-off error when non-zero digits exceed the fixed precision.
1244
1245The effects of round-off error can be amplified by the addition or subtraction
1246of nearly offsetting quantities resulting in loss of significance. Knuth
1247provides two instructive examples where rounded floating point arithmetic with
1248insufficient precision causes the breakdown of the associative and distributive
1249properties of addition::
1250
1251 # Examples from Seminumerical Algorithms, Section 4.2.2.
1252 >>> from decimal import Decimal, getcontext
1253 >>> getcontext().prec = 8
1254
1255 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1256 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001257 Decimal('9.5111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001258 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001259 Decimal('10')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001260
1261 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1262 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001263 Decimal('0.01')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001264 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001265 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001266
1267The :mod:`decimal` module makes it possible to restore the identities by
1268expanding the precision sufficiently to avoid loss of significance::
1269
1270 >>> getcontext().prec = 20
1271 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1272 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001273 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001274 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001275 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001276 >>>
1277 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1278 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001279 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001280 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001281 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001282
1283
1284Special values
1285^^^^^^^^^^^^^^
1286
1287The number system for the :mod:`decimal` module provides special values
1288including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001289and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001290
1291Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1292they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1293not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1294can result from rounding beyond the limits of the largest representable number.
1295
1296The infinities are signed (affine) and can be used in arithmetic operations
1297where they get treated as very large, indeterminate numbers. For instance,
1298adding a constant to infinity gives another infinite result.
1299
1300Some operations are indeterminate and return :const:`NaN`, or if the
1301:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1302``0/0`` returns :const:`NaN` which means "not a number". This variety of
1303:const:`NaN` is quiet and, once created, will flow through other computations
1304always resulting in another :const:`NaN`. This behavior can be useful for a
1305series of computations that occasionally have missing inputs --- it allows the
1306calculation to proceed while flagging specific results as invalid.
1307
1308A variant is :const:`sNaN` which signals rather than remaining quiet after every
1309operation. This is a useful return value when an invalid result needs to
1310interrupt a calculation for special handling.
1311
Mark Dickinson2fc92632008-02-06 22:10:50 +00001312The behavior of Python's comparison operators can be a little surprising where a
1313:const:`NaN` is involved. A test for equality where one of the operands is a
1314quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1315``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
Mark Dickinsonbafa9422008-02-06 22:25:16 +00001316:const:`True`. An attempt to compare two Decimals using any of the ``<``,
Mark Dickinson00c2e652008-02-07 01:42:06 +00001317``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1318if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Mark Dickinson3a94ee02008-02-10 15:19:58 +00001319not trapped. Note that the General Decimal Arithmetic specification does not
Mark Dickinson00c2e652008-02-07 01:42:06 +00001320specify the behavior of direct comparisons; these rules for comparisons
1321involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1322section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
Mark Dickinson2fc92632008-02-06 22:10:50 +00001323and :meth:`compare-signal` methods instead.
1324
Georg Brandl8ec7f652007-08-15 14:28:01 +00001325The signed zeros can result from calculations that underflow. They keep the sign
1326that would have resulted if the calculation had been carried out to greater
1327precision. Since their magnitude is zero, both positive and negative zeros are
1328treated as equal and their sign is informational.
1329
1330In addition to the two signed zeros which are distinct yet equal, there are
1331various representations of zero with differing precisions yet equivalent in
1332value. This takes a bit of getting used to. For an eye accustomed to
1333normalized floating point representations, it is not immediately obvious that
1334the following calculation returns a value equal to zero::
1335
1336 >>> 1 / Decimal('Infinity')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001337 Decimal('0E-1000000026')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001338
Georg Brandlb19be572007-12-29 10:57:00 +00001339.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001340
1341
1342.. _decimal-threads:
1343
1344Working with threads
1345--------------------
1346
1347The :func:`getcontext` function accesses a different :class:`Context` object for
1348each thread. Having separate thread contexts means that threads may make
1349changes (such as ``getcontext.prec=10``) without interfering with other threads.
1350
1351Likewise, the :func:`setcontext` function automatically assigns its target to
1352the current thread.
1353
1354If :func:`setcontext` has not been called before :func:`getcontext`, then
1355:func:`getcontext` will automatically create a new context for use in the
1356current thread.
1357
1358The new context is copied from a prototype context called *DefaultContext*. To
1359control the defaults so that each thread will use the same values throughout the
1360application, directly modify the *DefaultContext* object. This should be done
1361*before* any threads are started so that there won't be a race condition between
1362threads calling :func:`getcontext`. For example::
1363
1364 # Set applicationwide defaults for all threads about to be launched
1365 DefaultContext.prec = 12
1366 DefaultContext.rounding = ROUND_DOWN
1367 DefaultContext.traps = ExtendedContext.traps.copy()
1368 DefaultContext.traps[InvalidOperation] = 1
1369 setcontext(DefaultContext)
1370
1371 # Afterwards, the threads can be started
1372 t1.start()
1373 t2.start()
1374 t3.start()
1375 . . .
1376
Georg Brandlb19be572007-12-29 10:57:00 +00001377.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001378
1379
1380.. _decimal-recipes:
1381
1382Recipes
1383-------
1384
1385Here are a few recipes that serve as utility functions and that demonstrate ways
1386to work with the :class:`Decimal` class::
1387
1388 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1389 pos='', neg='-', trailneg=''):
1390 """Convert Decimal to a money formatted string.
1391
1392 places: required number of places after the decimal point
1393 curr: optional currency symbol before the sign (may be blank)
1394 sep: optional grouping separator (comma, period, space, or blank)
1395 dp: decimal point indicator (comma or period)
1396 only specify as blank when places is zero
1397 pos: optional sign for positive numbers: '+', space or blank
1398 neg: optional sign for negative numbers: '-', '(', space or blank
1399 trailneg:optional trailing minus indicator: '-', ')', space or blank
1400
1401 >>> d = Decimal('-1234567.8901')
1402 >>> moneyfmt(d, curr='$')
1403 '-$1,234,567.89'
1404 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1405 '1.234.568-'
1406 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1407 '($1,234,567.89)'
1408 >>> moneyfmt(Decimal(123456789), sep=' ')
1409 '123 456 789.00'
1410 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1411 '<.02>'
1412
1413 """
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001414 q = Decimal(10) ** -places # 2 places --> '0.01'
1415 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001416 result = []
1417 digits = map(str, digits)
1418 build, next = result.append, digits.pop
1419 if sign:
1420 build(trailneg)
1421 for i in range(places):
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001422 build(next() if digits else '0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001423 build(dp)
1424 i = 0
1425 while digits:
1426 build(next())
1427 i += 1
1428 if i == 3 and digits:
1429 i = 0
1430 build(sep)
1431 build(curr)
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001432 build(neg if sign else pos)
1433 return ''.join(reversed(result))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001434
1435 def pi():
1436 """Compute Pi to the current precision.
1437
1438 >>> print pi()
1439 3.141592653589793238462643383
1440
1441 """
1442 getcontext().prec += 2 # extra digits for intermediate steps
1443 three = Decimal(3) # substitute "three=3.0" for regular floats
1444 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1445 while s != lasts:
1446 lasts = s
1447 n, na = n+na, na+8
1448 d, da = d+da, da+32
1449 t = (t * n) / d
1450 s += t
1451 getcontext().prec -= 2
1452 return +s # unary plus applies the new precision
1453
1454 def exp(x):
1455 """Return e raised to the power of x. Result type matches input type.
1456
1457 >>> print exp(Decimal(1))
1458 2.718281828459045235360287471
1459 >>> print exp(Decimal(2))
1460 7.389056098930650227230427461
1461 >>> print exp(2.0)
1462 7.38905609893
1463 >>> print exp(2+0j)
1464 (7.38905609893+0j)
1465
1466 """
1467 getcontext().prec += 2
1468 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1469 while s != lasts:
1470 lasts = s
1471 i += 1
1472 fact *= i
1473 num *= x
1474 s += num / fact
1475 getcontext().prec -= 2
1476 return +s
1477
1478 def cos(x):
1479 """Return the cosine of x as measured in radians.
1480
1481 >>> print cos(Decimal('0.5'))
1482 0.8775825618903727161162815826
1483 >>> print cos(0.5)
1484 0.87758256189
1485 >>> print cos(0.5+0j)
1486 (0.87758256189+0j)
1487
1488 """
1489 getcontext().prec += 2
1490 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1491 while s != lasts:
1492 lasts = s
1493 i += 2
1494 fact *= i * (i-1)
1495 num *= x * x
1496 sign *= -1
1497 s += num / fact * sign
1498 getcontext().prec -= 2
1499 return +s
1500
1501 def sin(x):
1502 """Return the sine of x as measured in radians.
1503
1504 >>> print sin(Decimal('0.5'))
1505 0.4794255386042030002732879352
1506 >>> print sin(0.5)
1507 0.479425538604
1508 >>> print sin(0.5+0j)
1509 (0.479425538604+0j)
1510
1511 """
1512 getcontext().prec += 2
1513 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1514 while s != lasts:
1515 lasts = s
1516 i += 2
1517 fact *= i * (i-1)
1518 num *= x * x
1519 sign *= -1
1520 s += num / fact * sign
1521 getcontext().prec -= 2
1522 return +s
1523
1524
Georg Brandlb19be572007-12-29 10:57:00 +00001525.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001526
1527
1528.. _decimal-faq:
1529
1530Decimal FAQ
1531-----------
1532
1533Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1534minimize typing when using the interactive interpreter?
1535
Raymond Hettinger50361d42008-02-14 12:05:42 +00001536A. Some users abbreviate the constructor to just a single letter::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001537
1538 >>> D = decimal.Decimal
1539 >>> D('1.23') + D('3.45')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001540 Decimal('4.68')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001541
1542Q. In a fixed-point application with two decimal places, some inputs have many
1543places and need to be rounded. Others are not supposed to have excess digits
1544and need to be validated. What methods should be used?
1545
1546A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
1547the :const:`Inexact` trap is set, it is also useful for validation::
1548
1549 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1550
1551 >>> # Round to two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001552 >>> Decimal('3.214').quantize(TWOPLACES)
1553 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001554
1555 >>> # Validate that a number does not exceed two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001556 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1557 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001558
Raymond Hettingerabe32372008-02-14 02:41:22 +00001559 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001560 Traceback (most recent call last):
1561 ...
1562 Inexact: Changed in rounding
1563
1564Q. Once I have valid two place inputs, how do I maintain that invariant
1565throughout an application?
1566
Raymond Hettinger46314812008-02-14 10:46:57 +00001567A. Some operations like addition, subtraction, and multiplication by an integer
1568will automatically preserve fixed point. Others operations, like division and
1569non-integer multiplication, will change the number of decimal places and need to
Raymond Hettinger5111c522008-02-14 19:02:39 +00001570be followed-up with a :meth:`quantize` step::
Raymond Hettinger46314812008-02-14 10:46:57 +00001571
1572 >>> a = Decimal('102.72') # Initial fixed-point values
1573 >>> b = Decimal('3.17')
1574 >>> a + b # Addition preserves fixed-point
1575 Decimal('105.89')
1576 >>> a - b
1577 Decimal('99.55')
1578 >>> a * 42 # So does integer multiplication
1579 Decimal('4314.24')
1580 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1581 Decimal('325.62')
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001582 >>> (b / a).quantize(TWOPLACES) # And quantize division
Raymond Hettinger46314812008-02-14 10:46:57 +00001583 Decimal('0.03')
1584
1585In developing fixed-point applications, it is convenient to define functions
1586to handle the :meth:`quantize` step::
1587
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001588 >>> def mul(x, y, fp=TWOPLACES):
1589 ... return (x * y).quantize(fp)
1590 >>> def div(x, y, fp=TWOPLACES):
1591 ... return (x / y).quantize(fp)
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001592
Raymond Hettinger46314812008-02-14 10:46:57 +00001593 >>> mul(a, b) # Automatically preserve fixed-point
1594 Decimal('325.62')
1595 >>> div(b, a)
1596 Decimal('0.03')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001597
1598Q. There are many ways to express the same value. The numbers :const:`200`,
1599:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1600various precisions. Is there a way to transform them to a single recognizable
1601canonical value?
1602
1603A. The :meth:`normalize` method maps all equivalent values to a single
1604representative::
1605
1606 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1607 >>> [v.normalize() for v in values]
Raymond Hettingerabe32372008-02-14 02:41:22 +00001608 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001609
1610Q. Some decimal values always print with exponential notation. Is there a way
1611to get a non-exponential representation?
1612
1613A. For some values, exponential notation is the only way to express the number
1614of significant places in the coefficient. For example, expressing
1615:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1616original's two-place significance.
1617
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001618If an application does not care about tracking significance, it is easy to
Georg Brandl907a7202008-02-22 12:31:45 +00001619remove the exponent and trailing zeroes, losing significance, but keeping the
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001620value unchanged::
1621
1622 >>> def remove_exponent(d):
1623 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1624
1625 >>> remove_exponent(Decimal('5E+3'))
1626 Decimal('5000')
1627
Georg Brandl8ec7f652007-08-15 14:28:01 +00001628Q. Is there a way to convert a regular float to a :class:`Decimal`?
1629
1630A. Yes, all binary floating point numbers can be exactly expressed as a
1631Decimal. An exact conversion may take more precision than intuition would
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001632suggest, so we trap :const:`Inexact` to signal a need for more precision::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001633
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001634 def float_to_decimal(f):
1635 "Convert a floating point number to a Decimal with no loss of information"
1636 n, d = f.as_integer_ratio()
1637 with localcontext() as ctx:
1638 ctx.traps[Inexact] = True
1639 while True:
1640 try:
1641 return Decimal(n) / Decimal(d)
1642 except Inexact:
1643 ctx.prec += 1
Georg Brandl8ec7f652007-08-15 14:28:01 +00001644
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001645 >>> float_to_decimal(math.pi)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001646 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001647
Raymond Hettinger23bdcc92008-02-07 20:10:49 +00001648Q. Why isn't the :func:`float_to_decimal` routine included in the module?
Georg Brandl8ec7f652007-08-15 14:28:01 +00001649
1650A. There is some question about whether it is advisable to mix binary and
1651decimal floating point. Also, its use requires some care to avoid the
1652representation issues associated with binary floating point::
1653
Raymond Hettinger23bdcc92008-02-07 20:10:49 +00001654 >>> float_to_decimal(1.1)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001655 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001656
1657Q. Within a complex calculation, how can I make sure that I haven't gotten a
1658spurious result because of insufficient precision or rounding anomalies.
1659
1660A. The decimal module makes it easy to test results. A best practice is to
1661re-run calculations using greater precision and with various rounding modes.
1662Widely differing results indicate insufficient precision, rounding mode issues,
1663ill-conditioned inputs, or a numerically unstable algorithm.
1664
1665Q. I noticed that context precision is applied to the results of operations but
1666not to the inputs. Is there anything to watch out for when mixing values of
1667different precisions?
1668
1669A. Yes. The principle is that all values are considered to be exact and so is
1670the arithmetic on those values. Only the results are rounded. The advantage
1671for inputs is that "what you type is what you get". A disadvantage is that the
1672results can look odd if you forget that the inputs haven't been rounded::
1673
1674 >>> getcontext().prec = 3
1675 >>> Decimal('3.104') + D('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001676 Decimal('5.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001677 >>> Decimal('3.104') + D('0.000') + D('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001678 Decimal('5.20')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001679
1680The solution is either to increase precision or to force rounding of inputs
1681using the unary plus operation::
1682
1683 >>> getcontext().prec = 3
1684 >>> +Decimal('1.23456789') # unary plus triggers rounding
Raymond Hettingerabe32372008-02-14 02:41:22 +00001685 Decimal('1.23')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001686
1687Alternatively, inputs can be rounded upon creation using the
1688:meth:`Context.create_decimal` method::
1689
1690 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001691 Decimal('1.2345')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001692