blob: 04433c19e06557c05133c6e0e29f7846e3464e6c [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
Christian Heimesfe337bf2008-03-23 21:54:12 +000015.. import modules for testing inline doctests with the Sphinx doctest builder
16.. testsetup:: *
17
18 import decimal
19 import math
20 from decimal import *
21 # make sure each group gets a fresh context
22 setcontext(Context())
Georg Brandl116aa622007-08-15 14:28:22 +000023
Georg Brandl116aa622007-08-15 14:28:22 +000024The :mod:`decimal` module provides support for decimal floating point
Thomas Wouters1b7f8912007-09-19 03:06:30 +000025arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl116aa622007-08-15 14:28:22 +000026
Christian Heimes3feef612008-02-11 06:19:17 +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 Brandl116aa622007-08-15 14:28:22 +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
Thomas Wouters1b7f8912007-09-19 03:06:30 +000038 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl116aa622007-08-15 14:28:22 +000039 is :const:`5.5511151231257827e-017`. While near to zero, the differences
40 prevent reliable equality testing and differences can accumulate. For this
Christian Heimes3feef612008-02-11 06:19:17 +000041 reason, decimal is preferred in accounting applications which have strict
Georg Brandl116aa622007-08-15 14:28:22 +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
Thomas Wouters1b7f8912007-09-19 03:06:30 +000052 alterable precision (defaulting to 28 places) which can be as large as needed for
Christian Heimesfe337bf2008-03-23 21:54:12 +000053 a given problem:
Georg Brandl116aa622007-08-15 14:28:22 +000054
55 >>> getcontext().prec = 6
56 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000057 Decimal('0.142857')
Georg Brandl116aa622007-08-15 14:28:22 +000058 >>> getcontext().prec = 28
59 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000060 Decimal('0.1428571428571428571428571429')
Georg Brandl116aa622007-08-15 14:28:22 +000061
62* Both binary and decimal floating point are implemented in terms of published
63 standards. While the built-in float type exposes only a modest portion of its
64 capabilities, the decimal module exposes all required parts of the standard.
65 When needed, the programmer has full control over rounding and signal handling.
Christian Heimes3feef612008-02-11 06:19:17 +000066 This includes an option to enforce exact arithmetic by using exceptions
67 to block any inexact operations.
68
69* The decimal module was designed to support "without prejudice, both exact
70 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
71 and rounded floating-point arithmetic." -- excerpt from the decimal
72 arithmetic specification.
Georg Brandl116aa622007-08-15 14:28:22 +000073
74The module design is centered around three concepts: the decimal number, the
75context for arithmetic, and signals.
76
77A decimal number is immutable. It has a sign, coefficient digits, and an
78exponent. To preserve significance, the coefficient digits do not truncate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000079trailing zeros. Decimals also include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +000080:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
81differentiates :const:`-0` from :const:`+0`.
82
83The context for arithmetic is an environment specifying precision, rounding
84rules, limits on exponents, flags indicating the results of operations, and trap
85enablers which determine whether signals are treated as exceptions. Rounding
86options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
87:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +000088:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl116aa622007-08-15 14:28:22 +000089
90Signals are groups of exceptional conditions arising during the course of
91computation. Depending on the needs of the application, signals may be ignored,
92considered as informational, or treated as exceptions. The signals in the
93decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
94:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
95:const:`Overflow`, and :const:`Underflow`.
96
97For each signal there is a flag and a trap enabler. When a signal is
Raymond Hettinger86173da2008-02-01 20:38:12 +000098encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl116aa622007-08-15 14:28:22 +000099set to one, an exception is raised. Flags are sticky, so the user needs to
100reset them before monitoring a calculation.
101
102
103.. seealso::
104
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000105 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
106 Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000108 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Christian Heimes77c02eb2008-02-09 02:18:51 +0000109 <http://754r.ucbtest.org/standards/854.pdf>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000111.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113
114.. _decimal-tutorial:
115
116Quick-start Tutorial
117--------------------
118
119The usual start to using decimals is importing the module, viewing the current
120context with :func:`getcontext` and, if necessary, setting new values for
121precision, rounding, or enabled traps::
122
123 >>> from decimal import *
124 >>> getcontext()
125 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000126 capitals=1, flags=[], traps=[Overflow, DivisionByZero,
127 InvalidOperation])
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129 >>> getcontext().prec = 7 # Set a new precision
130
131Decimal instances can be constructed from integers, strings, or tuples. To
132create a Decimal from a :class:`float`, first convert it to a string. This
133serves as an explicit reminder of the details of the conversion (including
134representation error). Decimal numbers include special values such as
135:const:`NaN` which stands for "Not a number", positive and negative
Christian Heimesfe337bf2008-03-23 21:54:12 +0000136:const:`Infinity`, and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138 >>> Decimal(10)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000139 Decimal('10')
140 >>> Decimal('3.14')
141 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000142 >>> Decimal((0, (3, 1, 4), -2))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000143 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000144 >>> Decimal(str(2.0 ** 0.5))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000145 Decimal('1.41421356237')
146 >>> Decimal(2) ** Decimal('0.5')
147 Decimal('1.414213562373095048801688724')
148 >>> Decimal('NaN')
149 Decimal('NaN')
150 >>> Decimal('-Infinity')
151 Decimal('-Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153The significance of a new Decimal is determined solely by the number of digits
154input. Context precision and rounding only come into play during arithmetic
Christian Heimesfe337bf2008-03-23 21:54:12 +0000155operations.
156
157.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159 >>> getcontext().prec = 6
160 >>> Decimal('3.0')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000161 Decimal('3.0')
Georg Brandl116aa622007-08-15 14:28:22 +0000162 >>> Decimal('3.1415926535')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000163 Decimal('3.1415926535')
Georg Brandl116aa622007-08-15 14:28:22 +0000164 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000165 Decimal('5.85987')
Georg Brandl116aa622007-08-15 14:28:22 +0000166 >>> getcontext().rounding = ROUND_UP
167 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000168 Decimal('5.85988')
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170Decimals interact well with much of the rest of Python. Here is a small decimal
Christian Heimesfe337bf2008-03-23 21:54:12 +0000171floating point flying circus:
172
173.. doctest::
174 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000175
176 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
177 >>> max(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000178 Decimal('9.25')
Georg Brandl116aa622007-08-15 14:28:22 +0000179 >>> min(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000180 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +0000181 >>> sorted(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000182 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
183 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl116aa622007-08-15 14:28:22 +0000184 >>> sum(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000185 Decimal('19.29')
Georg Brandl116aa622007-08-15 14:28:22 +0000186 >>> a,b,c = data[:3]
187 >>> str(a)
188 '1.34'
189 >>> float(a)
190 1.3400000000000001
191 >>> round(a, 1) # round() first converts to binary floating point
192 1.3
193 >>> int(a)
194 1
195 >>> a * 5
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000196 Decimal('6.70')
Georg Brandl116aa622007-08-15 14:28:22 +0000197 >>> a * b
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000198 Decimal('2.5058')
Georg Brandl116aa622007-08-15 14:28:22 +0000199 >>> c % a
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000200 Decimal('0.77')
Georg Brandl116aa622007-08-15 14:28:22 +0000201
Christian Heimesfe337bf2008-03-23 21:54:12 +0000202And some mathematical functions are also available to Decimal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000203
204 >>> Decimal(2).sqrt()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000205 Decimal('1.414213562373095048801688724')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000206 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000207 Decimal('2.718281828459045235360287471')
208 >>> Decimal('10').ln()
209 Decimal('2.302585092994045684017991455')
210 >>> Decimal('10').log10()
211 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000212
Georg Brandl116aa622007-08-15 14:28:22 +0000213The :meth:`quantize` method rounds a number to a fixed exponent. This method is
214useful for monetary applications that often round results to a fixed number of
Christian Heimesfe337bf2008-03-23 21:54:12 +0000215places:
Georg Brandl116aa622007-08-15 14:28:22 +0000216
217 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000218 Decimal('7.32')
Georg Brandl116aa622007-08-15 14:28:22 +0000219 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000220 Decimal('8')
Georg Brandl116aa622007-08-15 14:28:22 +0000221
222As shown above, the :func:`getcontext` function accesses the current context and
223allows the settings to be changed. This approach meets the needs of most
224applications.
225
226For more advanced work, it may be useful to create alternate contexts using the
227Context() constructor. To make an alternate active, use the :func:`setcontext`
228function.
229
230In accordance with the standard, the :mod:`Decimal` module provides two ready to
231use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
232former is especially useful for debugging because many of the traps are
Christian Heimesfe337bf2008-03-23 21:54:12 +0000233enabled:
234
235.. doctest:: newcontext
236 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000237
238 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
239 >>> setcontext(myothercontext)
240 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000241 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243 >>> ExtendedContext
244 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
245 capitals=1, flags=[], traps=[])
246 >>> setcontext(ExtendedContext)
247 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000248 Decimal('0.142857143')
Georg Brandl116aa622007-08-15 14:28:22 +0000249 >>> Decimal(42) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000250 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000251
252 >>> setcontext(BasicContext)
253 >>> Decimal(42) / Decimal(0)
254 Traceback (most recent call last):
255 File "<pyshell#143>", line 1, in -toplevel-
256 Decimal(42) / Decimal(0)
257 DivisionByZero: x / 0
258
259Contexts also have signal flags for monitoring exceptional conditions
260encountered during computations. The flags remain set until explicitly cleared,
261so it is best to clear the flags before each set of monitored computations by
262using the :meth:`clear_flags` method. ::
263
264 >>> setcontext(ExtendedContext)
265 >>> getcontext().clear_flags()
266 >>> Decimal(355) / Decimal(113)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000267 Decimal('3.14159292')
Georg Brandl116aa622007-08-15 14:28:22 +0000268 >>> getcontext()
269 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000270 capitals=1, flags=[Rounded, Inexact], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272The *flags* entry shows that the rational approximation to :const:`Pi` was
273rounded (digits beyond the context precision were thrown away) and that the
274result is inexact (some of the discarded digits were non-zero).
275
276Individual traps are set using the dictionary in the :attr:`traps` field of a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000277context:
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Christian Heimesfe337bf2008-03-23 21:54:12 +0000279.. doctest:: newcontext
280
281 >>> setcontext(ExtendedContext)
Georg Brandl116aa622007-08-15 14:28:22 +0000282 >>> Decimal(1) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000283 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000284 >>> getcontext().traps[DivisionByZero] = 1
285 >>> Decimal(1) / Decimal(0)
286 Traceback (most recent call last):
287 File "<pyshell#112>", line 1, in -toplevel-
288 Decimal(1) / Decimal(0)
289 DivisionByZero: x / 0
290
291Most programs adjust the current context only once, at the beginning of the
292program. And, in many applications, data is converted to :class:`Decimal` with
293a single cast inside a loop. With context set and decimals created, the bulk of
294the program manipulates the data no differently than with other Python numeric
295types.
296
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000297.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000298
299
300.. _decimal-decimal:
301
302Decimal objects
303---------------
304
305
306.. class:: Decimal([value [, context]])
307
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000308 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
Christian Heimesa62da1d2008-01-12 19:39:10 +0000310 *value* can be an integer, string, tuple, or another :class:`Decimal`
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000311 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Christian Heimesa62da1d2008-01-12 19:39:10 +0000312 string, it should conform to the decimal numeric string syntax after leading
313 and trailing whitespace characters are removed::
Georg Brandl116aa622007-08-15 14:28:22 +0000314
315 sign ::= '+' | '-'
316 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
317 indicator ::= 'e' | 'E'
318 digits ::= digit [digit]...
319 decimal-part ::= digits '.' [digits] | ['.'] digits
320 exponent-part ::= indicator [sign] digits
321 infinity ::= 'Infinity' | 'Inf'
322 nan ::= 'NaN' [digits] | 'sNaN' [digits]
323 numeric-value ::= decimal-part [exponent-part] | infinity
324 numeric-string ::= [sign] numeric-value | [sign] nan
325
326 If *value* is a :class:`tuple`, it should have three components, a sign
327 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
328 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000329 returns ``Decimal('1.414')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331 The *context* precision does not affect how many digits are stored. That is
332 determined exclusively by the number of digits in *value*. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000333 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl116aa622007-08-15 14:28:22 +0000334 only three.
335
336 The purpose of the *context* argument is determining what to do if *value* is a
337 malformed string. If the context traps :const:`InvalidOperation`, an exception
338 is raised; otherwise, the constructor returns a new Decimal with the value of
339 :const:`NaN`.
340
341 Once constructed, :class:`Decimal` objects are immutable.
342
Christian Heimesa62da1d2008-01-12 19:39:10 +0000343 .. versionchanged:: 2.6
344 leading and trailing whitespace characters are permitted when
345 creating a Decimal instance from a string.
346
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000347Decimal floating point objects share many properties with the other built-in
Georg Brandl116aa622007-08-15 14:28:22 +0000348numeric types such as :class:`float` and :class:`int`. All of the usual math
349operations and special methods apply. Likewise, decimal objects can be copied,
350pickled, printed, used as dictionary keys, used as set elements, compared,
Neil Schemenauer16c70752007-09-21 20:19:23 +0000351sorted, and converted to another type (such as :class:`float` or :class:`int`).
Georg Brandl116aa622007-08-15 14:28:22 +0000352
353In addition to the standard numeric properties, decimal floating point objects
354also have a number of specialized methods:
355
356
357.. method:: Decimal.adjusted()
358
359 Return the adjusted exponent after shifting out the coefficient's rightmost
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000360 digits until only the lead digit remains: ``Decimal('321e+5').adjusted()``
Georg Brandl116aa622007-08-15 14:28:22 +0000361 returns seven. Used for determining the position of the most significant digit
362 with respect to the decimal point.
363
364
365.. method:: Decimal.as_tuple()
366
Christian Heimes25bb7832008-01-11 16:17:00 +0000367 Return a :term:`named tuple` representation of the number:
368 ``DecimalTuple(sign, digits, exponent)``.
369
370 .. versionchanged:: 2.6
371 Use a named tuple.
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000374.. method:: Decimal.canonical()
375
376 Return the canonical encoding of the argument. Currently, the
377 encoding of a :class:`Decimal` instance is always canonical, so
378 this operation returns its argument unchanged.
379
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000380
Georg Brandl116aa622007-08-15 14:28:22 +0000381.. method:: Decimal.compare(other[, context])
382
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000383 Compare the values of two Decimal instances. This operation
384 behaves in the same way as the usual comparison method
385 :meth:`__cmp__`, except that :meth:`compare` returns a Decimal
386 instance rather than an integer, and if either operand is a NaN
387 then the result is a NaN::
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000389 a or b is a NaN ==> Decimal('NaN')
390 a < b ==> Decimal('-1')
391 a == b ==> Decimal('0')
392 a > b ==> Decimal('1')
Georg Brandl116aa622007-08-15 14:28:22 +0000393
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000394.. method:: Decimal.compare_signal(other[, context])
395
396 This operation is identical to the :meth:`compare` method, except
397 that all NaNs signal. That is, if neither operand is a signaling
398 NaN then any quiet NaN operand is treated as though it were a
399 signaling NaN.
400
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000401
402.. method:: Decimal.compare_total(other)
403
404 Compare two operands using their abstract representation rather
405 than their numerical value. Similar to the :meth:`compare` method,
406 but the result gives a total ordering on :class:`Decimal`
407 instances. Two :class:`Decimal` instances with the same numeric
408 value but different representations compare unequal in this
Christian Heimesfe337bf2008-03-23 21:54:12 +0000409 ordering:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000410
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000411 >>> Decimal('12.0').compare_total(Decimal('12'))
412 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000413
414 Quiet and signaling NaNs are also included in the total ordering.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000415 The result of this function is ``Decimal('0')`` if both operands
416 have the same representation, ``Decimal('-1')`` if the first
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000417 operand is lower in the total order than the second, and
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000418 ``Decimal('1')`` if the first operand is higher in the total order
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000419 than the second operand. See the specification for details of the
420 total order.
421
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000422
423.. method:: Decimal.compare_total_mag(other)
424
425 Compare two operands using their abstract representation rather
426 than their value as in :meth:`compare_total`, but ignoring the sign
427 of each operand. ``x.compare_total_mag(y)`` is equivalent to
428 ``x.copy_abs().compare_total(y.copy_abs())``.
429
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000430
431.. method:: Decimal.copy_abs()
432
433 Return the absolute value of the argument. This operation is
434 unaffected by the context and is quiet: no flags are changed and no
435 rounding is performed.
436
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000437
438.. method:: Decimal.copy_negate()
439
440 Return the negation of the argument. This operation is unaffected
441 by the context and is quiet: no flags are changed and no rounding
442 is performed.
443
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000444
445.. method:: Decimal.copy_sign(other)
446
447 Return a copy of the first operand with the sign set to be the
Christian Heimesfe337bf2008-03-23 21:54:12 +0000448 same as the sign of the second operand. For example:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000449
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000450 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
451 Decimal('-2.3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000452
453 This operation is unaffected by the context and is quiet: no flags
454 are changed and no rounding is performed.
455
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000456
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
463 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000464 Decimal('2.718281828459045235360287471')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000465 >>> Decimal(321).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000466 Decimal('2.561702493119680037517373933E+139')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000467
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000468
469.. method:: Decimal.fma(other, third[, context])
470
471 Fused multiply-add. Return self*other+third with no rounding of
472 the intermediate product self*other.
473
474 >>> Decimal(2).fma(3, 5)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000475 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000476
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000477
478.. method:: Decimal.is_canonical()
479
480 Return :const:`True` if the argument is canonical and
481 :const:`False` otherwise. Currently, a :class:`Decimal` instance
482 is always canonical, so this operation always returns
483 :const:`True`.
484
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000485
486.. method:: is_finite()
487
488 Return :const:`True` if the argument is a finite number, and
489 :const:`False` if the argument is an infinity or a NaN.
490
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000491
492.. method:: is_infinite()
493
494 Return :const:`True` if the argument is either positive or
495 negative infinity and :const:`False` otherwise.
496
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000497
498.. method:: is_nan()
499
500 Return :const:`True` if the argument is a (quiet or signaling)
501 NaN and :const:`False` otherwise.
502
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503
504.. method:: is_normal()
505
506 Return :const:`True` if the argument is a *normal* finite number.
507 Return :const:`False` if the argument is zero, subnormal, infinite
508 or a NaN.
509
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510
511.. method:: is_qnan()
512
513 Return :const:`True` if the argument is a quiet NaN, and
514 :const:`False` otherwise.
515
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000516
517.. method:: is_signed()
518
519 Return :const:`True` if the argument has a negative sign and
520 :const:`False` otherwise. Note that zeros and NaNs can both carry
521 signs.
522
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000523
524.. method:: is_snan()
525
526 Return :const:`True` if the argument is a signaling NaN and
527 :const:`False` otherwise.
528
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000529
530.. method:: is_subnormal()
531
532 Return :const:`True` if the argument is subnormal, and
533 :const:`False` otherwise.
534
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000535
536.. method:: is_zero()
537
538 Return :const:`True` if the argument is a (positive or negative)
539 zero and :const:`False` otherwise.
540
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000541
542.. method:: Decimal.ln([context])
543
544 Return the natural (base e) logarithm of the operand. The result
545 is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
546 mode.
547
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000548
549.. method:: Decimal.log10([context])
550
551 Return the base ten logarithm of the operand. The result is
552 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
553
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000554
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000555.. method:: Decimal.logb([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000556
557 For a nonzero number, return the adjusted exponent of its operand
558 as a :class:`Decimal` instance. If the operand is a zero then
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000559 ``Decimal('-Infinity')`` is returned and the
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000560 :const:`DivisionByZero` flag is raised. If the operand is an
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000561 infinity then ``Decimal('Infinity')`` is returned.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000562
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000563
564.. method:: Decimal.logical_and(other[, context])
565
566 :meth:`logical_and` is a logical operation which takes two
567 *logical operands* (see :ref:`logical_operands_label`). The result
568 is the digit-wise ``and`` of the two operands.
569
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570
571.. method:: Decimal.logical_invert(other[, context])
572
573 :meth:`logical_invert` is a logical operation. The argument must
574 be a *logical operand* (see :ref:`logical_operands_label`). The
575 result is the digit-wise inversion of the operand.
576
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000577
578.. method:: Decimal.logical_or(other[, context])
579
580 :meth:`logical_or` is a logical operation which takes two *logical
581 operands* (see :ref:`logical_operands_label`). The result is the
582 digit-wise ``or`` of the two operands.
583
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000584
585.. method:: Decimal.logical_xor(other[, context])
586
587 :meth:`logical_xor` is a logical operation which takes two
588 *logical operands* (see :ref:`logical_operands_label`). The result
589 is the digit-wise exclusive or of the two operands.
590
Georg Brandl116aa622007-08-15 14:28:22 +0000591
592.. method:: Decimal.max(other[, context])
593
594 Like ``max(self, other)`` except that the context rounding rule is applied
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000595 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl116aa622007-08-15 14:28:22 +0000596 (depending on the context and whether they are signaling or quiet).
597
Georg Brandl6554cb92007-12-02 23:15:43 +0000598
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000599.. method:: Decimal.max_mag(other[, context])
600
601 Similar to the :meth:`max` method, but the comparison is done using
602 the absolute values of the operands.
603
Georg Brandl116aa622007-08-15 14:28:22 +0000604
605.. method:: Decimal.min(other[, context])
606
607 Like ``min(self, other)`` except that the context rounding rule is applied
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000608 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl116aa622007-08-15 14:28:22 +0000609 (depending on the context and whether they are signaling or quiet).
610
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000611.. method:: Decimal.min_mag(other[, context])
612
613 Similar to the :meth:`min` method, but the comparison is done using
614 the absolute values of the operands.
615
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616
617.. method:: Decimal.next_minus([context])
618
619 Return the largest number representable in the given context (or
620 in the current thread's context if no context is given) that is smaller
621 than the given operand.
622
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000623
624.. method:: Decimal.next_plus([context])
625
626 Return the smallest number representable in the given context (or
627 in the current thread's context if no context is given) that is
628 larger than the given operand.
629
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000630
631.. method:: Decimal.next_toward(other[, context])
632
633 If the two operands are unequal, return the number closest to the
634 first operand in the direction of the second operand. If both
635 operands are numerically equal, return a copy of the first operand
636 with the sign set to be the same as the sign of the second operand.
637
Georg Brandl116aa622007-08-15 14:28:22 +0000638
639.. method:: Decimal.normalize([context])
640
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000641 Normalize the number by stripping the rightmost trailing zeros and converting
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000642 any result equal to :const:`Decimal('0')` to :const:`Decimal('0e0')`. Used for
Georg Brandl116aa622007-08-15 14:28:22 +0000643 producing canonical values for members of an equivalence class. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000644 ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both normalize to the
645 equivalent value ``Decimal('32.1')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000646
Georg Brandl6554cb92007-12-02 23:15:43 +0000647
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000648.. method:: Decimal.number_class([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000649
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000650 Return a string describing the *class* of the operand. The
651 returned value is one of the following ten strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000652
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653 * ``"-Infinity"``, indicating that the operand is negative infinity.
654 * ``"-Normal"``, indicating that the operand is a negative normal number.
655 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
656 * ``"-Zero"``, indicating that the operand is a negative zero.
657 * ``"+Zero"``, indicating that the operand is a positive zero.
658 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
659 * ``"+Normal"``, indicating that the operand is a positive normal number.
660 * ``"+Infinity"``, indicating that the operand is positive infinity.
661 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
662 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000663
Georg Brandl116aa622007-08-15 14:28:22 +0000664
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]])
666
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000667 Return a value equal to the first operand after rounding and
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668 having the exponent of the second operand.
669
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000670 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
671 Decimal('1.414')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000672
673 Unlike other operations, if the length of the coefficient after the
674 quantize operation would be greater than precision, then an
675 :const:`InvalidOperation` is signaled. This guarantees that, unless
676 there is an error condition, the quantized exponent is always equal
677 to that of the right-hand operand.
678
679 Also unlike other operations, quantize never signals Underflow,
680 even if the result is subnormal and inexact.
681
682 If the exponent of the second operand is larger than that of the
683 first then rounding may be necessary. In this case, the rounding
684 mode is determined by the ``rounding`` argument if given, else by
685 the given ``context`` argument; if neither argument is given the
686 rounding mode of the current thread's context is used.
687
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000688 If *watchexp* is set (default), then an error is returned whenever the
689 resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000690
691.. method:: Decimal.radix()
692
693 Return ``Decimal(10)``, the radix (base) in which the
694 :class:`Decimal` class does all its arithmetic. Included for
695 compatibility with the specification.
696
Georg Brandl116aa622007-08-15 14:28:22 +0000697
698.. method:: Decimal.remainder_near(other[, context])
699
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000700 Compute the modulo as either a positive or negative value depending on which is
Georg Brandl116aa622007-08-15 14:28:22 +0000701 closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000702 ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
704 If both are equally close, the one chosen will have the same sign as *self*.
705
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000706.. method:: Decimal.rotate(other[, context])
707
708 Return the result of rotating the digits of the first operand by
709 an amount specified by the second operand. The second operand
710 must be an integer in the range -precision through precision. The
711 absolute value of the second operand gives the number of places to
712 rotate. If the second operand is positive then rotation is to the
713 left; otherwise rotation is to the right. The coefficient of the
714 first operand is padded on the left with zeros to length precision
715 if necessary. The sign and exponent of the first operand are
716 unchanged.
717
Georg Brandl116aa622007-08-15 14:28:22 +0000718
719.. method:: Decimal.same_quantum(other[, context])
720
721 Test whether self and other have the same exponent or whether both are
722 :const:`NaN`.
723
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000724.. method:: Decimal.scaleb(other[, context])
725
726 Return the first operand with exponent adjusted by the second.
727 Equivalently, return the first operand multiplied by ``10**other``.
728 The second operand must be an integer.
729
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000730
731.. method:: Decimal.shift(other[, context])
732
733 Return the result of shifting the digits of the first operand by
734 an amount specified by the second operand. The second operand must
735 be an integer in the range -precision through precision. The
736 absolute value of the second operand gives the number of places to
737 shift. If the second operand is positive then the shift is to the
738 left; otherwise the shift is to the right. Digits shifted into the
739 coefficient are zeros. The sign and exponent of the first operand
740 are unchanged.
741
Georg Brandl116aa622007-08-15 14:28:22 +0000742
743.. method:: Decimal.sqrt([context])
744
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000746
747
748.. method:: Decimal.to_eng_string([context])
749
750 Convert to an engineering-type string.
751
752 Engineering notation has an exponent which is a multiple of 3, so there are up
753 to 3 digits left of the decimal place. For example, converts
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000754 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Georg Brandl116aa622007-08-15 14:28:22 +0000755
Georg Brandl116aa622007-08-15 14:28:22 +0000756.. method:: Decimal.to_integral([rounding[, context]])
757
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000758 Identical to the :meth:`to_integral_value` method. The ``to_integral``
759 name has been kept for compatibility with older versions.
760
761.. method:: Decimal.to_integral_exact([rounding[, context]])
762
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000763 Round to the nearest integer, signaling
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000764 :const:`Inexact` or :const:`Rounded` as appropriate if rounding
765 occurs. The rounding mode is determined by the ``rounding``
766 parameter if given, else by the given ``context``. If neither
767 parameter is given then the rounding mode of the current context is
768 used.
769
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000770
771.. method:: Decimal.to_integral_value([rounding[, context]])
772
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000773 Round to the nearest integer without signaling :const:`Inexact` or
Georg Brandl116aa622007-08-15 14:28:22 +0000774 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding
775 method in either the supplied *context* or the current context.
776
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000777
778.. method:: Decimal.trim()
779
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000780 Return the decimal with *insignificant* trailing zeros removed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000781 Here, a trailing zero is considered insignificant either if it
782 follows the decimal point, or if the exponent of the argument (that
783 is, the last element of the :meth:`as_tuple` representation) is
784 positive.
785
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000786
787.. _logical_operands_label:
788
789Logical operands
790^^^^^^^^^^^^^^^^
791
792The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
793and :meth:`logical_xor` methods expect their arguments to be *logical
794operands*. A *logical operand* is a :class:`Decimal` instance whose
795exponent and sign are both zero, and whose digits are all either
796:const:`0` or :const:`1`.
797
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000798.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000799
800
801.. _decimal-context:
802
803Context objects
804---------------
805
806Contexts are environments for arithmetic operations. They govern precision, set
807rules for rounding, determine which signals are treated as exceptions, and limit
808the range for exponents.
809
810Each thread has its own current context which is accessed or changed using the
811:func:`getcontext` and :func:`setcontext` functions:
812
813
814.. function:: getcontext()
815
816 Return the current context for the active thread.
817
818
819.. function:: setcontext(c)
820
821 Set the current context for the active thread to *c*.
822
823Beginning with Python 2.5, you can also use the :keyword:`with` statement and
824the :func:`localcontext` function to temporarily change the active context.
825
826
827.. function:: localcontext([c])
828
829 Return a context manager that will set the current context for the active thread
830 to a copy of *c* on entry to the with-statement and restore the previous context
831 when exiting the with-statement. If no context is specified, a copy of the
832 current context is used.
833
Georg Brandl116aa622007-08-15 14:28:22 +0000834 For example, the following code sets the current decimal precision to 42 places,
835 performs a calculation, and then automatically restores the previous context::
836
Georg Brandl116aa622007-08-15 14:28:22 +0000837 from decimal import localcontext
838
839 with localcontext() as ctx:
840 ctx.prec = 42 # Perform a high precision calculation
841 s = calculate_something()
842 s = +s # Round the final result back to the default precision
843
844New contexts can also be created using the :class:`Context` constructor
845described below. In addition, the module provides three pre-made contexts:
846
847
848.. class:: BasicContext
849
850 This is a standard context defined by the General Decimal Arithmetic
851 Specification. Precision is set to nine. Rounding is set to
852 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
853 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
854 :const:`Subnormal`.
855
856 Because many of the traps are enabled, this context is useful for debugging.
857
858
859.. class:: ExtendedContext
860
861 This is a standard context defined by the General Decimal Arithmetic
862 Specification. Precision is set to nine. Rounding is set to
863 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
864 exceptions are not raised during computations).
865
Christian Heimes3feef612008-02-11 06:19:17 +0000866 Because the traps are disabled, this context is useful for applications that
Georg Brandl116aa622007-08-15 14:28:22 +0000867 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
868 raising exceptions. This allows an application to complete a run in the
869 presence of conditions that would otherwise halt the program.
870
871
872.. class:: DefaultContext
873
874 This context is used by the :class:`Context` constructor as a prototype for new
875 contexts. Changing a field (such a precision) has the effect of changing the
876 default for new contexts creating by the :class:`Context` constructor.
877
878 This context is most useful in multi-threaded environments. Changing one of the
879 fields before threads are started has the effect of setting system-wide
880 defaults. Changing the fields after threads have started is not recommended as
881 it would require thread synchronization to prevent race conditions.
882
883 In single threaded environments, it is preferable to not use this context at
884 all. Instead, simply create contexts explicitly as described below.
885
886 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
887 for Overflow, InvalidOperation, and DivisionByZero.
888
889In addition to the three supplied contexts, new contexts can be created with the
890:class:`Context` constructor.
891
892
893.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
894
895 Creates a new context. If a field is not specified or is :const:`None`, the
896 default values are copied from the :const:`DefaultContext`. If the *flags*
897 field is not specified or is :const:`None`, all flags are cleared.
898
899 The *prec* field is a positive integer that sets the precision for arithmetic
900 operations in the context.
901
902 The *rounding* option is one of:
903
904 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
905 * :const:`ROUND_DOWN` (towards zero),
906 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
907 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
908 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
909 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
910 * :const:`ROUND_UP` (away from zero).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
912 would have been 0 or 5; otherwise towards zero)
Georg Brandl116aa622007-08-15 14:28:22 +0000913
914 The *traps* and *flags* fields list any signals to be set. Generally, new
915 contexts should only set traps and leave the flags clear.
916
917 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
918 for exponents.
919
920 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
921 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
922 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
923
Georg Brandl116aa622007-08-15 14:28:22 +0000924
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925The :class:`Context` class defines several general purpose methods as
926well as a large number of methods for doing arithmetic directly in a
927given context. In addition, for each of the :class:`Decimal` methods
928described above (with the exception of the :meth:`adjusted` and
929:meth:`as_tuple` methods) there is a corresponding :class:`Context`
930method. For example, ``C.exp(x)`` is equivalent to
931``x.exp(context=C)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000932
933.. method:: Context.clear_flags()
934
935 Resets all of the flags to :const:`0`.
936
937
938.. method:: Context.copy()
939
940 Return a duplicate of the context.
941
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000942.. method:: Context.copy_decimal(num)
943
944 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +0000945
946.. method:: Context.create_decimal(num)
947
948 Creates a new Decimal instance from *num* but using *self* as context. Unlike
949 the :class:`Decimal` constructor, the context precision, rounding method, flags,
950 and traps are applied to the conversion.
951
952 This is useful because constants are often given to a greater precision than is
953 needed by the application. Another benefit is that rounding immediately
954 eliminates unintended effects from digits beyond the current precision. In the
955 following example, using unrounded inputs means that adding zero to a sum can
Christian Heimesfe337bf2008-03-23 21:54:12 +0000956 change the result:
957
958 .. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000959
960 >>> getcontext().prec = 3
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000961 >>> Decimal('3.4445') + Decimal('1.0023')
962 Decimal('4.45')
963 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
964 Decimal('4.44')
Georg Brandl116aa622007-08-15 14:28:22 +0000965
Christian Heimesa62da1d2008-01-12 19:39:10 +0000966 This method implements the to-number operation of the IBM
967 specification. If the argument is a string, no leading or trailing
968 whitespace is permitted.
Georg Brandl116aa622007-08-15 14:28:22 +0000969
970.. method:: Context.Etiny()
971
972 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
973 for subnormal results. When underflow occurs, the exponent is set to
974 :const:`Etiny`.
975
976
977.. method:: Context.Etop()
978
979 Returns a value equal to ``Emax - prec + 1``.
980
981The usual approach to working with decimals is to create :class:`Decimal`
982instances and then apply arithmetic operations which take place within the
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000983current context for the active thread. An alternative approach is to use context
Georg Brandl116aa622007-08-15 14:28:22 +0000984methods for calculating within a specific context. The methods are similar to
985those for the :class:`Decimal` class and are only briefly recounted here.
986
987
988.. method:: Context.abs(x)
989
990 Returns the absolute value of *x*.
991
992
993.. method:: Context.add(x, y)
994
995 Return the sum of *x* and *y*.
996
997
Georg Brandl116aa622007-08-15 14:28:22 +0000998.. method:: Context.divide(x, y)
999
1000 Return *x* divided by *y*.
1001
1002
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001003.. method:: Context.divide_int(x, y)
1004
1005 Return *x* divided by *y*, truncated to an integer.
1006
1007
Georg Brandl116aa622007-08-15 14:28:22 +00001008.. method:: Context.divmod(x, y)
1009
1010 Divides two numbers and returns the integer part of the result.
1011
1012
Georg Brandl116aa622007-08-15 14:28:22 +00001013.. method:: Context.minus(x)
1014
1015 Minus corresponds to the unary prefix minus operator in Python.
1016
1017
1018.. method:: Context.multiply(x, y)
1019
1020 Return the product of *x* and *y*.
1021
1022
Georg Brandl116aa622007-08-15 14:28:22 +00001023.. method:: Context.plus(x)
1024
1025 Plus corresponds to the unary prefix plus operator in Python. This operation
1026 applies the context precision and rounding, so it is *not* an identity
1027 operation.
1028
1029
1030.. method:: Context.power(x, y[, modulo])
1031
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001032 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if
1033 given.
Georg Brandl116aa622007-08-15 14:28:22 +00001034
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001035 With two arguments, compute ``x**y``. If ``x`` is negative then
1036 ``y`` must be integral. The result will be inexact unless ``y`` is
1037 integral and the result is finite and can be expressed exactly in
1038 'precision' digits. The result should always be correctly rounded,
1039 using the rounding mode of the current thread's context.
Georg Brandl116aa622007-08-15 14:28:22 +00001040
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001041 With three arguments, compute ``(x**y) % modulo``. For the three
1042 argument form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +00001043
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001044 - all three arguments must be integral
1045 - ``y`` must be nonnegative
1046 - at least one of ``x`` or ``y`` must be nonzero
1047 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +00001048
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001049 The result of ``Context.power(x, y, modulo)`` is identical to
1050 the result that would be obtained by computing ``(x**y) %
1051 modulo`` with unbounded precision, but is computed more
1052 efficiently. It is always exact.
Georg Brandl116aa622007-08-15 14:28:22 +00001053
Georg Brandl116aa622007-08-15 14:28:22 +00001054
1055.. method:: Context.remainder(x, y)
1056
1057 Returns the remainder from integer division.
1058
1059 The sign of the result, if non-zero, is the same as that of the original
1060 dividend.
1061
Georg Brandl116aa622007-08-15 14:28:22 +00001062.. method:: Context.subtract(x, y)
1063
1064 Return the difference between *x* and *y*.
1065
Georg Brandl116aa622007-08-15 14:28:22 +00001066.. method:: Context.to_sci_string(x)
1067
1068 Converts a number to a string using scientific notation.
1069
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001070.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001071
1072
1073.. _decimal-signals:
1074
1075Signals
1076-------
1077
1078Signals represent conditions that arise during computation. Each corresponds to
1079one context flag and one context trap enabler.
1080
Raymond Hettinger86173da2008-02-01 20:38:12 +00001081The context flag is set whenever the condition is encountered. After the
Georg Brandl116aa622007-08-15 14:28:22 +00001082computation, flags may be checked for informational purposes (for instance, to
1083determine whether a computation was exact). After checking the flags, be sure to
1084clear all flags before starting the next computation.
1085
1086If the context's trap enabler is set for the signal, then the condition causes a
1087Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1088is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1089condition.
1090
1091
1092.. class:: Clamped
1093
1094 Altered an exponent to fit representation constraints.
1095
1096 Typically, clamping occurs when an exponent falls outside the context's
1097 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001098 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001099
1100
1101.. class:: DecimalException
1102
1103 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1104
1105
1106.. class:: DivisionByZero
1107
1108 Signals the division of a non-infinite number by zero.
1109
1110 Can occur with division, modulo division, or when raising a number to a negative
1111 power. If this signal is not trapped, returns :const:`Infinity` or
1112 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1113
1114
1115.. class:: Inexact
1116
1117 Indicates that rounding occurred and the result is not exact.
1118
1119 Signals when non-zero digits were discarded during rounding. The rounded result
1120 is returned. The signal flag or trap is used to detect when results are
1121 inexact.
1122
1123
1124.. class:: InvalidOperation
1125
1126 An invalid operation was performed.
1127
1128 Indicates that an operation was requested that does not make sense. If not
1129 trapped, returns :const:`NaN`. Possible causes include::
1130
1131 Infinity - Infinity
1132 0 * Infinity
1133 Infinity / Infinity
1134 x % 0
1135 Infinity % x
1136 x._rescale( non-integer )
1137 sqrt(-x) and x > 0
1138 0 ** 0
1139 x ** (non-integer)
1140 x ** Infinity
1141
1142
1143.. class:: Overflow
1144
1145 Numerical overflow.
1146
1147 Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
1148 If not trapped, the result depends on the rounding mode, either pulling inward
1149 to the largest representable finite number or rounding outward to
1150 :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are
1151 also signaled.
1152
1153
1154.. class:: Rounded
1155
1156 Rounding occurred though possibly no information was lost.
1157
1158 Signaled whenever rounding discards digits; even if those digits are zero (such
1159 as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result
1160 unchanged. This signal is used to detect loss of significant digits.
1161
1162
1163.. class:: Subnormal
1164
1165 Exponent was lower than :attr:`Emin` prior to rounding.
1166
1167 Occurs when an operation result is subnormal (the exponent is too small). If not
1168 trapped, returns the result unchanged.
1169
1170
1171.. class:: Underflow
1172
1173 Numerical underflow with result rounded to zero.
1174
1175 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1176 and :class:`Subnormal` are also signaled.
1177
1178The following table summarizes the hierarchy of signals::
1179
1180 exceptions.ArithmeticError(exceptions.Exception)
1181 DecimalException
1182 Clamped
1183 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1184 Inexact
1185 Overflow(Inexact, Rounded)
1186 Underflow(Inexact, Rounded, Subnormal)
1187 InvalidOperation
1188 Rounded
1189 Subnormal
1190
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001191.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001192
1193
1194.. _decimal-notes:
1195
1196Floating Point Notes
1197--------------------
1198
1199
1200Mitigating round-off error with increased precision
1201^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1202
1203The use of decimal floating point eliminates decimal representation error
1204(making it possible to represent :const:`0.1` exactly); however, some operations
1205can still incur round-off error when non-zero digits exceed the fixed precision.
1206
1207The effects of round-off error can be amplified by the addition or subtraction
1208of nearly offsetting quantities resulting in loss of significance. Knuth
1209provides two instructive examples where rounded floating point arithmetic with
1210insufficient precision causes the breakdown of the associative and distributive
Christian Heimesfe337bf2008-03-23 21:54:12 +00001211properties of addition:
1212
1213.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001214
1215 # Examples from Seminumerical Algorithms, Section 4.2.2.
1216 >>> from decimal import Decimal, getcontext
1217 >>> getcontext().prec = 8
1218
1219 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1220 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001221 Decimal('9.5111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001222 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001223 Decimal('10')
Georg Brandl116aa622007-08-15 14:28:22 +00001224
1225 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1226 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001227 Decimal('0.01')
Georg Brandl116aa622007-08-15 14:28:22 +00001228 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001229 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001230
1231The :mod:`decimal` module makes it possible to restore the identities by
Christian Heimesfe337bf2008-03-23 21:54:12 +00001232expanding the precision sufficiently to avoid loss of significance:
1233
1234.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001235
1236 >>> getcontext().prec = 20
1237 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1238 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001239 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001240 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001241 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001242 >>>
1243 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1244 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001245 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001246 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001247 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001248
1249
1250Special values
1251^^^^^^^^^^^^^^
1252
1253The number system for the :mod:`decimal` module provides special values
1254including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001255and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001256
1257Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1258they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1259not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1260can result from rounding beyond the limits of the largest representable number.
1261
1262The infinities are signed (affine) and can be used in arithmetic operations
1263where they get treated as very large, indeterminate numbers. For instance,
1264adding a constant to infinity gives another infinite result.
1265
1266Some operations are indeterminate and return :const:`NaN`, or if the
1267:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1268``0/0`` returns :const:`NaN` which means "not a number". This variety of
1269:const:`NaN` is quiet and, once created, will flow through other computations
1270always resulting in another :const:`NaN`. This behavior can be useful for a
1271series of computations that occasionally have missing inputs --- it allows the
1272calculation to proceed while flagging specific results as invalid.
1273
1274A variant is :const:`sNaN` which signals rather than remaining quiet after every
1275operation. This is a useful return value when an invalid result needs to
1276interrupt a calculation for special handling.
1277
Christian Heimes77c02eb2008-02-09 02:18:51 +00001278The behavior of Python's comparison operators can be a little surprising where a
1279:const:`NaN` is involved. A test for equality where one of the operands is a
1280quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1281``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1282:const:`True`. An attempt to compare two Decimals using any of the ``<``,
1283``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1284if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes3feef612008-02-11 06:19:17 +00001285not trapped. Note that the General Decimal Arithmetic specification does not
Christian Heimes77c02eb2008-02-09 02:18:51 +00001286specify the behavior of direct comparisons; these rules for comparisons
1287involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1288section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1289and :meth:`compare-signal` methods instead.
1290
Georg Brandl116aa622007-08-15 14:28:22 +00001291The signed zeros can result from calculations that underflow. They keep the sign
1292that would have resulted if the calculation had been carried out to greater
1293precision. Since their magnitude is zero, both positive and negative zeros are
1294treated as equal and their sign is informational.
1295
1296In addition to the two signed zeros which are distinct yet equal, there are
1297various representations of zero with differing precisions yet equivalent in
1298value. This takes a bit of getting used to. For an eye accustomed to
1299normalized floating point representations, it is not immediately obvious that
Christian Heimesfe337bf2008-03-23 21:54:12 +00001300the following calculation returns a value equal to zero:
Georg Brandl116aa622007-08-15 14:28:22 +00001301
1302 >>> 1 / Decimal('Infinity')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001303 Decimal('0E-1000000026')
Georg Brandl116aa622007-08-15 14:28:22 +00001304
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001305.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001306
1307
1308.. _decimal-threads:
1309
1310Working with threads
1311--------------------
1312
1313The :func:`getcontext` function accesses a different :class:`Context` object for
1314each thread. Having separate thread contexts means that threads may make
1315changes (such as ``getcontext.prec=10``) without interfering with other threads.
1316
1317Likewise, the :func:`setcontext` function automatically assigns its target to
1318the current thread.
1319
1320If :func:`setcontext` has not been called before :func:`getcontext`, then
1321:func:`getcontext` will automatically create a new context for use in the
1322current thread.
1323
1324The new context is copied from a prototype context called *DefaultContext*. To
1325control the defaults so that each thread will use the same values throughout the
1326application, directly modify the *DefaultContext* object. This should be done
1327*before* any threads are started so that there won't be a race condition between
1328threads calling :func:`getcontext`. For example::
1329
1330 # Set applicationwide defaults for all threads about to be launched
1331 DefaultContext.prec = 12
1332 DefaultContext.rounding = ROUND_DOWN
1333 DefaultContext.traps = ExtendedContext.traps.copy()
1334 DefaultContext.traps[InvalidOperation] = 1
1335 setcontext(DefaultContext)
1336
1337 # Afterwards, the threads can be started
1338 t1.start()
1339 t2.start()
1340 t3.start()
1341 . . .
1342
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001343.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001344
1345
1346.. _decimal-recipes:
1347
1348Recipes
1349-------
1350
1351Here are a few recipes that serve as utility functions and that demonstrate ways
1352to work with the :class:`Decimal` class::
1353
1354 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1355 pos='', neg='-', trailneg=''):
1356 """Convert Decimal to a money formatted string.
1357
1358 places: required number of places after the decimal point
1359 curr: optional currency symbol before the sign (may be blank)
1360 sep: optional grouping separator (comma, period, space, or blank)
1361 dp: decimal point indicator (comma or period)
1362 only specify as blank when places is zero
1363 pos: optional sign for positive numbers: '+', space or blank
1364 neg: optional sign for negative numbers: '-', '(', space or blank
1365 trailneg:optional trailing minus indicator: '-', ')', space or blank
1366
1367 >>> d = Decimal('-1234567.8901')
1368 >>> moneyfmt(d, curr='$')
1369 '-$1,234,567.89'
1370 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1371 '1.234.568-'
1372 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1373 '($1,234,567.89)'
1374 >>> moneyfmt(Decimal(123456789), sep=' ')
1375 '123 456 789.00'
1376 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1377 '<.02>'
1378
1379 """
Christian Heimesa156e092008-02-16 07:38:31 +00001380 q = Decimal(10) ** -places # 2 places --> '0.01'
1381 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +00001382 result = []
1383 digits = map(str, digits)
1384 build, next = result.append, digits.pop
1385 if sign:
1386 build(trailneg)
1387 for i in range(places):
Christian Heimesa156e092008-02-16 07:38:31 +00001388 build(next() if digits else '0')
Georg Brandl116aa622007-08-15 14:28:22 +00001389 build(dp)
1390 i = 0
1391 while digits:
1392 build(next())
1393 i += 1
1394 if i == 3 and digits:
1395 i = 0
1396 build(sep)
1397 build(curr)
Christian Heimesa156e092008-02-16 07:38:31 +00001398 build(neg if sign else pos)
1399 return ''.join(reversed(result))
Georg Brandl116aa622007-08-15 14:28:22 +00001400
1401 def pi():
1402 """Compute Pi to the current precision.
1403
Georg Brandl6911e3c2007-09-04 07:15:32 +00001404 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001405 3.141592653589793238462643383
1406
1407 """
1408 getcontext().prec += 2 # extra digits for intermediate steps
1409 three = Decimal(3) # substitute "three=3.0" for regular floats
1410 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1411 while s != lasts:
1412 lasts = s
1413 n, na = n+na, na+8
1414 d, da = d+da, da+32
1415 t = (t * n) / d
1416 s += t
1417 getcontext().prec -= 2
1418 return +s # unary plus applies the new precision
1419
1420 def exp(x):
1421 """Return e raised to the power of x. Result type matches input type.
1422
Georg Brandl6911e3c2007-09-04 07:15:32 +00001423 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001424 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001425 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001426 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001427 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001428 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001429 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001430 (7.38905609893+0j)
1431
1432 """
1433 getcontext().prec += 2
1434 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1435 while s != lasts:
1436 lasts = s
1437 i += 1
1438 fact *= i
1439 num *= x
1440 s += num / fact
1441 getcontext().prec -= 2
1442 return +s
1443
1444 def cos(x):
1445 """Return the cosine of x as measured in radians.
1446
Georg Brandl6911e3c2007-09-04 07:15:32 +00001447 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001448 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001449 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001450 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001451 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001452 (0.87758256189+0j)
1453
1454 """
1455 getcontext().prec += 2
1456 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1457 while s != lasts:
1458 lasts = s
1459 i += 2
1460 fact *= i * (i-1)
1461 num *= x * x
1462 sign *= -1
1463 s += num / fact * sign
1464 getcontext().prec -= 2
1465 return +s
1466
1467 def sin(x):
1468 """Return the sine of x as measured in radians.
1469
Georg Brandl6911e3c2007-09-04 07:15:32 +00001470 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001471 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001472 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001473 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001474 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001475 (0.479425538604+0j)
1476
1477 """
1478 getcontext().prec += 2
1479 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1480 while s != lasts:
1481 lasts = s
1482 i += 2
1483 fact *= i * (i-1)
1484 num *= x * x
1485 sign *= -1
1486 s += num / fact * sign
1487 getcontext().prec -= 2
1488 return +s
1489
1490
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001491.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001492
1493
1494.. _decimal-faq:
1495
1496Decimal FAQ
1497-----------
1498
1499Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1500minimize typing when using the interactive interpreter?
1501
Christian Heimesfe337bf2008-03-23 21:54:12 +00001502A. Some users abbreviate the constructor to just a single letter:
Georg Brandl116aa622007-08-15 14:28:22 +00001503
1504 >>> D = decimal.Decimal
1505 >>> D('1.23') + D('3.45')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001506 Decimal('4.68')
Georg Brandl116aa622007-08-15 14:28:22 +00001507
1508Q. In a fixed-point application with two decimal places, some inputs have many
1509places and need to be rounded. Others are not supposed to have excess digits
1510and need to be validated. What methods should be used?
1511
1512A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Christian Heimesfe337bf2008-03-23 21:54:12 +00001513the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl116aa622007-08-15 14:28:22 +00001514
1515 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1516
1517 >>> # Round to two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001518 >>> Decimal('3.214').quantize(TWOPLACES)
1519 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001520
1521 >>> # Validate that a number does not exceed two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001522 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1523 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001524
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001525 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl116aa622007-08-15 14:28:22 +00001526 Traceback (most recent call last):
1527 ...
Christian Heimesfe337bf2008-03-23 21:54:12 +00001528 Inexact
Georg Brandl116aa622007-08-15 14:28:22 +00001529
1530Q. Once I have valid two place inputs, how do I maintain that invariant
1531throughout an application?
1532
Christian Heimesa156e092008-02-16 07:38:31 +00001533A. Some operations like addition, subtraction, and multiplication by an integer
1534will automatically preserve fixed point. Others operations, like division and
1535non-integer multiplication, will change the number of decimal places and need to
Christian Heimesfe337bf2008-03-23 21:54:12 +00001536be followed-up with a :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001537
1538 >>> a = Decimal('102.72') # Initial fixed-point values
1539 >>> b = Decimal('3.17')
1540 >>> a + b # Addition preserves fixed-point
1541 Decimal('105.89')
1542 >>> a - b
1543 Decimal('99.55')
1544 >>> a * 42 # So does integer multiplication
1545 Decimal('4314.24')
1546 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1547 Decimal('325.62')
1548 >>> (b / a).quantize(TWOPLACES) # And quantize division
1549 Decimal('0.03')
1550
1551In developing fixed-point applications, it is convenient to define functions
Christian Heimesfe337bf2008-03-23 21:54:12 +00001552to handle the :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001553
1554 >>> def mul(x, y, fp=TWOPLACES):
1555 ... return (x * y).quantize(fp)
1556 >>> def div(x, y, fp=TWOPLACES):
1557 ... return (x / y).quantize(fp)
1558
1559 >>> mul(a, b) # Automatically preserve fixed-point
1560 Decimal('325.62')
1561 >>> div(b, a)
1562 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +00001563
1564Q. There are many ways to express the same value. The numbers :const:`200`,
1565:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1566various precisions. Is there a way to transform them to a single recognizable
1567canonical value?
1568
1569A. The :meth:`normalize` method maps all equivalent values to a single
Christian Heimesfe337bf2008-03-23 21:54:12 +00001570representative:
Georg Brandl116aa622007-08-15 14:28:22 +00001571
1572 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1573 >>> [v.normalize() for v in values]
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001574 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl116aa622007-08-15 14:28:22 +00001575
1576Q. Some decimal values always print with exponential notation. Is there a way
1577to get a non-exponential representation?
1578
1579A. For some values, exponential notation is the only way to express the number
1580of significant places in the coefficient. For example, expressing
1581:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1582original's two-place significance.
1583
Christian Heimesa156e092008-02-16 07:38:31 +00001584If an application does not care about tracking significance, it is easy to
Christian Heimesc3f30c42008-02-22 16:37:40 +00001585remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001586value unchanged:
Christian Heimesa156e092008-02-16 07:38:31 +00001587
1588 >>> def remove_exponent(d):
1589 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1590
1591 >>> remove_exponent(Decimal('5E+3'))
1592 Decimal('5000')
1593
Georg Brandl116aa622007-08-15 14:28:22 +00001594Q. Is there a way to convert a regular float to a :class:`Decimal`?
1595
1596A. Yes, all binary floating point numbers can be exactly expressed as a
1597Decimal. An exact conversion may take more precision than intuition would
Christian Heimesfe337bf2008-03-23 21:54:12 +00001598suggest, so we trap :const:`Inexact` to signal a need for more precision:
1599
1600.. testcode::
Georg Brandl116aa622007-08-15 14:28:22 +00001601
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001602 def float_to_decimal(f):
1603 "Convert a floating point number to a Decimal with no loss of information"
1604 n, d = f.as_integer_ratio()
1605 with localcontext() as ctx:
1606 ctx.traps[Inexact] = True
1607 while True:
1608 try:
1609 return Decimal(n) / Decimal(d)
1610 except Inexact:
1611 ctx.prec += 1
Georg Brandl116aa622007-08-15 14:28:22 +00001612
Christian Heimesfe337bf2008-03-23 21:54:12 +00001613.. doctest::
1614
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001615 >>> float_to_decimal(math.pi)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001616 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl116aa622007-08-15 14:28:22 +00001617
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001618Q. Why isn't the :func:`float_to_decimal` routine included in the module?
Georg Brandl116aa622007-08-15 14:28:22 +00001619
1620A. There is some question about whether it is advisable to mix binary and
1621decimal floating point. Also, its use requires some care to avoid the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001622representation issues associated with binary floating point:
Georg Brandl116aa622007-08-15 14:28:22 +00001623
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001624 >>> float_to_decimal(1.1)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001625 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl116aa622007-08-15 14:28:22 +00001626
1627Q. Within a complex calculation, how can I make sure that I haven't gotten a
1628spurious result because of insufficient precision or rounding anomalies.
1629
1630A. The decimal module makes it easy to test results. A best practice is to
1631re-run calculations using greater precision and with various rounding modes.
1632Widely differing results indicate insufficient precision, rounding mode issues,
1633ill-conditioned inputs, or a numerically unstable algorithm.
1634
1635Q. I noticed that context precision is applied to the results of operations but
1636not to the inputs. Is there anything to watch out for when mixing values of
1637different precisions?
1638
1639A. Yes. The principle is that all values are considered to be exact and so is
1640the arithmetic on those values. Only the results are rounded. The advantage
1641for inputs is that "what you type is what you get". A disadvantage is that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001642results can look odd if you forget that the inputs haven't been rounded:
1643
1644.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001645
1646 >>> getcontext().prec = 3
Christian Heimesfe337bf2008-03-23 21:54:12 +00001647 >>> Decimal('3.104') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001648 Decimal('5.21')
Christian Heimesfe337bf2008-03-23 21:54:12 +00001649 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001650 Decimal('5.20')
Georg Brandl116aa622007-08-15 14:28:22 +00001651
1652The solution is either to increase precision or to force rounding of inputs
Christian Heimesfe337bf2008-03-23 21:54:12 +00001653using the unary plus operation:
1654
1655.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001656
1657 >>> getcontext().prec = 3
1658 >>> +Decimal('1.23456789') # unary plus triggers rounding
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001659 Decimal('1.23')
Georg Brandl116aa622007-08-15 14:28:22 +00001660
1661Alternatively, inputs can be rounded upon creation using the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001662:meth:`Context.create_decimal` method:
Georg Brandl116aa622007-08-15 14:28:22 +00001663
1664 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001665 Decimal('1.2345')
Georg Brandl116aa622007-08-15 14:28:22 +00001666