blob: a792f411337f54b12885864df4003169d54fee47 [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
Georg Brandl838b4b02008-03-22 13:07:06 +0000178.. doctest::
179 :options: +NORMALIZE_WHITESPACE
180
Georg Brandl8ec7f652007-08-15 14:28:01 +0000181 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
182 >>> max(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000183 Decimal('9.25')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000184 >>> min(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000185 Decimal('0.03')
Georg Brandl838b4b02008-03-22 13:07:06 +0000186 >>> sorted(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000187 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
188 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000189 >>> sum(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000190 Decimal('19.29')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000191 >>> a,b,c = data[:3]
192 >>> str(a)
193 '1.34'
194 >>> float(a)
195 1.3400000000000001
196 >>> round(a, 1) # round() first converts to binary floating point
197 1.3
198 >>> int(a)
199 1
200 >>> a * 5
Raymond Hettingerabe32372008-02-14 02:41:22 +0000201 Decimal('6.70')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000202 >>> a * b
Raymond Hettingerabe32372008-02-14 02:41:22 +0000203 Decimal('2.5058')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000204 >>> c % a
Raymond Hettingerabe32372008-02-14 02:41:22 +0000205 Decimal('0.77')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000206
Georg Brandl9f662322008-03-22 11:47:10 +0000207And some mathematical functions are also available to Decimal:
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000208
209 >>> Decimal(2).sqrt()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000210 Decimal('1.414213562373095048801688724')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000211 >>> Decimal(1).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000212 Decimal('2.718281828459045235360287471')
213 >>> Decimal('10').ln()
214 Decimal('2.302585092994045684017991455')
215 >>> Decimal('10').log10()
216 Decimal('1')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000217
Georg Brandl8ec7f652007-08-15 14:28:01 +0000218The :meth:`quantize` method rounds a number to a fixed exponent. This method is
219useful for monetary applications that often round results to a fixed number of
Georg Brandl9f662322008-03-22 11:47:10 +0000220places:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000221
222 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000223 Decimal('7.32')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000224 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000225 Decimal('8')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000226
227As shown above, the :func:`getcontext` function accesses the current context and
228allows the settings to be changed. This approach meets the needs of most
229applications.
230
231For more advanced work, it may be useful to create alternate contexts using the
232Context() constructor. To make an alternate active, use the :func:`setcontext`
233function.
234
235In accordance with the standard, the :mod:`Decimal` module provides two ready to
236use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
237former is especially useful for debugging because many of the traps are
Georg Brandl9f662322008-03-22 11:47:10 +0000238enabled:
239
240.. doctest:: newcontext
241 :options: +NORMALIZE_WHITESPACE
Georg Brandl8ec7f652007-08-15 14:28:01 +0000242
243 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
244 >>> setcontext(myothercontext)
245 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000246 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000247
248 >>> ExtendedContext
249 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
250 capitals=1, flags=[], traps=[])
251 >>> setcontext(ExtendedContext)
252 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000253 Decimal('0.142857143')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000254 >>> Decimal(42) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000255 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000256
257 >>> setcontext(BasicContext)
258 >>> Decimal(42) / Decimal(0)
259 Traceback (most recent call last):
260 File "<pyshell#143>", line 1, in -toplevel-
261 Decimal(42) / Decimal(0)
262 DivisionByZero: x / 0
263
264Contexts also have signal flags for monitoring exceptional conditions
265encountered during computations. The flags remain set until explicitly cleared,
266so it is best to clear the flags before each set of monitored computations by
267using the :meth:`clear_flags` method. ::
268
269 >>> setcontext(ExtendedContext)
270 >>> getcontext().clear_flags()
271 >>> Decimal(355) / Decimal(113)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000272 Decimal('3.14159292')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000273 >>> getcontext()
274 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Georg Brandl9f662322008-03-22 11:47:10 +0000275 capitals=1, flags=[Rounded, Inexact], traps=[])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000276
277The *flags* entry shows that the rational approximation to :const:`Pi` was
278rounded (digits beyond the context precision were thrown away) and that the
279result is inexact (some of the discarded digits were non-zero).
280
281Individual traps are set using the dictionary in the :attr:`traps` field of a
Georg Brandl9f662322008-03-22 11:47:10 +0000282context:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283
Georg Brandl9f662322008-03-22 11:47:10 +0000284.. doctest:: newcontext
285
286 >>> setcontext(ExtendedContext)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000287 >>> Decimal(1) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000288 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000289 >>> getcontext().traps[DivisionByZero] = 1
290 >>> Decimal(1) / Decimal(0)
291 Traceback (most recent call last):
292 File "<pyshell#112>", line 1, in -toplevel-
293 Decimal(1) / Decimal(0)
294 DivisionByZero: x / 0
295
296Most programs adjust the current context only once, at the beginning of the
297program. And, in many applications, data is converted to :class:`Decimal` with
298a single cast inside a loop. With context set and decimals created, the bulk of
299the program manipulates the data no differently than with other Python numeric
300types.
301
Georg Brandlb19be572007-12-29 10:57:00 +0000302.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000303
304
305.. _decimal-decimal:
306
307Decimal objects
308---------------
309
310
311.. class:: Decimal([value [, context]])
312
Georg Brandlb19be572007-12-29 10:57:00 +0000313 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000314
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000315 *value* can be an integer, string, tuple, or another :class:`Decimal`
Raymond Hettingerabe32372008-02-14 02:41:22 +0000316 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000317 string, it should conform to the decimal numeric string syntax after leading
318 and trailing whitespace characters are removed::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000319
320 sign ::= '+' | '-'
321 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
322 indicator ::= 'e' | 'E'
323 digits ::= digit [digit]...
324 decimal-part ::= digits '.' [digits] | ['.'] digits
325 exponent-part ::= indicator [sign] digits
326 infinity ::= 'Infinity' | 'Inf'
327 nan ::= 'NaN' [digits] | 'sNaN' [digits]
328 numeric-value ::= decimal-part [exponent-part] | infinity
329 numeric-string ::= [sign] numeric-value | [sign] nan
330
331 If *value* is a :class:`tuple`, it should have three components, a sign
332 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
333 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Raymond Hettingerabe32372008-02-14 02:41:22 +0000334 returns ``Decimal('1.414')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000335
336 The *context* precision does not affect how many digits are stored. That is
337 determined exclusively by the number of digits in *value*. For example,
Raymond Hettingerabe32372008-02-14 02:41:22 +0000338 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000339 only three.
340
341 The purpose of the *context* argument is determining what to do if *value* is a
342 malformed string. If the context traps :const:`InvalidOperation`, an exception
343 is raised; otherwise, the constructor returns a new Decimal with the value of
344 :const:`NaN`.
345
346 Once constructed, :class:`Decimal` objects are immutable.
347
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000348 .. versionchanged:: 2.6
349 leading and trailing whitespace characters are permitted when
350 creating a Decimal instance from a string.
351
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000352Decimal floating point objects share many properties with the other built-in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000353numeric types such as :class:`float` and :class:`int`. All of the usual math
354operations and special methods apply. Likewise, decimal objects can be copied,
355pickled, printed, used as dictionary keys, used as set elements, compared,
356sorted, and coerced to another type (such as :class:`float` or :class:`long`).
357
358In addition to the standard numeric properties, decimal floating point objects
359also have a number of specialized methods:
360
361
362.. method:: Decimal.adjusted()
363
364 Return the adjusted exponent after shifting out the coefficient's rightmost
Raymond Hettingerabe32372008-02-14 02:41:22 +0000365 digits until only the lead digit remains: ``Decimal('321e+5').adjusted()``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000366 returns seven. Used for determining the position of the most significant digit
367 with respect to the decimal point.
368
369
370.. method:: Decimal.as_tuple()
371
Georg Brandle3c3db52008-01-11 09:55:53 +0000372 Return a :term:`named tuple` representation of the number:
373 ``DecimalTuple(sign, digits, exponent)``.
374
375 .. versionchanged:: 2.6
376 Use a named tuple.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000377
378
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000379.. method:: Decimal.canonical()
380
381 Return the canonical encoding of the argument. Currently, the
382 encoding of a :class:`Decimal` instance is always canonical, so
383 this operation returns its argument unchanged.
384
385 .. versionadded:: 2.6
386
Georg Brandl8ec7f652007-08-15 14:28:01 +0000387.. method:: Decimal.compare(other[, context])
388
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000389 Compare the values of two Decimal instances. This operation
390 behaves in the same way as the usual comparison method
391 :meth:`__cmp__`, except that :meth:`compare` returns a Decimal
392 instance rather than an integer, and if either operand is a NaN
393 then the result is a NaN::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000394
Raymond Hettingerabe32372008-02-14 02:41:22 +0000395 a or b is a NaN ==> Decimal('NaN')
396 a < b ==> Decimal('-1')
397 a == b ==> Decimal('0')
398 a > b ==> Decimal('1')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000399
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000400.. method:: Decimal.compare_signal(other[, context])
401
402 This operation is identical to the :meth:`compare` method, except
403 that all NaNs signal. That is, if neither operand is a signaling
404 NaN then any quiet NaN operand is treated as though it were a
405 signaling NaN.
406
407 .. versionadded:: 2.6
408
409.. method:: Decimal.compare_total(other)
410
411 Compare two operands using their abstract representation rather
412 than their numerical value. Similar to the :meth:`compare` method,
413 but the result gives a total ordering on :class:`Decimal`
414 instances. Two :class:`Decimal` instances with the same numeric
415 value but different representations compare unequal in this
Georg Brandl9f662322008-03-22 11:47:10 +0000416 ordering:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000417
Raymond Hettingerabe32372008-02-14 02:41:22 +0000418 >>> Decimal('12.0').compare_total(Decimal('12'))
419 Decimal('-1')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000420
421 Quiet and signaling NaNs are also included in the total ordering.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000422 The result of this function is ``Decimal('0')`` if both operands
423 have the same representation, ``Decimal('-1')`` if the first
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000424 operand is lower in the total order than the second, and
Raymond Hettingerabe32372008-02-14 02:41:22 +0000425 ``Decimal('1')`` if the first operand is higher in the total order
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000426 than the second operand. See the specification for details of the
427 total order.
428
429 .. versionadded:: 2.6
430
431.. method:: Decimal.compare_total_mag(other)
432
433 Compare two operands using their abstract representation rather
434 than their value as in :meth:`compare_total`, but ignoring the sign
435 of each operand. ``x.compare_total_mag(y)`` is equivalent to
436 ``x.copy_abs().compare_total(y.copy_abs())``.
437
438 .. versionadded:: 2.6
439
440.. method:: Decimal.copy_abs()
441
442 Return the absolute value of the argument. This operation is
443 unaffected by the context and is quiet: no flags are changed and no
444 rounding is performed.
445
446 .. versionadded:: 2.6
447
448.. method:: Decimal.copy_negate()
449
450 Return the negation of the argument. This operation is unaffected
451 by the context and is quiet: no flags are changed and no rounding
452 is performed.
453
454 .. versionadded:: 2.6
455
456.. method:: Decimal.copy_sign(other)
457
458 Return a copy of the first operand with the sign set to be the
Georg Brandl9f662322008-03-22 11:47:10 +0000459 same as the sign of the second operand. For example:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000460
Raymond Hettingerabe32372008-02-14 02:41:22 +0000461 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
462 Decimal('-2.3')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000463
464 This operation is unaffected by the context and is quiet: no flags
465 are changed and no rounding is performed.
466
467 .. versionadded:: 2.6
468
469.. method:: Decimal.exp([context])
470
471 Return the value of the (natural) exponential function ``e**x`` at the
472 given number. The result is correctly rounded using the
473 :const:`ROUND_HALF_EVEN` rounding mode.
474
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000475 >>> Decimal(1).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000476 Decimal('2.718281828459045235360287471')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000477 >>> Decimal(321).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000478 Decimal('2.561702493119680037517373933E+139')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000479
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000480 .. versionadded:: 2.6
481
482.. method:: Decimal.fma(other, third[, context])
483
484 Fused multiply-add. Return self*other+third with no rounding of
485 the intermediate product self*other.
486
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000487 >>> Decimal(2).fma(3, 5)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000488 Decimal('11')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000489
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000490 .. versionadded:: 2.6
491
492.. method:: Decimal.is_canonical()
493
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000494 Return :const:`True` if the argument is canonical and
495 :const:`False` otherwise. Currently, a :class:`Decimal` instance
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000496 is always canonical, so this operation always returns
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000497 :const:`True`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000498
499 .. versionadded:: 2.6
500
501.. method:: is_finite()
502
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000503 Return :const:`True` if the argument is a finite number, and
504 :const:`False` if the argument is an infinity or a NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000505
506 .. versionadded:: 2.6
507
508.. method:: is_infinite()
509
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000510 Return :const:`True` if the argument is either positive or
511 negative infinity and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000512
513 .. versionadded:: 2.6
514
515.. method:: is_nan()
516
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000517 Return :const:`True` if the argument is a (quiet or signaling)
518 NaN and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000519
520 .. versionadded:: 2.6
521
522.. method:: is_normal()
523
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000524 Return :const:`True` if the argument is a *normal* finite number.
525 Return :const:`False` if the argument is zero, subnormal, infinite
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000526 or a NaN.
527
528 .. versionadded:: 2.6
529
530.. method:: is_qnan()
531
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000532 Return :const:`True` if the argument is a quiet NaN, and
533 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000534
535 .. versionadded:: 2.6
536
537.. method:: is_signed()
538
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000539 Return :const:`True` if the argument has a negative sign and
540 :const:`False` otherwise. Note that zeros and NaNs can both carry
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000541 signs.
542
543 .. versionadded:: 2.6
544
545.. method:: is_snan()
546
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000547 Return :const:`True` if the argument is a signaling NaN and
548 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000549
550 .. versionadded:: 2.6
551
552.. method:: is_subnormal()
553
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000554 Return :const:`True` if the argument is subnormal, and
555 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000556
557 .. versionadded:: 2.6
558
559.. method:: is_zero()
560
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000561 Return :const:`True` if the argument is a (positive or negative)
562 zero and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000563
564 .. versionadded:: 2.6
565
566.. method:: Decimal.ln([context])
567
568 Return the natural (base e) logarithm of the operand. The result
569 is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
570 mode.
571
572 .. versionadded:: 2.6
573
574.. method:: Decimal.log10([context])
575
576 Return the base ten logarithm of the operand. The result is
577 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
578
579 .. versionadded:: 2.6
580
Georg Brandlb19be572007-12-29 10:57:00 +0000581.. method:: Decimal.logb([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000582
583 For a nonzero number, return the adjusted exponent of its operand
584 as a :class:`Decimal` instance. If the operand is a zero then
Raymond Hettingerabe32372008-02-14 02:41:22 +0000585 ``Decimal('-Infinity')`` is returned and the
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000586 :const:`DivisionByZero` flag is raised. If the operand is an
Raymond Hettingerabe32372008-02-14 02:41:22 +0000587 infinity then ``Decimal('Infinity')`` is returned.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000588
589 .. versionadded:: 2.6
590
591.. method:: Decimal.logical_and(other[, context])
592
593 :meth:`logical_and` is a logical operation which takes two
594 *logical operands* (see :ref:`logical_operands_label`). The result
595 is the digit-wise ``and`` of the two operands.
596
597 .. versionadded:: 2.6
598
599.. method:: Decimal.logical_invert(other[, context])
600
601 :meth:`logical_invert` is a logical operation. The argument must
602 be a *logical operand* (see :ref:`logical_operands_label`). The
603 result is the digit-wise inversion of the operand.
604
605 .. versionadded:: 2.6
606
607.. method:: Decimal.logical_or(other[, context])
608
609 :meth:`logical_or` is a logical operation which takes two *logical
610 operands* (see :ref:`logical_operands_label`). The result is the
611 digit-wise ``or`` of the two operands.
612
613 .. versionadded:: 2.6
614
615.. method:: Decimal.logical_xor(other[, context])
616
617 :meth:`logical_xor` is a logical operation which takes two
618 *logical operands* (see :ref:`logical_operands_label`). The result
619 is the digit-wise exclusive or of the two operands.
620
621 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000622
623.. method:: Decimal.max(other[, context])
624
625 Like ``max(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000626 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000627 (depending on the context and whether they are signaling or quiet).
628
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000629.. method:: Decimal.max_mag(other[, context])
630
631 Similar to the :meth:`max` method, but the comparison is done using
632 the absolute values of the operands.
633
634 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000635
636.. method:: Decimal.min(other[, context])
637
638 Like ``min(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000639 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000640 (depending on the context and whether they are signaling or quiet).
641
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000642.. method:: Decimal.min_mag(other[, context])
643
644 Similar to the :meth:`min` method, but the comparison is done using
645 the absolute values of the operands.
646
647 .. versionadded:: 2.6
648
649.. method:: Decimal.next_minus([context])
650
651 Return the largest number representable in the given context (or
652 in the current thread's context if no context is given) that is smaller
653 than the given operand.
654
655 .. versionadded:: 2.6
656
657.. method:: Decimal.next_plus([context])
658
659 Return the smallest number representable in the given context (or
660 in the current thread's context if no context is given) that is
661 larger than the given operand.
662
663 .. versionadded:: 2.6
664
665.. method:: Decimal.next_toward(other[, context])
666
667 If the two operands are unequal, return the number closest to the
668 first operand in the direction of the second operand. If both
669 operands are numerically equal, return a copy of the first operand
670 with the sign set to be the same as the sign of the second operand.
671
672 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000673
674.. method:: Decimal.normalize([context])
675
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000676 Normalize the number by stripping the rightmost trailing zeros and converting
Raymond Hettingerabe32372008-02-14 02:41:22 +0000677 any result equal to :const:`Decimal('0')` to :const:`Decimal('0e0')`. Used for
Georg Brandl8ec7f652007-08-15 14:28:01 +0000678 producing canonical values for members of an equivalence class. For example,
Raymond Hettingerabe32372008-02-14 02:41:22 +0000679 ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both normalize to the
680 equivalent value ``Decimal('32.1')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000681
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000682.. method:: Decimal.number_class([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000683
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000684 Return a string describing the *class* of the operand. The
685 returned value is one of the following ten strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000686
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000687 * ``"-Infinity"``, indicating that the operand is negative infinity.
688 * ``"-Normal"``, indicating that the operand is a negative normal number.
689 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
690 * ``"-Zero"``, indicating that the operand is a negative zero.
691 * ``"+Zero"``, indicating that the operand is a positive zero.
692 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
693 * ``"+Normal"``, indicating that the operand is a positive normal number.
694 * ``"+Infinity"``, indicating that the operand is positive infinity.
695 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
696 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000697
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000698 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000699
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000700.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]])
701
Georg Brandlb19be572007-12-29 10:57:00 +0000702 Return a value equal to the first operand after rounding and
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000703 having the exponent of the second operand.
704
Raymond Hettingerabe32372008-02-14 02:41:22 +0000705 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
706 Decimal('1.414')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000707
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000708 Unlike other operations, if the length of the coefficient after the
709 quantize operation would be greater than precision, then an
710 :const:`InvalidOperation` is signaled. This guarantees that, unless
711 there is an error condition, the quantized exponent is always equal
712 to that of the right-hand operand.
713
714 Also unlike other operations, quantize never signals Underflow,
715 even if the result is subnormal and inexact.
716
717 If the exponent of the second operand is larger than that of the
718 first then rounding may be necessary. In this case, the rounding
719 mode is determined by the ``rounding`` argument if given, else by
720 the given ``context`` argument; if neither argument is given the
721 rounding mode of the current thread's context is used.
722
Georg Brandlb19be572007-12-29 10:57:00 +0000723 If *watchexp* is set (default), then an error is returned whenever the
724 resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000725
726.. method:: Decimal.radix()
727
728 Return ``Decimal(10)``, the radix (base) in which the
729 :class:`Decimal` class does all its arithmetic. Included for
730 compatibility with the specification.
731
732 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000733
734.. method:: Decimal.remainder_near(other[, context])
735
Georg Brandlb19be572007-12-29 10:57:00 +0000736 Compute the modulo as either a positive or negative value depending on which is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000737 closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
Raymond Hettingerabe32372008-02-14 02:41:22 +0000738 ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000739
740 If both are equally close, the one chosen will have the same sign as *self*.
741
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000742.. method:: Decimal.rotate(other[, context])
743
744 Return the result of rotating the digits of the first operand by
745 an amount specified by the second operand. The second operand
746 must be an integer in the range -precision through precision. The
747 absolute value of the second operand gives the number of places to
748 rotate. If the second operand is positive then rotation is to the
749 left; otherwise rotation is to the right. The coefficient of the
750 first operand is padded on the left with zeros to length precision
751 if necessary. The sign and exponent of the first operand are
752 unchanged.
753
754 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000755
756.. method:: Decimal.same_quantum(other[, context])
757
758 Test whether self and other have the same exponent or whether both are
759 :const:`NaN`.
760
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000761.. method:: Decimal.scaleb(other[, context])
762
763 Return the first operand with exponent adjusted by the second.
764 Equivalently, return the first operand multiplied by ``10**other``.
765 The second operand must be an integer.
766
767 .. versionadded:: 2.6
768
769.. method:: Decimal.shift(other[, context])
770
771 Return the result of shifting the digits of the first operand by
772 an amount specified by the second operand. The second operand must
773 be an integer in the range -precision through precision. The
774 absolute value of the second operand gives the number of places to
775 shift. If the second operand is positive then the shift is to the
776 left; otherwise the shift is to the right. Digits shifted into the
777 coefficient are zeros. The sign and exponent of the first operand
778 are unchanged.
779
780 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000781
782.. method:: Decimal.sqrt([context])
783
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000784 Return the square root of the argument to full precision.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000785
786
787.. method:: Decimal.to_eng_string([context])
788
789 Convert to an engineering-type string.
790
791 Engineering notation has an exponent which is a multiple of 3, so there are up
792 to 3 digits left of the decimal place. For example, converts
Raymond Hettingerabe32372008-02-14 02:41:22 +0000793 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000794
Georg Brandl8ec7f652007-08-15 14:28:01 +0000795.. method:: Decimal.to_integral([rounding[, context]])
796
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000797 Identical to the :meth:`to_integral_value` method. The ``to_integral``
798 name has been kept for compatibility with older versions.
799
800.. method:: Decimal.to_integral_exact([rounding[, context]])
801
Georg Brandlb19be572007-12-29 10:57:00 +0000802 Round to the nearest integer, signaling
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000803 :const:`Inexact` or :const:`Rounded` as appropriate if rounding
804 occurs. The rounding mode is determined by the ``rounding``
805 parameter if given, else by the given ``context``. If neither
806 parameter is given then the rounding mode of the current context is
807 used.
808
809 .. versionadded:: 2.6
810
811.. method:: Decimal.to_integral_value([rounding[, context]])
812
Georg Brandlb19be572007-12-29 10:57:00 +0000813 Round to the nearest integer without signaling :const:`Inexact` or
Georg Brandl8ec7f652007-08-15 14:28:01 +0000814 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding
815 method in either the supplied *context* or the current context.
816
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000817 .. versionchanged:: 2.6
818 renamed from ``to_integral`` to ``to_integral_value``. The old name
819 remains valid for compatibility.
820
821.. method:: Decimal.trim()
822
Georg Brandlb19be572007-12-29 10:57:00 +0000823 Return the decimal with *insignificant* trailing zeros removed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000824 Here, a trailing zero is considered insignificant either if it
825 follows the decimal point, or if the exponent of the argument (that
826 is, the last element of the :meth:`as_tuple` representation) is
827 positive.
828
829 .. versionadded:: 2.6
830
831.. _logical_operands_label:
832
833Logical operands
834^^^^^^^^^^^^^^^^
835
836The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
837and :meth:`logical_xor` methods expect their arguments to be *logical
838operands*. A *logical operand* is a :class:`Decimal` instance whose
839exponent and sign are both zero, and whose digits are all either
840:const:`0` or :const:`1`.
841
Georg Brandlb19be572007-12-29 10:57:00 +0000842.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000843
844
845.. _decimal-context:
846
847Context objects
848---------------
849
850Contexts are environments for arithmetic operations. They govern precision, set
851rules for rounding, determine which signals are treated as exceptions, and limit
852the range for exponents.
853
854Each thread has its own current context which is accessed or changed using the
855:func:`getcontext` and :func:`setcontext` functions:
856
857
858.. function:: getcontext()
859
860 Return the current context for the active thread.
861
862
863.. function:: setcontext(c)
864
865 Set the current context for the active thread to *c*.
866
867Beginning with Python 2.5, you can also use the :keyword:`with` statement and
868the :func:`localcontext` function to temporarily change the active context.
869
870
871.. function:: localcontext([c])
872
873 Return a context manager that will set the current context for the active thread
874 to a copy of *c* on entry to the with-statement and restore the previous context
875 when exiting the with-statement. If no context is specified, a copy of the
876 current context is used.
877
878 .. versionadded:: 2.5
879
880 For example, the following code sets the current decimal precision to 42 places,
881 performs a calculation, and then automatically restores the previous context::
882
Georg Brandl8ec7f652007-08-15 14:28:01 +0000883 from decimal import localcontext
884
885 with localcontext() as ctx:
886 ctx.prec = 42 # Perform a high precision calculation
887 s = calculate_something()
888 s = +s # Round the final result back to the default precision
889
890New contexts can also be created using the :class:`Context` constructor
891described below. In addition, the module provides three pre-made contexts:
892
893
894.. class:: BasicContext
895
896 This is a standard context defined by the General Decimal Arithmetic
897 Specification. Precision is set to nine. Rounding is set to
898 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
899 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
900 :const:`Subnormal`.
901
902 Because many of the traps are enabled, this context is useful for debugging.
903
904
905.. class:: ExtendedContext
906
907 This is a standard context defined by the General Decimal Arithmetic
908 Specification. Precision is set to nine. Rounding is set to
909 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
910 exceptions are not raised during computations).
911
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000912 Because the traps are disabled, this context is useful for applications that
Georg Brandl8ec7f652007-08-15 14:28:01 +0000913 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
914 raising exceptions. This allows an application to complete a run in the
915 presence of conditions that would otherwise halt the program.
916
917
918.. class:: DefaultContext
919
920 This context is used by the :class:`Context` constructor as a prototype for new
921 contexts. Changing a field (such a precision) has the effect of changing the
922 default for new contexts creating by the :class:`Context` constructor.
923
924 This context is most useful in multi-threaded environments. Changing one of the
925 fields before threads are started has the effect of setting system-wide
926 defaults. Changing the fields after threads have started is not recommended as
927 it would require thread synchronization to prevent race conditions.
928
929 In single threaded environments, it is preferable to not use this context at
930 all. Instead, simply create contexts explicitly as described below.
931
932 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
933 for Overflow, InvalidOperation, and DivisionByZero.
934
935In addition to the three supplied contexts, new contexts can be created with the
936:class:`Context` constructor.
937
938
939.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
940
941 Creates a new context. If a field is not specified or is :const:`None`, the
942 default values are copied from the :const:`DefaultContext`. If the *flags*
943 field is not specified or is :const:`None`, all flags are cleared.
944
945 The *prec* field is a positive integer that sets the precision for arithmetic
946 operations in the context.
947
948 The *rounding* option is one of:
949
950 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
951 * :const:`ROUND_DOWN` (towards zero),
952 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
953 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
954 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
955 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
956 * :const:`ROUND_UP` (away from zero).
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000957 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
958 would have been 0 or 5; otherwise towards zero)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000959
960 The *traps* and *flags* fields list any signals to be set. Generally, new
961 contexts should only set traps and leave the flags clear.
962
963 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
964 for exponents.
965
966 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
967 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
968 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
969
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000970 .. versionchanged:: 2.6
971 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000972
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000973The :class:`Context` class defines several general purpose methods as
974well as a large number of methods for doing arithmetic directly in a
975given context. In addition, for each of the :class:`Decimal` methods
976described above (with the exception of the :meth:`adjusted` and
977:meth:`as_tuple` methods) there is a corresponding :class:`Context`
978method. For example, ``C.exp(x)`` is equivalent to
979``x.exp(context=C)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000980
981.. method:: Context.clear_flags()
982
983 Resets all of the flags to :const:`0`.
984
985
986.. method:: Context.copy()
987
988 Return a duplicate of the context.
989
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000990.. method:: Context.copy_decimal(num)
991
992 Return a copy of the Decimal instance num.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000993
994.. method:: Context.create_decimal(num)
995
996 Creates a new Decimal instance from *num* but using *self* as context. Unlike
997 the :class:`Decimal` constructor, the context precision, rounding method, flags,
998 and traps are applied to the conversion.
999
1000 This is useful because constants are often given to a greater precision than is
1001 needed by the application. Another benefit is that rounding immediately
1002 eliminates unintended effects from digits beyond the current precision. In the
1003 following example, using unrounded inputs means that adding zero to a sum can
Georg Brandl9f662322008-03-22 11:47:10 +00001004 change the result:
1005
1006 .. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001007
1008 >>> getcontext().prec = 3
Raymond Hettingerabe32372008-02-14 02:41:22 +00001009 >>> Decimal('3.4445') + Decimal('1.0023')
1010 Decimal('4.45')
1011 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1012 Decimal('4.44')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001013
Mark Dickinson59bc20b2008-01-12 01:56:00 +00001014 This method implements the to-number operation of the IBM
1015 specification. If the argument is a string, no leading or trailing
1016 whitespace is permitted.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001017
1018.. method:: Context.Etiny()
1019
1020 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
1021 for subnormal results. When underflow occurs, the exponent is set to
1022 :const:`Etiny`.
1023
1024
1025.. method:: Context.Etop()
1026
1027 Returns a value equal to ``Emax - prec + 1``.
1028
1029The usual approach to working with decimals is to create :class:`Decimal`
1030instances and then apply arithmetic operations which take place within the
Georg Brandl5d242ee2007-09-20 08:44:59 +00001031current context for the active thread. An alternative approach is to use context
Georg Brandl8ec7f652007-08-15 14:28:01 +00001032methods for calculating within a specific context. The methods are similar to
1033those for the :class:`Decimal` class and are only briefly recounted here.
1034
1035
1036.. method:: Context.abs(x)
1037
1038 Returns the absolute value of *x*.
1039
1040
1041.. method:: Context.add(x, y)
1042
1043 Return the sum of *x* and *y*.
1044
1045
Georg Brandl8ec7f652007-08-15 14:28:01 +00001046.. method:: Context.divide(x, y)
1047
1048 Return *x* divided by *y*.
1049
1050
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001051.. method:: Context.divide_int(x, y)
1052
1053 Return *x* divided by *y*, truncated to an integer.
1054
1055
Georg Brandl8ec7f652007-08-15 14:28:01 +00001056.. method:: Context.divmod(x, y)
1057
1058 Divides two numbers and returns the integer part of the result.
1059
1060
Georg Brandl8ec7f652007-08-15 14:28:01 +00001061.. method:: Context.minus(x)
1062
1063 Minus corresponds to the unary prefix minus operator in Python.
1064
1065
1066.. method:: Context.multiply(x, y)
1067
1068 Return the product of *x* and *y*.
1069
1070
Georg Brandl8ec7f652007-08-15 14:28:01 +00001071.. method:: Context.plus(x)
1072
1073 Plus corresponds to the unary prefix plus operator in Python. This operation
1074 applies the context precision and rounding, so it is *not* an identity
1075 operation.
1076
1077
1078.. method:: Context.power(x, y[, modulo])
1079
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001080 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if
1081 given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001082
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001083 With two arguments, compute ``x**y``. If ``x`` is negative then
1084 ``y`` must be integral. The result will be inexact unless ``y`` is
1085 integral and the result is finite and can be expressed exactly in
1086 'precision' digits. The result should always be correctly rounded,
1087 using the rounding mode of the current thread's context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001088
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001089 With three arguments, compute ``(x**y) % modulo``. For the three
1090 argument form, the following restrictions on the arguments hold:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001091
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001092 - all three arguments must be integral
1093 - ``y`` must be nonnegative
1094 - at least one of ``x`` or ``y`` must be nonzero
1095 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl8ec7f652007-08-15 14:28:01 +00001096
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001097 The result of ``Context.power(x, y, modulo)`` is identical to
1098 the result that would be obtained by computing ``(x**y) %
1099 modulo`` with unbounded precision, but is computed more
1100 efficiently. It is always exact.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001101
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001102 .. versionchanged:: 2.6
1103 ``y`` may now be nonintegral in ``x**y``.
1104 Stricter requirements for the three-argument version.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001105
1106
1107.. method:: Context.remainder(x, y)
1108
1109 Returns the remainder from integer division.
1110
1111 The sign of the result, if non-zero, is the same as that of the original
1112 dividend.
1113
Georg Brandl8ec7f652007-08-15 14:28:01 +00001114.. method:: Context.subtract(x, y)
1115
1116 Return the difference between *x* and *y*.
1117
Georg Brandl8ec7f652007-08-15 14:28:01 +00001118.. method:: Context.to_sci_string(x)
1119
1120 Converts a number to a string using scientific notation.
1121
Georg Brandlb19be572007-12-29 10:57:00 +00001122.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001123
1124
1125.. _decimal-signals:
1126
1127Signals
1128-------
1129
1130Signals represent conditions that arise during computation. Each corresponds to
1131one context flag and one context trap enabler.
1132
1133The context flag is incremented whenever the condition is encountered. After the
1134computation, flags may be checked for informational purposes (for instance, to
1135determine whether a computation was exact). After checking the flags, be sure to
1136clear all flags before starting the next computation.
1137
1138If the context's trap enabler is set for the signal, then the condition causes a
1139Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1140is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1141condition.
1142
1143
1144.. class:: Clamped
1145
1146 Altered an exponent to fit representation constraints.
1147
1148 Typically, clamping occurs when an exponent falls outside the context's
1149 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001150 fit by adding zeros to the coefficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001151
1152
1153.. class:: DecimalException
1154
1155 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1156
1157
1158.. class:: DivisionByZero
1159
1160 Signals the division of a non-infinite number by zero.
1161
1162 Can occur with division, modulo division, or when raising a number to a negative
1163 power. If this signal is not trapped, returns :const:`Infinity` or
1164 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1165
1166
1167.. class:: Inexact
1168
1169 Indicates that rounding occurred and the result is not exact.
1170
1171 Signals when non-zero digits were discarded during rounding. The rounded result
1172 is returned. The signal flag or trap is used to detect when results are
1173 inexact.
1174
1175
1176.. class:: InvalidOperation
1177
1178 An invalid operation was performed.
1179
1180 Indicates that an operation was requested that does not make sense. If not
1181 trapped, returns :const:`NaN`. Possible causes include::
1182
1183 Infinity - Infinity
1184 0 * Infinity
1185 Infinity / Infinity
1186 x % 0
1187 Infinity % x
1188 x._rescale( non-integer )
1189 sqrt(-x) and x > 0
1190 0 ** 0
1191 x ** (non-integer)
1192 x ** Infinity
1193
1194
1195.. class:: Overflow
1196
1197 Numerical overflow.
1198
1199 Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
1200 If not trapped, the result depends on the rounding mode, either pulling inward
1201 to the largest representable finite number or rounding outward to
1202 :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are
1203 also signaled.
1204
1205
1206.. class:: Rounded
1207
1208 Rounding occurred though possibly no information was lost.
1209
1210 Signaled whenever rounding discards digits; even if those digits are zero (such
1211 as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result
1212 unchanged. This signal is used to detect loss of significant digits.
1213
1214
1215.. class:: Subnormal
1216
1217 Exponent was lower than :attr:`Emin` prior to rounding.
1218
1219 Occurs when an operation result is subnormal (the exponent is too small). If not
1220 trapped, returns the result unchanged.
1221
1222
1223.. class:: Underflow
1224
1225 Numerical underflow with result rounded to zero.
1226
1227 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1228 and :class:`Subnormal` are also signaled.
1229
1230The following table summarizes the hierarchy of signals::
1231
1232 exceptions.ArithmeticError(exceptions.StandardError)
1233 DecimalException
1234 Clamped
1235 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1236 Inexact
1237 Overflow(Inexact, Rounded)
1238 Underflow(Inexact, Rounded, Subnormal)
1239 InvalidOperation
1240 Rounded
1241 Subnormal
1242
Georg Brandlb19be572007-12-29 10:57:00 +00001243.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001244
1245
1246.. _decimal-notes:
1247
1248Floating Point Notes
1249--------------------
1250
1251
1252Mitigating round-off error with increased precision
1253^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1254
1255The use of decimal floating point eliminates decimal representation error
1256(making it possible to represent :const:`0.1` exactly); however, some operations
1257can still incur round-off error when non-zero digits exceed the fixed precision.
1258
1259The effects of round-off error can be amplified by the addition or subtraction
1260of nearly offsetting quantities resulting in loss of significance. Knuth
1261provides two instructive examples where rounded floating point arithmetic with
1262insufficient precision causes the breakdown of the associative and distributive
Georg Brandl9f662322008-03-22 11:47:10 +00001263properties of addition:
1264
1265.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001266
1267 # Examples from Seminumerical Algorithms, Section 4.2.2.
1268 >>> from decimal import Decimal, getcontext
1269 >>> getcontext().prec = 8
1270
1271 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1272 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001273 Decimal('9.5111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001274 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001275 Decimal('10')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001276
1277 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1278 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001279 Decimal('0.01')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001280 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001281 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001282
1283The :mod:`decimal` module makes it possible to restore the identities by
Georg Brandl9f662322008-03-22 11:47:10 +00001284expanding the precision sufficiently to avoid loss of significance:
1285
1286.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001287
1288 >>> getcontext().prec = 20
1289 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1290 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001291 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001292 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001293 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001294 >>>
1295 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1296 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001297 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001298 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001299 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001300
1301
1302Special values
1303^^^^^^^^^^^^^^
1304
1305The number system for the :mod:`decimal` module provides special values
1306including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001307and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001308
1309Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1310they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1311not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1312can result from rounding beyond the limits of the largest representable number.
1313
1314The infinities are signed (affine) and can be used in arithmetic operations
1315where they get treated as very large, indeterminate numbers. For instance,
1316adding a constant to infinity gives another infinite result.
1317
1318Some operations are indeterminate and return :const:`NaN`, or if the
1319:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1320``0/0`` returns :const:`NaN` which means "not a number". This variety of
1321:const:`NaN` is quiet and, once created, will flow through other computations
1322always resulting in another :const:`NaN`. This behavior can be useful for a
1323series of computations that occasionally have missing inputs --- it allows the
1324calculation to proceed while flagging specific results as invalid.
1325
1326A variant is :const:`sNaN` which signals rather than remaining quiet after every
1327operation. This is a useful return value when an invalid result needs to
1328interrupt a calculation for special handling.
1329
Mark Dickinson2fc92632008-02-06 22:10:50 +00001330The behavior of Python's comparison operators can be a little surprising where a
1331:const:`NaN` is involved. A test for equality where one of the operands is a
1332quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1333``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
Mark Dickinsonbafa9422008-02-06 22:25:16 +00001334:const:`True`. An attempt to compare two Decimals using any of the ``<``,
Mark Dickinson00c2e652008-02-07 01:42:06 +00001335``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1336if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Mark Dickinson3a94ee02008-02-10 15:19:58 +00001337not trapped. Note that the General Decimal Arithmetic specification does not
Mark Dickinson00c2e652008-02-07 01:42:06 +00001338specify the behavior of direct comparisons; these rules for comparisons
1339involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1340section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
Mark Dickinson2fc92632008-02-06 22:10:50 +00001341and :meth:`compare-signal` methods instead.
1342
Georg Brandl8ec7f652007-08-15 14:28:01 +00001343The signed zeros can result from calculations that underflow. They keep the sign
1344that would have resulted if the calculation had been carried out to greater
1345precision. Since their magnitude is zero, both positive and negative zeros are
1346treated as equal and their sign is informational.
1347
1348In addition to the two signed zeros which are distinct yet equal, there are
1349various representations of zero with differing precisions yet equivalent in
1350value. This takes a bit of getting used to. For an eye accustomed to
1351normalized floating point representations, it is not immediately obvious that
Georg Brandl9f662322008-03-22 11:47:10 +00001352the following calculation returns a value equal to zero:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001353
1354 >>> 1 / Decimal('Infinity')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001355 Decimal('0E-1000000026')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001356
Georg Brandlb19be572007-12-29 10:57:00 +00001357.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001358
1359
1360.. _decimal-threads:
1361
1362Working with threads
1363--------------------
1364
1365The :func:`getcontext` function accesses a different :class:`Context` object for
1366each thread. Having separate thread contexts means that threads may make
1367changes (such as ``getcontext.prec=10``) without interfering with other threads.
1368
1369Likewise, the :func:`setcontext` function automatically assigns its target to
1370the current thread.
1371
1372If :func:`setcontext` has not been called before :func:`getcontext`, then
1373:func:`getcontext` will automatically create a new context for use in the
1374current thread.
1375
1376The new context is copied from a prototype context called *DefaultContext*. To
1377control the defaults so that each thread will use the same values throughout the
1378application, directly modify the *DefaultContext* object. This should be done
1379*before* any threads are started so that there won't be a race condition between
1380threads calling :func:`getcontext`. For example::
1381
1382 # Set applicationwide defaults for all threads about to be launched
1383 DefaultContext.prec = 12
1384 DefaultContext.rounding = ROUND_DOWN
1385 DefaultContext.traps = ExtendedContext.traps.copy()
1386 DefaultContext.traps[InvalidOperation] = 1
1387 setcontext(DefaultContext)
1388
1389 # Afterwards, the threads can be started
1390 t1.start()
1391 t2.start()
1392 t3.start()
1393 . . .
1394
Georg Brandlb19be572007-12-29 10:57:00 +00001395.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001396
1397
1398.. _decimal-recipes:
1399
1400Recipes
1401-------
1402
1403Here are a few recipes that serve as utility functions and that demonstrate ways
1404to work with the :class:`Decimal` class::
1405
1406 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1407 pos='', neg='-', trailneg=''):
1408 """Convert Decimal to a money formatted string.
1409
1410 places: required number of places after the decimal point
1411 curr: optional currency symbol before the sign (may be blank)
1412 sep: optional grouping separator (comma, period, space, or blank)
1413 dp: decimal point indicator (comma or period)
1414 only specify as blank when places is zero
1415 pos: optional sign for positive numbers: '+', space or blank
1416 neg: optional sign for negative numbers: '-', '(', space or blank
1417 trailneg:optional trailing minus indicator: '-', ')', space or blank
1418
1419 >>> d = Decimal('-1234567.8901')
1420 >>> moneyfmt(d, curr='$')
1421 '-$1,234,567.89'
1422 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1423 '1.234.568-'
1424 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1425 '($1,234,567.89)'
1426 >>> moneyfmt(Decimal(123456789), sep=' ')
1427 '123 456 789.00'
1428 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001429 '<0.02>'
Georg Brandl8ec7f652007-08-15 14:28:01 +00001430
1431 """
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001432 q = Decimal(10) ** -places # 2 places --> '0.01'
1433 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001434 result = []
1435 digits = map(str, digits)
1436 build, next = result.append, digits.pop
1437 if sign:
1438 build(trailneg)
1439 for i in range(places):
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001440 build(next() if digits else '0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001441 build(dp)
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001442 if not digits:
1443 build('0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001444 i = 0
1445 while digits:
1446 build(next())
1447 i += 1
1448 if i == 3 and digits:
1449 i = 0
1450 build(sep)
1451 build(curr)
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001452 build(neg if sign else pos)
1453 return ''.join(reversed(result))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001454
1455 def pi():
1456 """Compute Pi to the current precision.
1457
1458 >>> print pi()
1459 3.141592653589793238462643383
1460
1461 """
1462 getcontext().prec += 2 # extra digits for intermediate steps
1463 three = Decimal(3) # substitute "three=3.0" for regular floats
1464 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1465 while s != lasts:
1466 lasts = s
1467 n, na = n+na, na+8
1468 d, da = d+da, da+32
1469 t = (t * n) / d
1470 s += t
1471 getcontext().prec -= 2
1472 return +s # unary plus applies the new precision
1473
1474 def exp(x):
1475 """Return e raised to the power of x. Result type matches input type.
1476
1477 >>> print exp(Decimal(1))
1478 2.718281828459045235360287471
1479 >>> print exp(Decimal(2))
1480 7.389056098930650227230427461
1481 >>> print exp(2.0)
1482 7.38905609893
1483 >>> print exp(2+0j)
1484 (7.38905609893+0j)
1485
1486 """
1487 getcontext().prec += 2
1488 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1489 while s != lasts:
1490 lasts = s
1491 i += 1
1492 fact *= i
1493 num *= x
1494 s += num / fact
1495 getcontext().prec -= 2
1496 return +s
1497
1498 def cos(x):
1499 """Return the cosine of x as measured in radians.
1500
1501 >>> print cos(Decimal('0.5'))
1502 0.8775825618903727161162815826
1503 >>> print cos(0.5)
1504 0.87758256189
1505 >>> print cos(0.5+0j)
1506 (0.87758256189+0j)
1507
1508 """
1509 getcontext().prec += 2
1510 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1511 while s != lasts:
1512 lasts = s
1513 i += 2
1514 fact *= i * (i-1)
1515 num *= x * x
1516 sign *= -1
1517 s += num / fact * sign
1518 getcontext().prec -= 2
1519 return +s
1520
1521 def sin(x):
1522 """Return the sine of x as measured in radians.
1523
1524 >>> print sin(Decimal('0.5'))
1525 0.4794255386042030002732879352
1526 >>> print sin(0.5)
1527 0.479425538604
1528 >>> print sin(0.5+0j)
1529 (0.479425538604+0j)
1530
1531 """
1532 getcontext().prec += 2
1533 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1534 while s != lasts:
1535 lasts = s
1536 i += 2
1537 fact *= i * (i-1)
1538 num *= x * x
1539 sign *= -1
1540 s += num / fact * sign
1541 getcontext().prec -= 2
1542 return +s
1543
1544
Georg Brandlb19be572007-12-29 10:57:00 +00001545.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001546
1547
1548.. _decimal-faq:
1549
1550Decimal FAQ
1551-----------
1552
1553Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1554minimize typing when using the interactive interpreter?
1555
Georg Brandl9f662322008-03-22 11:47:10 +00001556A. Some users abbreviate the constructor to just a single letter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001557
1558 >>> D = decimal.Decimal
1559 >>> D('1.23') + D('3.45')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001560 Decimal('4.68')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001561
1562Q. In a fixed-point application with two decimal places, some inputs have many
1563places and need to be rounded. Others are not supposed to have excess digits
1564and need to be validated. What methods should be used?
1565
1566A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Georg Brandl9f662322008-03-22 11:47:10 +00001567the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001568
1569 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1570
1571 >>> # Round to two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001572 >>> Decimal('3.214').quantize(TWOPLACES)
1573 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001574
1575 >>> # Validate that a number does not exceed two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001576 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1577 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001578
Raymond Hettingerabe32372008-02-14 02:41:22 +00001579 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001580 Traceback (most recent call last):
1581 ...
Georg Brandl9f662322008-03-22 11:47:10 +00001582 Inexact
Georg Brandl8ec7f652007-08-15 14:28:01 +00001583
1584Q. Once I have valid two place inputs, how do I maintain that invariant
1585throughout an application?
1586
Raymond Hettinger46314812008-02-14 10:46:57 +00001587A. Some operations like addition, subtraction, and multiplication by an integer
1588will automatically preserve fixed point. Others operations, like division and
1589non-integer multiplication, will change the number of decimal places and need to
Georg Brandl9f662322008-03-22 11:47:10 +00001590be followed-up with a :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001591
1592 >>> a = Decimal('102.72') # Initial fixed-point values
1593 >>> b = Decimal('3.17')
1594 >>> a + b # Addition preserves fixed-point
1595 Decimal('105.89')
1596 >>> a - b
1597 Decimal('99.55')
1598 >>> a * 42 # So does integer multiplication
1599 Decimal('4314.24')
1600 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1601 Decimal('325.62')
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001602 >>> (b / a).quantize(TWOPLACES) # And quantize division
Raymond Hettinger46314812008-02-14 10:46:57 +00001603 Decimal('0.03')
1604
1605In developing fixed-point applications, it is convenient to define functions
Georg Brandl9f662322008-03-22 11:47:10 +00001606to handle the :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001607
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001608 >>> def mul(x, y, fp=TWOPLACES):
1609 ... return (x * y).quantize(fp)
1610 >>> def div(x, y, fp=TWOPLACES):
1611 ... return (x / y).quantize(fp)
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001612
Raymond Hettinger46314812008-02-14 10:46:57 +00001613 >>> mul(a, b) # Automatically preserve fixed-point
1614 Decimal('325.62')
1615 >>> div(b, a)
1616 Decimal('0.03')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001617
1618Q. There are many ways to express the same value. The numbers :const:`200`,
1619:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1620various precisions. Is there a way to transform them to a single recognizable
1621canonical value?
1622
1623A. The :meth:`normalize` method maps all equivalent values to a single
Georg Brandl9f662322008-03-22 11:47:10 +00001624representative:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001625
1626 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1627 >>> [v.normalize() for v in values]
Raymond Hettingerabe32372008-02-14 02:41:22 +00001628 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001629
1630Q. Some decimal values always print with exponential notation. Is there a way
1631to get a non-exponential representation?
1632
1633A. For some values, exponential notation is the only way to express the number
1634of significant places in the coefficient. For example, expressing
1635:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1636original's two-place significance.
1637
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001638If an application does not care about tracking significance, it is easy to
Georg Brandl907a7202008-02-22 12:31:45 +00001639remove the exponent and trailing zeroes, losing significance, but keeping the
Georg Brandl9f662322008-03-22 11:47:10 +00001640value unchanged:
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001641
1642 >>> def remove_exponent(d):
1643 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1644
1645 >>> remove_exponent(Decimal('5E+3'))
1646 Decimal('5000')
1647
Georg Brandl8ec7f652007-08-15 14:28:01 +00001648Q. Is there a way to convert a regular float to a :class:`Decimal`?
1649
1650A. Yes, all binary floating point numbers can be exactly expressed as a
1651Decimal. An exact conversion may take more precision than intuition would
Georg Brandl9f662322008-03-22 11:47:10 +00001652suggest, so we trap :const:`Inexact` to signal a need for more precision:
1653
Georg Brandl838b4b02008-03-22 13:07:06 +00001654.. testcode::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001655
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001656 def float_to_decimal(f):
1657 "Convert a floating point number to a Decimal with no loss of information"
1658 n, d = f.as_integer_ratio()
1659 with localcontext() as ctx:
1660 ctx.traps[Inexact] = True
1661 while True:
1662 try:
1663 return Decimal(n) / Decimal(d)
1664 except Inexact:
1665 ctx.prec += 1
Georg Brandl8ec7f652007-08-15 14:28:01 +00001666
Georg Brandl838b4b02008-03-22 13:07:06 +00001667.. doctest::
Georg Brandl9f662322008-03-22 11:47:10 +00001668
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001669 >>> float_to_decimal(math.pi)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001670 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001671
Raymond Hettinger23bdcc92008-02-07 20:10:49 +00001672Q. Why isn't the :func:`float_to_decimal` routine included in the module?
Georg Brandl8ec7f652007-08-15 14:28:01 +00001673
1674A. There is some question about whether it is advisable to mix binary and
1675decimal floating point. Also, its use requires some care to avoid the
Georg Brandl9f662322008-03-22 11:47:10 +00001676representation issues associated with binary floating point:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001677
Raymond Hettinger23bdcc92008-02-07 20:10:49 +00001678 >>> float_to_decimal(1.1)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001679 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001680
1681Q. Within a complex calculation, how can I make sure that I haven't gotten a
1682spurious result because of insufficient precision or rounding anomalies.
1683
1684A. The decimal module makes it easy to test results. A best practice is to
1685re-run calculations using greater precision and with various rounding modes.
1686Widely differing results indicate insufficient precision, rounding mode issues,
1687ill-conditioned inputs, or a numerically unstable algorithm.
1688
1689Q. I noticed that context precision is applied to the results of operations but
1690not to the inputs. Is there anything to watch out for when mixing values of
1691different precisions?
1692
1693A. Yes. The principle is that all values are considered to be exact and so is
1694the arithmetic on those values. Only the results are rounded. The advantage
1695for inputs is that "what you type is what you get". A disadvantage is that the
Georg Brandl9f662322008-03-22 11:47:10 +00001696results can look odd if you forget that the inputs haven't been rounded:
1697
1698.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001699
1700 >>> getcontext().prec = 3
Georg Brandl9f662322008-03-22 11:47:10 +00001701 >>> Decimal('3.104') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001702 Decimal('5.21')
Georg Brandl9f662322008-03-22 11:47:10 +00001703 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001704 Decimal('5.20')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001705
1706The solution is either to increase precision or to force rounding of inputs
Georg Brandl9f662322008-03-22 11:47:10 +00001707using the unary plus operation:
1708
1709.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001710
1711 >>> getcontext().prec = 3
1712 >>> +Decimal('1.23456789') # unary plus triggers rounding
Raymond Hettingerabe32372008-02-14 02:41:22 +00001713 Decimal('1.23')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001714
1715Alternatively, inputs can be rounded upon creation using the
Georg Brandl9f662322008-03-22 11:47:10 +00001716:meth:`Context.create_decimal` method:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001717
1718 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001719 Decimal('1.2345')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001720