blob: dbdb4bddfedea3f27a984f97f04a871c7ebc247b [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
Raymond Hettinger13a70752008-02-10 07:21:09 +00002:mod:`decimal` --- Decimal fixed point and floating point arithmetic
3====================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00004
5.. module:: decimal
6 :synopsis: Implementation of the General Decimal Arithmetic Specification.
7
8
9.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
10.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
11.. moduleauthor:: Raymond Hettinger <python at rcn.com>
12.. moduleauthor:: Aahz <aahz at pobox.com>
13.. moduleauthor:: Tim Peters <tim.one at comcast.net>
14
15
16.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
17
Georg Brandl8ec7f652007-08-15 14:28:01 +000018.. versionadded:: 2.4
19
Georg Brandl9f662322008-03-22 11:47:10 +000020.. import modules for testing inline doctests with the Sphinx doctest builder
Georg Brandl17baef02008-03-22 10:56:23 +000021.. testsetup:: *
22
Georg Brandl9f662322008-03-22 11:47:10 +000023 import decimal
24 import math
Georg Brandl17baef02008-03-22 10:56:23 +000025 from decimal import *
Georg Brandl9f662322008-03-22 11:47:10 +000026 # make sure each group gets a fresh context
27 setcontext(Context())
Georg Brandl17baef02008-03-22 10:56:23 +000028
Georg Brandl8ec7f652007-08-15 14:28:01 +000029The :mod:`decimal` module provides support for decimal floating point
Facundo Batista7c82a3e92007-09-14 18:58:34 +000030arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
Raymond Hettinger13a70752008-02-10 07:21:09 +000032* Decimal "is based on a floating-point model which was designed with people
33 in mind, and necessarily has a paramount guiding principle -- computers must
34 provide an arithmetic that works in the same way as the arithmetic that
35 people learn at school." -- excerpt from the decimal arithmetic specification.
36
Georg Brandl8ec7f652007-08-15 14:28:01 +000037* Decimal numbers can be represented exactly. In contrast, numbers like
38 :const:`1.1` do not have an exact representation in binary floating point. End
39 users typically would not expect :const:`1.1` to display as
40 :const:`1.1000000000000001` as it does with binary floating point.
41
42* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Facundo Batista7c82a3e92007-09-14 18:58:34 +000043 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl8ec7f652007-08-15 14:28:01 +000044 is :const:`5.5511151231257827e-017`. While near to zero, the differences
45 prevent reliable equality testing and differences can accumulate. For this
Raymond Hettinger13a70752008-02-10 07:21:09 +000046 reason, decimal is preferred in accounting applications which have strict
Georg Brandl8ec7f652007-08-15 14:28:01 +000047 equality invariants.
48
49* The decimal module incorporates a notion of significant places so that ``1.30
50 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
51 This is the customary presentation for monetary applications. For
52 multiplication, the "schoolbook" approach uses all the figures in the
53 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
54 1.20`` gives :const:`1.5600`.
55
56* Unlike hardware based binary floating point, the decimal module has a user
Facundo Batista7c82a3e92007-09-14 18:58:34 +000057 alterable precision (defaulting to 28 places) which can be as large as needed for
Georg Brandl17baef02008-03-22 10:56:23 +000058 a given problem:
Georg Brandl8ec7f652007-08-15 14:28:01 +000059
60 >>> getcontext().prec = 6
61 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +000062 Decimal('0.142857')
Georg Brandl8ec7f652007-08-15 14:28:01 +000063 >>> getcontext().prec = 28
64 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +000065 Decimal('0.1428571428571428571428571429')
Georg Brandl8ec7f652007-08-15 14:28:01 +000066
67* Both binary and decimal floating point are implemented in terms of published
68 standards. While the built-in float type exposes only a modest portion of its
69 capabilities, the decimal module exposes all required parts of the standard.
70 When needed, the programmer has full control over rounding and signal handling.
Raymond Hettinger13a70752008-02-10 07:21:09 +000071 This includes an option to enforce exact arithmetic by using exceptions
72 to block any inexact operations.
73
74* The decimal module was designed to support "without prejudice, both exact
75 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
76 and rounded floating-point arithmetic." -- excerpt from the decimal
77 arithmetic specification.
Georg Brandl8ec7f652007-08-15 14:28:01 +000078
79The module design is centered around three concepts: the decimal number, the
80context for arithmetic, and signals.
81
82A decimal number is immutable. It has a sign, coefficient digits, and an
83exponent. To preserve significance, the coefficient digits do not truncate
Facundo Batista7c82a3e92007-09-14 18:58:34 +000084trailing zeros. Decimals also include special values such as
Georg Brandl8ec7f652007-08-15 14:28:01 +000085:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
86differentiates :const:`-0` from :const:`+0`.
87
88The context for arithmetic is an environment specifying precision, rounding
89rules, limits on exponents, flags indicating the results of operations, and trap
90enablers which determine whether signals are treated as exceptions. Rounding
91options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
92:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +000093:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000094
95Signals are groups of exceptional conditions arising during the course of
96computation. Depending on the needs of the application, signals may be ignored,
97considered as informational, or treated as exceptions. The signals in the
98decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
99:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
100:const:`Overflow`, and :const:`Underflow`.
101
102For each signal there is a flag and a trap enabler. When a signal is
103encountered, its flag is incremented from zero and, then, if the trap enabler is
104set to one, an exception is raised. Flags are sticky, so the user needs to
105reset them before monitoring a calculation.
106
107
108.. seealso::
109
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000110 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
111 Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000112
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000113 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Mark Dickinsonff6672f2008-02-07 01:14:23 +0000114 <http://754r.ucbtest.org/standards/854.pdf>`_.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000115
Georg Brandlb19be572007-12-29 10:57:00 +0000116.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000117
118
119.. _decimal-tutorial:
120
121Quick-start Tutorial
122--------------------
123
124The usual start to using decimals is importing the module, viewing the current
125context with :func:`getcontext` and, if necessary, setting new values for
Georg Brandl9f662322008-03-22 11:47:10 +0000126precision, rounding, or enabled traps::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000127
128 >>> from decimal import *
129 >>> getcontext()
130 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Georg Brandl9f662322008-03-22 11:47:10 +0000131 capitals=1, flags=[], traps=[Overflow, DivisionByZero,
132 InvalidOperation])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000133
134 >>> getcontext().prec = 7 # Set a new precision
135
136Decimal instances can be constructed from integers, strings, or tuples. To
137create a Decimal from a :class:`float`, first convert it to a string. This
138serves as an explicit reminder of the details of the conversion (including
139representation error). Decimal numbers include special values such as
140:const:`NaN` which stands for "Not a number", positive and negative
Georg Brandl17baef02008-03-22 10:56:23 +0000141:const:`Infinity`, and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000142
143 >>> Decimal(10)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000144 Decimal('10')
145 >>> Decimal('3.14')
146 Decimal('3.14')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000147 >>> Decimal((0, (3, 1, 4), -2))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000148 Decimal('3.14')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000149 >>> Decimal(str(2.0 ** 0.5))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000150 Decimal('1.41421356237')
151 >>> Decimal(2) ** Decimal('0.5')
152 Decimal('1.414213562373095048801688724')
153 >>> Decimal('NaN')
154 Decimal('NaN')
155 >>> Decimal('-Infinity')
156 Decimal('-Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000157
158The significance of a new Decimal is determined solely by the number of digits
159input. Context precision and rounding only come into play during arithmetic
Georg Brandl17baef02008-03-22 10:56:23 +0000160operations.
161
162.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +0000163
164 >>> getcontext().prec = 6
165 >>> Decimal('3.0')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000166 Decimal('3.0')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000167 >>> Decimal('3.1415926535')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000168 Decimal('3.1415926535')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000169 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000170 Decimal('5.85987')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000171 >>> getcontext().rounding = ROUND_UP
172 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000173 Decimal('5.85988')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000174
175Decimals interact well with much of the rest of Python. Here is a small decimal
Georg Brandl9f662322008-03-22 11:47:10 +0000176floating point flying circus:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000177
178 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
179 >>> max(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000180 Decimal('9.25')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000181 >>> min(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000182 Decimal('0.03')
Georg Brandl9f662322008-03-22 11:47:10 +0000183 >>> sorted(data) # doctest: +NORMALIZE_WHITESPACE
Raymond Hettingerabe32372008-02-14 02:41:22 +0000184 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
185 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000186 >>> sum(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000187 Decimal('19.29')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000188 >>> a,b,c = data[:3]
189 >>> str(a)
190 '1.34'
191 >>> float(a)
192 1.3400000000000001
193 >>> round(a, 1) # round() first converts to binary floating point
194 1.3
195 >>> int(a)
196 1
197 >>> a * 5
Raymond Hettingerabe32372008-02-14 02:41:22 +0000198 Decimal('6.70')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000199 >>> a * b
Raymond Hettingerabe32372008-02-14 02:41:22 +0000200 Decimal('2.5058')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000201 >>> c % a
Raymond Hettingerabe32372008-02-14 02:41:22 +0000202 Decimal('0.77')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000203
Georg Brandl9f662322008-03-22 11:47:10 +0000204And some mathematical functions are also available to Decimal:
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000205
206 >>> Decimal(2).sqrt()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000207 Decimal('1.414213562373095048801688724')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000208 >>> Decimal(1).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000209 Decimal('2.718281828459045235360287471')
210 >>> Decimal('10').ln()
211 Decimal('2.302585092994045684017991455')
212 >>> Decimal('10').log10()
213 Decimal('1')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000214
Georg Brandl8ec7f652007-08-15 14:28:01 +0000215The :meth:`quantize` method rounds a number to a fixed exponent. This method is
216useful for monetary applications that often round results to a fixed number of
Georg Brandl9f662322008-03-22 11:47:10 +0000217places:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000218
219 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000220 Decimal('7.32')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000221 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000222 Decimal('8')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000223
224As shown above, the :func:`getcontext` function accesses the current context and
225allows the settings to be changed. This approach meets the needs of most
226applications.
227
228For more advanced work, it may be useful to create alternate contexts using the
229Context() constructor. To make an alternate active, use the :func:`setcontext`
230function.
231
232In accordance with the standard, the :mod:`Decimal` module provides two ready to
233use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
234former is especially useful for debugging because many of the traps are
Georg Brandl9f662322008-03-22 11:47:10 +0000235enabled:
236
237.. doctest:: newcontext
238 :options: +NORMALIZE_WHITESPACE
Georg Brandl8ec7f652007-08-15 14:28:01 +0000239
240 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
241 >>> setcontext(myothercontext)
242 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000243 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000244
245 >>> ExtendedContext
246 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
247 capitals=1, flags=[], traps=[])
248 >>> setcontext(ExtendedContext)
249 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000250 Decimal('0.142857143')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000251 >>> Decimal(42) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000252 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000253
254 >>> setcontext(BasicContext)
255 >>> Decimal(42) / Decimal(0)
256 Traceback (most recent call last):
257 File "<pyshell#143>", line 1, in -toplevel-
258 Decimal(42) / Decimal(0)
259 DivisionByZero: x / 0
260
261Contexts also have signal flags for monitoring exceptional conditions
262encountered during computations. The flags remain set until explicitly cleared,
263so it is best to clear the flags before each set of monitored computations by
264using the :meth:`clear_flags` method. ::
265
266 >>> setcontext(ExtendedContext)
267 >>> getcontext().clear_flags()
268 >>> Decimal(355) / Decimal(113)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000269 Decimal('3.14159292')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000270 >>> getcontext()
271 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Georg Brandl9f662322008-03-22 11:47:10 +0000272 capitals=1, flags=[Rounded, Inexact], traps=[])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000273
274The *flags* entry shows that the rational approximation to :const:`Pi` was
275rounded (digits beyond the context precision were thrown away) and that the
276result is inexact (some of the discarded digits were non-zero).
277
278Individual traps are set using the dictionary in the :attr:`traps` field of a
Georg Brandl9f662322008-03-22 11:47:10 +0000279context:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000280
Georg Brandl9f662322008-03-22 11:47:10 +0000281.. doctest:: newcontext
282
283 >>> setcontext(ExtendedContext)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000284 >>> Decimal(1) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000285 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000286 >>> getcontext().traps[DivisionByZero] = 1
287 >>> Decimal(1) / Decimal(0)
288 Traceback (most recent call last):
289 File "<pyshell#112>", line 1, in -toplevel-
290 Decimal(1) / Decimal(0)
291 DivisionByZero: x / 0
292
293Most programs adjust the current context only once, at the beginning of the
294program. And, in many applications, data is converted to :class:`Decimal` with
295a single cast inside a loop. With context set and decimals created, the bulk of
296the program manipulates the data no differently than with other Python numeric
297types.
298
Georg Brandlb19be572007-12-29 10:57:00 +0000299.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000300
301
302.. _decimal-decimal:
303
304Decimal objects
305---------------
306
307
308.. class:: Decimal([value [, context]])
309
Georg Brandlb19be572007-12-29 10:57:00 +0000310 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000311
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000312 *value* can be an integer, string, tuple, or another :class:`Decimal`
Raymond Hettingerabe32372008-02-14 02:41:22 +0000313 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000314 string, it should conform to the decimal numeric string syntax after leading
315 and trailing whitespace characters are removed::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000316
317 sign ::= '+' | '-'
318 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
319 indicator ::= 'e' | 'E'
320 digits ::= digit [digit]...
321 decimal-part ::= digits '.' [digits] | ['.'] digits
322 exponent-part ::= indicator [sign] digits
323 infinity ::= 'Infinity' | 'Inf'
324 nan ::= 'NaN' [digits] | 'sNaN' [digits]
325 numeric-value ::= decimal-part [exponent-part] | infinity
326 numeric-string ::= [sign] numeric-value | [sign] nan
327
328 If *value* is a :class:`tuple`, it should have three components, a sign
329 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
330 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Raymond Hettingerabe32372008-02-14 02:41:22 +0000331 returns ``Decimal('1.414')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000332
333 The *context* precision does not affect how many digits are stored. That is
334 determined exclusively by the number of digits in *value*. For example,
Raymond Hettingerabe32372008-02-14 02:41:22 +0000335 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000336 only three.
337
338 The purpose of the *context* argument is determining what to do if *value* is a
339 malformed string. If the context traps :const:`InvalidOperation`, an exception
340 is raised; otherwise, the constructor returns a new Decimal with the value of
341 :const:`NaN`.
342
343 Once constructed, :class:`Decimal` objects are immutable.
344
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000345 .. versionchanged:: 2.6
346 leading and trailing whitespace characters are permitted when
347 creating a Decimal instance from a string.
348
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000349Decimal floating point objects share many properties with the other built-in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000350numeric types such as :class:`float` and :class:`int`. All of the usual math
351operations and special methods apply. Likewise, decimal objects can be copied,
352pickled, printed, used as dictionary keys, used as set elements, compared,
353sorted, and coerced to another type (such as :class:`float` or :class:`long`).
354
355In addition to the standard numeric properties, decimal floating point objects
356also have a number of specialized methods:
357
358
359.. method:: Decimal.adjusted()
360
361 Return the adjusted exponent after shifting out the coefficient's rightmost
Raymond Hettingerabe32372008-02-14 02:41:22 +0000362 digits until only the lead digit remains: ``Decimal('321e+5').adjusted()``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000363 returns seven. Used for determining the position of the most significant digit
364 with respect to the decimal point.
365
366
367.. method:: Decimal.as_tuple()
368
Georg Brandle3c3db52008-01-11 09:55:53 +0000369 Return a :term:`named tuple` representation of the number:
370 ``DecimalTuple(sign, digits, exponent)``.
371
372 .. versionchanged:: 2.6
373 Use a named tuple.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000374
375
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000376.. method:: Decimal.canonical()
377
378 Return the canonical encoding of the argument. Currently, the
379 encoding of a :class:`Decimal` instance is always canonical, so
380 this operation returns its argument unchanged.
381
382 .. versionadded:: 2.6
383
Georg Brandl8ec7f652007-08-15 14:28:01 +0000384.. method:: Decimal.compare(other[, context])
385
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000386 Compare the values of two Decimal instances. This operation
387 behaves in the same way as the usual comparison method
388 :meth:`__cmp__`, except that :meth:`compare` returns a Decimal
389 instance rather than an integer, and if either operand is a NaN
390 then the result is a NaN::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000391
Raymond Hettingerabe32372008-02-14 02:41:22 +0000392 a or b is a NaN ==> Decimal('NaN')
393 a < b ==> Decimal('-1')
394 a == b ==> Decimal('0')
395 a > b ==> Decimal('1')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000396
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000397.. method:: Decimal.compare_signal(other[, context])
398
399 This operation is identical to the :meth:`compare` method, except
400 that all NaNs signal. That is, if neither operand is a signaling
401 NaN then any quiet NaN operand is treated as though it were a
402 signaling NaN.
403
404 .. versionadded:: 2.6
405
406.. method:: Decimal.compare_total(other)
407
408 Compare two operands using their abstract representation rather
409 than their numerical value. Similar to the :meth:`compare` method,
410 but the result gives a total ordering on :class:`Decimal`
411 instances. Two :class:`Decimal` instances with the same numeric
412 value but different representations compare unequal in this
Georg Brandl9f662322008-03-22 11:47:10 +0000413 ordering:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000414
Raymond Hettingerabe32372008-02-14 02:41:22 +0000415 >>> Decimal('12.0').compare_total(Decimal('12'))
416 Decimal('-1')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000417
418 Quiet and signaling NaNs are also included in the total ordering.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000419 The result of this function is ``Decimal('0')`` if both operands
420 have the same representation, ``Decimal('-1')`` if the first
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000421 operand is lower in the total order than the second, and
Raymond Hettingerabe32372008-02-14 02:41:22 +0000422 ``Decimal('1')`` if the first operand is higher in the total order
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000423 than the second operand. See the specification for details of the
424 total order.
425
426 .. versionadded:: 2.6
427
428.. method:: Decimal.compare_total_mag(other)
429
430 Compare two operands using their abstract representation rather
431 than their value as in :meth:`compare_total`, but ignoring the sign
432 of each operand. ``x.compare_total_mag(y)`` is equivalent to
433 ``x.copy_abs().compare_total(y.copy_abs())``.
434
435 .. versionadded:: 2.6
436
437.. method:: Decimal.copy_abs()
438
439 Return the absolute value of the argument. This operation is
440 unaffected by the context and is quiet: no flags are changed and no
441 rounding is performed.
442
443 .. versionadded:: 2.6
444
445.. method:: Decimal.copy_negate()
446
447 Return the negation of the argument. This operation is unaffected
448 by the context and is quiet: no flags are changed and no rounding
449 is performed.
450
451 .. versionadded:: 2.6
452
453.. method:: Decimal.copy_sign(other)
454
455 Return a copy of the first operand with the sign set to be the
Georg Brandl9f662322008-03-22 11:47:10 +0000456 same as the sign of the second operand. For example:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000457
Raymond Hettingerabe32372008-02-14 02:41:22 +0000458 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
459 Decimal('-2.3')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000460
461 This operation is unaffected by the context and is quiet: no flags
462 are changed and no rounding is performed.
463
464 .. versionadded:: 2.6
465
466.. method:: Decimal.exp([context])
467
468 Return the value of the (natural) exponential function ``e**x`` at the
469 given number. The result is correctly rounded using the
470 :const:`ROUND_HALF_EVEN` rounding mode.
471
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000472 >>> Decimal(1).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000473 Decimal('2.718281828459045235360287471')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000474 >>> Decimal(321).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000475 Decimal('2.561702493119680037517373933E+139')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000476
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000477 .. versionadded:: 2.6
478
479.. method:: Decimal.fma(other, third[, context])
480
481 Fused multiply-add. Return self*other+third with no rounding of
482 the intermediate product self*other.
483
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000484 >>> Decimal(2).fma(3, 5)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000485 Decimal('11')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000486
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000487 .. versionadded:: 2.6
488
489.. method:: Decimal.is_canonical()
490
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000491 Return :const:`True` if the argument is canonical and
492 :const:`False` otherwise. Currently, a :class:`Decimal` instance
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000493 is always canonical, so this operation always returns
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000494 :const:`True`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000495
496 .. versionadded:: 2.6
497
498.. method:: is_finite()
499
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000500 Return :const:`True` if the argument is a finite number, and
501 :const:`False` if the argument is an infinity or a NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000502
503 .. versionadded:: 2.6
504
505.. method:: is_infinite()
506
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000507 Return :const:`True` if the argument is either positive or
508 negative infinity and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000509
510 .. versionadded:: 2.6
511
512.. method:: is_nan()
513
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000514 Return :const:`True` if the argument is a (quiet or signaling)
515 NaN and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000516
517 .. versionadded:: 2.6
518
519.. method:: is_normal()
520
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000521 Return :const:`True` if the argument is a *normal* finite number.
522 Return :const:`False` if the argument is zero, subnormal, infinite
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000523 or a NaN.
524
525 .. versionadded:: 2.6
526
527.. method:: is_qnan()
528
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000529 Return :const:`True` if the argument is a quiet NaN, and
530 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000531
532 .. versionadded:: 2.6
533
534.. method:: is_signed()
535
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000536 Return :const:`True` if the argument has a negative sign and
537 :const:`False` otherwise. Note that zeros and NaNs can both carry
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000538 signs.
539
540 .. versionadded:: 2.6
541
542.. method:: is_snan()
543
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000544 Return :const:`True` if the argument is a signaling NaN and
545 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000546
547 .. versionadded:: 2.6
548
549.. method:: is_subnormal()
550
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000551 Return :const:`True` if the argument is subnormal, and
552 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000553
554 .. versionadded:: 2.6
555
556.. method:: is_zero()
557
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000558 Return :const:`True` if the argument is a (positive or negative)
559 zero and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000560
561 .. versionadded:: 2.6
562
563.. method:: Decimal.ln([context])
564
565 Return the natural (base e) logarithm of the operand. The result
566 is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
567 mode.
568
569 .. versionadded:: 2.6
570
571.. method:: Decimal.log10([context])
572
573 Return the base ten logarithm of the operand. The result is
574 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
575
576 .. versionadded:: 2.6
577
Georg Brandlb19be572007-12-29 10:57:00 +0000578.. method:: Decimal.logb([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000579
580 For a nonzero number, return the adjusted exponent of its operand
581 as a :class:`Decimal` instance. If the operand is a zero then
Raymond Hettingerabe32372008-02-14 02:41:22 +0000582 ``Decimal('-Infinity')`` is returned and the
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000583 :const:`DivisionByZero` flag is raised. If the operand is an
Raymond Hettingerabe32372008-02-14 02:41:22 +0000584 infinity then ``Decimal('Infinity')`` is returned.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000585
586 .. versionadded:: 2.6
587
588.. method:: Decimal.logical_and(other[, context])
589
590 :meth:`logical_and` is a logical operation which takes two
591 *logical operands* (see :ref:`logical_operands_label`). The result
592 is the digit-wise ``and`` of the two operands.
593
594 .. versionadded:: 2.6
595
596.. method:: Decimal.logical_invert(other[, context])
597
598 :meth:`logical_invert` is a logical operation. The argument must
599 be a *logical operand* (see :ref:`logical_operands_label`). The
600 result is the digit-wise inversion of the operand.
601
602 .. versionadded:: 2.6
603
604.. method:: Decimal.logical_or(other[, context])
605
606 :meth:`logical_or` is a logical operation which takes two *logical
607 operands* (see :ref:`logical_operands_label`). The result is the
608 digit-wise ``or`` of the two operands.
609
610 .. versionadded:: 2.6
611
612.. method:: Decimal.logical_xor(other[, context])
613
614 :meth:`logical_xor` is a logical operation which takes two
615 *logical operands* (see :ref:`logical_operands_label`). The result
616 is the digit-wise exclusive or of the two operands.
617
618 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000619
620.. method:: Decimal.max(other[, context])
621
622 Like ``max(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000623 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000624 (depending on the context and whether they are signaling or quiet).
625
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000626.. method:: Decimal.max_mag(other[, context])
627
628 Similar to the :meth:`max` method, but the comparison is done using
629 the absolute values of the operands.
630
631 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000632
633.. method:: Decimal.min(other[, context])
634
635 Like ``min(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000636 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000637 (depending on the context and whether they are signaling or quiet).
638
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000639.. method:: Decimal.min_mag(other[, context])
640
641 Similar to the :meth:`min` method, but the comparison is done using
642 the absolute values of the operands.
643
644 .. versionadded:: 2.6
645
646.. method:: Decimal.next_minus([context])
647
648 Return the largest number representable in the given context (or
649 in the current thread's context if no context is given) that is smaller
650 than the given operand.
651
652 .. versionadded:: 2.6
653
654.. method:: Decimal.next_plus([context])
655
656 Return the smallest number representable in the given context (or
657 in the current thread's context if no context is given) that is
658 larger than the given operand.
659
660 .. versionadded:: 2.6
661
662.. method:: Decimal.next_toward(other[, context])
663
664 If the two operands are unequal, return the number closest to the
665 first operand in the direction of the second operand. If both
666 operands are numerically equal, return a copy of the first operand
667 with the sign set to be the same as the sign of the second operand.
668
669 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000670
671.. method:: Decimal.normalize([context])
672
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000673 Normalize the number by stripping the rightmost trailing zeros and converting
Raymond Hettingerabe32372008-02-14 02:41:22 +0000674 any result equal to :const:`Decimal('0')` to :const:`Decimal('0e0')`. Used for
Georg Brandl8ec7f652007-08-15 14:28:01 +0000675 producing canonical values for members of an equivalence class. For example,
Raymond Hettingerabe32372008-02-14 02:41:22 +0000676 ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both normalize to the
677 equivalent value ``Decimal('32.1')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000678
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000679.. method:: Decimal.number_class([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000680
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000681 Return a string describing the *class* of the operand. The
682 returned value is one of the following ten strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000683
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000684 * ``"-Infinity"``, indicating that the operand is negative infinity.
685 * ``"-Normal"``, indicating that the operand is a negative normal number.
686 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
687 * ``"-Zero"``, indicating that the operand is a negative zero.
688 * ``"+Zero"``, indicating that the operand is a positive zero.
689 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
690 * ``"+Normal"``, indicating that the operand is a positive normal number.
691 * ``"+Infinity"``, indicating that the operand is positive infinity.
692 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
693 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000694
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000695 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000696
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000697.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]])
698
Georg Brandlb19be572007-12-29 10:57:00 +0000699 Return a value equal to the first operand after rounding and
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000700 having the exponent of the second operand.
701
Raymond Hettingerabe32372008-02-14 02:41:22 +0000702 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
703 Decimal('1.414')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000704
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000705 Unlike other operations, if the length of the coefficient after the
706 quantize operation would be greater than precision, then an
707 :const:`InvalidOperation` is signaled. This guarantees that, unless
708 there is an error condition, the quantized exponent is always equal
709 to that of the right-hand operand.
710
711 Also unlike other operations, quantize never signals Underflow,
712 even if the result is subnormal and inexact.
713
714 If the exponent of the second operand is larger than that of the
715 first then rounding may be necessary. In this case, the rounding
716 mode is determined by the ``rounding`` argument if given, else by
717 the given ``context`` argument; if neither argument is given the
718 rounding mode of the current thread's context is used.
719
Georg Brandlb19be572007-12-29 10:57:00 +0000720 If *watchexp* is set (default), then an error is returned whenever the
721 resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000722
723.. method:: Decimal.radix()
724
725 Return ``Decimal(10)``, the radix (base) in which the
726 :class:`Decimal` class does all its arithmetic. Included for
727 compatibility with the specification.
728
729 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000730
731.. method:: Decimal.remainder_near(other[, context])
732
Georg Brandlb19be572007-12-29 10:57:00 +0000733 Compute the modulo as either a positive or negative value depending on which is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000734 closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
Raymond Hettingerabe32372008-02-14 02:41:22 +0000735 ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000736
737 If both are equally close, the one chosen will have the same sign as *self*.
738
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000739.. method:: Decimal.rotate(other[, context])
740
741 Return the result of rotating the digits of the first operand by
742 an amount specified by the second operand. The second operand
743 must be an integer in the range -precision through precision. The
744 absolute value of the second operand gives the number of places to
745 rotate. If the second operand is positive then rotation is to the
746 left; otherwise rotation is to the right. The coefficient of the
747 first operand is padded on the left with zeros to length precision
748 if necessary. The sign and exponent of the first operand are
749 unchanged.
750
751 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000752
753.. method:: Decimal.same_quantum(other[, context])
754
755 Test whether self and other have the same exponent or whether both are
756 :const:`NaN`.
757
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000758.. method:: Decimal.scaleb(other[, context])
759
760 Return the first operand with exponent adjusted by the second.
761 Equivalently, return the first operand multiplied by ``10**other``.
762 The second operand must be an integer.
763
764 .. versionadded:: 2.6
765
766.. method:: Decimal.shift(other[, context])
767
768 Return the result of shifting the digits of the first operand by
769 an amount specified by the second operand. The second operand must
770 be an integer in the range -precision through precision. The
771 absolute value of the second operand gives the number of places to
772 shift. If the second operand is positive then the shift is to the
773 left; otherwise the shift is to the right. Digits shifted into the
774 coefficient are zeros. The sign and exponent of the first operand
775 are unchanged.
776
777 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000778
779.. method:: Decimal.sqrt([context])
780
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000781 Return the square root of the argument to full precision.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000782
783
784.. method:: Decimal.to_eng_string([context])
785
786 Convert to an engineering-type string.
787
788 Engineering notation has an exponent which is a multiple of 3, so there are up
789 to 3 digits left of the decimal place. For example, converts
Raymond Hettingerabe32372008-02-14 02:41:22 +0000790 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000791
Georg Brandl8ec7f652007-08-15 14:28:01 +0000792.. method:: Decimal.to_integral([rounding[, context]])
793
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000794 Identical to the :meth:`to_integral_value` method. The ``to_integral``
795 name has been kept for compatibility with older versions.
796
797.. method:: Decimal.to_integral_exact([rounding[, context]])
798
Georg Brandlb19be572007-12-29 10:57:00 +0000799 Round to the nearest integer, signaling
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000800 :const:`Inexact` or :const:`Rounded` as appropriate if rounding
801 occurs. The rounding mode is determined by the ``rounding``
802 parameter if given, else by the given ``context``. If neither
803 parameter is given then the rounding mode of the current context is
804 used.
805
806 .. versionadded:: 2.6
807
808.. method:: Decimal.to_integral_value([rounding[, context]])
809
Georg Brandlb19be572007-12-29 10:57:00 +0000810 Round to the nearest integer without signaling :const:`Inexact` or
Georg Brandl8ec7f652007-08-15 14:28:01 +0000811 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding
812 method in either the supplied *context* or the current context.
813
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000814 .. versionchanged:: 2.6
815 renamed from ``to_integral`` to ``to_integral_value``. The old name
816 remains valid for compatibility.
817
818.. method:: Decimal.trim()
819
Georg Brandlb19be572007-12-29 10:57:00 +0000820 Return the decimal with *insignificant* trailing zeros removed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000821 Here, a trailing zero is considered insignificant either if it
822 follows the decimal point, or if the exponent of the argument (that
823 is, the last element of the :meth:`as_tuple` representation) is
824 positive.
825
826 .. versionadded:: 2.6
827
828.. _logical_operands_label:
829
830Logical operands
831^^^^^^^^^^^^^^^^
832
833The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
834and :meth:`logical_xor` methods expect their arguments to be *logical
835operands*. A *logical operand* is a :class:`Decimal` instance whose
836exponent and sign are both zero, and whose digits are all either
837:const:`0` or :const:`1`.
838
Georg Brandlb19be572007-12-29 10:57:00 +0000839.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000840
841
842.. _decimal-context:
843
844Context objects
845---------------
846
847Contexts are environments for arithmetic operations. They govern precision, set
848rules for rounding, determine which signals are treated as exceptions, and limit
849the range for exponents.
850
851Each thread has its own current context which is accessed or changed using the
852:func:`getcontext` and :func:`setcontext` functions:
853
854
855.. function:: getcontext()
856
857 Return the current context for the active thread.
858
859
860.. function:: setcontext(c)
861
862 Set the current context for the active thread to *c*.
863
864Beginning with Python 2.5, you can also use the :keyword:`with` statement and
865the :func:`localcontext` function to temporarily change the active context.
866
867
868.. function:: localcontext([c])
869
870 Return a context manager that will set the current context for the active thread
871 to a copy of *c* on entry to the with-statement and restore the previous context
872 when exiting the with-statement. If no context is specified, a copy of the
873 current context is used.
874
875 .. versionadded:: 2.5
876
877 For example, the following code sets the current decimal precision to 42 places,
878 performs a calculation, and then automatically restores the previous context::
879
Georg Brandl8ec7f652007-08-15 14:28:01 +0000880 from decimal import localcontext
881
882 with localcontext() as ctx:
883 ctx.prec = 42 # Perform a high precision calculation
884 s = calculate_something()
885 s = +s # Round the final result back to the default precision
886
887New contexts can also be created using the :class:`Context` constructor
888described below. In addition, the module provides three pre-made contexts:
889
890
891.. class:: BasicContext
892
893 This is a standard context defined by the General Decimal Arithmetic
894 Specification. Precision is set to nine. Rounding is set to
895 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
896 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
897 :const:`Subnormal`.
898
899 Because many of the traps are enabled, this context is useful for debugging.
900
901
902.. class:: ExtendedContext
903
904 This is a standard context defined by the General Decimal Arithmetic
905 Specification. Precision is set to nine. Rounding is set to
906 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
907 exceptions are not raised during computations).
908
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000909 Because the traps are disabled, this context is useful for applications that
Georg Brandl8ec7f652007-08-15 14:28:01 +0000910 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
911 raising exceptions. This allows an application to complete a run in the
912 presence of conditions that would otherwise halt the program.
913
914
915.. class:: DefaultContext
916
917 This context is used by the :class:`Context` constructor as a prototype for new
918 contexts. Changing a field (such a precision) has the effect of changing the
919 default for new contexts creating by the :class:`Context` constructor.
920
921 This context is most useful in multi-threaded environments. Changing one of the
922 fields before threads are started has the effect of setting system-wide
923 defaults. Changing the fields after threads have started is not recommended as
924 it would require thread synchronization to prevent race conditions.
925
926 In single threaded environments, it is preferable to not use this context at
927 all. Instead, simply create contexts explicitly as described below.
928
929 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
930 for Overflow, InvalidOperation, and DivisionByZero.
931
932In addition to the three supplied contexts, new contexts can be created with the
933:class:`Context` constructor.
934
935
936.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
937
938 Creates a new context. If a field is not specified or is :const:`None`, the
939 default values are copied from the :const:`DefaultContext`. If the *flags*
940 field is not specified or is :const:`None`, all flags are cleared.
941
942 The *prec* field is a positive integer that sets the precision for arithmetic
943 operations in the context.
944
945 The *rounding* option is one of:
946
947 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
948 * :const:`ROUND_DOWN` (towards zero),
949 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
950 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
951 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
952 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
953 * :const:`ROUND_UP` (away from zero).
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000954 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
955 would have been 0 or 5; otherwise towards zero)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000956
957 The *traps* and *flags* fields list any signals to be set. Generally, new
958 contexts should only set traps and leave the flags clear.
959
960 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
961 for exponents.
962
963 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
964 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
965 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
966
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000967 .. versionchanged:: 2.6
968 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000969
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000970The :class:`Context` class defines several general purpose methods as
971well as a large number of methods for doing arithmetic directly in a
972given context. In addition, for each of the :class:`Decimal` methods
973described above (with the exception of the :meth:`adjusted` and
974:meth:`as_tuple` methods) there is a corresponding :class:`Context`
975method. For example, ``C.exp(x)`` is equivalent to
976``x.exp(context=C)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000977
978.. method:: Context.clear_flags()
979
980 Resets all of the flags to :const:`0`.
981
982
983.. method:: Context.copy()
984
985 Return a duplicate of the context.
986
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000987.. method:: Context.copy_decimal(num)
988
989 Return a copy of the Decimal instance num.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000990
991.. method:: Context.create_decimal(num)
992
993 Creates a new Decimal instance from *num* but using *self* as context. Unlike
994 the :class:`Decimal` constructor, the context precision, rounding method, flags,
995 and traps are applied to the conversion.
996
997 This is useful because constants are often given to a greater precision than is
998 needed by the application. Another benefit is that rounding immediately
999 eliminates unintended effects from digits beyond the current precision. In the
1000 following example, using unrounded inputs means that adding zero to a sum can
Georg Brandl9f662322008-03-22 11:47:10 +00001001 change the result:
1002
1003 .. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001004
1005 >>> getcontext().prec = 3
Raymond Hettingerabe32372008-02-14 02:41:22 +00001006 >>> Decimal('3.4445') + Decimal('1.0023')
1007 Decimal('4.45')
1008 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1009 Decimal('4.44')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001010
Mark Dickinson59bc20b2008-01-12 01:56:00 +00001011 This method implements the to-number operation of the IBM
1012 specification. If the argument is a string, no leading or trailing
1013 whitespace is permitted.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001014
1015.. method:: Context.Etiny()
1016
1017 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
1018 for subnormal results. When underflow occurs, the exponent is set to
1019 :const:`Etiny`.
1020
1021
1022.. method:: Context.Etop()
1023
1024 Returns a value equal to ``Emax - prec + 1``.
1025
1026The usual approach to working with decimals is to create :class:`Decimal`
1027instances and then apply arithmetic operations which take place within the
Georg Brandl5d242ee2007-09-20 08:44:59 +00001028current context for the active thread. An alternative approach is to use context
Georg Brandl8ec7f652007-08-15 14:28:01 +00001029methods for calculating within a specific context. The methods are similar to
1030those for the :class:`Decimal` class and are only briefly recounted here.
1031
1032
1033.. method:: Context.abs(x)
1034
1035 Returns the absolute value of *x*.
1036
1037
1038.. method:: Context.add(x, y)
1039
1040 Return the sum of *x* and *y*.
1041
1042
Georg Brandl8ec7f652007-08-15 14:28:01 +00001043.. method:: Context.divide(x, y)
1044
1045 Return *x* divided by *y*.
1046
1047
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001048.. method:: Context.divide_int(x, y)
1049
1050 Return *x* divided by *y*, truncated to an integer.
1051
1052
Georg Brandl8ec7f652007-08-15 14:28:01 +00001053.. method:: Context.divmod(x, y)
1054
1055 Divides two numbers and returns the integer part of the result.
1056
1057
Georg Brandl8ec7f652007-08-15 14:28:01 +00001058.. method:: Context.minus(x)
1059
1060 Minus corresponds to the unary prefix minus operator in Python.
1061
1062
1063.. method:: Context.multiply(x, y)
1064
1065 Return the product of *x* and *y*.
1066
1067
Georg Brandl8ec7f652007-08-15 14:28:01 +00001068.. method:: Context.plus(x)
1069
1070 Plus corresponds to the unary prefix plus operator in Python. This operation
1071 applies the context precision and rounding, so it is *not* an identity
1072 operation.
1073
1074
1075.. method:: Context.power(x, y[, modulo])
1076
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001077 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if
1078 given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001079
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001080 With two arguments, compute ``x**y``. If ``x`` is negative then
1081 ``y`` must be integral. The result will be inexact unless ``y`` is
1082 integral and the result is finite and can be expressed exactly in
1083 'precision' digits. The result should always be correctly rounded,
1084 using the rounding mode of the current thread's context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001085
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001086 With three arguments, compute ``(x**y) % modulo``. For the three
1087 argument form, the following restrictions on the arguments hold:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001088
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001089 - all three arguments must be integral
1090 - ``y`` must be nonnegative
1091 - at least one of ``x`` or ``y`` must be nonzero
1092 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl8ec7f652007-08-15 14:28:01 +00001093
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001094 The result of ``Context.power(x, y, modulo)`` is identical to
1095 the result that would be obtained by computing ``(x**y) %
1096 modulo`` with unbounded precision, but is computed more
1097 efficiently. It is always exact.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001098
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001099 .. versionchanged:: 2.6
1100 ``y`` may now be nonintegral in ``x**y``.
1101 Stricter requirements for the three-argument version.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001102
1103
1104.. method:: Context.remainder(x, y)
1105
1106 Returns the remainder from integer division.
1107
1108 The sign of the result, if non-zero, is the same as that of the original
1109 dividend.
1110
Georg Brandl8ec7f652007-08-15 14:28:01 +00001111.. method:: Context.subtract(x, y)
1112
1113 Return the difference between *x* and *y*.
1114
Georg Brandl8ec7f652007-08-15 14:28:01 +00001115.. method:: Context.to_sci_string(x)
1116
1117 Converts a number to a string using scientific notation.
1118
Georg Brandlb19be572007-12-29 10:57:00 +00001119.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001120
1121
1122.. _decimal-signals:
1123
1124Signals
1125-------
1126
1127Signals represent conditions that arise during computation. Each corresponds to
1128one context flag and one context trap enabler.
1129
1130The context flag is incremented whenever the condition is encountered. After the
1131computation, flags may be checked for informational purposes (for instance, to
1132determine whether a computation was exact). After checking the flags, be sure to
1133clear all flags before starting the next computation.
1134
1135If the context's trap enabler is set for the signal, then the condition causes a
1136Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1137is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1138condition.
1139
1140
1141.. class:: Clamped
1142
1143 Altered an exponent to fit representation constraints.
1144
1145 Typically, clamping occurs when an exponent falls outside the context's
1146 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001147 fit by adding zeros to the coefficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001148
1149
1150.. class:: DecimalException
1151
1152 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1153
1154
1155.. class:: DivisionByZero
1156
1157 Signals the division of a non-infinite number by zero.
1158
1159 Can occur with division, modulo division, or when raising a number to a negative
1160 power. If this signal is not trapped, returns :const:`Infinity` or
1161 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1162
1163
1164.. class:: Inexact
1165
1166 Indicates that rounding occurred and the result is not exact.
1167
1168 Signals when non-zero digits were discarded during rounding. The rounded result
1169 is returned. The signal flag or trap is used to detect when results are
1170 inexact.
1171
1172
1173.. class:: InvalidOperation
1174
1175 An invalid operation was performed.
1176
1177 Indicates that an operation was requested that does not make sense. If not
1178 trapped, returns :const:`NaN`. Possible causes include::
1179
1180 Infinity - Infinity
1181 0 * Infinity
1182 Infinity / Infinity
1183 x % 0
1184 Infinity % x
1185 x._rescale( non-integer )
1186 sqrt(-x) and x > 0
1187 0 ** 0
1188 x ** (non-integer)
1189 x ** Infinity
1190
1191
1192.. class:: Overflow
1193
1194 Numerical overflow.
1195
1196 Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
1197 If not trapped, the result depends on the rounding mode, either pulling inward
1198 to the largest representable finite number or rounding outward to
1199 :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are
1200 also signaled.
1201
1202
1203.. class:: Rounded
1204
1205 Rounding occurred though possibly no information was lost.
1206
1207 Signaled whenever rounding discards digits; even if those digits are zero (such
1208 as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result
1209 unchanged. This signal is used to detect loss of significant digits.
1210
1211
1212.. class:: Subnormal
1213
1214 Exponent was lower than :attr:`Emin` prior to rounding.
1215
1216 Occurs when an operation result is subnormal (the exponent is too small). If not
1217 trapped, returns the result unchanged.
1218
1219
1220.. class:: Underflow
1221
1222 Numerical underflow with result rounded to zero.
1223
1224 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1225 and :class:`Subnormal` are also signaled.
1226
1227The following table summarizes the hierarchy of signals::
1228
1229 exceptions.ArithmeticError(exceptions.StandardError)
1230 DecimalException
1231 Clamped
1232 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1233 Inexact
1234 Overflow(Inexact, Rounded)
1235 Underflow(Inexact, Rounded, Subnormal)
1236 InvalidOperation
1237 Rounded
1238 Subnormal
1239
Georg Brandlb19be572007-12-29 10:57:00 +00001240.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001241
1242
1243.. _decimal-notes:
1244
1245Floating Point Notes
1246--------------------
1247
1248
1249Mitigating round-off error with increased precision
1250^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1251
1252The use of decimal floating point eliminates decimal representation error
1253(making it possible to represent :const:`0.1` exactly); however, some operations
1254can still incur round-off error when non-zero digits exceed the fixed precision.
1255
1256The effects of round-off error can be amplified by the addition or subtraction
1257of nearly offsetting quantities resulting in loss of significance. Knuth
1258provides two instructive examples where rounded floating point arithmetic with
1259insufficient precision causes the breakdown of the associative and distributive
Georg Brandl9f662322008-03-22 11:47:10 +00001260properties of addition:
1261
1262.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001263
1264 # Examples from Seminumerical Algorithms, Section 4.2.2.
1265 >>> from decimal import Decimal, getcontext
1266 >>> getcontext().prec = 8
1267
1268 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1269 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001270 Decimal('9.5111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001271 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001272 Decimal('10')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001273
1274 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1275 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001276 Decimal('0.01')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001277 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001278 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001279
1280The :mod:`decimal` module makes it possible to restore the identities by
Georg Brandl9f662322008-03-22 11:47:10 +00001281expanding the precision sufficiently to avoid loss of significance:
1282
1283.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001284
1285 >>> getcontext().prec = 20
1286 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1287 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001288 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001289 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001290 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001291 >>>
1292 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1293 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001294 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001295 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001296 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001297
1298
1299Special values
1300^^^^^^^^^^^^^^
1301
1302The number system for the :mod:`decimal` module provides special values
1303including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001304and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001305
1306Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1307they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1308not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1309can result from rounding beyond the limits of the largest representable number.
1310
1311The infinities are signed (affine) and can be used in arithmetic operations
1312where they get treated as very large, indeterminate numbers. For instance,
1313adding a constant to infinity gives another infinite result.
1314
1315Some operations are indeterminate and return :const:`NaN`, or if the
1316:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1317``0/0`` returns :const:`NaN` which means "not a number". This variety of
1318:const:`NaN` is quiet and, once created, will flow through other computations
1319always resulting in another :const:`NaN`. This behavior can be useful for a
1320series of computations that occasionally have missing inputs --- it allows the
1321calculation to proceed while flagging specific results as invalid.
1322
1323A variant is :const:`sNaN` which signals rather than remaining quiet after every
1324operation. This is a useful return value when an invalid result needs to
1325interrupt a calculation for special handling.
1326
Mark Dickinson2fc92632008-02-06 22:10:50 +00001327The behavior of Python's comparison operators can be a little surprising where a
1328:const:`NaN` is involved. A test for equality where one of the operands is a
1329quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1330``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
Mark Dickinsonbafa9422008-02-06 22:25:16 +00001331:const:`True`. An attempt to compare two Decimals using any of the ``<``,
Mark Dickinson00c2e652008-02-07 01:42:06 +00001332``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1333if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Mark Dickinson3a94ee02008-02-10 15:19:58 +00001334not trapped. Note that the General Decimal Arithmetic specification does not
Mark Dickinson00c2e652008-02-07 01:42:06 +00001335specify the behavior of direct comparisons; these rules for comparisons
1336involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1337section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
Mark Dickinson2fc92632008-02-06 22:10:50 +00001338and :meth:`compare-signal` methods instead.
1339
Georg Brandl8ec7f652007-08-15 14:28:01 +00001340The signed zeros can result from calculations that underflow. They keep the sign
1341that would have resulted if the calculation had been carried out to greater
1342precision. Since their magnitude is zero, both positive and negative zeros are
1343treated as equal and their sign is informational.
1344
1345In addition to the two signed zeros which are distinct yet equal, there are
1346various representations of zero with differing precisions yet equivalent in
1347value. This takes a bit of getting used to. For an eye accustomed to
1348normalized floating point representations, it is not immediately obvious that
Georg Brandl9f662322008-03-22 11:47:10 +00001349the following calculation returns a value equal to zero:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001350
1351 >>> 1 / Decimal('Infinity')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001352 Decimal('0E-1000000026')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001353
Georg Brandlb19be572007-12-29 10:57:00 +00001354.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001355
1356
1357.. _decimal-threads:
1358
1359Working with threads
1360--------------------
1361
1362The :func:`getcontext` function accesses a different :class:`Context` object for
1363each thread. Having separate thread contexts means that threads may make
1364changes (such as ``getcontext.prec=10``) without interfering with other threads.
1365
1366Likewise, the :func:`setcontext` function automatically assigns its target to
1367the current thread.
1368
1369If :func:`setcontext` has not been called before :func:`getcontext`, then
1370:func:`getcontext` will automatically create a new context for use in the
1371current thread.
1372
1373The new context is copied from a prototype context called *DefaultContext*. To
1374control the defaults so that each thread will use the same values throughout the
1375application, directly modify the *DefaultContext* object. This should be done
1376*before* any threads are started so that there won't be a race condition between
1377threads calling :func:`getcontext`. For example::
1378
1379 # Set applicationwide defaults for all threads about to be launched
1380 DefaultContext.prec = 12
1381 DefaultContext.rounding = ROUND_DOWN
1382 DefaultContext.traps = ExtendedContext.traps.copy()
1383 DefaultContext.traps[InvalidOperation] = 1
1384 setcontext(DefaultContext)
1385
1386 # Afterwards, the threads can be started
1387 t1.start()
1388 t2.start()
1389 t3.start()
1390 . . .
1391
Georg Brandlb19be572007-12-29 10:57:00 +00001392.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001393
1394
1395.. _decimal-recipes:
1396
1397Recipes
1398-------
1399
1400Here are a few recipes that serve as utility functions and that demonstrate ways
1401to work with the :class:`Decimal` class::
1402
1403 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1404 pos='', neg='-', trailneg=''):
1405 """Convert Decimal to a money formatted string.
1406
1407 places: required number of places after the decimal point
1408 curr: optional currency symbol before the sign (may be blank)
1409 sep: optional grouping separator (comma, period, space, or blank)
1410 dp: decimal point indicator (comma or period)
1411 only specify as blank when places is zero
1412 pos: optional sign for positive numbers: '+', space or blank
1413 neg: optional sign for negative numbers: '-', '(', space or blank
1414 trailneg:optional trailing minus indicator: '-', ')', space or blank
1415
1416 >>> d = Decimal('-1234567.8901')
1417 >>> moneyfmt(d, curr='$')
1418 '-$1,234,567.89'
1419 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1420 '1.234.568-'
1421 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1422 '($1,234,567.89)'
1423 >>> moneyfmt(Decimal(123456789), sep=' ')
1424 '123 456 789.00'
1425 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1426 '<.02>'
1427
1428 """
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001429 q = Decimal(10) ** -places # 2 places --> '0.01'
1430 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001431 result = []
1432 digits = map(str, digits)
1433 build, next = result.append, digits.pop
1434 if sign:
1435 build(trailneg)
1436 for i in range(places):
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001437 build(next() if digits else '0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001438 build(dp)
1439 i = 0
1440 while digits:
1441 build(next())
1442 i += 1
1443 if i == 3 and digits:
1444 i = 0
1445 build(sep)
1446 build(curr)
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001447 build(neg if sign else pos)
1448 return ''.join(reversed(result))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001449
1450 def pi():
1451 """Compute Pi to the current precision.
1452
1453 >>> print pi()
1454 3.141592653589793238462643383
1455
1456 """
1457 getcontext().prec += 2 # extra digits for intermediate steps
1458 three = Decimal(3) # substitute "three=3.0" for regular floats
1459 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1460 while s != lasts:
1461 lasts = s
1462 n, na = n+na, na+8
1463 d, da = d+da, da+32
1464 t = (t * n) / d
1465 s += t
1466 getcontext().prec -= 2
1467 return +s # unary plus applies the new precision
1468
1469 def exp(x):
1470 """Return e raised to the power of x. Result type matches input type.
1471
1472 >>> print exp(Decimal(1))
1473 2.718281828459045235360287471
1474 >>> print exp(Decimal(2))
1475 7.389056098930650227230427461
1476 >>> print exp(2.0)
1477 7.38905609893
1478 >>> print exp(2+0j)
1479 (7.38905609893+0j)
1480
1481 """
1482 getcontext().prec += 2
1483 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1484 while s != lasts:
1485 lasts = s
1486 i += 1
1487 fact *= i
1488 num *= x
1489 s += num / fact
1490 getcontext().prec -= 2
1491 return +s
1492
1493 def cos(x):
1494 """Return the cosine of x as measured in radians.
1495
1496 >>> print cos(Decimal('0.5'))
1497 0.8775825618903727161162815826
1498 >>> print cos(0.5)
1499 0.87758256189
1500 >>> print cos(0.5+0j)
1501 (0.87758256189+0j)
1502
1503 """
1504 getcontext().prec += 2
1505 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1506 while s != lasts:
1507 lasts = s
1508 i += 2
1509 fact *= i * (i-1)
1510 num *= x * x
1511 sign *= -1
1512 s += num / fact * sign
1513 getcontext().prec -= 2
1514 return +s
1515
1516 def sin(x):
1517 """Return the sine of x as measured in radians.
1518
1519 >>> print sin(Decimal('0.5'))
1520 0.4794255386042030002732879352
1521 >>> print sin(0.5)
1522 0.479425538604
1523 >>> print sin(0.5+0j)
1524 (0.479425538604+0j)
1525
1526 """
1527 getcontext().prec += 2
1528 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1529 while s != lasts:
1530 lasts = s
1531 i += 2
1532 fact *= i * (i-1)
1533 num *= x * x
1534 sign *= -1
1535 s += num / fact * sign
1536 getcontext().prec -= 2
1537 return +s
1538
1539
Georg Brandlb19be572007-12-29 10:57:00 +00001540.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001541
1542
1543.. _decimal-faq:
1544
1545Decimal FAQ
1546-----------
1547
1548Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1549minimize typing when using the interactive interpreter?
1550
Georg Brandl9f662322008-03-22 11:47:10 +00001551A. Some users abbreviate the constructor to just a single letter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001552
1553 >>> D = decimal.Decimal
1554 >>> D('1.23') + D('3.45')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001555 Decimal('4.68')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001556
1557Q. In a fixed-point application with two decimal places, some inputs have many
1558places and need to be rounded. Others are not supposed to have excess digits
1559and need to be validated. What methods should be used?
1560
1561A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Georg Brandl9f662322008-03-22 11:47:10 +00001562the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001563
1564 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1565
1566 >>> # Round to two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001567 >>> Decimal('3.214').quantize(TWOPLACES)
1568 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001569
1570 >>> # Validate that a number does not exceed two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001571 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1572 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001573
Raymond Hettingerabe32372008-02-14 02:41:22 +00001574 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001575 Traceback (most recent call last):
1576 ...
Georg Brandl9f662322008-03-22 11:47:10 +00001577 Inexact
Georg Brandl8ec7f652007-08-15 14:28:01 +00001578
1579Q. Once I have valid two place inputs, how do I maintain that invariant
1580throughout an application?
1581
Raymond Hettinger46314812008-02-14 10:46:57 +00001582A. Some operations like addition, subtraction, and multiplication by an integer
1583will automatically preserve fixed point. Others operations, like division and
1584non-integer multiplication, will change the number of decimal places and need to
Georg Brandl9f662322008-03-22 11:47:10 +00001585be followed-up with a :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001586
1587 >>> a = Decimal('102.72') # Initial fixed-point values
1588 >>> b = Decimal('3.17')
1589 >>> a + b # Addition preserves fixed-point
1590 Decimal('105.89')
1591 >>> a - b
1592 Decimal('99.55')
1593 >>> a * 42 # So does integer multiplication
1594 Decimal('4314.24')
1595 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1596 Decimal('325.62')
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001597 >>> (b / a).quantize(TWOPLACES) # And quantize division
Raymond Hettinger46314812008-02-14 10:46:57 +00001598 Decimal('0.03')
1599
1600In developing fixed-point applications, it is convenient to define functions
Georg Brandl9f662322008-03-22 11:47:10 +00001601to handle the :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001602
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001603 >>> def mul(x, y, fp=TWOPLACES):
1604 ... return (x * y).quantize(fp)
1605 >>> def div(x, y, fp=TWOPLACES):
1606 ... return (x / y).quantize(fp)
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001607
Raymond Hettinger46314812008-02-14 10:46:57 +00001608 >>> mul(a, b) # Automatically preserve fixed-point
1609 Decimal('325.62')
1610 >>> div(b, a)
1611 Decimal('0.03')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001612
1613Q. There are many ways to express the same value. The numbers :const:`200`,
1614:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1615various precisions. Is there a way to transform them to a single recognizable
1616canonical value?
1617
1618A. The :meth:`normalize` method maps all equivalent values to a single
Georg Brandl9f662322008-03-22 11:47:10 +00001619representative:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001620
1621 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1622 >>> [v.normalize() for v in values]
Raymond Hettingerabe32372008-02-14 02:41:22 +00001623 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001624
1625Q. Some decimal values always print with exponential notation. Is there a way
1626to get a non-exponential representation?
1627
1628A. For some values, exponential notation is the only way to express the number
1629of significant places in the coefficient. For example, expressing
1630:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1631original's two-place significance.
1632
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001633If an application does not care about tracking significance, it is easy to
Georg Brandl907a7202008-02-22 12:31:45 +00001634remove the exponent and trailing zeroes, losing significance, but keeping the
Georg Brandl9f662322008-03-22 11:47:10 +00001635value unchanged:
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001636
1637 >>> def remove_exponent(d):
1638 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1639
1640 >>> remove_exponent(Decimal('5E+3'))
1641 Decimal('5000')
1642
Georg Brandl8ec7f652007-08-15 14:28:01 +00001643Q. Is there a way to convert a regular float to a :class:`Decimal`?
1644
1645A. Yes, all binary floating point numbers can be exactly expressed as a
1646Decimal. An exact conversion may take more precision than intuition would
Georg Brandl9f662322008-03-22 11:47:10 +00001647suggest, so we trap :const:`Inexact` to signal a need for more precision:
1648
1649.. testcode:: doctest_block
Georg Brandl8ec7f652007-08-15 14:28:01 +00001650
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001651 def float_to_decimal(f):
1652 "Convert a floating point number to a Decimal with no loss of information"
1653 n, d = f.as_integer_ratio()
1654 with localcontext() as ctx:
1655 ctx.traps[Inexact] = True
1656 while True:
1657 try:
1658 return Decimal(n) / Decimal(d)
1659 except Inexact:
1660 ctx.prec += 1
Georg Brandl8ec7f652007-08-15 14:28:01 +00001661
Georg Brandl9f662322008-03-22 11:47:10 +00001662.. doctest:: doctest_block
1663
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001664 >>> float_to_decimal(math.pi)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001665 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001666
Raymond Hettinger23bdcc92008-02-07 20:10:49 +00001667Q. Why isn't the :func:`float_to_decimal` routine included in the module?
Georg Brandl8ec7f652007-08-15 14:28:01 +00001668
1669A. There is some question about whether it is advisable to mix binary and
1670decimal floating point. Also, its use requires some care to avoid the
Georg Brandl9f662322008-03-22 11:47:10 +00001671representation issues associated with binary floating point:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001672
Raymond Hettinger23bdcc92008-02-07 20:10:49 +00001673 >>> float_to_decimal(1.1)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001674 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001675
1676Q. Within a complex calculation, how can I make sure that I haven't gotten a
1677spurious result because of insufficient precision or rounding anomalies.
1678
1679A. The decimal module makes it easy to test results. A best practice is to
1680re-run calculations using greater precision and with various rounding modes.
1681Widely differing results indicate insufficient precision, rounding mode issues,
1682ill-conditioned inputs, or a numerically unstable algorithm.
1683
1684Q. I noticed that context precision is applied to the results of operations but
1685not to the inputs. Is there anything to watch out for when mixing values of
1686different precisions?
1687
1688A. Yes. The principle is that all values are considered to be exact and so is
1689the arithmetic on those values. Only the results are rounded. The advantage
1690for inputs is that "what you type is what you get". A disadvantage is that the
Georg Brandl9f662322008-03-22 11:47:10 +00001691results can look odd if you forget that the inputs haven't been rounded:
1692
1693.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001694
1695 >>> getcontext().prec = 3
Georg Brandl9f662322008-03-22 11:47:10 +00001696 >>> Decimal('3.104') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001697 Decimal('5.21')
Georg Brandl9f662322008-03-22 11:47:10 +00001698 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001699 Decimal('5.20')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001700
1701The solution is either to increase precision or to force rounding of inputs
Georg Brandl9f662322008-03-22 11:47:10 +00001702using the unary plus operation:
1703
1704.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001705
1706 >>> getcontext().prec = 3
1707 >>> +Decimal('1.23456789') # unary plus triggers rounding
Raymond Hettingerabe32372008-02-14 02:41:22 +00001708 Decimal('1.23')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001709
1710Alternatively, inputs can be rounded upon creation using the
Georg Brandl9f662322008-03-22 11:47:10 +00001711:meth:`Context.create_decimal` method:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001712
1713 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001714 Decimal('1.2345')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001715