blob: 3359703a38836b3ef9aa5844e886dd11d6c9e99c [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
Mark Dickinson1840c1a2008-05-03 18:23:14 +0000103encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000104set 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
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000352 Decimal floating point objects share many properties with the other built-in
353 numeric types such as :class:`float` and :class:`int`. All of the usual math
354 operations and special methods apply. Likewise, decimal objects can be
355 copied, pickled, printed, used as dictionary keys, used as set elements,
356 compared, sorted, and coerced to another type (such as :class:`float` or
357 :class:`long`).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000358
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000359 In addition to the standard numeric properties, decimal floating point
360 objects also have a number of specialized methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000361
362
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000363 .. method:: adjusted()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000364
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000365 Return the adjusted exponent after shifting out the coefficient's
366 rightmost digits until only the lead digit remains:
367 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
368 position of the most significant digit with respect to the decimal point.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000369
370
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000371 .. method:: as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000372
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000373 Return a :term:`named tuple` representation of the number:
374 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandle3c3db52008-01-11 09:55:53 +0000375
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000376 .. versionchanged:: 2.6
377 Use a named tuple.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000378
379
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000380 .. method:: canonical()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000381
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000382 Return the canonical encoding of the argument. Currently, the encoding of
383 a :class:`Decimal` instance is always canonical, so this operation returns
384 its argument unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000385
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000386 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000387
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000388 .. method:: compare(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000389
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000390 Compare the values of two Decimal instances. This operation behaves in
391 the same way as the usual comparison method :meth:`__cmp__`, except that
392 :meth:`compare` returns a Decimal instance rather than an integer, and if
393 either operand is a NaN then the result is a NaN::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000394
Benjamin Petersonc7b05922008-04-25 01:29:10 +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
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000400 .. method:: compare_signal(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000401
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000402 This operation is identical to the :meth:`compare` method, except that all
403 NaNs signal. That is, if neither operand is a signaling NaN then any
404 quiet NaN operand is treated as though it were a signaling NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000405
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000406 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000407
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000408 .. method:: compare_total(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000409
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000410 Compare two operands using their abstract representation rather than their
411 numerical value. Similar to the :meth:`compare` method, but the result
412 gives a total ordering on :class:`Decimal` instances. Two
413 :class:`Decimal` instances with the same numeric value but different
414 representations compare unequal in this ordering:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000415
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000416 >>> Decimal('12.0').compare_total(Decimal('12'))
417 Decimal('-1')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000418
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000419 Quiet and signaling NaNs are also included in the total ordering. The
420 result of this function is ``Decimal('0')`` if both operands have the same
421 representation, ``Decimal('-1')`` if the first operand is lower in the
422 total order than the second, and ``Decimal('1')`` if the first operand is
423 higher in the total order than the second operand. See the specification
424 for details of the total order.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000425
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000426 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000427
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000428 .. method:: compare_total_mag(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000429
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000430 Compare two operands using their abstract representation rather than their
431 value as in :meth:`compare_total`, but ignoring the sign of each operand.
432 ``x.compare_total_mag(y)`` is equivalent to
433 ``x.copy_abs().compare_total(y.copy_abs())``.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000434
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000435 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000436
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000437 .. method:: copy_abs()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000438
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000439 Return the absolute value of the argument. This operation is unaffected
440 by the context and is quiet: no flags are changed and no rounding is
441 performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000442
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000443 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000444
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000445 .. method:: copy_negate()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000446
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000447 Return the negation of the argument. This operation is unaffected by the
448 context and is quiet: no flags are changed and no rounding is performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000449
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000450 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000451
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000452 .. method:: copy_sign(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000453
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000454 Return a copy of the first operand with the sign set to be the same as the
455 sign of the second operand. For example:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000456
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000457 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
458 Decimal('-2.3')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000459
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000460 This operation is unaffected by the context and is quiet: no flags are
461 changed and no rounding is performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000462
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000463 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000464
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000465 .. method:: exp([context])
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000466
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000467 Return the value of the (natural) exponential function ``e**x`` at the
468 given number. The result is correctly rounded using the
469 :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000470
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000471 >>> Decimal(1).exp()
472 Decimal('2.718281828459045235360287471')
473 >>> Decimal(321).exp()
474 Decimal('2.561702493119680037517373933E+139')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000475
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000476 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000477
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000478 .. method:: fma(other, third[, context])
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000479
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000480 Fused multiply-add. Return self*other+third with no rounding of the
481 intermediate product self*other.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000482
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000483 >>> Decimal(2).fma(3, 5)
484 Decimal('11')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000485
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000486 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000487
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000488 .. method:: is_canonical()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000489
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000490 Return :const:`True` if the argument is canonical and :const:`False`
491 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
492 this operation always returns :const:`True`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000493
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000494 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000495
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000496 .. method:: is_finite()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000497
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000498 Return :const:`True` if the argument is a finite number, and
499 :const:`False` if the argument is an infinity or a NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000500
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000501 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000502
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000503 .. method:: is_infinite()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000504
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000505 Return :const:`True` if the argument is either positive or negative
506 infinity and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000507
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000508 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000509
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000510 .. method:: is_nan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000511
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000512 Return :const:`True` if the argument is a (quiet or signaling) NaN and
513 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000514
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000515 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000516
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000517 .. method:: is_normal()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000518
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000519 Return :const:`True` if the argument is a *normal* finite number. Return
520 :const:`False` if the argument is zero, subnormal, infinite or a NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000521
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000522 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000523
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000524 .. method:: is_qnan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000525
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000526 Return :const:`True` if the argument is a quiet NaN, and
527 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000528
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000529 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000530
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000531 .. method:: is_signed()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000532
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000533 Return :const:`True` if the argument has a negative sign and
534 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000535
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000536 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000537
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000538 .. method:: is_snan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000539
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000540 Return :const:`True` if the argument is a signaling NaN and :const:`False`
541 otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000542
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000543 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000544
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000545 .. method:: is_subnormal()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000546
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000547 Return :const:`True` if the argument is subnormal, and :const:`False`
548 otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000549
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000550 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000551
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000552 .. method:: is_zero()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000553
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000554 Return :const:`True` if the argument is a (positive or negative) zero and
555 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000556
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000557 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000558
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000559 .. method:: ln([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000560
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000561 Return the natural (base e) logarithm of the operand. The result is
562 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000563
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000564 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000565
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000566 .. method:: log10([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000567
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000568 Return the base ten logarithm of the operand. The result is correctly
569 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000570
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000571 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000572
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000573 .. method:: logb([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000574
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000575 For a nonzero number, return the adjusted exponent of its operand as a
576 :class:`Decimal` instance. If the operand is a zero then
577 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
578 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
579 returned.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000580
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000581 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000582
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000583 .. method:: logical_and(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000584
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000585 :meth:`logical_and` is a logical operation which takes two *logical
586 operands* (see :ref:`logical_operands_label`). The result is the
587 digit-wise ``and`` of the two operands.
588
589 .. versionadded:: 2.6
590
591 .. method:: logical_invert(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000592
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000593 :meth:`logical_invert` is a logical operation. The argument must
594 be a *logical operand* (see :ref:`logical_operands_label`). The
595 result is the digit-wise inversion of the operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000596
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000597 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000598
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000599 .. method:: logical_or(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000600
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000601 :meth:`logical_or` is a logical operation which takes two *logical
602 operands* (see :ref:`logical_operands_label`). The result is the
603 digit-wise ``or`` of the two operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000604
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000605 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000606
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000607 .. method:: logical_xor(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000608
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000609 :meth:`logical_xor` is a logical operation which takes two *logical
610 operands* (see :ref:`logical_operands_label`). The result is the
611 digit-wise exclusive or of the two operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000612
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000613 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000614
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000615 .. method:: max(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000616
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000617 Like ``max(self, other)`` except that the context rounding rule is applied
618 before returning and that :const:`NaN` values are either signaled or
619 ignored (depending on the context and whether they are signaling or
620 quiet).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000621
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000622 .. method:: max_mag(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000623
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000624 Similar to the :meth:`max` method, but the comparison is done using the
625 absolute values of the operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000626
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000627 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000628
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000629 .. method:: min(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000630
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000631 Like ``min(self, other)`` except that the context rounding rule is applied
632 before returning and that :const:`NaN` values are either signaled or
633 ignored (depending on the context and whether they are signaling or
634 quiet).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000635
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000636 .. method:: min_mag(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000637
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000638 Similar to the :meth:`min` method, but the comparison is done using the
639 absolute values of the operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000640
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000641 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000642
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000643 .. method:: next_minus([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000644
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000645 Return the largest number representable in the given context (or in the
646 current thread's context if no context is given) that is smaller than the
647 given operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000648
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000649 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000650
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000651 .. method:: next_plus([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000652
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000653 Return the smallest number representable in the given context (or in the
654 current thread's context if no context is given) that is larger than the
655 given operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000656
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000657 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000658
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000659 .. method:: next_toward(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000660
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000661 If the two operands are unequal, return the number closest to the first
662 operand in the direction of the second operand. If both operands are
663 numerically equal, return a copy of the first operand with the sign set to
664 be the same as the sign of the second operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000665
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000666 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000667
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000668 .. method:: normalize([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000669
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000670 Normalize the number by stripping the rightmost trailing zeros and
671 converting any result equal to :const:`Decimal('0')` to
672 :const:`Decimal('0e0')`. Used for producing canonical values for members
673 of an equivalence class. For example, ``Decimal('32.100')`` and
674 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
675 ``Decimal('32.1')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000676
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000677 .. method:: number_class([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000678
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000679 Return a string describing the *class* of the operand. The returned value
680 is one of the following ten strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000681
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000682 * ``"-Infinity"``, indicating that the operand is negative infinity.
683 * ``"-Normal"``, indicating that the operand is a negative normal number.
684 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
685 * ``"-Zero"``, indicating that the operand is a negative zero.
686 * ``"+Zero"``, indicating that the operand is a positive zero.
687 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
688 * ``"+Normal"``, indicating that the operand is a positive normal number.
689 * ``"+Infinity"``, indicating that the operand is positive infinity.
690 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
691 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000692
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000693 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000694
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000695 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000696
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000697 Return a value equal to the first operand after rounding and having the
698 exponent of the second operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000699
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000700 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
701 Decimal('1.414')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000702
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000703 Unlike other operations, if the length of the coefficient after the
704 quantize operation would be greater than precision, then an
705 :const:`InvalidOperation` is signaled. This guarantees that, unless there
706 is an error condition, the quantized exponent is always equal to that of
707 the right-hand operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000708
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000709 Also unlike other operations, quantize never signals Underflow, even if
710 the result is subnormal and inexact.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000711
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000712 If the exponent of the second operand is larger than that of the first
713 then rounding may be necessary. In this case, the rounding mode is
714 determined by the ``rounding`` argument if given, else by the given
715 ``context`` argument; if neither argument is given the rounding mode of
716 the current thread's context is used.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000717
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000718 If *watchexp* is set (default), then an error is returned whenever the
719 resulting exponent is greater than :attr:`Emax` or less than
720 :attr:`Etiny`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000721
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000722 .. method:: radix()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000723
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000724 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
725 class does all its arithmetic. Included for compatibility with the
726 specification.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000727
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000728 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000729
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000730 .. method:: remainder_near(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000731
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000732 Compute the modulo as either a positive or negative value depending on
733 which is closest to zero. For instance, ``Decimal(10).remainder_near(6)``
734 returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000735
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000736 If both are equally close, the one chosen will have the same sign as
737 *self*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000738
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000739 .. method:: rotate(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000740
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000741 Return the result of rotating the digits of the first operand by an amount
742 specified by the second operand. The second operand must be an integer in
743 the range -precision through precision. The absolute value of the second
744 operand gives the number of places to rotate. If the second operand is
745 positive then rotation is to the left; otherwise rotation is to the right.
746 The coefficient of the first operand is padded on the left with zeros to
747 length precision if necessary. The sign and exponent of the first operand
748 are unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000749
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000750 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000752 .. method:: same_quantum(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000753
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000754 Test whether self and other have the same exponent or whether both are
755 :const:`NaN`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000756
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000757 .. method:: scaleb(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000758
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000759 Return the first operand with exponent adjusted by the second.
760 Equivalently, return the first operand multiplied by ``10**other``. The
761 second operand must be an integer.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000762
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000763 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000764
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000765 .. method:: shift(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000766
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000767 Return the result of shifting the digits of the first operand by an amount
768 specified by the second operand. The second operand must be an integer in
769 the range -precision through precision. The absolute value of the second
770 operand gives the number of places to shift. If the second operand is
771 positive then the shift is to the left; otherwise the shift is to the
772 right. Digits shifted into the coefficient are zeros. The sign and
773 exponent of the first operand are unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000774
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000775 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000776
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000777 .. method:: sqrt([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000778
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000779 Return the square root of the argument to full precision.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000780
781
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000782 .. method:: to_eng_string([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000783
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000784 Convert to an engineering-type string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000785
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000786 Engineering notation has an exponent which is a multiple of 3, so there
787 are up to 3 digits left of the decimal place. For example, converts
788 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000789
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000790 .. method:: to_integral([rounding[, context]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000791
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000792 Identical to the :meth:`to_integral_value` method. The ``to_integral``
793 name has been kept for compatibility with older versions.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000794
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000795 .. method:: to_integral_exact([rounding[, context]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000796
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000797 Round to the nearest integer, signaling :const:`Inexact` or
798 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
799 determined by the ``rounding`` parameter if given, else by the given
800 ``context``. If neither parameter is given then the rounding mode of the
801 current context is used.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000802
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000803 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000804
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000805 .. method:: to_integral_value([rounding[, context]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000806
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000807 Round to the nearest integer without signaling :const:`Inexact` or
808 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
809 rounding method in either the supplied *context* or the current context.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000810
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000811 .. versionchanged:: 2.6
812 renamed from ``to_integral`` to ``to_integral_value``. The old name
813 remains valid for compatibility.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000814
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000815 .. method:: trim()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000816
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000817 Return the decimal with *insignificant* trailing zeros removed. Here, a
818 trailing zero is considered insignificant either if it follows the decimal
819 point, or if the exponent of the argument (that is, the last element of
820 the :meth:`as_tuple` representation) is positive.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000821
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000822 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000823
824.. _logical_operands_label:
825
826Logical operands
827^^^^^^^^^^^^^^^^
828
829The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
830and :meth:`logical_xor` methods expect their arguments to be *logical
831operands*. A *logical operand* is a :class:`Decimal` instance whose
832exponent and sign are both zero, and whose digits are all either
833:const:`0` or :const:`1`.
834
Georg Brandlb19be572007-12-29 10:57:00 +0000835.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000836
837
838.. _decimal-context:
839
840Context objects
841---------------
842
843Contexts are environments for arithmetic operations. They govern precision, set
844rules for rounding, determine which signals are treated as exceptions, and limit
845the range for exponents.
846
847Each thread has its own current context which is accessed or changed using the
848:func:`getcontext` and :func:`setcontext` functions:
849
850
851.. function:: getcontext()
852
853 Return the current context for the active thread.
854
855
856.. function:: setcontext(c)
857
858 Set the current context for the active thread to *c*.
859
860Beginning with Python 2.5, you can also use the :keyword:`with` statement and
861the :func:`localcontext` function to temporarily change the active context.
862
863
864.. function:: localcontext([c])
865
866 Return a context manager that will set the current context for the active thread
867 to a copy of *c* on entry to the with-statement and restore the previous context
868 when exiting the with-statement. If no context is specified, a copy of the
869 current context is used.
870
871 .. versionadded:: 2.5
872
873 For example, the following code sets the current decimal precision to 42 places,
874 performs a calculation, and then automatically restores the previous context::
875
Georg Brandl8ec7f652007-08-15 14:28:01 +0000876 from decimal import localcontext
877
878 with localcontext() as ctx:
879 ctx.prec = 42 # Perform a high precision calculation
880 s = calculate_something()
881 s = +s # Round the final result back to the default precision
882
883New contexts can also be created using the :class:`Context` constructor
884described below. In addition, the module provides three pre-made contexts:
885
886
887.. class:: BasicContext
888
889 This is a standard context defined by the General Decimal Arithmetic
890 Specification. Precision is set to nine. Rounding is set to
891 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
892 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
893 :const:`Subnormal`.
894
895 Because many of the traps are enabled, this context is useful for debugging.
896
897
898.. class:: ExtendedContext
899
900 This is a standard context defined by the General Decimal Arithmetic
901 Specification. Precision is set to nine. Rounding is set to
902 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
903 exceptions are not raised during computations).
904
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000905 Because the traps are disabled, this context is useful for applications that
Georg Brandl8ec7f652007-08-15 14:28:01 +0000906 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
907 raising exceptions. This allows an application to complete a run in the
908 presence of conditions that would otherwise halt the program.
909
910
911.. class:: DefaultContext
912
913 This context is used by the :class:`Context` constructor as a prototype for new
914 contexts. Changing a field (such a precision) has the effect of changing the
915 default for new contexts creating by the :class:`Context` constructor.
916
917 This context is most useful in multi-threaded environments. Changing one of the
918 fields before threads are started has the effect of setting system-wide
919 defaults. Changing the fields after threads have started is not recommended as
920 it would require thread synchronization to prevent race conditions.
921
922 In single threaded environments, it is preferable to not use this context at
923 all. Instead, simply create contexts explicitly as described below.
924
925 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
926 for Overflow, InvalidOperation, and DivisionByZero.
927
928In addition to the three supplied contexts, new contexts can be created with the
929:class:`Context` constructor.
930
931
932.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
933
934 Creates a new context. If a field is not specified or is :const:`None`, the
935 default values are copied from the :const:`DefaultContext`. If the *flags*
936 field is not specified or is :const:`None`, all flags are cleared.
937
938 The *prec* field is a positive integer that sets the precision for arithmetic
939 operations in the context.
940
941 The *rounding* option is one of:
942
943 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
944 * :const:`ROUND_DOWN` (towards zero),
945 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
946 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
947 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
948 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
949 * :const:`ROUND_UP` (away from zero).
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000950 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
951 would have been 0 or 5; otherwise towards zero)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000952
953 The *traps* and *flags* fields list any signals to be set. Generally, new
954 contexts should only set traps and leave the flags clear.
955
956 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
957 for exponents.
958
959 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
960 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
961 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
962
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000963 .. versionchanged:: 2.6
964 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000965
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000966 The :class:`Context` class defines several general purpose methods as well as
967 a large number of methods for doing arithmetic directly in a given context.
968 In addition, for each of the :class:`Decimal` methods described above (with
969 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
970 a corresponding :class:`Context` method. For example, ``C.exp(x)`` is
971 equivalent to ``x.exp(context=C)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000972
973
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000974 .. method:: clear_flags()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000975
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000976 Resets all of the flags to :const:`0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000977
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000978 .. method:: copy()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000979
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000980 Return a duplicate of the context.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000981
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000982 .. method:: copy_decimal(num)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000983
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000984 Return a copy of the Decimal instance num.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000985
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000986 .. method:: create_decimal(num)
Georg Brandl9f662322008-03-22 11:47:10 +0000987
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000988 Creates a new Decimal instance from *num* but using *self* as
989 context. Unlike the :class:`Decimal` constructor, the context precision,
990 rounding method, flags, and traps are applied to the conversion.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000991
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000992 This is useful because constants are often given to a greater precision
993 than is needed by the application. Another benefit is that rounding
994 immediately eliminates unintended effects from digits beyond the current
995 precision. In the following example, using unrounded inputs means that
996 adding zero to a sum can change the result:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000997
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000998 .. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +0000999
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001000 >>> getcontext().prec = 3
1001 >>> Decimal('3.4445') + Decimal('1.0023')
1002 Decimal('4.45')
1003 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1004 Decimal('4.44')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001005
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001006 This method implements the to-number operation of the IBM specification.
1007 If the argument is a string, no leading or trailing whitespace is
1008 permitted.
1009
1010 .. method:: Etiny()
1011
1012 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
1013 value for subnormal results. When underflow occurs, the exponent is set
1014 to :const:`Etiny`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001015
1016
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001017 .. method:: Etop()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001018
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001019 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001020
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001021 The usual approach to working with decimals is to create :class:`Decimal`
1022 instances and then apply arithmetic operations which take place within the
1023 current context for the active thread. An alternative approach is to use
1024 context methods for calculating within a specific context. The methods are
1025 similar to those for the :class:`Decimal` class and are only briefly
1026 recounted here.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001027
1028
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001029 .. method:: abs(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001030
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001031 Returns the absolute value of *x*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001032
1033
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001034 .. method:: add(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001035
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001036 Return the sum of *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001037
1038
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001039 .. method:: divide(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001040
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001041 Return *x* divided by *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001042
1043
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001044 .. method:: divide_int(x, y)
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001045
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001046 Return *x* divided by *y*, truncated to an integer.
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001047
1048
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001049 .. method:: divmod(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001050
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001051 Divides two numbers and returns the integer part of the result.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001052
1053
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001054 .. method:: minus(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001055
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001056 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001057
1058
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001059 .. method:: multiply(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001060
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001061 Return the product of *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001062
1063
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001064 .. method:: plus(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001065
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001066 Plus corresponds to the unary prefix plus operator in Python. This
1067 operation applies the context precision and rounding, so it is *not* an
1068 identity operation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001069
1070
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001071 .. method:: power(x, y[, modulo])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001072
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001073 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001074
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001075 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1076 must be integral. The result will be inexact unless ``y`` is integral and
1077 the result is finite and can be expressed exactly in 'precision' digits.
1078 The result should always be correctly rounded, using the rounding mode of
1079 the current thread's context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001080
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001081 With three arguments, compute ``(x**y) % modulo``. For the three argument
1082 form, the following restrictions on the arguments hold:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001083
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001084 - all three arguments must be integral
1085 - ``y`` must be nonnegative
1086 - at least one of ``x`` or ``y`` must be nonzero
1087 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl8ec7f652007-08-15 14:28:01 +00001088
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001089 The result of ``Context.power(x, y, modulo)`` is identical to the result
1090 that would be obtained by computing ``(x**y) % modulo`` with unbounded
1091 precision, but is computed more efficiently. It is always exact.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001092
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001093 .. versionchanged:: 2.6
1094 ``y`` may now be nonintegral in ``x**y``.
1095 Stricter requirements for the three-argument version.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001096
1097
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001098 .. method:: remainder(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001099
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001100 Returns the remainder from integer division.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001101
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001102 The sign of the result, if non-zero, is the same as that of the original
1103 dividend.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001104
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001105 .. method:: subtract(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001106
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001107 Return the difference between *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001108
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001109 .. method:: to_sci_string(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001110
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001111 Converts a number to a string using scientific notation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001112
Georg Brandlb19be572007-12-29 10:57:00 +00001113.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001114
1115
1116.. _decimal-signals:
1117
1118Signals
1119-------
1120
1121Signals represent conditions that arise during computation. Each corresponds to
1122one context flag and one context trap enabler.
1123
Mark Dickinson1840c1a2008-05-03 18:23:14 +00001124The context flag is set whenever the condition is encountered. After the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001125computation, flags may be checked for informational purposes (for instance, to
1126determine whether a computation was exact). After checking the flags, be sure to
1127clear all flags before starting the next computation.
1128
1129If the context's trap enabler is set for the signal, then the condition causes a
1130Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1131is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1132condition.
1133
1134
1135.. class:: Clamped
1136
1137 Altered an exponent to fit representation constraints.
1138
1139 Typically, clamping occurs when an exponent falls outside the context's
1140 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001141 fit by adding zeros to the coefficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001142
1143
1144.. class:: DecimalException
1145
1146 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1147
1148
1149.. class:: DivisionByZero
1150
1151 Signals the division of a non-infinite number by zero.
1152
1153 Can occur with division, modulo division, or when raising a number to a negative
1154 power. If this signal is not trapped, returns :const:`Infinity` or
1155 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1156
1157
1158.. class:: Inexact
1159
1160 Indicates that rounding occurred and the result is not exact.
1161
1162 Signals when non-zero digits were discarded during rounding. The rounded result
1163 is returned. The signal flag or trap is used to detect when results are
1164 inexact.
1165
1166
1167.. class:: InvalidOperation
1168
1169 An invalid operation was performed.
1170
1171 Indicates that an operation was requested that does not make sense. If not
1172 trapped, returns :const:`NaN`. Possible causes include::
1173
1174 Infinity - Infinity
1175 0 * Infinity
1176 Infinity / Infinity
1177 x % 0
1178 Infinity % x
1179 x._rescale( non-integer )
1180 sqrt(-x) and x > 0
1181 0 ** 0
1182 x ** (non-integer)
1183 x ** Infinity
1184
1185
1186.. class:: Overflow
1187
1188 Numerical overflow.
1189
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001190 Indicates the exponent is larger than :attr:`Emax` after rounding has
1191 occurred. If not trapped, the result depends on the rounding mode, either
1192 pulling inward to the largest representable finite number or rounding outward
1193 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1194 are also signaled.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001195
1196
1197.. class:: Rounded
1198
1199 Rounding occurred though possibly no information was lost.
1200
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001201 Signaled whenever rounding discards digits; even if those digits are zero
1202 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1203 the result unchanged. This signal is used to detect loss of significant
1204 digits.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001205
1206
1207.. class:: Subnormal
1208
1209 Exponent was lower than :attr:`Emin` prior to rounding.
1210
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001211 Occurs when an operation result is subnormal (the exponent is too small). If
1212 not trapped, returns the result unchanged.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001213
1214
1215.. class:: Underflow
1216
1217 Numerical underflow with result rounded to zero.
1218
1219 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1220 and :class:`Subnormal` are also signaled.
1221
1222The following table summarizes the hierarchy of signals::
1223
1224 exceptions.ArithmeticError(exceptions.StandardError)
1225 DecimalException
1226 Clamped
1227 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1228 Inexact
1229 Overflow(Inexact, Rounded)
1230 Underflow(Inexact, Rounded, Subnormal)
1231 InvalidOperation
1232 Rounded
1233 Subnormal
1234
Georg Brandlb19be572007-12-29 10:57:00 +00001235.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001236
1237
1238.. _decimal-notes:
1239
1240Floating Point Notes
1241--------------------
1242
1243
1244Mitigating round-off error with increased precision
1245^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1246
1247The use of decimal floating point eliminates decimal representation error
1248(making it possible to represent :const:`0.1` exactly); however, some operations
1249can still incur round-off error when non-zero digits exceed the fixed precision.
1250
1251The effects of round-off error can be amplified by the addition or subtraction
1252of nearly offsetting quantities resulting in loss of significance. Knuth
1253provides two instructive examples where rounded floating point arithmetic with
1254insufficient precision causes the breakdown of the associative and distributive
Georg Brandl9f662322008-03-22 11:47:10 +00001255properties of addition:
1256
1257.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001258
1259 # Examples from Seminumerical Algorithms, Section 4.2.2.
1260 >>> from decimal import Decimal, getcontext
1261 >>> getcontext().prec = 8
1262
1263 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1264 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001265 Decimal('9.5111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001266 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001267 Decimal('10')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001268
1269 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1270 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001271 Decimal('0.01')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001272 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001273 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001274
1275The :mod:`decimal` module makes it possible to restore the identities by
Georg Brandl9f662322008-03-22 11:47:10 +00001276expanding the precision sufficiently to avoid loss of significance:
1277
1278.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001279
1280 >>> getcontext().prec = 20
1281 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1282 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001283 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001284 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001285 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001286 >>>
1287 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1288 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001289 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001290 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001291 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001292
1293
1294Special values
1295^^^^^^^^^^^^^^
1296
1297The number system for the :mod:`decimal` module provides special values
1298including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001299and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001300
1301Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1302they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1303not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1304can result from rounding beyond the limits of the largest representable number.
1305
1306The infinities are signed (affine) and can be used in arithmetic operations
1307where they get treated as very large, indeterminate numbers. For instance,
1308adding a constant to infinity gives another infinite result.
1309
1310Some operations are indeterminate and return :const:`NaN`, or if the
1311:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1312``0/0`` returns :const:`NaN` which means "not a number". This variety of
1313:const:`NaN` is quiet and, once created, will flow through other computations
1314always resulting in another :const:`NaN`. This behavior can be useful for a
1315series of computations that occasionally have missing inputs --- it allows the
1316calculation to proceed while flagging specific results as invalid.
1317
1318A variant is :const:`sNaN` which signals rather than remaining quiet after every
1319operation. This is a useful return value when an invalid result needs to
1320interrupt a calculation for special handling.
1321
Mark Dickinson2fc92632008-02-06 22:10:50 +00001322The behavior of Python's comparison operators can be a little surprising where a
1323:const:`NaN` is involved. A test for equality where one of the operands is a
1324quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1325``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
Mark Dickinsonbafa9422008-02-06 22:25:16 +00001326:const:`True`. An attempt to compare two Decimals using any of the ``<``,
Mark Dickinson00c2e652008-02-07 01:42:06 +00001327``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1328if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Mark Dickinson3a94ee02008-02-10 15:19:58 +00001329not trapped. Note that the General Decimal Arithmetic specification does not
Mark Dickinson00c2e652008-02-07 01:42:06 +00001330specify the behavior of direct comparisons; these rules for comparisons
1331involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1332section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
Mark Dickinson2fc92632008-02-06 22:10:50 +00001333and :meth:`compare-signal` methods instead.
1334
Georg Brandl8ec7f652007-08-15 14:28:01 +00001335The signed zeros can result from calculations that underflow. They keep the sign
1336that would have resulted if the calculation had been carried out to greater
1337precision. Since their magnitude is zero, both positive and negative zeros are
1338treated as equal and their sign is informational.
1339
1340In addition to the two signed zeros which are distinct yet equal, there are
1341various representations of zero with differing precisions yet equivalent in
1342value. This takes a bit of getting used to. For an eye accustomed to
1343normalized floating point representations, it is not immediately obvious that
Georg Brandl9f662322008-03-22 11:47:10 +00001344the following calculation returns a value equal to zero:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001345
1346 >>> 1 / Decimal('Infinity')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001347 Decimal('0E-1000000026')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001348
Georg Brandlb19be572007-12-29 10:57:00 +00001349.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001350
1351
1352.. _decimal-threads:
1353
1354Working with threads
1355--------------------
1356
1357The :func:`getcontext` function accesses a different :class:`Context` object for
1358each thread. Having separate thread contexts means that threads may make
1359changes (such as ``getcontext.prec=10``) without interfering with other threads.
1360
1361Likewise, the :func:`setcontext` function automatically assigns its target to
1362the current thread.
1363
1364If :func:`setcontext` has not been called before :func:`getcontext`, then
1365:func:`getcontext` will automatically create a new context for use in the
1366current thread.
1367
1368The new context is copied from a prototype context called *DefaultContext*. To
1369control the defaults so that each thread will use the same values throughout the
1370application, directly modify the *DefaultContext* object. This should be done
1371*before* any threads are started so that there won't be a race condition between
1372threads calling :func:`getcontext`. For example::
1373
1374 # Set applicationwide defaults for all threads about to be launched
1375 DefaultContext.prec = 12
1376 DefaultContext.rounding = ROUND_DOWN
1377 DefaultContext.traps = ExtendedContext.traps.copy()
1378 DefaultContext.traps[InvalidOperation] = 1
1379 setcontext(DefaultContext)
1380
1381 # Afterwards, the threads can be started
1382 t1.start()
1383 t2.start()
1384 t3.start()
1385 . . .
1386
Georg Brandlb19be572007-12-29 10:57:00 +00001387.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001388
1389
1390.. _decimal-recipes:
1391
1392Recipes
1393-------
1394
1395Here are a few recipes that serve as utility functions and that demonstrate ways
1396to work with the :class:`Decimal` class::
1397
1398 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1399 pos='', neg='-', trailneg=''):
1400 """Convert Decimal to a money formatted string.
1401
1402 places: required number of places after the decimal point
1403 curr: optional currency symbol before the sign (may be blank)
1404 sep: optional grouping separator (comma, period, space, or blank)
1405 dp: decimal point indicator (comma or period)
1406 only specify as blank when places is zero
1407 pos: optional sign for positive numbers: '+', space or blank
1408 neg: optional sign for negative numbers: '-', '(', space or blank
1409 trailneg:optional trailing minus indicator: '-', ')', space or blank
1410
1411 >>> d = Decimal('-1234567.8901')
1412 >>> moneyfmt(d, curr='$')
1413 '-$1,234,567.89'
1414 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1415 '1.234.568-'
1416 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1417 '($1,234,567.89)'
1418 >>> moneyfmt(Decimal(123456789), sep=' ')
1419 '123 456 789.00'
1420 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001421 '<0.02>'
Georg Brandl8ec7f652007-08-15 14:28:01 +00001422
1423 """
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001424 q = Decimal(10) ** -places # 2 places --> '0.01'
1425 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001426 result = []
1427 digits = map(str, digits)
1428 build, next = result.append, digits.pop
1429 if sign:
1430 build(trailneg)
1431 for i in range(places):
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001432 build(next() if digits else '0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001433 build(dp)
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001434 if not digits:
1435 build('0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001436 i = 0
1437 while digits:
1438 build(next())
1439 i += 1
1440 if i == 3 and digits:
1441 i = 0
1442 build(sep)
1443 build(curr)
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001444 build(neg if sign else pos)
1445 return ''.join(reversed(result))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001446
1447 def pi():
1448 """Compute Pi to the current precision.
1449
1450 >>> print pi()
1451 3.141592653589793238462643383
1452
1453 """
1454 getcontext().prec += 2 # extra digits for intermediate steps
1455 three = Decimal(3) # substitute "three=3.0" for regular floats
1456 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1457 while s != lasts:
1458 lasts = s
1459 n, na = n+na, na+8
1460 d, da = d+da, da+32
1461 t = (t * n) / d
1462 s += t
1463 getcontext().prec -= 2
1464 return +s # unary plus applies the new precision
1465
1466 def exp(x):
1467 """Return e raised to the power of x. Result type matches input type.
1468
1469 >>> print exp(Decimal(1))
1470 2.718281828459045235360287471
1471 >>> print exp(Decimal(2))
1472 7.389056098930650227230427461
1473 >>> print exp(2.0)
1474 7.38905609893
1475 >>> print exp(2+0j)
1476 (7.38905609893+0j)
1477
1478 """
1479 getcontext().prec += 2
1480 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1481 while s != lasts:
1482 lasts = s
1483 i += 1
1484 fact *= i
1485 num *= x
1486 s += num / fact
1487 getcontext().prec -= 2
1488 return +s
1489
1490 def cos(x):
1491 """Return the cosine of x as measured in radians.
1492
1493 >>> print cos(Decimal('0.5'))
1494 0.8775825618903727161162815826
1495 >>> print cos(0.5)
1496 0.87758256189
1497 >>> print cos(0.5+0j)
1498 (0.87758256189+0j)
1499
1500 """
1501 getcontext().prec += 2
1502 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1503 while s != lasts:
1504 lasts = s
1505 i += 2
1506 fact *= i * (i-1)
1507 num *= x * x
1508 sign *= -1
1509 s += num / fact * sign
1510 getcontext().prec -= 2
1511 return +s
1512
1513 def sin(x):
1514 """Return the sine of x as measured in radians.
1515
1516 >>> print sin(Decimal('0.5'))
1517 0.4794255386042030002732879352
1518 >>> print sin(0.5)
1519 0.479425538604
1520 >>> print sin(0.5+0j)
1521 (0.479425538604+0j)
1522
1523 """
1524 getcontext().prec += 2
1525 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1526 while s != lasts:
1527 lasts = s
1528 i += 2
1529 fact *= i * (i-1)
1530 num *= x * x
1531 sign *= -1
1532 s += num / fact * sign
1533 getcontext().prec -= 2
1534 return +s
1535
1536
Georg Brandlb19be572007-12-29 10:57:00 +00001537.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001538
1539
1540.. _decimal-faq:
1541
1542Decimal FAQ
1543-----------
1544
1545Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1546minimize typing when using the interactive interpreter?
1547
Georg Brandl9f662322008-03-22 11:47:10 +00001548A. Some users abbreviate the constructor to just a single letter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001549
1550 >>> D = decimal.Decimal
1551 >>> D('1.23') + D('3.45')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001552 Decimal('4.68')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001553
1554Q. In a fixed-point application with two decimal places, some inputs have many
1555places and need to be rounded. Others are not supposed to have excess digits
1556and need to be validated. What methods should be used?
1557
1558A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Georg Brandl9f662322008-03-22 11:47:10 +00001559the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001560
1561 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1562
1563 >>> # Round to two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001564 >>> Decimal('3.214').quantize(TWOPLACES)
1565 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001566
1567 >>> # Validate that a number does not exceed two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001568 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1569 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001570
Raymond Hettingerabe32372008-02-14 02:41:22 +00001571 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001572 Traceback (most recent call last):
1573 ...
Georg Brandl9f662322008-03-22 11:47:10 +00001574 Inexact
Georg Brandl8ec7f652007-08-15 14:28:01 +00001575
1576Q. Once I have valid two place inputs, how do I maintain that invariant
1577throughout an application?
1578
Raymond Hettinger46314812008-02-14 10:46:57 +00001579A. Some operations like addition, subtraction, and multiplication by an integer
1580will automatically preserve fixed point. Others operations, like division and
1581non-integer multiplication, will change the number of decimal places and need to
Georg Brandl9f662322008-03-22 11:47:10 +00001582be followed-up with a :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001583
1584 >>> a = Decimal('102.72') # Initial fixed-point values
1585 >>> b = Decimal('3.17')
1586 >>> a + b # Addition preserves fixed-point
1587 Decimal('105.89')
1588 >>> a - b
1589 Decimal('99.55')
1590 >>> a * 42 # So does integer multiplication
1591 Decimal('4314.24')
1592 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1593 Decimal('325.62')
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001594 >>> (b / a).quantize(TWOPLACES) # And quantize division
Raymond Hettinger46314812008-02-14 10:46:57 +00001595 Decimal('0.03')
1596
1597In developing fixed-point applications, it is convenient to define functions
Georg Brandl9f662322008-03-22 11:47:10 +00001598to handle the :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001599
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001600 >>> def mul(x, y, fp=TWOPLACES):
1601 ... return (x * y).quantize(fp)
1602 >>> def div(x, y, fp=TWOPLACES):
1603 ... return (x / y).quantize(fp)
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001604
Raymond Hettinger46314812008-02-14 10:46:57 +00001605 >>> mul(a, b) # Automatically preserve fixed-point
1606 Decimal('325.62')
1607 >>> div(b, a)
1608 Decimal('0.03')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001609
1610Q. There are many ways to express the same value. The numbers :const:`200`,
1611:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1612various precisions. Is there a way to transform them to a single recognizable
1613canonical value?
1614
1615A. The :meth:`normalize` method maps all equivalent values to a single
Georg Brandl9f662322008-03-22 11:47:10 +00001616representative:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001617
1618 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1619 >>> [v.normalize() for v in values]
Raymond Hettingerabe32372008-02-14 02:41:22 +00001620 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001621
1622Q. Some decimal values always print with exponential notation. Is there a way
1623to get a non-exponential representation?
1624
1625A. For some values, exponential notation is the only way to express the number
1626of significant places in the coefficient. For example, expressing
1627:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1628original's two-place significance.
1629
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001630If an application does not care about tracking significance, it is easy to
Georg Brandl907a7202008-02-22 12:31:45 +00001631remove the exponent and trailing zeroes, losing significance, but keeping the
Georg Brandl9f662322008-03-22 11:47:10 +00001632value unchanged:
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001633
1634 >>> def remove_exponent(d):
1635 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1636
1637 >>> remove_exponent(Decimal('5E+3'))
1638 Decimal('5000')
1639
Georg Brandl8ec7f652007-08-15 14:28:01 +00001640Q. Is there a way to convert a regular float to a :class:`Decimal`?
1641
1642A. Yes, all binary floating point numbers can be exactly expressed as a
1643Decimal. An exact conversion may take more precision than intuition would
Georg Brandl9f662322008-03-22 11:47:10 +00001644suggest, so we trap :const:`Inexact` to signal a need for more precision:
1645
Georg Brandl838b4b02008-03-22 13:07:06 +00001646.. testcode::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001647
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001648 def float_to_decimal(f):
1649 "Convert a floating point number to a Decimal with no loss of information"
1650 n, d = f.as_integer_ratio()
1651 with localcontext() as ctx:
1652 ctx.traps[Inexact] = True
1653 while True:
1654 try:
1655 return Decimal(n) / Decimal(d)
1656 except Inexact:
1657 ctx.prec += 1
Georg Brandl8ec7f652007-08-15 14:28:01 +00001658
Georg Brandl838b4b02008-03-22 13:07:06 +00001659.. doctest::
Georg Brandl9f662322008-03-22 11:47:10 +00001660
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001661 >>> float_to_decimal(math.pi)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001662 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001663
Raymond Hettinger23bdcc92008-02-07 20:10:49 +00001664Q. Why isn't the :func:`float_to_decimal` routine included in the module?
Georg Brandl8ec7f652007-08-15 14:28:01 +00001665
1666A. There is some question about whether it is advisable to mix binary and
1667decimal floating point. Also, its use requires some care to avoid the
Georg Brandl9f662322008-03-22 11:47:10 +00001668representation issues associated with binary floating point:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001669
Raymond Hettinger23bdcc92008-02-07 20:10:49 +00001670 >>> float_to_decimal(1.1)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001671 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001672
1673Q. Within a complex calculation, how can I make sure that I haven't gotten a
1674spurious result because of insufficient precision or rounding anomalies.
1675
1676A. The decimal module makes it easy to test results. A best practice is to
1677re-run calculations using greater precision and with various rounding modes.
1678Widely differing results indicate insufficient precision, rounding mode issues,
1679ill-conditioned inputs, or a numerically unstable algorithm.
1680
1681Q. I noticed that context precision is applied to the results of operations but
1682not to the inputs. Is there anything to watch out for when mixing values of
1683different precisions?
1684
1685A. Yes. The principle is that all values are considered to be exact and so is
1686the arithmetic on those values. Only the results are rounded. The advantage
1687for inputs is that "what you type is what you get". A disadvantage is that the
Georg Brandl9f662322008-03-22 11:47:10 +00001688results can look odd if you forget that the inputs haven't been rounded:
1689
1690.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001691
1692 >>> getcontext().prec = 3
Georg Brandl9f662322008-03-22 11:47:10 +00001693 >>> Decimal('3.104') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001694 Decimal('5.21')
Georg Brandl9f662322008-03-22 11:47:10 +00001695 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001696 Decimal('5.20')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001697
1698The solution is either to increase precision or to force rounding of inputs
Georg Brandl9f662322008-03-22 11:47:10 +00001699using the unary plus operation:
1700
1701.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001702
1703 >>> getcontext().prec = 3
1704 >>> +Decimal('1.23456789') # unary plus triggers rounding
Raymond Hettingerabe32372008-02-14 02:41:22 +00001705 Decimal('1.23')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001706
1707Alternatively, inputs can be rounded upon creation using the
Georg Brandl9f662322008-03-22 11:47:10 +00001708:meth:`Context.create_decimal` method:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001709
1710 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001711 Decimal('1.2345')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001712