blob: ac21b57acf038644ba9e4d218a8bee4c31eb968b [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
Christian Heimes3feef612008-02-11 06:19:17 +00002:mod:`decimal` --- Decimal fixed point and floating point arithmetic
3====================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00004
5.. module:: decimal
6 :synopsis: Implementation of the General Decimal Arithmetic Specification.
7
Georg Brandl116aa622007-08-15 14:28:22 +00008.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
9.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
10.. moduleauthor:: Raymond Hettinger <python at rcn.com>
11.. moduleauthor:: Aahz <aahz at pobox.com>
12.. moduleauthor:: Tim Peters <tim.one at comcast.net>
Georg Brandl116aa622007-08-15 14:28:22 +000013.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
14
15
Georg Brandl116aa622007-08-15 14:28:22 +000016The :mod:`decimal` module provides support for decimal floating point
Thomas Wouters1b7f8912007-09-19 03:06:30 +000017arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl116aa622007-08-15 14:28:22 +000018
Christian Heimes3feef612008-02-11 06:19:17 +000019* Decimal "is based on a floating-point model which was designed with people
20 in mind, and necessarily has a paramount guiding principle -- computers must
21 provide an arithmetic that works in the same way as the arithmetic that
22 people learn at school." -- excerpt from the decimal arithmetic specification.
23
Georg Brandl116aa622007-08-15 14:28:22 +000024* Decimal numbers can be represented exactly. In contrast, numbers like
25 :const:`1.1` do not have an exact representation in binary floating point. End
26 users typically would not expect :const:`1.1` to display as
27 :const:`1.1000000000000001` as it does with binary floating point.
28
29* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl116aa622007-08-15 14:28:22 +000031 is :const:`5.5511151231257827e-017`. While near to zero, the differences
32 prevent reliable equality testing and differences can accumulate. For this
Christian Heimes3feef612008-02-11 06:19:17 +000033 reason, decimal is preferred in accounting applications which have strict
Georg Brandl116aa622007-08-15 14:28:22 +000034 equality invariants.
35
36* The decimal module incorporates a notion of significant places so that ``1.30
37 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
38 This is the customary presentation for monetary applications. For
39 multiplication, the "schoolbook" approach uses all the figures in the
40 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
41 1.20`` gives :const:`1.5600`.
42
43* Unlike hardware based binary floating point, the decimal module has a user
Thomas Wouters1b7f8912007-09-19 03:06:30 +000044 alterable precision (defaulting to 28 places) which can be as large as needed for
Georg Brandl116aa622007-08-15 14:28:22 +000045 a given problem::
46
47 >>> getcontext().prec = 6
48 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000049 Decimal('0.142857')
Georg Brandl116aa622007-08-15 14:28:22 +000050 >>> getcontext().prec = 28
51 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000052 Decimal('0.1428571428571428571428571429')
Georg Brandl116aa622007-08-15 14:28:22 +000053
54* Both binary and decimal floating point are implemented in terms of published
55 standards. While the built-in float type exposes only a modest portion of its
56 capabilities, the decimal module exposes all required parts of the standard.
57 When needed, the programmer has full control over rounding and signal handling.
Christian Heimes3feef612008-02-11 06:19:17 +000058 This includes an option to enforce exact arithmetic by using exceptions
59 to block any inexact operations.
60
61* The decimal module was designed to support "without prejudice, both exact
62 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
63 and rounded floating-point arithmetic." -- excerpt from the decimal
64 arithmetic specification.
Georg Brandl116aa622007-08-15 14:28:22 +000065
66The module design is centered around three concepts: the decimal number, the
67context for arithmetic, and signals.
68
69A decimal number is immutable. It has a sign, coefficient digits, and an
70exponent. To preserve significance, the coefficient digits do not truncate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000071trailing zeros. Decimals also include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +000072:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
73differentiates :const:`-0` from :const:`+0`.
74
75The context for arithmetic is an environment specifying precision, rounding
76rules, limits on exponents, flags indicating the results of operations, and trap
77enablers which determine whether signals are treated as exceptions. Rounding
78options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
79:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +000080:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl116aa622007-08-15 14:28:22 +000081
82Signals are groups of exceptional conditions arising during the course of
83computation. Depending on the needs of the application, signals may be ignored,
84considered as informational, or treated as exceptions. The signals in the
85decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
86:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
87:const:`Overflow`, and :const:`Underflow`.
88
89For each signal there is a flag and a trap enabler. When a signal is
Raymond Hettinger86173da2008-02-01 20:38:12 +000090encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl116aa622007-08-15 14:28:22 +000091set to one, an exception is raised. Flags are sticky, so the user needs to
92reset them before monitoring a calculation.
93
94
95.. seealso::
96
Thomas Wouters1b7f8912007-09-19 03:06:30 +000097 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
98 Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +000099
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000100 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Christian Heimes77c02eb2008-02-09 02:18:51 +0000101 <http://754r.ucbtest.org/standards/854.pdf>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000102
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000103.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000104
105
106.. _decimal-tutorial:
107
108Quick-start Tutorial
109--------------------
110
111The usual start to using decimals is importing the module, viewing the current
112context with :func:`getcontext` and, if necessary, setting new values for
113precision, rounding, or enabled traps::
114
115 >>> from decimal import *
116 >>> getcontext()
117 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
118 capitals=1, flags=[], traps=[Overflow, InvalidOperation,
119 DivisionByZero])
120
121 >>> getcontext().prec = 7 # Set a new precision
122
123Decimal instances can be constructed from integers, strings, or tuples. To
124create a Decimal from a :class:`float`, first convert it to a string. This
125serves as an explicit reminder of the details of the conversion (including
126representation error). Decimal numbers include special values such as
127:const:`NaN` which stands for "Not a number", positive and negative
128:const:`Infinity`, and :const:`-0`. ::
129
130 >>> Decimal(10)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000131 Decimal('10')
132 >>> Decimal('3.14')
133 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000134 >>> Decimal((0, (3, 1, 4), -2))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000135 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000136 >>> Decimal(str(2.0 ** 0.5))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000137 Decimal('1.41421356237')
138 >>> Decimal(2) ** Decimal('0.5')
139 Decimal('1.414213562373095048801688724')
140 >>> Decimal('NaN')
141 Decimal('NaN')
142 >>> Decimal('-Infinity')
143 Decimal('-Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145The significance of a new Decimal is determined solely by the number of digits
146input. Context precision and rounding only come into play during arithmetic
147operations. ::
148
149 >>> getcontext().prec = 6
150 >>> Decimal('3.0')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000151 Decimal('3.0')
Georg Brandl116aa622007-08-15 14:28:22 +0000152 >>> Decimal('3.1415926535')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000153 Decimal('3.1415926535')
Georg Brandl116aa622007-08-15 14:28:22 +0000154 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000155 Decimal('5.85987')
Georg Brandl116aa622007-08-15 14:28:22 +0000156 >>> getcontext().rounding = ROUND_UP
157 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000158 Decimal('5.85988')
Georg Brandl116aa622007-08-15 14:28:22 +0000159
160Decimals interact well with much of the rest of Python. Here is a small decimal
161floating point flying circus::
162
163 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
164 >>> max(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000165 Decimal('9.25')
Georg Brandl116aa622007-08-15 14:28:22 +0000166 >>> min(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000167 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +0000168 >>> sorted(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000169 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
170 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl116aa622007-08-15 14:28:22 +0000171 >>> sum(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000172 Decimal('19.29')
Georg Brandl116aa622007-08-15 14:28:22 +0000173 >>> a,b,c = data[:3]
174 >>> str(a)
175 '1.34'
176 >>> float(a)
177 1.3400000000000001
178 >>> round(a, 1) # round() first converts to binary floating point
179 1.3
180 >>> int(a)
181 1
182 >>> a * 5
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000183 Decimal('6.70')
Georg Brandl116aa622007-08-15 14:28:22 +0000184 >>> a * b
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000185 Decimal('2.5058')
Georg Brandl116aa622007-08-15 14:28:22 +0000186 >>> c % a
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000187 Decimal('0.77')
Georg Brandl116aa622007-08-15 14:28:22 +0000188
Georg Brandl9afde1c2007-11-01 20:32:30 +0000189And some mathematical functions are also available to Decimal::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000190
191 >>> Decimal(2).sqrt()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000192 Decimal('1.414213562373095048801688724')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000193 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000194 Decimal('2.718281828459045235360287471')
195 >>> Decimal('10').ln()
196 Decimal('2.302585092994045684017991455')
197 >>> Decimal('10').log10()
198 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000199
Georg Brandl116aa622007-08-15 14:28:22 +0000200The :meth:`quantize` method rounds a number to a fixed exponent. This method is
201useful for monetary applications that often round results to a fixed number of
202places::
203
204 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000205 Decimal('7.32')
Georg Brandl116aa622007-08-15 14:28:22 +0000206 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000207 Decimal('8')
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209As shown above, the :func:`getcontext` function accesses the current context and
210allows the settings to be changed. This approach meets the needs of most
211applications.
212
213For more advanced work, it may be useful to create alternate contexts using the
214Context() constructor. To make an alternate active, use the :func:`setcontext`
215function.
216
217In accordance with the standard, the :mod:`Decimal` module provides two ready to
218use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
219former is especially useful for debugging because many of the traps are
220enabled::
221
222 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
223 >>> setcontext(myothercontext)
224 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000225 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227 >>> ExtendedContext
228 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
229 capitals=1, flags=[], traps=[])
230 >>> setcontext(ExtendedContext)
231 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000232 Decimal('0.142857143')
Georg Brandl116aa622007-08-15 14:28:22 +0000233 >>> Decimal(42) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000234 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236 >>> setcontext(BasicContext)
237 >>> Decimal(42) / Decimal(0)
238 Traceback (most recent call last):
239 File "<pyshell#143>", line 1, in -toplevel-
240 Decimal(42) / Decimal(0)
241 DivisionByZero: x / 0
242
243Contexts also have signal flags for monitoring exceptional conditions
244encountered during computations. The flags remain set until explicitly cleared,
245so it is best to clear the flags before each set of monitored computations by
246using the :meth:`clear_flags` method. ::
247
248 >>> setcontext(ExtendedContext)
249 >>> getcontext().clear_flags()
250 >>> Decimal(355) / Decimal(113)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000251 Decimal('3.14159292')
Georg Brandl116aa622007-08-15 14:28:22 +0000252 >>> getcontext()
253 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
254 capitals=1, flags=[Inexact, Rounded], traps=[])
255
256The *flags* entry shows that the rational approximation to :const:`Pi` was
257rounded (digits beyond the context precision were thrown away) and that the
258result is inexact (some of the discarded digits were non-zero).
259
260Individual traps are set using the dictionary in the :attr:`traps` field of a
261context::
262
263 >>> Decimal(1) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000264 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000265 >>> getcontext().traps[DivisionByZero] = 1
266 >>> Decimal(1) / Decimal(0)
267 Traceback (most recent call last):
268 File "<pyshell#112>", line 1, in -toplevel-
269 Decimal(1) / Decimal(0)
270 DivisionByZero: x / 0
271
272Most programs adjust the current context only once, at the beginning of the
273program. And, in many applications, data is converted to :class:`Decimal` with
274a single cast inside a loop. With context set and decimals created, the bulk of
275the program manipulates the data no differently than with other Python numeric
276types.
277
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000278.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280
281.. _decimal-decimal:
282
283Decimal objects
284---------------
285
286
287.. class:: Decimal([value [, context]])
288
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000289 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl116aa622007-08-15 14:28:22 +0000290
Christian Heimesa62da1d2008-01-12 19:39:10 +0000291 *value* can be an integer, string, tuple, or another :class:`Decimal`
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000292 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Christian Heimesa62da1d2008-01-12 19:39:10 +0000293 string, it should conform to the decimal numeric string syntax after leading
294 and trailing whitespace characters are removed::
Georg Brandl116aa622007-08-15 14:28:22 +0000295
296 sign ::= '+' | '-'
297 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
298 indicator ::= 'e' | 'E'
299 digits ::= digit [digit]...
300 decimal-part ::= digits '.' [digits] | ['.'] digits
301 exponent-part ::= indicator [sign] digits
302 infinity ::= 'Infinity' | 'Inf'
303 nan ::= 'NaN' [digits] | 'sNaN' [digits]
304 numeric-value ::= decimal-part [exponent-part] | infinity
305 numeric-string ::= [sign] numeric-value | [sign] nan
306
307 If *value* is a :class:`tuple`, it should have three components, a sign
308 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
309 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000310 returns ``Decimal('1.414')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312 The *context* precision does not affect how many digits are stored. That is
313 determined exclusively by the number of digits in *value*. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000314 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl116aa622007-08-15 14:28:22 +0000315 only three.
316
317 The purpose of the *context* argument is determining what to do if *value* is a
318 malformed string. If the context traps :const:`InvalidOperation`, an exception
319 is raised; otherwise, the constructor returns a new Decimal with the value of
320 :const:`NaN`.
321
322 Once constructed, :class:`Decimal` objects are immutable.
323
Christian Heimesa62da1d2008-01-12 19:39:10 +0000324 .. versionchanged:: 2.6
325 leading and trailing whitespace characters are permitted when
326 creating a Decimal instance from a string.
327
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000328Decimal floating point objects share many properties with the other built-in
Georg Brandl116aa622007-08-15 14:28:22 +0000329numeric types such as :class:`float` and :class:`int`. All of the usual math
330operations and special methods apply. Likewise, decimal objects can be copied,
331pickled, printed, used as dictionary keys, used as set elements, compared,
Neil Schemenauer16c70752007-09-21 20:19:23 +0000332sorted, and converted to another type (such as :class:`float` or :class:`int`).
Georg Brandl116aa622007-08-15 14:28:22 +0000333
334In addition to the standard numeric properties, decimal floating point objects
335also have a number of specialized methods:
336
337
338.. method:: Decimal.adjusted()
339
340 Return the adjusted exponent after shifting out the coefficient's rightmost
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000341 digits until only the lead digit remains: ``Decimal('321e+5').adjusted()``
Georg Brandl116aa622007-08-15 14:28:22 +0000342 returns seven. Used for determining the position of the most significant digit
343 with respect to the decimal point.
344
345
346.. method:: Decimal.as_tuple()
347
Christian Heimes25bb7832008-01-11 16:17:00 +0000348 Return a :term:`named tuple` representation of the number:
349 ``DecimalTuple(sign, digits, exponent)``.
350
351 .. versionchanged:: 2.6
352 Use a named tuple.
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000355.. method:: Decimal.canonical()
356
357 Return the canonical encoding of the argument. Currently, the
358 encoding of a :class:`Decimal` instance is always canonical, so
359 this operation returns its argument unchanged.
360
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000361
Georg Brandl116aa622007-08-15 14:28:22 +0000362.. method:: Decimal.compare(other[, context])
363
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000364 Compare the values of two Decimal instances. This operation
365 behaves in the same way as the usual comparison method
366 :meth:`__cmp__`, except that :meth:`compare` returns a Decimal
367 instance rather than an integer, and if either operand is a NaN
368 then the result is a NaN::
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000370 a or b is a NaN ==> Decimal('NaN')
371 a < b ==> Decimal('-1')
372 a == b ==> Decimal('0')
373 a > b ==> Decimal('1')
Georg Brandl116aa622007-08-15 14:28:22 +0000374
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000375.. method:: Decimal.compare_signal(other[, context])
376
377 This operation is identical to the :meth:`compare` method, except
378 that all NaNs signal. That is, if neither operand is a signaling
379 NaN then any quiet NaN operand is treated as though it were a
380 signaling NaN.
381
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000382
383.. method:: Decimal.compare_total(other)
384
385 Compare two operands using their abstract representation rather
386 than their numerical value. Similar to the :meth:`compare` method,
387 but the result gives a total ordering on :class:`Decimal`
388 instances. Two :class:`Decimal` instances with the same numeric
389 value but different representations compare unequal in this
390 ordering::
391
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000392 >>> Decimal('12.0').compare_total(Decimal('12'))
393 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000394
395 Quiet and signaling NaNs are also included in the total ordering.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000396 The result of this function is ``Decimal('0')`` if both operands
397 have the same representation, ``Decimal('-1')`` if the first
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000398 operand is lower in the total order than the second, and
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000399 ``Decimal('1')`` if the first operand is higher in the total order
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000400 than the second operand. See the specification for details of the
401 total order.
402
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000403
404.. method:: Decimal.compare_total_mag(other)
405
406 Compare two operands using their abstract representation rather
407 than their value as in :meth:`compare_total`, but ignoring the sign
408 of each operand. ``x.compare_total_mag(y)`` is equivalent to
409 ``x.copy_abs().compare_total(y.copy_abs())``.
410
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000411
412.. method:: Decimal.copy_abs()
413
414 Return the absolute value of the argument. This operation is
415 unaffected by the context and is quiet: no flags are changed and no
416 rounding is performed.
417
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000418
419.. method:: Decimal.copy_negate()
420
421 Return the negation of the argument. This operation is unaffected
422 by the context and is quiet: no flags are changed and no rounding
423 is performed.
424
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000425
426.. method:: Decimal.copy_sign(other)
427
428 Return a copy of the first operand with the sign set to be the
429 same as the sign of the second operand. For example::
430
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000431 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
432 Decimal('-2.3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000433
434 This operation is unaffected by the context and is quiet: no flags
435 are changed and no rounding is performed.
436
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000437
438.. method:: Decimal.exp([context])
439
440 Return the value of the (natural) exponential function ``e**x`` at the
441 given number. The result is correctly rounded using the
442 :const:`ROUND_HALF_EVEN` rounding mode.
443
444 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000445 Decimal('2.718281828459045235360287471')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000446 >>> Decimal(321).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000447 Decimal('2.561702493119680037517373933E+139')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000448
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000449
450.. method:: Decimal.fma(other, third[, context])
451
452 Fused multiply-add. Return self*other+third with no rounding of
453 the intermediate product self*other.
454
455 >>> Decimal(2).fma(3, 5)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000456 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000457
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000458
459.. method:: Decimal.is_canonical()
460
461 Return :const:`True` if the argument is canonical and
462 :const:`False` otherwise. Currently, a :class:`Decimal` instance
463 is always canonical, so this operation always returns
464 :const:`True`.
465
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000466
467.. method:: is_finite()
468
469 Return :const:`True` if the argument is a finite number, and
470 :const:`False` if the argument is an infinity or a NaN.
471
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000472
473.. method:: is_infinite()
474
475 Return :const:`True` if the argument is either positive or
476 negative infinity and :const:`False` otherwise.
477
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000478
479.. method:: is_nan()
480
481 Return :const:`True` if the argument is a (quiet or signaling)
482 NaN and :const:`False` otherwise.
483
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000484
485.. method:: is_normal()
486
487 Return :const:`True` if the argument is a *normal* finite number.
488 Return :const:`False` if the argument is zero, subnormal, infinite
489 or a NaN.
490
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000491
492.. method:: is_qnan()
493
494 Return :const:`True` if the argument is a quiet NaN, and
495 :const:`False` otherwise.
496
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000497
498.. method:: is_signed()
499
500 Return :const:`True` if the argument has a negative sign and
501 :const:`False` otherwise. Note that zeros and NaNs can both carry
502 signs.
503
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000504
505.. method:: is_snan()
506
507 Return :const:`True` if the argument is a signaling NaN and
508 :const:`False` otherwise.
509
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510
511.. method:: is_subnormal()
512
513 Return :const:`True` if the argument is subnormal, and
514 :const:`False` otherwise.
515
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000516
517.. method:: is_zero()
518
519 Return :const:`True` if the argument is a (positive or negative)
520 zero and :const:`False` otherwise.
521
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522
523.. method:: Decimal.ln([context])
524
525 Return the natural (base e) logarithm of the operand. The result
526 is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
527 mode.
528
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000529
530.. method:: Decimal.log10([context])
531
532 Return the base ten logarithm of the operand. The result is
533 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
534
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000535
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000536.. method:: Decimal.logb([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537
538 For a nonzero number, return the adjusted exponent of its operand
539 as a :class:`Decimal` instance. If the operand is a zero then
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000540 ``Decimal('-Infinity')`` is returned and the
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000541 :const:`DivisionByZero` flag is raised. If the operand is an
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000542 infinity then ``Decimal('Infinity')`` is returned.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000543
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000544
545.. method:: Decimal.logical_and(other[, context])
546
547 :meth:`logical_and` is a logical operation which takes two
548 *logical operands* (see :ref:`logical_operands_label`). The result
549 is the digit-wise ``and`` of the two operands.
550
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000551
552.. method:: Decimal.logical_invert(other[, context])
553
554 :meth:`logical_invert` is a logical operation. The argument must
555 be a *logical operand* (see :ref:`logical_operands_label`). The
556 result is the digit-wise inversion of the operand.
557
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000558
559.. method:: Decimal.logical_or(other[, context])
560
561 :meth:`logical_or` is a logical operation which takes two *logical
562 operands* (see :ref:`logical_operands_label`). The result is the
563 digit-wise ``or`` of the two operands.
564
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000565
566.. method:: Decimal.logical_xor(other[, context])
567
568 :meth:`logical_xor` is a logical operation which takes two
569 *logical operands* (see :ref:`logical_operands_label`). The result
570 is the digit-wise exclusive or of the two operands.
571
Georg Brandl116aa622007-08-15 14:28:22 +0000572
573.. method:: Decimal.max(other[, context])
574
575 Like ``max(self, other)`` except that the context rounding rule is applied
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000576 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl116aa622007-08-15 14:28:22 +0000577 (depending on the context and whether they are signaling or quiet).
578
Georg Brandl6554cb92007-12-02 23:15:43 +0000579
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000580.. method:: Decimal.max_mag(other[, context])
581
582 Similar to the :meth:`max` method, but the comparison is done using
583 the absolute values of the operands.
584
Georg Brandl116aa622007-08-15 14:28:22 +0000585
586.. method:: Decimal.min(other[, context])
587
588 Like ``min(self, other)`` except that the context rounding rule is applied
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000589 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl116aa622007-08-15 14:28:22 +0000590 (depending on the context and whether they are signaling or quiet).
591
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000592.. method:: Decimal.min_mag(other[, context])
593
594 Similar to the :meth:`min` method, but the comparison is done using
595 the absolute values of the operands.
596
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000597
598.. method:: Decimal.next_minus([context])
599
600 Return the largest number representable in the given context (or
601 in the current thread's context if no context is given) that is smaller
602 than the given operand.
603
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
605.. method:: Decimal.next_plus([context])
606
607 Return the smallest number representable in the given context (or
608 in the current thread's context if no context is given) that is
609 larger than the given operand.
610
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000611
612.. method:: Decimal.next_toward(other[, context])
613
614 If the two operands are unequal, return the number closest to the
615 first operand in the direction of the second operand. If both
616 operands are numerically equal, return a copy of the first operand
617 with the sign set to be the same as the sign of the second operand.
618
Georg Brandl116aa622007-08-15 14:28:22 +0000619
620.. method:: Decimal.normalize([context])
621
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000622 Normalize the number by stripping the rightmost trailing zeros and converting
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000623 any result equal to :const:`Decimal('0')` to :const:`Decimal('0e0')`. Used for
Georg Brandl116aa622007-08-15 14:28:22 +0000624 producing canonical values for members of an equivalence class. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000625 ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both normalize to the
626 equivalent value ``Decimal('32.1')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000627
Georg Brandl6554cb92007-12-02 23:15:43 +0000628
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000629.. method:: Decimal.number_class([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000630
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000631 Return a string describing the *class* of the operand. The
632 returned value is one of the following ten strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000633
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634 * ``"-Infinity"``, indicating that the operand is negative infinity.
635 * ``"-Normal"``, indicating that the operand is a negative normal number.
636 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
637 * ``"-Zero"``, indicating that the operand is a negative zero.
638 * ``"+Zero"``, indicating that the operand is a positive zero.
639 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
640 * ``"+Normal"``, indicating that the operand is a positive normal number.
641 * ``"+Infinity"``, indicating that the operand is positive infinity.
642 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
643 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000644
Georg Brandl116aa622007-08-15 14:28:22 +0000645
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000646.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]])
647
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000648 Return a value equal to the first operand after rounding and
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000649 having the exponent of the second operand.
650
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000651 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
652 Decimal('1.414')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653
654 Unlike other operations, if the length of the coefficient after the
655 quantize operation would be greater than precision, then an
656 :const:`InvalidOperation` is signaled. This guarantees that, unless
657 there is an error condition, the quantized exponent is always equal
658 to that of the right-hand operand.
659
660 Also unlike other operations, quantize never signals Underflow,
661 even if the result is subnormal and inexact.
662
663 If the exponent of the second operand is larger than that of the
664 first then rounding may be necessary. In this case, the rounding
665 mode is determined by the ``rounding`` argument if given, else by
666 the given ``context`` argument; if neither argument is given the
667 rounding mode of the current thread's context is used.
668
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000669 If *watchexp* is set (default), then an error is returned whenever the
670 resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000671
672.. method:: Decimal.radix()
673
674 Return ``Decimal(10)``, the radix (base) in which the
675 :class:`Decimal` class does all its arithmetic. Included for
676 compatibility with the specification.
677
Georg Brandl116aa622007-08-15 14:28:22 +0000678
679.. method:: Decimal.remainder_near(other[, context])
680
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000681 Compute the modulo as either a positive or negative value depending on which is
Georg Brandl116aa622007-08-15 14:28:22 +0000682 closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000683 ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000684
685 If both are equally close, the one chosen will have the same sign as *self*.
686
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000687.. method:: Decimal.rotate(other[, context])
688
689 Return the result of rotating the digits of the first operand by
690 an amount specified by the second operand. The second operand
691 must be an integer in the range -precision through precision. The
692 absolute value of the second operand gives the number of places to
693 rotate. If the second operand is positive then rotation is to the
694 left; otherwise rotation is to the right. The coefficient of the
695 first operand is padded on the left with zeros to length precision
696 if necessary. The sign and exponent of the first operand are
697 unchanged.
698
Georg Brandl116aa622007-08-15 14:28:22 +0000699
700.. method:: Decimal.same_quantum(other[, context])
701
702 Test whether self and other have the same exponent or whether both are
703 :const:`NaN`.
704
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705.. method:: Decimal.scaleb(other[, context])
706
707 Return the first operand with exponent adjusted by the second.
708 Equivalently, return the first operand multiplied by ``10**other``.
709 The second operand must be an integer.
710
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000711
712.. method:: Decimal.shift(other[, context])
713
714 Return the result of shifting the digits of the first operand by
715 an amount specified by the second operand. The second operand must
716 be an integer in the range -precision through precision. The
717 absolute value of the second operand gives the number of places to
718 shift. If the second operand is positive then the shift is to the
719 left; otherwise the shift is to the right. Digits shifted into the
720 coefficient are zeros. The sign and exponent of the first operand
721 are unchanged.
722
Georg Brandl116aa622007-08-15 14:28:22 +0000723
724.. method:: Decimal.sqrt([context])
725
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000726 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000727
728
729.. method:: Decimal.to_eng_string([context])
730
731 Convert to an engineering-type string.
732
733 Engineering notation has an exponent which is a multiple of 3, so there are up
734 to 3 digits left of the decimal place. For example, converts
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000735 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Georg Brandl116aa622007-08-15 14:28:22 +0000736
Georg Brandl116aa622007-08-15 14:28:22 +0000737.. method:: Decimal.to_integral([rounding[, context]])
738
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000739 Identical to the :meth:`to_integral_value` method. The ``to_integral``
740 name has been kept for compatibility with older versions.
741
742.. method:: Decimal.to_integral_exact([rounding[, context]])
743
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000744 Round to the nearest integer, signaling
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745 :const:`Inexact` or :const:`Rounded` as appropriate if rounding
746 occurs. The rounding mode is determined by the ``rounding``
747 parameter if given, else by the given ``context``. If neither
748 parameter is given then the rounding mode of the current context is
749 used.
750
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000751
752.. method:: Decimal.to_integral_value([rounding[, context]])
753
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000754 Round to the nearest integer without signaling :const:`Inexact` or
Georg Brandl116aa622007-08-15 14:28:22 +0000755 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding
756 method in either the supplied *context* or the current context.
757
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000758
759.. method:: Decimal.trim()
760
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000761 Return the decimal with *insignificant* trailing zeros removed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000762 Here, a trailing zero is considered insignificant either if it
763 follows the decimal point, or if the exponent of the argument (that
764 is, the last element of the :meth:`as_tuple` representation) is
765 positive.
766
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000767
768.. _logical_operands_label:
769
770Logical operands
771^^^^^^^^^^^^^^^^
772
773The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
774and :meth:`logical_xor` methods expect their arguments to be *logical
775operands*. A *logical operand* is a :class:`Decimal` instance whose
776exponent and sign are both zero, and whose digits are all either
777:const:`0` or :const:`1`.
778
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000779.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000780
781
782.. _decimal-context:
783
784Context objects
785---------------
786
787Contexts are environments for arithmetic operations. They govern precision, set
788rules for rounding, determine which signals are treated as exceptions, and limit
789the range for exponents.
790
791Each thread has its own current context which is accessed or changed using the
792:func:`getcontext` and :func:`setcontext` functions:
793
794
795.. function:: getcontext()
796
797 Return the current context for the active thread.
798
799
800.. function:: setcontext(c)
801
802 Set the current context for the active thread to *c*.
803
804Beginning with Python 2.5, you can also use the :keyword:`with` statement and
805the :func:`localcontext` function to temporarily change the active context.
806
807
808.. function:: localcontext([c])
809
810 Return a context manager that will set the current context for the active thread
811 to a copy of *c* on entry to the with-statement and restore the previous context
812 when exiting the with-statement. If no context is specified, a copy of the
813 current context is used.
814
Georg Brandl116aa622007-08-15 14:28:22 +0000815 For example, the following code sets the current decimal precision to 42 places,
816 performs a calculation, and then automatically restores the previous context::
817
Georg Brandl116aa622007-08-15 14:28:22 +0000818 from decimal import localcontext
819
820 with localcontext() as ctx:
821 ctx.prec = 42 # Perform a high precision calculation
822 s = calculate_something()
823 s = +s # Round the final result back to the default precision
824
825New contexts can also be created using the :class:`Context` constructor
826described below. In addition, the module provides three pre-made contexts:
827
828
829.. class:: BasicContext
830
831 This is a standard context defined by the General Decimal Arithmetic
832 Specification. Precision is set to nine. Rounding is set to
833 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
834 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
835 :const:`Subnormal`.
836
837 Because many of the traps are enabled, this context is useful for debugging.
838
839
840.. class:: ExtendedContext
841
842 This is a standard context defined by the General Decimal Arithmetic
843 Specification. Precision is set to nine. Rounding is set to
844 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
845 exceptions are not raised during computations).
846
Christian Heimes3feef612008-02-11 06:19:17 +0000847 Because the traps are disabled, this context is useful for applications that
Georg Brandl116aa622007-08-15 14:28:22 +0000848 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
849 raising exceptions. This allows an application to complete a run in the
850 presence of conditions that would otherwise halt the program.
851
852
853.. class:: DefaultContext
854
855 This context is used by the :class:`Context` constructor as a prototype for new
856 contexts. Changing a field (such a precision) has the effect of changing the
857 default for new contexts creating by the :class:`Context` constructor.
858
859 This context is most useful in multi-threaded environments. Changing one of the
860 fields before threads are started has the effect of setting system-wide
861 defaults. Changing the fields after threads have started is not recommended as
862 it would require thread synchronization to prevent race conditions.
863
864 In single threaded environments, it is preferable to not use this context at
865 all. Instead, simply create contexts explicitly as described below.
866
867 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
868 for Overflow, InvalidOperation, and DivisionByZero.
869
870In addition to the three supplied contexts, new contexts can be created with the
871:class:`Context` constructor.
872
873
874.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
875
876 Creates a new context. If a field is not specified or is :const:`None`, the
877 default values are copied from the :const:`DefaultContext`. If the *flags*
878 field is not specified or is :const:`None`, all flags are cleared.
879
880 The *prec* field is a positive integer that sets the precision for arithmetic
881 operations in the context.
882
883 The *rounding* option is one of:
884
885 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
886 * :const:`ROUND_DOWN` (towards zero),
887 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
888 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
889 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
890 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
891 * :const:`ROUND_UP` (away from zero).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
893 would have been 0 or 5; otherwise towards zero)
Georg Brandl116aa622007-08-15 14:28:22 +0000894
895 The *traps* and *flags* fields list any signals to be set. Generally, new
896 contexts should only set traps and leave the flags clear.
897
898 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
899 for exponents.
900
901 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
902 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
903 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
904
Georg Brandl116aa622007-08-15 14:28:22 +0000905
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000906The :class:`Context` class defines several general purpose methods as
907well as a large number of methods for doing arithmetic directly in a
908given context. In addition, for each of the :class:`Decimal` methods
909described above (with the exception of the :meth:`adjusted` and
910:meth:`as_tuple` methods) there is a corresponding :class:`Context`
911method. For example, ``C.exp(x)`` is equivalent to
912``x.exp(context=C)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000913
914.. method:: Context.clear_flags()
915
916 Resets all of the flags to :const:`0`.
917
918
919.. method:: Context.copy()
920
921 Return a duplicate of the context.
922
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923.. method:: Context.copy_decimal(num)
924
925 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +0000926
927.. method:: Context.create_decimal(num)
928
929 Creates a new Decimal instance from *num* but using *self* as context. Unlike
930 the :class:`Decimal` constructor, the context precision, rounding method, flags,
931 and traps are applied to the conversion.
932
933 This is useful because constants are often given to a greater precision than is
934 needed by the application. Another benefit is that rounding immediately
935 eliminates unintended effects from digits beyond the current precision. In the
936 following example, using unrounded inputs means that adding zero to a sum can
937 change the result::
938
939 >>> getcontext().prec = 3
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000940 >>> Decimal('3.4445') + Decimal('1.0023')
941 Decimal('4.45')
942 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
943 Decimal('4.44')
Georg Brandl116aa622007-08-15 14:28:22 +0000944
Christian Heimesa62da1d2008-01-12 19:39:10 +0000945 This method implements the to-number operation of the IBM
946 specification. If the argument is a string, no leading or trailing
947 whitespace is permitted.
Georg Brandl116aa622007-08-15 14:28:22 +0000948
949.. method:: Context.Etiny()
950
951 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
952 for subnormal results. When underflow occurs, the exponent is set to
953 :const:`Etiny`.
954
955
956.. method:: Context.Etop()
957
958 Returns a value equal to ``Emax - prec + 1``.
959
960The usual approach to working with decimals is to create :class:`Decimal`
961instances and then apply arithmetic operations which take place within the
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000962current context for the active thread. An alternative approach is to use context
Georg Brandl116aa622007-08-15 14:28:22 +0000963methods for calculating within a specific context. The methods are similar to
964those for the :class:`Decimal` class and are only briefly recounted here.
965
966
967.. method:: Context.abs(x)
968
969 Returns the absolute value of *x*.
970
971
972.. method:: Context.add(x, y)
973
974 Return the sum of *x* and *y*.
975
976
Georg Brandl116aa622007-08-15 14:28:22 +0000977.. method:: Context.divide(x, y)
978
979 Return *x* divided by *y*.
980
981
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000982.. method:: Context.divide_int(x, y)
983
984 Return *x* divided by *y*, truncated to an integer.
985
986
Georg Brandl116aa622007-08-15 14:28:22 +0000987.. method:: Context.divmod(x, y)
988
989 Divides two numbers and returns the integer part of the result.
990
991
Georg Brandl116aa622007-08-15 14:28:22 +0000992.. method:: Context.minus(x)
993
994 Minus corresponds to the unary prefix minus operator in Python.
995
996
997.. method:: Context.multiply(x, y)
998
999 Return the product of *x* and *y*.
1000
1001
Georg Brandl116aa622007-08-15 14:28:22 +00001002.. method:: Context.plus(x)
1003
1004 Plus corresponds to the unary prefix plus operator in Python. This operation
1005 applies the context precision and rounding, so it is *not* an identity
1006 operation.
1007
1008
1009.. method:: Context.power(x, y[, modulo])
1010
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001011 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if
1012 given.
Georg Brandl116aa622007-08-15 14:28:22 +00001013
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001014 With two arguments, compute ``x**y``. If ``x`` is negative then
1015 ``y`` must be integral. The result will be inexact unless ``y`` is
1016 integral and the result is finite and can be expressed exactly in
1017 'precision' digits. The result should always be correctly rounded,
1018 using the rounding mode of the current thread's context.
Georg Brandl116aa622007-08-15 14:28:22 +00001019
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001020 With three arguments, compute ``(x**y) % modulo``. For the three
1021 argument form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +00001022
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001023 - all three arguments must be integral
1024 - ``y`` must be nonnegative
1025 - at least one of ``x`` or ``y`` must be nonzero
1026 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +00001027
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001028 The result of ``Context.power(x, y, modulo)`` is identical to
1029 the result that would be obtained by computing ``(x**y) %
1030 modulo`` with unbounded precision, but is computed more
1031 efficiently. It is always exact.
Georg Brandl116aa622007-08-15 14:28:22 +00001032
Georg Brandl116aa622007-08-15 14:28:22 +00001033
1034.. method:: Context.remainder(x, y)
1035
1036 Returns the remainder from integer division.
1037
1038 The sign of the result, if non-zero, is the same as that of the original
1039 dividend.
1040
Georg Brandl116aa622007-08-15 14:28:22 +00001041.. method:: Context.subtract(x, y)
1042
1043 Return the difference between *x* and *y*.
1044
Georg Brandl116aa622007-08-15 14:28:22 +00001045.. method:: Context.to_sci_string(x)
1046
1047 Converts a number to a string using scientific notation.
1048
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001049.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001050
1051
1052.. _decimal-signals:
1053
1054Signals
1055-------
1056
1057Signals represent conditions that arise during computation. Each corresponds to
1058one context flag and one context trap enabler.
1059
Raymond Hettinger86173da2008-02-01 20:38:12 +00001060The context flag is set whenever the condition is encountered. After the
Georg Brandl116aa622007-08-15 14:28:22 +00001061computation, flags may be checked for informational purposes (for instance, to
1062determine whether a computation was exact). After checking the flags, be sure to
1063clear all flags before starting the next computation.
1064
1065If the context's trap enabler is set for the signal, then the condition causes a
1066Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1067is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1068condition.
1069
1070
1071.. class:: Clamped
1072
1073 Altered an exponent to fit representation constraints.
1074
1075 Typically, clamping occurs when an exponent falls outside the context's
1076 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001077 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001078
1079
1080.. class:: DecimalException
1081
1082 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1083
1084
1085.. class:: DivisionByZero
1086
1087 Signals the division of a non-infinite number by zero.
1088
1089 Can occur with division, modulo division, or when raising a number to a negative
1090 power. If this signal is not trapped, returns :const:`Infinity` or
1091 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1092
1093
1094.. class:: Inexact
1095
1096 Indicates that rounding occurred and the result is not exact.
1097
1098 Signals when non-zero digits were discarded during rounding. The rounded result
1099 is returned. The signal flag or trap is used to detect when results are
1100 inexact.
1101
1102
1103.. class:: InvalidOperation
1104
1105 An invalid operation was performed.
1106
1107 Indicates that an operation was requested that does not make sense. If not
1108 trapped, returns :const:`NaN`. Possible causes include::
1109
1110 Infinity - Infinity
1111 0 * Infinity
1112 Infinity / Infinity
1113 x % 0
1114 Infinity % x
1115 x._rescale( non-integer )
1116 sqrt(-x) and x > 0
1117 0 ** 0
1118 x ** (non-integer)
1119 x ** Infinity
1120
1121
1122.. class:: Overflow
1123
1124 Numerical overflow.
1125
1126 Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
1127 If not trapped, the result depends on the rounding mode, either pulling inward
1128 to the largest representable finite number or rounding outward to
1129 :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are
1130 also signaled.
1131
1132
1133.. class:: Rounded
1134
1135 Rounding occurred though possibly no information was lost.
1136
1137 Signaled whenever rounding discards digits; even if those digits are zero (such
1138 as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result
1139 unchanged. This signal is used to detect loss of significant digits.
1140
1141
1142.. class:: Subnormal
1143
1144 Exponent was lower than :attr:`Emin` prior to rounding.
1145
1146 Occurs when an operation result is subnormal (the exponent is too small). If not
1147 trapped, returns the result unchanged.
1148
1149
1150.. class:: Underflow
1151
1152 Numerical underflow with result rounded to zero.
1153
1154 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1155 and :class:`Subnormal` are also signaled.
1156
1157The following table summarizes the hierarchy of signals::
1158
1159 exceptions.ArithmeticError(exceptions.Exception)
1160 DecimalException
1161 Clamped
1162 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1163 Inexact
1164 Overflow(Inexact, Rounded)
1165 Underflow(Inexact, Rounded, Subnormal)
1166 InvalidOperation
1167 Rounded
1168 Subnormal
1169
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001170.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001171
1172
1173.. _decimal-notes:
1174
1175Floating Point Notes
1176--------------------
1177
1178
1179Mitigating round-off error with increased precision
1180^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1181
1182The use of decimal floating point eliminates decimal representation error
1183(making it possible to represent :const:`0.1` exactly); however, some operations
1184can still incur round-off error when non-zero digits exceed the fixed precision.
1185
1186The effects of round-off error can be amplified by the addition or subtraction
1187of nearly offsetting quantities resulting in loss of significance. Knuth
1188provides two instructive examples where rounded floating point arithmetic with
1189insufficient precision causes the breakdown of the associative and distributive
1190properties of addition::
1191
1192 # Examples from Seminumerical Algorithms, Section 4.2.2.
1193 >>> from decimal import Decimal, getcontext
1194 >>> getcontext().prec = 8
1195
1196 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1197 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001198 Decimal('9.5111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001199 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001200 Decimal('10')
Georg Brandl116aa622007-08-15 14:28:22 +00001201
1202 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1203 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001204 Decimal('0.01')
Georg Brandl116aa622007-08-15 14:28:22 +00001205 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001206 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001207
1208The :mod:`decimal` module makes it possible to restore the identities by
1209expanding the precision sufficiently to avoid loss of significance::
1210
1211 >>> getcontext().prec = 20
1212 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1213 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001214 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001215 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001216 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001217 >>>
1218 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1219 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001220 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001221 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001222 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001223
1224
1225Special values
1226^^^^^^^^^^^^^^
1227
1228The number system for the :mod:`decimal` module provides special values
1229including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001230and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001231
1232Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1233they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1234not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1235can result from rounding beyond the limits of the largest representable number.
1236
1237The infinities are signed (affine) and can be used in arithmetic operations
1238where they get treated as very large, indeterminate numbers. For instance,
1239adding a constant to infinity gives another infinite result.
1240
1241Some operations are indeterminate and return :const:`NaN`, or if the
1242:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1243``0/0`` returns :const:`NaN` which means "not a number". This variety of
1244:const:`NaN` is quiet and, once created, will flow through other computations
1245always resulting in another :const:`NaN`. This behavior can be useful for a
1246series of computations that occasionally have missing inputs --- it allows the
1247calculation to proceed while flagging specific results as invalid.
1248
1249A variant is :const:`sNaN` which signals rather than remaining quiet after every
1250operation. This is a useful return value when an invalid result needs to
1251interrupt a calculation for special handling.
1252
Christian Heimes77c02eb2008-02-09 02:18:51 +00001253The behavior of Python's comparison operators can be a little surprising where a
1254:const:`NaN` is involved. A test for equality where one of the operands is a
1255quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1256``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1257:const:`True`. An attempt to compare two Decimals using any of the ``<``,
1258``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1259if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes3feef612008-02-11 06:19:17 +00001260not trapped. Note that the General Decimal Arithmetic specification does not
Christian Heimes77c02eb2008-02-09 02:18:51 +00001261specify the behavior of direct comparisons; these rules for comparisons
1262involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1263section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1264and :meth:`compare-signal` methods instead.
1265
Georg Brandl116aa622007-08-15 14:28:22 +00001266The signed zeros can result from calculations that underflow. They keep the sign
1267that would have resulted if the calculation had been carried out to greater
1268precision. Since their magnitude is zero, both positive and negative zeros are
1269treated as equal and their sign is informational.
1270
1271In addition to the two signed zeros which are distinct yet equal, there are
1272various representations of zero with differing precisions yet equivalent in
1273value. This takes a bit of getting used to. For an eye accustomed to
1274normalized floating point representations, it is not immediately obvious that
1275the following calculation returns a value equal to zero::
1276
1277 >>> 1 / Decimal('Infinity')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001278 Decimal('0E-1000000026')
Georg Brandl116aa622007-08-15 14:28:22 +00001279
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001280.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001281
1282
1283.. _decimal-threads:
1284
1285Working with threads
1286--------------------
1287
1288The :func:`getcontext` function accesses a different :class:`Context` object for
1289each thread. Having separate thread contexts means that threads may make
1290changes (such as ``getcontext.prec=10``) without interfering with other threads.
1291
1292Likewise, the :func:`setcontext` function automatically assigns its target to
1293the current thread.
1294
1295If :func:`setcontext` has not been called before :func:`getcontext`, then
1296:func:`getcontext` will automatically create a new context for use in the
1297current thread.
1298
1299The new context is copied from a prototype context called *DefaultContext*. To
1300control the defaults so that each thread will use the same values throughout the
1301application, directly modify the *DefaultContext* object. This should be done
1302*before* any threads are started so that there won't be a race condition between
1303threads calling :func:`getcontext`. For example::
1304
1305 # Set applicationwide defaults for all threads about to be launched
1306 DefaultContext.prec = 12
1307 DefaultContext.rounding = ROUND_DOWN
1308 DefaultContext.traps = ExtendedContext.traps.copy()
1309 DefaultContext.traps[InvalidOperation] = 1
1310 setcontext(DefaultContext)
1311
1312 # Afterwards, the threads can be started
1313 t1.start()
1314 t2.start()
1315 t3.start()
1316 . . .
1317
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001318.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001319
1320
1321.. _decimal-recipes:
1322
1323Recipes
1324-------
1325
1326Here are a few recipes that serve as utility functions and that demonstrate ways
1327to work with the :class:`Decimal` class::
1328
1329 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1330 pos='', neg='-', trailneg=''):
1331 """Convert Decimal to a money formatted string.
1332
1333 places: required number of places after the decimal point
1334 curr: optional currency symbol before the sign (may be blank)
1335 sep: optional grouping separator (comma, period, space, or blank)
1336 dp: decimal point indicator (comma or period)
1337 only specify as blank when places is zero
1338 pos: optional sign for positive numbers: '+', space or blank
1339 neg: optional sign for negative numbers: '-', '(', space or blank
1340 trailneg:optional trailing minus indicator: '-', ')', space or blank
1341
1342 >>> d = Decimal('-1234567.8901')
1343 >>> moneyfmt(d, curr='$')
1344 '-$1,234,567.89'
1345 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1346 '1.234.568-'
1347 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1348 '($1,234,567.89)'
1349 >>> moneyfmt(Decimal(123456789), sep=' ')
1350 '123 456 789.00'
1351 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1352 '<.02>'
1353
1354 """
Christian Heimesa156e092008-02-16 07:38:31 +00001355 q = Decimal(10) ** -places # 2 places --> '0.01'
1356 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +00001357 result = []
1358 digits = map(str, digits)
1359 build, next = result.append, digits.pop
1360 if sign:
1361 build(trailneg)
1362 for i in range(places):
Christian Heimesa156e092008-02-16 07:38:31 +00001363 build(next() if digits else '0')
Georg Brandl116aa622007-08-15 14:28:22 +00001364 build(dp)
1365 i = 0
1366 while digits:
1367 build(next())
1368 i += 1
1369 if i == 3 and digits:
1370 i = 0
1371 build(sep)
1372 build(curr)
Christian Heimesa156e092008-02-16 07:38:31 +00001373 build(neg if sign else pos)
1374 return ''.join(reversed(result))
Georg Brandl116aa622007-08-15 14:28:22 +00001375
1376 def pi():
1377 """Compute Pi to the current precision.
1378
Georg Brandl6911e3c2007-09-04 07:15:32 +00001379 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001380 3.141592653589793238462643383
1381
1382 """
1383 getcontext().prec += 2 # extra digits for intermediate steps
1384 three = Decimal(3) # substitute "three=3.0" for regular floats
1385 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1386 while s != lasts:
1387 lasts = s
1388 n, na = n+na, na+8
1389 d, da = d+da, da+32
1390 t = (t * n) / d
1391 s += t
1392 getcontext().prec -= 2
1393 return +s # unary plus applies the new precision
1394
1395 def exp(x):
1396 """Return e raised to the power of x. Result type matches input type.
1397
Georg Brandl6911e3c2007-09-04 07:15:32 +00001398 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001399 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001400 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001401 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001402 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001403 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001404 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001405 (7.38905609893+0j)
1406
1407 """
1408 getcontext().prec += 2
1409 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1410 while s != lasts:
1411 lasts = s
1412 i += 1
1413 fact *= i
1414 num *= x
1415 s += num / fact
1416 getcontext().prec -= 2
1417 return +s
1418
1419 def cos(x):
1420 """Return the cosine of x as measured in radians.
1421
Georg Brandl6911e3c2007-09-04 07:15:32 +00001422 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001423 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001424 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001425 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001426 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001427 (0.87758256189+0j)
1428
1429 """
1430 getcontext().prec += 2
1431 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1432 while s != lasts:
1433 lasts = s
1434 i += 2
1435 fact *= i * (i-1)
1436 num *= x * x
1437 sign *= -1
1438 s += num / fact * sign
1439 getcontext().prec -= 2
1440 return +s
1441
1442 def sin(x):
1443 """Return the sine of x as measured in radians.
1444
Georg Brandl6911e3c2007-09-04 07:15:32 +00001445 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001446 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001447 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001448 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001449 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001450 (0.479425538604+0j)
1451
1452 """
1453 getcontext().prec += 2
1454 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1455 while s != lasts:
1456 lasts = s
1457 i += 2
1458 fact *= i * (i-1)
1459 num *= x * x
1460 sign *= -1
1461 s += num / fact * sign
1462 getcontext().prec -= 2
1463 return +s
1464
1465
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001466.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001467
1468
1469.. _decimal-faq:
1470
1471Decimal FAQ
1472-----------
1473
1474Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1475minimize typing when using the interactive interpreter?
1476
Christian Heimesa156e092008-02-16 07:38:31 +00001477A. Some users abbreviate the constructor to just a single letter::
Georg Brandl116aa622007-08-15 14:28:22 +00001478
1479 >>> D = decimal.Decimal
1480 >>> D('1.23') + D('3.45')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001481 Decimal('4.68')
Georg Brandl116aa622007-08-15 14:28:22 +00001482
1483Q. In a fixed-point application with two decimal places, some inputs have many
1484places and need to be rounded. Others are not supposed to have excess digits
1485and need to be validated. What methods should be used?
1486
1487A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
1488the :const:`Inexact` trap is set, it is also useful for validation::
1489
1490 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1491
1492 >>> # Round to two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001493 >>> Decimal('3.214').quantize(TWOPLACES)
1494 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001495
1496 >>> # Validate that a number does not exceed two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001497 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1498 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001499
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001500 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl116aa622007-08-15 14:28:22 +00001501 Traceback (most recent call last):
1502 ...
1503 Inexact: Changed in rounding
1504
1505Q. Once I have valid two place inputs, how do I maintain that invariant
1506throughout an application?
1507
Christian Heimesa156e092008-02-16 07:38:31 +00001508A. Some operations like addition, subtraction, and multiplication by an integer
1509will automatically preserve fixed point. Others operations, like division and
1510non-integer multiplication, will change the number of decimal places and need to
1511be followed-up with a :meth:`quantize` step::
1512
1513 >>> a = Decimal('102.72') # Initial fixed-point values
1514 >>> b = Decimal('3.17')
1515 >>> a + b # Addition preserves fixed-point
1516 Decimal('105.89')
1517 >>> a - b
1518 Decimal('99.55')
1519 >>> a * 42 # So does integer multiplication
1520 Decimal('4314.24')
1521 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1522 Decimal('325.62')
1523 >>> (b / a).quantize(TWOPLACES) # And quantize division
1524 Decimal('0.03')
1525
1526In developing fixed-point applications, it is convenient to define functions
1527to handle the :meth:`quantize` step::
1528
1529 >>> def mul(x, y, fp=TWOPLACES):
1530 ... return (x * y).quantize(fp)
1531 >>> def div(x, y, fp=TWOPLACES):
1532 ... return (x / y).quantize(fp)
1533
1534 >>> mul(a, b) # Automatically preserve fixed-point
1535 Decimal('325.62')
1536 >>> div(b, a)
1537 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +00001538
1539Q. There are many ways to express the same value. The numbers :const:`200`,
1540:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1541various precisions. Is there a way to transform them to a single recognizable
1542canonical value?
1543
1544A. The :meth:`normalize` method maps all equivalent values to a single
1545representative::
1546
1547 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1548 >>> [v.normalize() for v in values]
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001549 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl116aa622007-08-15 14:28:22 +00001550
1551Q. Some decimal values always print with exponential notation. Is there a way
1552to get a non-exponential representation?
1553
1554A. For some values, exponential notation is the only way to express the number
1555of significant places in the coefficient. For example, expressing
1556:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1557original's two-place significance.
1558
Christian Heimesa156e092008-02-16 07:38:31 +00001559If an application does not care about tracking significance, it is easy to
Christian Heimesc3f30c42008-02-22 16:37:40 +00001560remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimesa156e092008-02-16 07:38:31 +00001561value unchanged::
1562
1563 >>> def remove_exponent(d):
1564 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1565
1566 >>> remove_exponent(Decimal('5E+3'))
1567 Decimal('5000')
1568
Georg Brandl116aa622007-08-15 14:28:22 +00001569Q. Is there a way to convert a regular float to a :class:`Decimal`?
1570
1571A. Yes, all binary floating point numbers can be exactly expressed as a
1572Decimal. An exact conversion may take more precision than intuition would
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001573suggest, so we trap :const:`Inexact` to signal a need for more precision::
Georg Brandl116aa622007-08-15 14:28:22 +00001574
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001575 def float_to_decimal(f):
1576 "Convert a floating point number to a Decimal with no loss of information"
1577 n, d = f.as_integer_ratio()
1578 with localcontext() as ctx:
1579 ctx.traps[Inexact] = True
1580 while True:
1581 try:
1582 return Decimal(n) / Decimal(d)
1583 except Inexact:
1584 ctx.prec += 1
Georg Brandl116aa622007-08-15 14:28:22 +00001585
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001586 >>> float_to_decimal(math.pi)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001587 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl116aa622007-08-15 14:28:22 +00001588
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001589Q. Why isn't the :func:`float_to_decimal` routine included in the module?
Georg Brandl116aa622007-08-15 14:28:22 +00001590
1591A. There is some question about whether it is advisable to mix binary and
1592decimal floating point. Also, its use requires some care to avoid the
1593representation issues associated with binary floating point::
1594
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001595 >>> float_to_decimal(1.1)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001596 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl116aa622007-08-15 14:28:22 +00001597
1598Q. Within a complex calculation, how can I make sure that I haven't gotten a
1599spurious result because of insufficient precision or rounding anomalies.
1600
1601A. The decimal module makes it easy to test results. A best practice is to
1602re-run calculations using greater precision and with various rounding modes.
1603Widely differing results indicate insufficient precision, rounding mode issues,
1604ill-conditioned inputs, or a numerically unstable algorithm.
1605
1606Q. I noticed that context precision is applied to the results of operations but
1607not to the inputs. Is there anything to watch out for when mixing values of
1608different precisions?
1609
1610A. Yes. The principle is that all values are considered to be exact and so is
1611the arithmetic on those values. Only the results are rounded. The advantage
1612for inputs is that "what you type is what you get". A disadvantage is that the
1613results can look odd if you forget that the inputs haven't been rounded::
1614
1615 >>> getcontext().prec = 3
1616 >>> Decimal('3.104') + D('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001617 Decimal('5.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001618 >>> Decimal('3.104') + D('0.000') + D('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001619 Decimal('5.20')
Georg Brandl116aa622007-08-15 14:28:22 +00001620
1621The solution is either to increase precision or to force rounding of inputs
1622using the unary plus operation::
1623
1624 >>> getcontext().prec = 3
1625 >>> +Decimal('1.23456789') # unary plus triggers rounding
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001626 Decimal('1.23')
Georg Brandl116aa622007-08-15 14:28:22 +00001627
1628Alternatively, inputs can be rounded upon creation using the
1629:meth:`Context.create_decimal` method::
1630
1631 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001632 Decimal('1.2345')
Georg Brandl116aa622007-08-15 14:28:22 +00001633