blob: 6f4821b240122891ff8d0ceb5956db26df426b89 [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
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000344Decimal floating point objects share many properties with the other built-in
Georg Brandl116aa622007-08-15 14:28:22 +0000345numeric types such as :class:`float` and :class:`int`. All of the usual math
346operations and special methods apply. Likewise, decimal objects can be copied,
347pickled, printed, used as dictionary keys, used as set elements, compared,
Neil Schemenauer16c70752007-09-21 20:19:23 +0000348sorted, and converted to another type (such as :class:`float` or :class:`int`).
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350In addition to the standard numeric properties, decimal floating point objects
351also have a number of specialized methods:
352
353
354.. method:: Decimal.adjusted()
355
356 Return the adjusted exponent after shifting out the coefficient's rightmost
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000357 digits until only the lead digit remains: ``Decimal('321e+5').adjusted()``
Georg Brandl116aa622007-08-15 14:28:22 +0000358 returns seven. Used for determining the position of the most significant digit
359 with respect to the decimal point.
360
361
362.. method:: Decimal.as_tuple()
363
Christian Heimes25bb7832008-01-11 16:17:00 +0000364 Return a :term:`named tuple` representation of the number:
365 ``DecimalTuple(sign, digits, exponent)``.
366
Georg Brandl116aa622007-08-15 14:28:22 +0000367
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000368.. method:: Decimal.canonical()
369
370 Return the canonical encoding of the argument. Currently, the
371 encoding of a :class:`Decimal` instance is always canonical, so
372 this operation returns its argument unchanged.
373
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000374
Georg Brandl116aa622007-08-15 14:28:22 +0000375.. method:: Decimal.compare(other[, context])
376
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000377 Compare the values of two Decimal instances. This operation
378 behaves in the same way as the usual comparison method
379 :meth:`__cmp__`, except that :meth:`compare` returns a Decimal
380 instance rather than an integer, and if either operand is a NaN
381 then the result is a NaN::
Georg Brandl116aa622007-08-15 14:28:22 +0000382
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000383 a or b is a NaN ==> Decimal('NaN')
384 a < b ==> Decimal('-1')
385 a == b ==> Decimal('0')
386 a > b ==> Decimal('1')
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000388.. method:: Decimal.compare_signal(other[, context])
389
390 This operation is identical to the :meth:`compare` method, except
391 that all NaNs signal. That is, if neither operand is a signaling
392 NaN then any quiet NaN operand is treated as though it were a
393 signaling NaN.
394
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000395
396.. method:: Decimal.compare_total(other)
397
398 Compare two operands using their abstract representation rather
399 than their numerical value. Similar to the :meth:`compare` method,
400 but the result gives a total ordering on :class:`Decimal`
401 instances. Two :class:`Decimal` instances with the same numeric
402 value but different representations compare unequal in this
Christian Heimesfe337bf2008-03-23 21:54:12 +0000403 ordering:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000404
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000405 >>> Decimal('12.0').compare_total(Decimal('12'))
406 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000407
408 Quiet and signaling NaNs are also included in the total ordering.
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000409 The result of this function is ``Decimal('0')`` if both operands
410 have the same representation, ``Decimal('-1')`` if the first
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000411 operand is lower in the total order than the second, and
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000412 ``Decimal('1')`` if the first operand is higher in the total order
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000413 than the second operand. See the specification for details of the
414 total order.
415
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000416
417.. method:: Decimal.compare_total_mag(other)
418
419 Compare two operands using their abstract representation rather
420 than their value as in :meth:`compare_total`, but ignoring the sign
421 of each operand. ``x.compare_total_mag(y)`` is equivalent to
422 ``x.copy_abs().compare_total(y.copy_abs())``.
423
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000424
425.. method:: Decimal.copy_abs()
426
427 Return the absolute value of the argument. This operation is
428 unaffected by the context and is quiet: no flags are changed and no
429 rounding is performed.
430
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000431
432.. method:: Decimal.copy_negate()
433
434 Return the negation of the argument. This operation is unaffected
435 by the context and is quiet: no flags are changed and no rounding
436 is performed.
437
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000438
439.. method:: Decimal.copy_sign(other)
440
441 Return a copy of the first operand with the sign set to be the
Christian Heimesfe337bf2008-03-23 21:54:12 +0000442 same as the sign of the second operand. For example:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000443
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000444 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
445 Decimal('-2.3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000446
447 This operation is unaffected by the context and is quiet: no flags
448 are changed and no rounding is performed.
449
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000450
451.. method:: Decimal.exp([context])
452
453 Return the value of the (natural) exponential function ``e**x`` at the
454 given number. The result is correctly rounded using the
455 :const:`ROUND_HALF_EVEN` rounding mode.
456
457 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000458 Decimal('2.718281828459045235360287471')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000459 >>> Decimal(321).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000460 Decimal('2.561702493119680037517373933E+139')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000461
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000462
463.. method:: Decimal.fma(other, third[, context])
464
465 Fused multiply-add. Return self*other+third with no rounding of
466 the intermediate product self*other.
467
468 >>> Decimal(2).fma(3, 5)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000469 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000470
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000471
472.. method:: Decimal.is_canonical()
473
474 Return :const:`True` if the argument is canonical and
475 :const:`False` otherwise. Currently, a :class:`Decimal` instance
476 is always canonical, so this operation always returns
477 :const:`True`.
478
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000479
480.. method:: is_finite()
481
482 Return :const:`True` if the argument is a finite number, and
483 :const:`False` if the argument is an infinity or a NaN.
484
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000485
486.. method:: is_infinite()
487
488 Return :const:`True` if the argument is either positive or
489 negative infinity and :const:`False` otherwise.
490
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000491
492.. method:: is_nan()
493
494 Return :const:`True` if the argument is a (quiet or signaling)
495 NaN and :const:`False` otherwise.
496
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000497
498.. method:: is_normal()
499
500 Return :const:`True` if the argument is a *normal* finite number.
501 Return :const:`False` if the argument is zero, subnormal, infinite
502 or a NaN.
503
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000504
505.. method:: is_qnan()
506
507 Return :const:`True` if the argument is a quiet NaN, and
508 :const:`False` otherwise.
509
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510
511.. method:: is_signed()
512
513 Return :const:`True` if the argument has a negative sign and
514 :const:`False` otherwise. Note that zeros and NaNs can both carry
515 signs.
516
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000517
518.. method:: is_snan()
519
520 Return :const:`True` if the argument is a signaling NaN and
521 :const:`False` otherwise.
522
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000523
524.. method:: is_subnormal()
525
526 Return :const:`True` if the argument is subnormal, and
527 :const:`False` otherwise.
528
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000529
530.. method:: is_zero()
531
532 Return :const:`True` if the argument is a (positive or negative)
533 zero and :const:`False` otherwise.
534
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000535
536.. method:: Decimal.ln([context])
537
538 Return the natural (base e) logarithm of the operand. The result
539 is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
540 mode.
541
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000542
543.. method:: Decimal.log10([context])
544
545 Return the base ten logarithm of the operand. The result is
546 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
547
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000548
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000549.. method:: Decimal.logb([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000550
551 For a nonzero number, return the adjusted exponent of its operand
552 as a :class:`Decimal` instance. If the operand is a zero then
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000553 ``Decimal('-Infinity')`` is returned and the
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000554 :const:`DivisionByZero` flag is raised. If the operand is an
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000555 infinity then ``Decimal('Infinity')`` is returned.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000556
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000557
558.. method:: Decimal.logical_and(other[, context])
559
560 :meth:`logical_and` is a logical operation which takes two
561 *logical operands* (see :ref:`logical_operands_label`). The result
562 is the digit-wise ``and`` of the two operands.
563
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000564
565.. method:: Decimal.logical_invert(other[, context])
566
567 :meth:`logical_invert` is a logical operation. The argument must
568 be a *logical operand* (see :ref:`logical_operands_label`). The
569 result is the digit-wise inversion of the operand.
570
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000571
572.. method:: Decimal.logical_or(other[, context])
573
574 :meth:`logical_or` is a logical operation which takes two *logical
575 operands* (see :ref:`logical_operands_label`). The result is the
576 digit-wise ``or`` of the two operands.
577
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000578
579.. method:: Decimal.logical_xor(other[, context])
580
581 :meth:`logical_xor` is a logical operation which takes two
582 *logical operands* (see :ref:`logical_operands_label`). The result
583 is the digit-wise exclusive or of the two operands.
584
Georg Brandl116aa622007-08-15 14:28:22 +0000585
586.. method:: Decimal.max(other[, context])
587
588 Like ``max(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
Georg Brandl6554cb92007-12-02 23:15:43 +0000592
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000593.. method:: Decimal.max_mag(other[, context])
594
595 Similar to the :meth:`max` method, but the comparison is done using
596 the absolute values of the operands.
597
Georg Brandl116aa622007-08-15 14:28:22 +0000598
599.. method:: Decimal.min(other[, context])
600
601 Like ``min(self, other)`` except that the context rounding rule is applied
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl116aa622007-08-15 14:28:22 +0000603 (depending on the context and whether they are signaling or quiet).
604
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000605.. method:: Decimal.min_mag(other[, context])
606
607 Similar to the :meth:`min` method, but the comparison is done using
608 the absolute values of the operands.
609
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000610
611.. method:: Decimal.next_minus([context])
612
613 Return the largest number representable in the given context (or
614 in the current thread's context if no context is given) that is smaller
615 than the given operand.
616
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000617
618.. method:: Decimal.next_plus([context])
619
620 Return the smallest number representable in the given context (or
621 in the current thread's context if no context is given) that is
622 larger than the given operand.
623
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624
625.. method:: Decimal.next_toward(other[, context])
626
627 If the two operands are unequal, return the number closest to the
628 first operand in the direction of the second operand. If both
629 operands are numerically equal, return a copy of the first operand
630 with the sign set to be the same as the sign of the second operand.
631
Georg Brandl116aa622007-08-15 14:28:22 +0000632
633.. method:: Decimal.normalize([context])
634
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000635 Normalize the number by stripping the rightmost trailing zeros and converting
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000636 any result equal to :const:`Decimal('0')` to :const:`Decimal('0e0')`. Used for
Georg Brandl116aa622007-08-15 14:28:22 +0000637 producing canonical values for members of an equivalence class. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000638 ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both normalize to the
639 equivalent value ``Decimal('32.1')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000640
Georg Brandl6554cb92007-12-02 23:15:43 +0000641
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000642.. method:: Decimal.number_class([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000643
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644 Return a string describing the *class* of the operand. The
645 returned value is one of the following ten strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000646
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000647 * ``"-Infinity"``, indicating that the operand is negative infinity.
648 * ``"-Normal"``, indicating that the operand is a negative normal number.
649 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
650 * ``"-Zero"``, indicating that the operand is a negative zero.
651 * ``"+Zero"``, indicating that the operand is a positive zero.
652 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
653 * ``"+Normal"``, indicating that the operand is a positive normal number.
654 * ``"+Infinity"``, indicating that the operand is positive infinity.
655 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
656 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000657
Georg Brandl116aa622007-08-15 14:28:22 +0000658
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000659.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]])
660
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000661 Return a value equal to the first operand after rounding and
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662 having the exponent of the second operand.
663
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000664 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
665 Decimal('1.414')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000666
667 Unlike other operations, if the length of the coefficient after the
668 quantize operation would be greater than precision, then an
669 :const:`InvalidOperation` is signaled. This guarantees that, unless
670 there is an error condition, the quantized exponent is always equal
671 to that of the right-hand operand.
672
673 Also unlike other operations, quantize never signals Underflow,
674 even if the result is subnormal and inexact.
675
676 If the exponent of the second operand is larger than that of the
677 first then rounding may be necessary. In this case, the rounding
678 mode is determined by the ``rounding`` argument if given, else by
679 the given ``context`` argument; if neither argument is given the
680 rounding mode of the current thread's context is used.
681
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000682 If *watchexp* is set (default), then an error is returned whenever the
683 resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000684
685.. method:: Decimal.radix()
686
687 Return ``Decimal(10)``, the radix (base) in which the
688 :class:`Decimal` class does all its arithmetic. Included for
689 compatibility with the specification.
690
Georg Brandl116aa622007-08-15 14:28:22 +0000691
692.. method:: Decimal.remainder_near(other[, context])
693
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000694 Compute the modulo as either a positive or negative value depending on which is
Georg Brandl116aa622007-08-15 14:28:22 +0000695 closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000696 ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000697
698 If both are equally close, the one chosen will have the same sign as *self*.
699
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000700.. method:: Decimal.rotate(other[, context])
701
702 Return the result of rotating the digits of the first operand by
703 an amount specified by the second operand. The second operand
704 must be an integer in the range -precision through precision. The
705 absolute value of the second operand gives the number of places to
706 rotate. If the second operand is positive then rotation is to the
707 left; otherwise rotation is to the right. The coefficient of the
708 first operand is padded on the left with zeros to length precision
709 if necessary. The sign and exponent of the first operand are
710 unchanged.
711
Georg Brandl116aa622007-08-15 14:28:22 +0000712
713.. method:: Decimal.same_quantum(other[, context])
714
715 Test whether self and other have the same exponent or whether both are
716 :const:`NaN`.
717
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000718.. method:: Decimal.scaleb(other[, context])
719
720 Return the first operand with exponent adjusted by the second.
721 Equivalently, return the first operand multiplied by ``10**other``.
722 The second operand must be an integer.
723
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000724
725.. method:: Decimal.shift(other[, context])
726
727 Return the result of shifting the digits of the first operand by
728 an amount specified by the second operand. The second operand must
729 be an integer in the range -precision through precision. The
730 absolute value of the second operand gives the number of places to
731 shift. If the second operand is positive then the shift is to the
732 left; otherwise the shift is to the right. Digits shifted into the
733 coefficient are zeros. The sign and exponent of the first operand
734 are unchanged.
735
Georg Brandl116aa622007-08-15 14:28:22 +0000736
737.. method:: Decimal.sqrt([context])
738
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000739 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000740
741
742.. method:: Decimal.to_eng_string([context])
743
744 Convert to an engineering-type string.
745
746 Engineering notation has an exponent which is a multiple of 3, so there are up
747 to 3 digits left of the decimal place. For example, converts
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000748 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Georg Brandl116aa622007-08-15 14:28:22 +0000749
Georg Brandl116aa622007-08-15 14:28:22 +0000750.. method:: Decimal.to_integral([rounding[, context]])
751
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000752 Identical to the :meth:`to_integral_value` method. The ``to_integral``
753 name has been kept for compatibility with older versions.
754
755.. method:: Decimal.to_integral_exact([rounding[, context]])
756
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000757 Round to the nearest integer, signaling
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000758 :const:`Inexact` or :const:`Rounded` as appropriate if rounding
759 occurs. The rounding mode is determined by the ``rounding``
760 parameter if given, else by the given ``context``. If neither
761 parameter is given then the rounding mode of the current context is
762 used.
763
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000764
765.. method:: Decimal.to_integral_value([rounding[, context]])
766
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000767 Round to the nearest integer without signaling :const:`Inexact` or
Georg Brandl116aa622007-08-15 14:28:22 +0000768 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding
769 method in either the supplied *context* or the current context.
770
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000771
772.. method:: Decimal.trim()
773
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000774 Return the decimal with *insignificant* trailing zeros removed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000775 Here, a trailing zero is considered insignificant either if it
776 follows the decimal point, or if the exponent of the argument (that
777 is, the last element of the :meth:`as_tuple` representation) is
778 positive.
779
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000780
781.. _logical_operands_label:
782
783Logical operands
784^^^^^^^^^^^^^^^^
785
786The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
787and :meth:`logical_xor` methods expect their arguments to be *logical
788operands*. A *logical operand* is a :class:`Decimal` instance whose
789exponent and sign are both zero, and whose digits are all either
790:const:`0` or :const:`1`.
791
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000792.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000793
794
795.. _decimal-context:
796
797Context objects
798---------------
799
800Contexts are environments for arithmetic operations. They govern precision, set
801rules for rounding, determine which signals are treated as exceptions, and limit
802the range for exponents.
803
804Each thread has its own current context which is accessed or changed using the
805:func:`getcontext` and :func:`setcontext` functions:
806
807
808.. function:: getcontext()
809
810 Return the current context for the active thread.
811
812
813.. function:: setcontext(c)
814
815 Set the current context for the active thread to *c*.
816
817Beginning with Python 2.5, you can also use the :keyword:`with` statement and
818the :func:`localcontext` function to temporarily change the active context.
819
820
821.. function:: localcontext([c])
822
823 Return a context manager that will set the current context for the active thread
824 to a copy of *c* on entry to the with-statement and restore the previous context
825 when exiting the with-statement. If no context is specified, a copy of the
826 current context is used.
827
Georg Brandl116aa622007-08-15 14:28:22 +0000828 For example, the following code sets the current decimal precision to 42 places,
829 performs a calculation, and then automatically restores the previous context::
830
Georg Brandl116aa622007-08-15 14:28:22 +0000831 from decimal import localcontext
832
833 with localcontext() as ctx:
834 ctx.prec = 42 # Perform a high precision calculation
835 s = calculate_something()
836 s = +s # Round the final result back to the default precision
837
838New contexts can also be created using the :class:`Context` constructor
839described below. In addition, the module provides three pre-made contexts:
840
841
842.. class:: BasicContext
843
844 This is a standard context defined by the General Decimal Arithmetic
845 Specification. Precision is set to nine. Rounding is set to
846 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
847 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
848 :const:`Subnormal`.
849
850 Because many of the traps are enabled, this context is useful for debugging.
851
852
853.. class:: ExtendedContext
854
855 This is a standard context defined by the General Decimal Arithmetic
856 Specification. Precision is set to nine. Rounding is set to
857 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
858 exceptions are not raised during computations).
859
Christian Heimes3feef612008-02-11 06:19:17 +0000860 Because the traps are disabled, this context is useful for applications that
Georg Brandl116aa622007-08-15 14:28:22 +0000861 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
862 raising exceptions. This allows an application to complete a run in the
863 presence of conditions that would otherwise halt the program.
864
865
866.. class:: DefaultContext
867
868 This context is used by the :class:`Context` constructor as a prototype for new
869 contexts. Changing a field (such a precision) has the effect of changing the
870 default for new contexts creating by the :class:`Context` constructor.
871
872 This context is most useful in multi-threaded environments. Changing one of the
873 fields before threads are started has the effect of setting system-wide
874 defaults. Changing the fields after threads have started is not recommended as
875 it would require thread synchronization to prevent race conditions.
876
877 In single threaded environments, it is preferable to not use this context at
878 all. Instead, simply create contexts explicitly as described below.
879
880 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
881 for Overflow, InvalidOperation, and DivisionByZero.
882
883In addition to the three supplied contexts, new contexts can be created with the
884:class:`Context` constructor.
885
886
887.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
888
889 Creates a new context. If a field is not specified or is :const:`None`, the
890 default values are copied from the :const:`DefaultContext`. If the *flags*
891 field is not specified or is :const:`None`, all flags are cleared.
892
893 The *prec* field is a positive integer that sets the precision for arithmetic
894 operations in the context.
895
896 The *rounding* option is one of:
897
898 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
899 * :const:`ROUND_DOWN` (towards zero),
900 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
901 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
902 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
903 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
904 * :const:`ROUND_UP` (away from zero).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000905 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
906 would have been 0 or 5; otherwise towards zero)
Georg Brandl116aa622007-08-15 14:28:22 +0000907
908 The *traps* and *flags* fields list any signals to be set. Generally, new
909 contexts should only set traps and leave the flags clear.
910
911 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
912 for exponents.
913
914 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
915 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
916 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
917
Georg Brandl116aa622007-08-15 14:28:22 +0000918
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000919The :class:`Context` class defines several general purpose methods as
920well as a large number of methods for doing arithmetic directly in a
921given context. In addition, for each of the :class:`Decimal` methods
922described above (with the exception of the :meth:`adjusted` and
923:meth:`as_tuple` methods) there is a corresponding :class:`Context`
924method. For example, ``C.exp(x)`` is equivalent to
925``x.exp(context=C)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000926
927.. method:: Context.clear_flags()
928
929 Resets all of the flags to :const:`0`.
930
931
932.. method:: Context.copy()
933
934 Return a duplicate of the context.
935
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000936.. method:: Context.copy_decimal(num)
937
938 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +0000939
940.. method:: Context.create_decimal(num)
941
942 Creates a new Decimal instance from *num* but using *self* as context. Unlike
943 the :class:`Decimal` constructor, the context precision, rounding method, flags,
944 and traps are applied to the conversion.
945
946 This is useful because constants are often given to a greater precision than is
947 needed by the application. Another benefit is that rounding immediately
948 eliminates unintended effects from digits beyond the current precision. In the
949 following example, using unrounded inputs means that adding zero to a sum can
Christian Heimesfe337bf2008-03-23 21:54:12 +0000950 change the result:
951
952 .. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000953
954 >>> getcontext().prec = 3
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000955 >>> Decimal('3.4445') + Decimal('1.0023')
956 Decimal('4.45')
957 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
958 Decimal('4.44')
Georg Brandl116aa622007-08-15 14:28:22 +0000959
Christian Heimesa62da1d2008-01-12 19:39:10 +0000960 This method implements the to-number operation of the IBM
961 specification. If the argument is a string, no leading or trailing
962 whitespace is permitted.
Georg Brandl116aa622007-08-15 14:28:22 +0000963
964.. method:: Context.Etiny()
965
966 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
967 for subnormal results. When underflow occurs, the exponent is set to
968 :const:`Etiny`.
969
970
971.. method:: Context.Etop()
972
973 Returns a value equal to ``Emax - prec + 1``.
974
975The usual approach to working with decimals is to create :class:`Decimal`
976instances and then apply arithmetic operations which take place within the
Thomas Wouters8ce81f72007-09-20 18:22:40 +0000977current context for the active thread. An alternative approach is to use context
Georg Brandl116aa622007-08-15 14:28:22 +0000978methods for calculating within a specific context. The methods are similar to
979those for the :class:`Decimal` class and are only briefly recounted here.
980
981
982.. method:: Context.abs(x)
983
984 Returns the absolute value of *x*.
985
986
987.. method:: Context.add(x, y)
988
989 Return the sum of *x* and *y*.
990
991
Georg Brandl116aa622007-08-15 14:28:22 +0000992.. method:: Context.divide(x, y)
993
994 Return *x* divided by *y*.
995
996
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000997.. method:: Context.divide_int(x, y)
998
999 Return *x* divided by *y*, truncated to an integer.
1000
1001
Georg Brandl116aa622007-08-15 14:28:22 +00001002.. method:: Context.divmod(x, y)
1003
1004 Divides two numbers and returns the integer part of the result.
1005
1006
Georg Brandl116aa622007-08-15 14:28:22 +00001007.. method:: Context.minus(x)
1008
1009 Minus corresponds to the unary prefix minus operator in Python.
1010
1011
1012.. method:: Context.multiply(x, y)
1013
1014 Return the product of *x* and *y*.
1015
1016
Georg Brandl116aa622007-08-15 14:28:22 +00001017.. method:: Context.plus(x)
1018
1019 Plus corresponds to the unary prefix plus operator in Python. This operation
1020 applies the context precision and rounding, so it is *not* an identity
1021 operation.
1022
1023
1024.. method:: Context.power(x, y[, modulo])
1025
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001026 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if
1027 given.
Georg Brandl116aa622007-08-15 14:28:22 +00001028
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001029 With two arguments, compute ``x**y``. If ``x`` is negative then
1030 ``y`` must be integral. The result will be inexact unless ``y`` is
1031 integral and the result is finite and can be expressed exactly in
1032 'precision' digits. The result should always be correctly rounded,
1033 using the rounding mode of the current thread's context.
Georg Brandl116aa622007-08-15 14:28:22 +00001034
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001035 With three arguments, compute ``(x**y) % modulo``. For the three
1036 argument form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +00001037
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001038 - all three arguments must be integral
1039 - ``y`` must be nonnegative
1040 - at least one of ``x`` or ``y`` must be nonzero
1041 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +00001042
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001043 The result of ``Context.power(x, y, modulo)`` is identical to
1044 the result that would be obtained by computing ``(x**y) %
1045 modulo`` with unbounded precision, but is computed more
1046 efficiently. It is always exact.
Georg Brandl116aa622007-08-15 14:28:22 +00001047
Georg Brandl116aa622007-08-15 14:28:22 +00001048
1049.. method:: Context.remainder(x, y)
1050
1051 Returns the remainder from integer division.
1052
1053 The sign of the result, if non-zero, is the same as that of the original
1054 dividend.
1055
Georg Brandl116aa622007-08-15 14:28:22 +00001056.. method:: Context.subtract(x, y)
1057
1058 Return the difference between *x* and *y*.
1059
Georg Brandl116aa622007-08-15 14:28:22 +00001060.. method:: Context.to_sci_string(x)
1061
1062 Converts a number to a string using scientific notation.
1063
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001064.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001065
1066
1067.. _decimal-signals:
1068
1069Signals
1070-------
1071
1072Signals represent conditions that arise during computation. Each corresponds to
1073one context flag and one context trap enabler.
1074
Raymond Hettinger86173da2008-02-01 20:38:12 +00001075The context flag is set whenever the condition is encountered. After the
Georg Brandl116aa622007-08-15 14:28:22 +00001076computation, flags may be checked for informational purposes (for instance, to
1077determine whether a computation was exact). After checking the flags, be sure to
1078clear all flags before starting the next computation.
1079
1080If the context's trap enabler is set for the signal, then the condition causes a
1081Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1082is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1083condition.
1084
1085
1086.. class:: Clamped
1087
1088 Altered an exponent to fit representation constraints.
1089
1090 Typically, clamping occurs when an exponent falls outside the context's
1091 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001092 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001093
1094
1095.. class:: DecimalException
1096
1097 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1098
1099
1100.. class:: DivisionByZero
1101
1102 Signals the division of a non-infinite number by zero.
1103
1104 Can occur with division, modulo division, or when raising a number to a negative
1105 power. If this signal is not trapped, returns :const:`Infinity` or
1106 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1107
1108
1109.. class:: Inexact
1110
1111 Indicates that rounding occurred and the result is not exact.
1112
1113 Signals when non-zero digits were discarded during rounding. The rounded result
1114 is returned. The signal flag or trap is used to detect when results are
1115 inexact.
1116
1117
1118.. class:: InvalidOperation
1119
1120 An invalid operation was performed.
1121
1122 Indicates that an operation was requested that does not make sense. If not
1123 trapped, returns :const:`NaN`. Possible causes include::
1124
1125 Infinity - Infinity
1126 0 * Infinity
1127 Infinity / Infinity
1128 x % 0
1129 Infinity % x
1130 x._rescale( non-integer )
1131 sqrt(-x) and x > 0
1132 0 ** 0
1133 x ** (non-integer)
1134 x ** Infinity
1135
1136
1137.. class:: Overflow
1138
1139 Numerical overflow.
1140
1141 Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
1142 If not trapped, the result depends on the rounding mode, either pulling inward
1143 to the largest representable finite number or rounding outward to
1144 :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are
1145 also signaled.
1146
1147
1148.. class:: Rounded
1149
1150 Rounding occurred though possibly no information was lost.
1151
1152 Signaled whenever rounding discards digits; even if those digits are zero (such
1153 as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result
1154 unchanged. This signal is used to detect loss of significant digits.
1155
1156
1157.. class:: Subnormal
1158
1159 Exponent was lower than :attr:`Emin` prior to rounding.
1160
1161 Occurs when an operation result is subnormal (the exponent is too small). If not
1162 trapped, returns the result unchanged.
1163
1164
1165.. class:: Underflow
1166
1167 Numerical underflow with result rounded to zero.
1168
1169 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1170 and :class:`Subnormal` are also signaled.
1171
1172The following table summarizes the hierarchy of signals::
1173
1174 exceptions.ArithmeticError(exceptions.Exception)
1175 DecimalException
1176 Clamped
1177 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1178 Inexact
1179 Overflow(Inexact, Rounded)
1180 Underflow(Inexact, Rounded, Subnormal)
1181 InvalidOperation
1182 Rounded
1183 Subnormal
1184
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001185.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001186
1187
1188.. _decimal-notes:
1189
1190Floating Point Notes
1191--------------------
1192
1193
1194Mitigating round-off error with increased precision
1195^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1196
1197The use of decimal floating point eliminates decimal representation error
1198(making it possible to represent :const:`0.1` exactly); however, some operations
1199can still incur round-off error when non-zero digits exceed the fixed precision.
1200
1201The effects of round-off error can be amplified by the addition or subtraction
1202of nearly offsetting quantities resulting in loss of significance. Knuth
1203provides two instructive examples where rounded floating point arithmetic with
1204insufficient precision causes the breakdown of the associative and distributive
Christian Heimesfe337bf2008-03-23 21:54:12 +00001205properties of addition:
1206
1207.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001208
1209 # Examples from Seminumerical Algorithms, Section 4.2.2.
1210 >>> from decimal import Decimal, getcontext
1211 >>> getcontext().prec = 8
1212
1213 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1214 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001215 Decimal('9.5111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001216 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001217 Decimal('10')
Georg Brandl116aa622007-08-15 14:28:22 +00001218
1219 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1220 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001221 Decimal('0.01')
Georg Brandl116aa622007-08-15 14:28:22 +00001222 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001223 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001224
1225The :mod:`decimal` module makes it possible to restore the identities by
Christian Heimesfe337bf2008-03-23 21:54:12 +00001226expanding the precision sufficiently to avoid loss of significance:
1227
1228.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001229
1230 >>> getcontext().prec = 20
1231 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1232 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001233 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001234 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001235 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001236 >>>
1237 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1238 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001239 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001240 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001241 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001242
1243
1244Special values
1245^^^^^^^^^^^^^^
1246
1247The number system for the :mod:`decimal` module provides special values
1248including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001249and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001250
1251Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1252they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1253not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1254can result from rounding beyond the limits of the largest representable number.
1255
1256The infinities are signed (affine) and can be used in arithmetic operations
1257where they get treated as very large, indeterminate numbers. For instance,
1258adding a constant to infinity gives another infinite result.
1259
1260Some operations are indeterminate and return :const:`NaN`, or if the
1261:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1262``0/0`` returns :const:`NaN` which means "not a number". This variety of
1263:const:`NaN` is quiet and, once created, will flow through other computations
1264always resulting in another :const:`NaN`. This behavior can be useful for a
1265series of computations that occasionally have missing inputs --- it allows the
1266calculation to proceed while flagging specific results as invalid.
1267
1268A variant is :const:`sNaN` which signals rather than remaining quiet after every
1269operation. This is a useful return value when an invalid result needs to
1270interrupt a calculation for special handling.
1271
Christian Heimes77c02eb2008-02-09 02:18:51 +00001272The behavior of Python's comparison operators can be a little surprising where a
1273:const:`NaN` is involved. A test for equality where one of the operands is a
1274quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1275``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1276:const:`True`. An attempt to compare two Decimals using any of the ``<``,
1277``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1278if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes3feef612008-02-11 06:19:17 +00001279not trapped. Note that the General Decimal Arithmetic specification does not
Christian Heimes77c02eb2008-02-09 02:18:51 +00001280specify the behavior of direct comparisons; these rules for comparisons
1281involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1282section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1283and :meth:`compare-signal` methods instead.
1284
Georg Brandl116aa622007-08-15 14:28:22 +00001285The signed zeros can result from calculations that underflow. They keep the sign
1286that would have resulted if the calculation had been carried out to greater
1287precision. Since their magnitude is zero, both positive and negative zeros are
1288treated as equal and their sign is informational.
1289
1290In addition to the two signed zeros which are distinct yet equal, there are
1291various representations of zero with differing precisions yet equivalent in
1292value. This takes a bit of getting used to. For an eye accustomed to
1293normalized floating point representations, it is not immediately obvious that
Christian Heimesfe337bf2008-03-23 21:54:12 +00001294the following calculation returns a value equal to zero:
Georg Brandl116aa622007-08-15 14:28:22 +00001295
1296 >>> 1 / Decimal('Infinity')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001297 Decimal('0E-1000000026')
Georg Brandl116aa622007-08-15 14:28:22 +00001298
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001299.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001300
1301
1302.. _decimal-threads:
1303
1304Working with threads
1305--------------------
1306
1307The :func:`getcontext` function accesses a different :class:`Context` object for
1308each thread. Having separate thread contexts means that threads may make
1309changes (such as ``getcontext.prec=10``) without interfering with other threads.
1310
1311Likewise, the :func:`setcontext` function automatically assigns its target to
1312the current thread.
1313
1314If :func:`setcontext` has not been called before :func:`getcontext`, then
1315:func:`getcontext` will automatically create a new context for use in the
1316current thread.
1317
1318The new context is copied from a prototype context called *DefaultContext*. To
1319control the defaults so that each thread will use the same values throughout the
1320application, directly modify the *DefaultContext* object. This should be done
1321*before* any threads are started so that there won't be a race condition between
1322threads calling :func:`getcontext`. For example::
1323
1324 # Set applicationwide defaults for all threads about to be launched
1325 DefaultContext.prec = 12
1326 DefaultContext.rounding = ROUND_DOWN
1327 DefaultContext.traps = ExtendedContext.traps.copy()
1328 DefaultContext.traps[InvalidOperation] = 1
1329 setcontext(DefaultContext)
1330
1331 # Afterwards, the threads can be started
1332 t1.start()
1333 t2.start()
1334 t3.start()
1335 . . .
1336
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001337.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001338
1339
1340.. _decimal-recipes:
1341
1342Recipes
1343-------
1344
1345Here are a few recipes that serve as utility functions and that demonstrate ways
1346to work with the :class:`Decimal` class::
1347
1348 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1349 pos='', neg='-', trailneg=''):
1350 """Convert Decimal to a money formatted string.
1351
1352 places: required number of places after the decimal point
1353 curr: optional currency symbol before the sign (may be blank)
1354 sep: optional grouping separator (comma, period, space, or blank)
1355 dp: decimal point indicator (comma or period)
1356 only specify as blank when places is zero
1357 pos: optional sign for positive numbers: '+', space or blank
1358 neg: optional sign for negative numbers: '-', '(', space or blank
1359 trailneg:optional trailing minus indicator: '-', ')', space or blank
1360
1361 >>> d = Decimal('-1234567.8901')
1362 >>> moneyfmt(d, curr='$')
1363 '-$1,234,567.89'
1364 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1365 '1.234.568-'
1366 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1367 '($1,234,567.89)'
1368 >>> moneyfmt(Decimal(123456789), sep=' ')
1369 '123 456 789.00'
1370 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Christian Heimesdae2a892008-04-19 00:55:37 +00001371 '<0.02>'
Georg Brandl116aa622007-08-15 14:28:22 +00001372
1373 """
Christian Heimesa156e092008-02-16 07:38:31 +00001374 q = Decimal(10) ** -places # 2 places --> '0.01'
1375 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +00001376 result = []
1377 digits = map(str, digits)
1378 build, next = result.append, digits.pop
1379 if sign:
1380 build(trailneg)
1381 for i in range(places):
Christian Heimesa156e092008-02-16 07:38:31 +00001382 build(next() if digits else '0')
Georg Brandl116aa622007-08-15 14:28:22 +00001383 build(dp)
Christian Heimesdae2a892008-04-19 00:55:37 +00001384 if not digits:
1385 build('0')
Georg Brandl116aa622007-08-15 14:28:22 +00001386 i = 0
1387 while digits:
1388 build(next())
1389 i += 1
1390 if i == 3 and digits:
1391 i = 0
1392 build(sep)
1393 build(curr)
Christian Heimesa156e092008-02-16 07:38:31 +00001394 build(neg if sign else pos)
1395 return ''.join(reversed(result))
Georg Brandl116aa622007-08-15 14:28:22 +00001396
1397 def pi():
1398 """Compute Pi to the current precision.
1399
Georg Brandl6911e3c2007-09-04 07:15:32 +00001400 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001401 3.141592653589793238462643383
1402
1403 """
1404 getcontext().prec += 2 # extra digits for intermediate steps
1405 three = Decimal(3) # substitute "three=3.0" for regular floats
1406 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1407 while s != lasts:
1408 lasts = s
1409 n, na = n+na, na+8
1410 d, da = d+da, da+32
1411 t = (t * n) / d
1412 s += t
1413 getcontext().prec -= 2
1414 return +s # unary plus applies the new precision
1415
1416 def exp(x):
1417 """Return e raised to the power of x. Result type matches input type.
1418
Georg Brandl6911e3c2007-09-04 07:15:32 +00001419 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001420 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001421 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001422 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001423 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001424 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001425 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001426 (7.38905609893+0j)
1427
1428 """
1429 getcontext().prec += 2
1430 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1431 while s != lasts:
1432 lasts = s
1433 i += 1
1434 fact *= i
1435 num *= x
1436 s += num / fact
1437 getcontext().prec -= 2
1438 return +s
1439
1440 def cos(x):
1441 """Return the cosine of x as measured in radians.
1442
Georg Brandl6911e3c2007-09-04 07:15:32 +00001443 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001444 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001445 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001446 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001447 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001448 (0.87758256189+0j)
1449
1450 """
1451 getcontext().prec += 2
1452 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1453 while s != lasts:
1454 lasts = s
1455 i += 2
1456 fact *= i * (i-1)
1457 num *= x * x
1458 sign *= -1
1459 s += num / fact * sign
1460 getcontext().prec -= 2
1461 return +s
1462
1463 def sin(x):
1464 """Return the sine of x as measured in radians.
1465
Georg Brandl6911e3c2007-09-04 07:15:32 +00001466 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001467 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001468 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001469 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001470 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001471 (0.479425538604+0j)
1472
1473 """
1474 getcontext().prec += 2
1475 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1476 while s != lasts:
1477 lasts = s
1478 i += 2
1479 fact *= i * (i-1)
1480 num *= x * x
1481 sign *= -1
1482 s += num / fact * sign
1483 getcontext().prec -= 2
1484 return +s
1485
1486
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001487.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001488
1489
1490.. _decimal-faq:
1491
1492Decimal FAQ
1493-----------
1494
1495Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1496minimize typing when using the interactive interpreter?
1497
Christian Heimesfe337bf2008-03-23 21:54:12 +00001498A. Some users abbreviate the constructor to just a single letter:
Georg Brandl116aa622007-08-15 14:28:22 +00001499
1500 >>> D = decimal.Decimal
1501 >>> D('1.23') + D('3.45')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001502 Decimal('4.68')
Georg Brandl116aa622007-08-15 14:28:22 +00001503
1504Q. In a fixed-point application with two decimal places, some inputs have many
1505places and need to be rounded. Others are not supposed to have excess digits
1506and need to be validated. What methods should be used?
1507
1508A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Christian Heimesfe337bf2008-03-23 21:54:12 +00001509the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl116aa622007-08-15 14:28:22 +00001510
1511 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1512
1513 >>> # Round to two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001514 >>> Decimal('3.214').quantize(TWOPLACES)
1515 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001516
1517 >>> # Validate that a number does not exceed two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001518 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1519 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001520
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001521 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl116aa622007-08-15 14:28:22 +00001522 Traceback (most recent call last):
1523 ...
Christian Heimesfe337bf2008-03-23 21:54:12 +00001524 Inexact
Georg Brandl116aa622007-08-15 14:28:22 +00001525
1526Q. Once I have valid two place inputs, how do I maintain that invariant
1527throughout an application?
1528
Christian Heimesa156e092008-02-16 07:38:31 +00001529A. Some operations like addition, subtraction, and multiplication by an integer
1530will automatically preserve fixed point. Others operations, like division and
1531non-integer multiplication, will change the number of decimal places and need to
Christian Heimesfe337bf2008-03-23 21:54:12 +00001532be followed-up with a :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001533
1534 >>> a = Decimal('102.72') # Initial fixed-point values
1535 >>> b = Decimal('3.17')
1536 >>> a + b # Addition preserves fixed-point
1537 Decimal('105.89')
1538 >>> a - b
1539 Decimal('99.55')
1540 >>> a * 42 # So does integer multiplication
1541 Decimal('4314.24')
1542 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1543 Decimal('325.62')
1544 >>> (b / a).quantize(TWOPLACES) # And quantize division
1545 Decimal('0.03')
1546
1547In developing fixed-point applications, it is convenient to define functions
Christian Heimesfe337bf2008-03-23 21:54:12 +00001548to handle the :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001549
1550 >>> def mul(x, y, fp=TWOPLACES):
1551 ... return (x * y).quantize(fp)
1552 >>> def div(x, y, fp=TWOPLACES):
1553 ... return (x / y).quantize(fp)
1554
1555 >>> mul(a, b) # Automatically preserve fixed-point
1556 Decimal('325.62')
1557 >>> div(b, a)
1558 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +00001559
1560Q. There are many ways to express the same value. The numbers :const:`200`,
1561:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1562various precisions. Is there a way to transform them to a single recognizable
1563canonical value?
1564
1565A. The :meth:`normalize` method maps all equivalent values to a single
Christian Heimesfe337bf2008-03-23 21:54:12 +00001566representative:
Georg Brandl116aa622007-08-15 14:28:22 +00001567
1568 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1569 >>> [v.normalize() for v in values]
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001570 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl116aa622007-08-15 14:28:22 +00001571
1572Q. Some decimal values always print with exponential notation. Is there a way
1573to get a non-exponential representation?
1574
1575A. For some values, exponential notation is the only way to express the number
1576of significant places in the coefficient. For example, expressing
1577:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1578original's two-place significance.
1579
Christian Heimesa156e092008-02-16 07:38:31 +00001580If an application does not care about tracking significance, it is easy to
Christian Heimesc3f30c42008-02-22 16:37:40 +00001581remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001582value unchanged:
Christian Heimesa156e092008-02-16 07:38:31 +00001583
1584 >>> def remove_exponent(d):
1585 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1586
1587 >>> remove_exponent(Decimal('5E+3'))
1588 Decimal('5000')
1589
Georg Brandl116aa622007-08-15 14:28:22 +00001590Q. Is there a way to convert a regular float to a :class:`Decimal`?
1591
1592A. Yes, all binary floating point numbers can be exactly expressed as a
1593Decimal. An exact conversion may take more precision than intuition would
Christian Heimesfe337bf2008-03-23 21:54:12 +00001594suggest, so we trap :const:`Inexact` to signal a need for more precision:
1595
1596.. testcode::
Georg Brandl116aa622007-08-15 14:28:22 +00001597
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001598 def float_to_decimal(f):
1599 "Convert a floating point number to a Decimal with no loss of information"
1600 n, d = f.as_integer_ratio()
1601 with localcontext() as ctx:
1602 ctx.traps[Inexact] = True
1603 while True:
1604 try:
1605 return Decimal(n) / Decimal(d)
1606 except Inexact:
1607 ctx.prec += 1
Georg Brandl116aa622007-08-15 14:28:22 +00001608
Christian Heimesfe337bf2008-03-23 21:54:12 +00001609.. doctest::
1610
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001611 >>> float_to_decimal(math.pi)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001612 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl116aa622007-08-15 14:28:22 +00001613
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001614Q. Why isn't the :func:`float_to_decimal` routine included in the module?
Georg Brandl116aa622007-08-15 14:28:22 +00001615
1616A. There is some question about whether it is advisable to mix binary and
1617decimal floating point. Also, its use requires some care to avoid the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001618representation issues associated with binary floating point:
Georg Brandl116aa622007-08-15 14:28:22 +00001619
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001620 >>> float_to_decimal(1.1)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001621 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl116aa622007-08-15 14:28:22 +00001622
1623Q. Within a complex calculation, how can I make sure that I haven't gotten a
1624spurious result because of insufficient precision or rounding anomalies.
1625
1626A. The decimal module makes it easy to test results. A best practice is to
1627re-run calculations using greater precision and with various rounding modes.
1628Widely differing results indicate insufficient precision, rounding mode issues,
1629ill-conditioned inputs, or a numerically unstable algorithm.
1630
1631Q. I noticed that context precision is applied to the results of operations but
1632not to the inputs. Is there anything to watch out for when mixing values of
1633different precisions?
1634
1635A. Yes. The principle is that all values are considered to be exact and so is
1636the arithmetic on those values. Only the results are rounded. The advantage
1637for inputs is that "what you type is what you get". A disadvantage is that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001638results can look odd if you forget that the inputs haven't been rounded:
1639
1640.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001641
1642 >>> getcontext().prec = 3
Christian Heimesfe337bf2008-03-23 21:54:12 +00001643 >>> Decimal('3.104') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001644 Decimal('5.21')
Christian Heimesfe337bf2008-03-23 21:54:12 +00001645 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001646 Decimal('5.20')
Georg Brandl116aa622007-08-15 14:28:22 +00001647
1648The solution is either to increase precision or to force rounding of inputs
Christian Heimesfe337bf2008-03-23 21:54:12 +00001649using the unary plus operation:
1650
1651.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001652
1653 >>> getcontext().prec = 3
1654 >>> +Decimal('1.23456789') # unary plus triggers rounding
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001655 Decimal('1.23')
Georg Brandl116aa622007-08-15 14:28:22 +00001656
1657Alternatively, inputs can be rounded upon creation using the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001658:meth:`Context.create_decimal` method:
Georg Brandl116aa622007-08-15 14:28:22 +00001659
1660 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001661 Decimal('1.2345')
Georg Brandl116aa622007-08-15 14:28:22 +00001662