blob: 6e45e84721e14f3f0c0a083a4e9b93b19d2fd0b9 [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
Georg Brandl51b72162009-10-27 13:54:57 +0000111 Specification <http://speleotrove.com/decimal/>`_.
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
Facundo Batista8e1c52a2008-06-21 17:30:06 +0000143 >>> getcontext().prec = 28
Georg Brandl8ec7f652007-08-15 14:28:01 +0000144 >>> Decimal(10)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000145 Decimal('10')
146 >>> Decimal('3.14')
147 Decimal('3.14')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000148 >>> Decimal((0, (3, 1, 4), -2))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000149 Decimal('3.14')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150 >>> Decimal(str(2.0 ** 0.5))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000151 Decimal('1.41421356237')
152 >>> Decimal(2) ** Decimal('0.5')
153 Decimal('1.414213562373095048801688724')
154 >>> Decimal('NaN')
155 Decimal('NaN')
156 >>> Decimal('-Infinity')
157 Decimal('-Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000158
159The significance of a new Decimal is determined solely by the number of digits
160input. Context precision and rounding only come into play during arithmetic
Georg Brandl17baef02008-03-22 10:56:23 +0000161operations.
162
163.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +0000164
165 >>> getcontext().prec = 6
166 >>> Decimal('3.0')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000167 Decimal('3.0')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000168 >>> Decimal('3.1415926535')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000169 Decimal('3.1415926535')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000170 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000171 Decimal('5.85987')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000172 >>> getcontext().rounding = ROUND_UP
173 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000174 Decimal('5.85988')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000175
176Decimals interact well with much of the rest of Python. Here is a small decimal
Georg Brandl9f662322008-03-22 11:47:10 +0000177floating point flying circus:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000178
Georg Brandl838b4b02008-03-22 13:07:06 +0000179.. doctest::
180 :options: +NORMALIZE_WHITESPACE
181
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
183 >>> max(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000184 Decimal('9.25')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000185 >>> min(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000186 Decimal('0.03')
Georg Brandl838b4b02008-03-22 13:07:06 +0000187 >>> sorted(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000188 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
189 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000190 >>> sum(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000191 Decimal('19.29')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000192 >>> a,b,c = data[:3]
193 >>> str(a)
194 '1.34'
195 >>> float(a)
196 1.3400000000000001
197 >>> round(a, 1) # round() first converts to binary floating point
198 1.3
199 >>> int(a)
200 1
201 >>> a * 5
Raymond Hettingerabe32372008-02-14 02:41:22 +0000202 Decimal('6.70')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000203 >>> a * b
Raymond Hettingerabe32372008-02-14 02:41:22 +0000204 Decimal('2.5058')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000205 >>> c % a
Raymond Hettingerabe32372008-02-14 02:41:22 +0000206 Decimal('0.77')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000207
Georg Brandl9f662322008-03-22 11:47:10 +0000208And some mathematical functions are also available to Decimal:
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000209
Facundo Batista8e1c52a2008-06-21 17:30:06 +0000210 >>> getcontext().prec = 28
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000211 >>> Decimal(2).sqrt()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000212 Decimal('1.414213562373095048801688724')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000213 >>> Decimal(1).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000214 Decimal('2.718281828459045235360287471')
215 >>> Decimal('10').ln()
216 Decimal('2.302585092994045684017991455')
217 >>> Decimal('10').log10()
218 Decimal('1')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000219
Georg Brandl8ec7f652007-08-15 14:28:01 +0000220The :meth:`quantize` method rounds a number to a fixed exponent. This method is
221useful for monetary applications that often round results to a fixed number of
Georg Brandl9f662322008-03-22 11:47:10 +0000222places:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000223
224 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000225 Decimal('7.32')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000226 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000227 Decimal('8')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000228
229As shown above, the :func:`getcontext` function accesses the current context and
230allows the settings to be changed. This approach meets the needs of most
231applications.
232
233For more advanced work, it may be useful to create alternate contexts using the
234Context() constructor. To make an alternate active, use the :func:`setcontext`
235function.
236
237In accordance with the standard, the :mod:`Decimal` module provides two ready to
238use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
239former is especially useful for debugging because many of the traps are
Georg Brandl9f662322008-03-22 11:47:10 +0000240enabled:
241
242.. doctest:: newcontext
243 :options: +NORMALIZE_WHITESPACE
Georg Brandl8ec7f652007-08-15 14:28:01 +0000244
245 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
246 >>> setcontext(myothercontext)
247 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000248 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000249
250 >>> ExtendedContext
251 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
252 capitals=1, flags=[], traps=[])
253 >>> setcontext(ExtendedContext)
254 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000255 Decimal('0.142857143')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000256 >>> Decimal(42) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000257 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000258
259 >>> setcontext(BasicContext)
260 >>> Decimal(42) / Decimal(0)
261 Traceback (most recent call last):
262 File "<pyshell#143>", line 1, in -toplevel-
263 Decimal(42) / Decimal(0)
264 DivisionByZero: x / 0
265
266Contexts also have signal flags for monitoring exceptional conditions
267encountered during computations. The flags remain set until explicitly cleared,
268so it is best to clear the flags before each set of monitored computations by
269using the :meth:`clear_flags` method. ::
270
271 >>> setcontext(ExtendedContext)
272 >>> getcontext().clear_flags()
273 >>> Decimal(355) / Decimal(113)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000274 Decimal('3.14159292')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000275 >>> getcontext()
276 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Georg Brandl9f662322008-03-22 11:47:10 +0000277 capitals=1, flags=[Rounded, Inexact], traps=[])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000278
279The *flags* entry shows that the rational approximation to :const:`Pi` was
280rounded (digits beyond the context precision were thrown away) and that the
281result is inexact (some of the discarded digits were non-zero).
282
283Individual traps are set using the dictionary in the :attr:`traps` field of a
Georg Brandl9f662322008-03-22 11:47:10 +0000284context:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000285
Georg Brandl9f662322008-03-22 11:47:10 +0000286.. doctest:: newcontext
287
288 >>> setcontext(ExtendedContext)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000289 >>> Decimal(1) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000290 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000291 >>> getcontext().traps[DivisionByZero] = 1
292 >>> Decimal(1) / Decimal(0)
293 Traceback (most recent call last):
294 File "<pyshell#112>", line 1, in -toplevel-
295 Decimal(1) / Decimal(0)
296 DivisionByZero: x / 0
297
298Most programs adjust the current context only once, at the beginning of the
299program. And, in many applications, data is converted to :class:`Decimal` with
300a single cast inside a loop. With context set and decimals created, the bulk of
301the program manipulates the data no differently than with other Python numeric
302types.
303
Georg Brandlb19be572007-12-29 10:57:00 +0000304.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000305
306
307.. _decimal-decimal:
308
309Decimal objects
310---------------
311
312
313.. class:: Decimal([value [, context]])
314
Georg Brandlb19be572007-12-29 10:57:00 +0000315 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000316
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000317 *value* can be an integer, string, tuple, or another :class:`Decimal`
Raymond Hettingerabe32372008-02-14 02:41:22 +0000318 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000319 string, it should conform to the decimal numeric string syntax after leading
320 and trailing whitespace characters are removed::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000321
322 sign ::= '+' | '-'
323 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
324 indicator ::= 'e' | 'E'
325 digits ::= digit [digit]...
326 decimal-part ::= digits '.' [digits] | ['.'] digits
327 exponent-part ::= indicator [sign] digits
328 infinity ::= 'Infinity' | 'Inf'
329 nan ::= 'NaN' [digits] | 'sNaN' [digits]
330 numeric-value ::= decimal-part [exponent-part] | infinity
Georg Brandl734373c2009-01-03 21:55:17 +0000331 numeric-string ::= [sign] numeric-value | [sign] nan
Georg Brandl8ec7f652007-08-15 14:28:01 +0000332
Mark Dickinson9a6e6452009-08-02 11:01:01 +0000333 If *value* is a unicode string then other Unicode decimal digits
334 are also permitted where ``digit`` appears above. These include
335 decimal digits from various other alphabets (for example,
336 Arabic-Indic and Devanāgarī digits) along with the fullwidth digits
337 ``u'\uff10'`` through ``u'\uff19'``.
338
Georg Brandl8ec7f652007-08-15 14:28:01 +0000339 If *value* is a :class:`tuple`, it should have three components, a sign
340 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
341 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Raymond Hettingerabe32372008-02-14 02:41:22 +0000342 returns ``Decimal('1.414')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000343
344 The *context* precision does not affect how many digits are stored. That is
345 determined exclusively by the number of digits in *value*. For example,
Raymond Hettingerabe32372008-02-14 02:41:22 +0000346 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000347 only three.
348
349 The purpose of the *context* argument is determining what to do if *value* is a
350 malformed string. If the context traps :const:`InvalidOperation`, an exception
351 is raised; otherwise, the constructor returns a new Decimal with the value of
352 :const:`NaN`.
353
354 Once constructed, :class:`Decimal` objects are immutable.
355
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000356 .. versionchanged:: 2.6
357 leading and trailing whitespace characters are permitted when
358 creating a Decimal instance from a string.
359
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000360 Decimal floating point objects share many properties with the other built-in
361 numeric types such as :class:`float` and :class:`int`. All of the usual math
362 operations and special methods apply. Likewise, decimal objects can be
363 copied, pickled, printed, used as dictionary keys, used as set elements,
364 compared, sorted, and coerced to another type (such as :class:`float` or
365 :class:`long`).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000366
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000367 In addition to the standard numeric properties, decimal floating point
368 objects also have a number of specialized methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000369
370
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000371 .. method:: adjusted()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000372
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000373 Return the adjusted exponent after shifting out the coefficient's
374 rightmost digits until only the lead digit remains:
375 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
376 position of the most significant digit with respect to the decimal point.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000377
378
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000379 .. method:: as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000380
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000381 Return a :term:`named tuple` representation of the number:
382 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandle3c3db52008-01-11 09:55:53 +0000383
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000384 .. versionchanged:: 2.6
385 Use a named tuple.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000386
387
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000388 .. method:: canonical()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000389
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000390 Return the canonical encoding of the argument. Currently, the encoding of
391 a :class:`Decimal` instance is always canonical, so this operation returns
392 its argument unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000393
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000394 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000395
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000396 .. method:: compare(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000397
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000398 Compare the values of two Decimal instances. This operation behaves in
399 the same way as the usual comparison method :meth:`__cmp__`, except that
400 :meth:`compare` returns a Decimal instance rather than an integer, and if
401 either operand is a NaN then the result is a NaN::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000402
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000403 a or b is a NaN ==> Decimal('NaN')
404 a < b ==> Decimal('-1')
405 a == b ==> Decimal('0')
406 a > b ==> Decimal('1')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000407
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000408 .. method:: compare_signal(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000409
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000410 This operation is identical to the :meth:`compare` method, except that all
411 NaNs signal. That is, if neither operand is a signaling NaN then any
412 quiet NaN operand is treated as though it were a signaling NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000413
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000414 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000415
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000416 .. method:: compare_total(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000417
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000418 Compare two operands using their abstract representation rather than their
419 numerical value. Similar to the :meth:`compare` method, but the result
420 gives a total ordering on :class:`Decimal` instances. Two
421 :class:`Decimal` instances with the same numeric value but different
422 representations compare unequal in this ordering:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000423
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000424 >>> Decimal('12.0').compare_total(Decimal('12'))
425 Decimal('-1')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000426
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000427 Quiet and signaling NaNs are also included in the total ordering. The
428 result of this function is ``Decimal('0')`` if both operands have the same
429 representation, ``Decimal('-1')`` if the first operand is lower in the
430 total order than the second, and ``Decimal('1')`` if the first operand is
431 higher in the total order than the second operand. See the specification
432 for details of the total order.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000433
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000434 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000435
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000436 .. method:: compare_total_mag(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000437
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000438 Compare two operands using their abstract representation rather than their
439 value as in :meth:`compare_total`, but ignoring the sign of each operand.
440 ``x.compare_total_mag(y)`` is equivalent to
441 ``x.copy_abs().compare_total(y.copy_abs())``.
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
Facundo Batista8e1c52a2008-06-21 17:30:06 +0000445 .. method:: conjugate()
446
447 Just returns self, this method is only to comply with the Decimal
448 Specification.
449
450 .. versionadded:: 2.6
451
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000452 .. method:: copy_abs()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000453
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000454 Return the absolute value of the argument. This operation is unaffected
455 by the context and is quiet: no flags are changed and no rounding is
456 performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000457
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000458 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000459
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000460 .. method:: copy_negate()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000461
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000462 Return the negation of the argument. This operation is unaffected by the
463 context and is quiet: no flags are changed and no rounding is performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000464
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000465 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000466
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000467 .. method:: copy_sign(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000468
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000469 Return a copy of the first operand with the sign set to be the same as the
470 sign of the second operand. For example:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000471
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000472 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
473 Decimal('-2.3')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000474
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000475 This operation is unaffected by the context and is quiet: no flags are
476 changed and no rounding is performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000477
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000478 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000479
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000480 .. method:: exp([context])
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000481
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000482 Return the value of the (natural) exponential function ``e**x`` at the
483 given number. The result is correctly rounded using the
484 :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000485
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000486 >>> Decimal(1).exp()
487 Decimal('2.718281828459045235360287471')
488 >>> Decimal(321).exp()
489 Decimal('2.561702493119680037517373933E+139')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000490
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000491 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000492
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000493 .. method:: fma(other, third[, context])
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000494
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000495 Fused multiply-add. Return self*other+third with no rounding of the
496 intermediate product self*other.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000497
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000498 >>> Decimal(2).fma(3, 5)
499 Decimal('11')
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_canonical()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000504
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000505 Return :const:`True` if the argument is canonical and :const:`False`
506 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
507 this operation always returns :const:`True`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000508
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000509 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000510
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000511 .. method:: is_finite()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000512
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000513 Return :const:`True` if the argument is a finite number, and
514 :const:`False` if the argument is an infinity or a NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000515
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000516 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000517
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000518 .. method:: is_infinite()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000519
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000520 Return :const:`True` if the argument is either positive or negative
521 infinity and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000522
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000523 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000524
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000525 .. method:: is_nan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000526
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000527 Return :const:`True` if the argument is a (quiet or signaling) NaN and
528 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000529
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000530 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000531
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000532 .. method:: is_normal()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000533
Georg Brandl51b72162009-10-27 13:54:57 +0000534 Return :const:`True` if the argument is a *normal* finite non-zero
535 number with an adjusted exponent greater than or equal to *Emin*.
536 Return :const:`False` if the argument is zero, subnormal, infinite or a
537 NaN. Note, the term *normal* is used here in a different sense with
538 the :meth:`normalize` method which is used to create canonical values.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000539
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000540 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000541
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000542 .. method:: is_qnan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000543
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000544 Return :const:`True` if the argument is a quiet NaN, and
545 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000546
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000547 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000548
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000549 .. method:: is_signed()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000550
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000551 Return :const:`True` if the argument has a negative sign and
552 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000553
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000554 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000555
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000556 .. method:: is_snan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000557
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000558 Return :const:`True` if the argument is a signaling NaN and :const:`False`
559 otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000560
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000561 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000562
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000563 .. method:: is_subnormal()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000564
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000565 Return :const:`True` if the argument is subnormal, and :const:`False`
Georg Brandl51b72162009-10-27 13:54:57 +0000566 otherwise. A number is subnormal is if it is nonzero, finite, and has an
567 adjusted exponent less than *Emin*.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000568
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000569 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000570
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000571 .. method:: is_zero()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000572
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000573 Return :const:`True` if the argument is a (positive or negative) zero and
574 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000575
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000576 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000577
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000578 .. method:: ln([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000579
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000580 Return the natural (base e) logarithm of the operand. The result is
581 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000582
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000583 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000584
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000585 .. method:: log10([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000586
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000587 Return the base ten logarithm of the operand. The result is correctly
588 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000589
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000590 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000591
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000592 .. method:: logb([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000593
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000594 For a nonzero number, return the adjusted exponent of its operand as a
595 :class:`Decimal` instance. If the operand is a zero then
596 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
597 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
598 returned.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000599
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000600 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000601
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000602 .. method:: logical_and(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000603
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000604 :meth:`logical_and` is a logical operation which takes two *logical
605 operands* (see :ref:`logical_operands_label`). The result is the
606 digit-wise ``and`` of the two operands.
607
608 .. versionadded:: 2.6
609
610 .. method:: logical_invert(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000611
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000612 :meth:`logical_invert` is a logical operation. The argument must
613 be a *logical operand* (see :ref:`logical_operands_label`). The
614 result is the digit-wise inversion of the operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000615
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000616 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000617
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000618 .. method:: logical_or(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000619
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000620 :meth:`logical_or` is a logical operation which takes two *logical
621 operands* (see :ref:`logical_operands_label`). The result is the
622 digit-wise ``or`` of the two operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000623
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000624 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000625
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000626 .. method:: logical_xor(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000627
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000628 :meth:`logical_xor` is a logical operation which takes two *logical
629 operands* (see :ref:`logical_operands_label`). The result is the
630 digit-wise exclusive or of the two operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000631
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000632 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000633
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000634 .. method:: max(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000635
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000636 Like ``max(self, other)`` except that the context rounding rule is applied
637 before returning and that :const:`NaN` values are either signaled or
638 ignored (depending on the context and whether they are signaling or
639 quiet).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000640
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000641 .. method:: max_mag(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000642
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000643 Similar to the :meth:`max` method, but the comparison is done using the
644 absolute values of the operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000645
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000646 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000647
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000648 .. method:: min(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000649
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000650 Like ``min(self, other)`` except that the context rounding rule is applied
651 before returning and that :const:`NaN` values are either signaled or
652 ignored (depending on the context and whether they are signaling or
653 quiet).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000654
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000655 .. method:: min_mag(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000656
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000657 Similar to the :meth:`min` method, but the comparison is done using the
658 absolute values of the operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000659
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000660 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000661
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000662 .. method:: next_minus([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000663
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000664 Return the largest number representable in the given context (or in the
665 current thread's context if no context is given) that is smaller than the
666 given operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000667
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000668 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000669
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000670 .. method:: next_plus([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000671
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000672 Return the smallest number representable in the given context (or in the
673 current thread's context if no context is given) that is larger than the
674 given operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000675
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000676 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000677
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000678 .. method:: next_toward(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000679
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000680 If the two operands are unequal, return the number closest to the first
681 operand in the direction of the second operand. If both operands are
682 numerically equal, return a copy of the first operand with the sign set to
683 be the same as the sign of the second operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000684
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000685 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000686
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000687 .. method:: normalize([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000688
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000689 Normalize the number by stripping the rightmost trailing zeros and
690 converting any result equal to :const:`Decimal('0')` to
691 :const:`Decimal('0e0')`. Used for producing canonical values for members
692 of an equivalence class. For example, ``Decimal('32.100')`` and
693 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
694 ``Decimal('32.1')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000695
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000696 .. method:: number_class([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000697
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000698 Return a string describing the *class* of the operand. The returned value
699 is one of the following ten strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000700
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000701 * ``"-Infinity"``, indicating that the operand is negative infinity.
702 * ``"-Normal"``, indicating that the operand is a negative normal number.
703 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
704 * ``"-Zero"``, indicating that the operand is a negative zero.
705 * ``"+Zero"``, indicating that the operand is a positive zero.
706 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
707 * ``"+Normal"``, indicating that the operand is a positive normal number.
708 * ``"+Infinity"``, indicating that the operand is positive infinity.
709 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
710 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000711
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000712 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000713
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000714 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000715
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000716 Return a value equal to the first operand after rounding and having the
717 exponent of the second operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000718
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000719 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
720 Decimal('1.414')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000721
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000722 Unlike other operations, if the length of the coefficient after the
723 quantize operation would be greater than precision, then an
724 :const:`InvalidOperation` is signaled. This guarantees that, unless there
725 is an error condition, the quantized exponent is always equal to that of
726 the right-hand operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000727
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000728 Also unlike other operations, quantize never signals Underflow, even if
729 the result is subnormal and inexact.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000730
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000731 If the exponent of the second operand is larger than that of the first
732 then rounding may be necessary. In this case, the rounding mode is
733 determined by the ``rounding`` argument if given, else by the given
734 ``context`` argument; if neither argument is given the rounding mode of
735 the current thread's context is used.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000736
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000737 If *watchexp* is set (default), then an error is returned whenever the
738 resulting exponent is greater than :attr:`Emax` or less than
739 :attr:`Etiny`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000740
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000741 .. method:: radix()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000742
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000743 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
744 class does all its arithmetic. Included for compatibility with the
745 specification.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000746
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000747 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000748
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000749 .. method:: remainder_near(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000750
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000751 Compute the modulo as either a positive or negative value depending on
752 which is closest to zero. For instance, ``Decimal(10).remainder_near(6)``
753 returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000754
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000755 If both are equally close, the one chosen will have the same sign as
756 *self*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000757
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000758 .. method:: rotate(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000759
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000760 Return the result of rotating the digits of the first operand by an amount
761 specified by the second operand. The second operand must be an integer in
762 the range -precision through precision. The absolute value of the second
763 operand gives the number of places to rotate. If the second operand is
764 positive then rotation is to the left; otherwise rotation is to the right.
765 The coefficient of the first operand is padded on the left with zeros to
766 length precision if necessary. The sign and exponent of the first operand
767 are unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000768
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000769 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000770
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000771 .. method:: same_quantum(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000772
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000773 Test whether self and other have the same exponent or whether both are
774 :const:`NaN`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000775
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000776 .. method:: scaleb(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000777
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000778 Return the first operand with exponent adjusted by the second.
779 Equivalently, return the first operand multiplied by ``10**other``. The
780 second operand must be an integer.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000781
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000782 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000783
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000784 .. method:: shift(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000785
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000786 Return the result of shifting the digits of the first operand by an amount
787 specified by the second operand. The second operand must be an integer in
788 the range -precision through precision. The absolute value of the second
789 operand gives the number of places to shift. If the second operand is
790 positive then the shift is to the left; otherwise the shift is to the
791 right. Digits shifted into the coefficient are zeros. The sign and
792 exponent of the first operand are unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000793
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000794 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000795
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000796 .. method:: sqrt([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000797
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000798 Return the square root of the argument to full precision.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000799
800
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000801 .. method:: to_eng_string([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000802
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000803 Convert to an engineering-type string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000804
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000805 Engineering notation has an exponent which is a multiple of 3, so there
806 are up to 3 digits left of the decimal place. For example, converts
807 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000808
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000809 .. method:: to_integral([rounding[, context]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000810
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000811 Identical to the :meth:`to_integral_value` method. The ``to_integral``
812 name has been kept for compatibility with older versions.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000813
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000814 .. method:: to_integral_exact([rounding[, context]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000815
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000816 Round to the nearest integer, signaling :const:`Inexact` or
817 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
818 determined by the ``rounding`` parameter if given, else by the given
819 ``context``. If neither parameter is given then the rounding mode of the
820 current context is used.
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
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000824 .. method:: to_integral_value([rounding[, context]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000825
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000826 Round to the nearest integer without signaling :const:`Inexact` or
827 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
828 rounding method in either the supplied *context* or the current context.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000829
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000830 .. versionchanged:: 2.6
831 renamed from ``to_integral`` to ``to_integral_value``. The old name
832 remains valid for compatibility.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000833
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000834.. _logical_operands_label:
835
836Logical operands
837^^^^^^^^^^^^^^^^
838
839The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
840and :meth:`logical_xor` methods expect their arguments to be *logical
841operands*. A *logical operand* is a :class:`Decimal` instance whose
842exponent and sign are both zero, and whose digits are all either
843:const:`0` or :const:`1`.
844
Georg Brandlb19be572007-12-29 10:57:00 +0000845.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000846
847
848.. _decimal-context:
849
850Context objects
851---------------
852
853Contexts are environments for arithmetic operations. They govern precision, set
854rules for rounding, determine which signals are treated as exceptions, and limit
855the range for exponents.
856
857Each thread has its own current context which is accessed or changed using the
858:func:`getcontext` and :func:`setcontext` functions:
859
860
861.. function:: getcontext()
862
863 Return the current context for the active thread.
864
865
866.. function:: setcontext(c)
867
868 Set the current context for the active thread to *c*.
869
870Beginning with Python 2.5, you can also use the :keyword:`with` statement and
871the :func:`localcontext` function to temporarily change the active context.
872
873
874.. function:: localcontext([c])
875
876 Return a context manager that will set the current context for the active thread
877 to a copy of *c* on entry to the with-statement and restore the previous context
878 when exiting the with-statement. If no context is specified, a copy of the
879 current context is used.
880
881 .. versionadded:: 2.5
882
883 For example, the following code sets the current decimal precision to 42 places,
884 performs a calculation, and then automatically restores the previous context::
885
Georg Brandl8ec7f652007-08-15 14:28:01 +0000886 from decimal import localcontext
887
888 with localcontext() as ctx:
889 ctx.prec = 42 # Perform a high precision calculation
890 s = calculate_something()
891 s = +s # Round the final result back to the default precision
892
893New contexts can also be created using the :class:`Context` constructor
894described below. In addition, the module provides three pre-made contexts:
895
896
897.. class:: BasicContext
898
899 This is a standard context defined by the General Decimal Arithmetic
900 Specification. Precision is set to nine. Rounding is set to
901 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
902 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
903 :const:`Subnormal`.
904
905 Because many of the traps are enabled, this context is useful for debugging.
906
907
908.. class:: ExtendedContext
909
910 This is a standard context defined by the General Decimal Arithmetic
911 Specification. Precision is set to nine. Rounding is set to
912 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
913 exceptions are not raised during computations).
914
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000915 Because the traps are disabled, this context is useful for applications that
Georg Brandl8ec7f652007-08-15 14:28:01 +0000916 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
917 raising exceptions. This allows an application to complete a run in the
918 presence of conditions that would otherwise halt the program.
919
920
921.. class:: DefaultContext
922
923 This context is used by the :class:`Context` constructor as a prototype for new
924 contexts. Changing a field (such a precision) has the effect of changing the
925 default for new contexts creating by the :class:`Context` constructor.
926
927 This context is most useful in multi-threaded environments. Changing one of the
928 fields before threads are started has the effect of setting system-wide
929 defaults. Changing the fields after threads have started is not recommended as
930 it would require thread synchronization to prevent race conditions.
931
932 In single threaded environments, it is preferable to not use this context at
933 all. Instead, simply create contexts explicitly as described below.
934
935 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
936 for Overflow, InvalidOperation, and DivisionByZero.
937
938In addition to the three supplied contexts, new contexts can be created with the
939:class:`Context` constructor.
940
941
942.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
943
944 Creates a new context. If a field is not specified or is :const:`None`, the
945 default values are copied from the :const:`DefaultContext`. If the *flags*
946 field is not specified or is :const:`None`, all flags are cleared.
947
948 The *prec* field is a positive integer that sets the precision for arithmetic
949 operations in the context.
950
951 The *rounding* option is one of:
952
953 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
954 * :const:`ROUND_DOWN` (towards zero),
955 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
956 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
957 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
958 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
959 * :const:`ROUND_UP` (away from zero).
Georg Brandl734373c2009-01-03 21:55:17 +0000960 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000961 would have been 0 or 5; otherwise towards zero)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000962
963 The *traps* and *flags* fields list any signals to be set. Generally, new
964 contexts should only set traps and leave the flags clear.
965
966 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
967 for exponents.
968
969 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
970 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
971 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
972
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000973 .. versionchanged:: 2.6
974 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000975
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000976 The :class:`Context` class defines several general purpose methods as well as
977 a large number of methods for doing arithmetic directly in a given context.
978 In addition, for each of the :class:`Decimal` methods described above (with
979 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
980 a corresponding :class:`Context` method. For example, ``C.exp(x)`` is
981 equivalent to ``x.exp(context=C)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000982
983
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000984 .. method:: clear_flags()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000985
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000986 Resets all of the flags to :const:`0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000987
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000988 .. method:: copy()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000989
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000990 Return a duplicate of the context.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000991
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000992 .. method:: copy_decimal(num)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000993
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000994 Return a copy of the Decimal instance num.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000995
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000996 .. method:: create_decimal(num)
Georg Brandl9f662322008-03-22 11:47:10 +0000997
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000998 Creates a new Decimal instance from *num* but using *self* as
999 context. Unlike the :class:`Decimal` constructor, the context precision,
1000 rounding method, flags, and traps are applied to the conversion.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001001
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001002 This is useful because constants are often given to a greater precision
1003 than is needed by the application. Another benefit is that rounding
1004 immediately eliminates unintended effects from digits beyond the current
1005 precision. In the following example, using unrounded inputs means that
1006 adding zero to a sum can change the result:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001007
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001008 .. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001009
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001010 >>> getcontext().prec = 3
1011 >>> Decimal('3.4445') + Decimal('1.0023')
1012 Decimal('4.45')
1013 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1014 Decimal('4.44')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001015
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001016 This method implements the to-number operation of the IBM specification.
1017 If the argument is a string, no leading or trailing whitespace is
1018 permitted.
1019
1020 .. method:: Etiny()
1021
1022 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
1023 value for subnormal results. When underflow occurs, the exponent is set
1024 to :const:`Etiny`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001025
1026
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001027 .. method:: Etop()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001028
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001029 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001030
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001031 The usual approach to working with decimals is to create :class:`Decimal`
1032 instances and then apply arithmetic operations which take place within the
1033 current context for the active thread. An alternative approach is to use
1034 context methods for calculating within a specific context. The methods are
1035 similar to those for the :class:`Decimal` class and are only briefly
1036 recounted here.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001037
1038
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001039 .. method:: abs(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001040
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001041 Returns the absolute value of *x*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001042
1043
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001044 .. method:: add(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001045
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001046 Return the sum of *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001047
1048
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001049 .. method:: canonical(x)
1050
1051 Returns the same Decimal object *x*.
1052
1053
1054 .. method:: compare(x, y)
1055
1056 Compares *x* and *y* numerically.
1057
1058
1059 .. method:: compare_signal(x, y)
1060
1061 Compares the values of the two operands numerically.
1062
1063
1064 .. method:: compare_total(x, y)
1065
1066 Compares two operands using their abstract representation.
1067
1068
1069 .. method:: compare_total_mag(x, y)
1070
1071 Compares two operands using their abstract representation, ignoring sign.
1072
1073
1074 .. method:: copy_abs(x)
1075
1076 Returns a copy of *x* with the sign set to 0.
1077
1078
1079 .. method:: copy_negate(x)
1080
1081 Returns a copy of *x* with the sign inverted.
1082
1083
1084 .. method:: copy_sign(x, y)
1085
1086 Copies the sign from *y* to *x*.
1087
1088
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001089 .. method:: divide(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001090
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001091 Return *x* divided by *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001092
1093
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001094 .. method:: divide_int(x, y)
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001095
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001096 Return *x* divided by *y*, truncated to an integer.
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001097
1098
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001099 .. method:: divmod(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001100
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001101 Divides two numbers and returns the integer part of the result.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001102
1103
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001104 .. method:: exp(x)
1105
1106 Returns `e ** x`.
1107
1108
1109 .. method:: fma(x, y, z)
1110
1111 Returns *x* multiplied by *y*, plus *z*.
1112
1113
1114 .. method:: is_canonical(x)
1115
1116 Returns True if *x* is canonical; otherwise returns False.
1117
1118
1119 .. method:: is_finite(x)
1120
1121 Returns True if *x* is finite; otherwise returns False.
1122
1123
1124 .. method:: is_infinite(x)
1125
1126 Returns True if *x* is infinite; otherwise returns False.
1127
1128
1129 .. method:: is_nan(x)
1130
1131 Returns True if *x* is a qNaN or sNaN; otherwise returns False.
1132
1133
1134 .. method:: is_normal(x)
1135
1136 Returns True if *x* is a normal number; otherwise returns False.
1137
1138
1139 .. method:: is_qnan(x)
1140
1141 Returns True if *x* is a quiet NaN; otherwise returns False.
1142
1143
1144 .. method:: is_signed(x)
1145
1146 Returns True if *x* is negative; otherwise returns False.
1147
1148
1149 .. method:: is_snan(x)
1150
1151 Returns True if *x* is a signaling NaN; otherwise returns False.
1152
1153
1154 .. method:: is_subnormal(x)
1155
1156 Returns True if *x* is subnormal; otherwise returns False.
1157
1158
1159 .. method:: is_zero(x)
1160
1161 Returns True if *x* is a zero; otherwise returns False.
1162
1163
1164 .. method:: ln(x)
1165
1166 Returns the natural (base e) logarithm of *x*.
1167
1168
1169 .. method:: log10(x)
1170
1171 Returns the base 10 logarithm of *x*.
1172
1173
1174 .. method:: logb(x)
1175
1176 Returns the exponent of the magnitude of the operand's MSD.
1177
1178
1179 .. method:: logical_and(x, y)
1180
Georg Brandl734373c2009-01-03 21:55:17 +00001181 Applies the logical operation *and* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001182
1183
1184 .. method:: logical_invert(x)
1185
1186 Invert all the digits in *x*.
1187
1188
1189 .. method:: logical_or(x, y)
1190
Georg Brandl734373c2009-01-03 21:55:17 +00001191 Applies the logical operation *or* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001192
1193
1194 .. method:: logical_xor(x, y)
1195
Georg Brandl734373c2009-01-03 21:55:17 +00001196 Applies the logical operation *xor* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001197
1198
1199 .. method:: max(x, y)
1200
1201 Compares two values numerically and returns the maximum.
1202
1203
1204 .. method:: max_mag(x, y)
1205
1206 Compares the values numerically with their sign ignored.
1207
1208
1209 .. method:: min(x, y)
1210
1211 Compares two values numerically and returns the minimum.
1212
1213
1214 .. method:: min_mag(x, y)
1215
1216 Compares the values numerically with their sign ignored.
1217
1218
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001219 .. method:: minus(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001220
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001221 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001222
1223
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001224 .. method:: multiply(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001225
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001226 Return the product of *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001227
1228
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001229 .. method:: next_minus(x)
1230
1231 Returns the largest representable number smaller than *x*.
1232
1233
1234 .. method:: next_plus(x)
1235
1236 Returns the smallest representable number larger than *x*.
1237
1238
1239 .. method:: next_toward(x, y)
1240
1241 Returns the number closest to *x*, in direction towards *y*.
1242
1243
1244 .. method:: normalize(x)
1245
1246 Reduces *x* to its simplest form.
1247
1248
1249 .. method:: number_class(x)
1250
1251 Returns an indication of the class of *x*.
1252
1253
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001254 .. method:: plus(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001255
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001256 Plus corresponds to the unary prefix plus operator in Python. This
1257 operation applies the context precision and rounding, so it is *not* an
1258 identity operation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001259
1260
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001261 .. method:: power(x, y[, modulo])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001262
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001263 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001264
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001265 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1266 must be integral. The result will be inexact unless ``y`` is integral and
1267 the result is finite and can be expressed exactly in 'precision' digits.
1268 The result should always be correctly rounded, using the rounding mode of
1269 the current thread's context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001270
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001271 With three arguments, compute ``(x**y) % modulo``. For the three argument
1272 form, the following restrictions on the arguments hold:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001273
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001274 - all three arguments must be integral
1275 - ``y`` must be nonnegative
1276 - at least one of ``x`` or ``y`` must be nonzero
1277 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl8ec7f652007-08-15 14:28:01 +00001278
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001279 The result of ``Context.power(x, y, modulo)`` is identical to the result
1280 that would be obtained by computing ``(x**y) % modulo`` with unbounded
1281 precision, but is computed more efficiently. It is always exact.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001282
Georg Brandl734373c2009-01-03 21:55:17 +00001283 .. versionchanged:: 2.6
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001284 ``y`` may now be nonintegral in ``x**y``.
1285 Stricter requirements for the three-argument version.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001286
1287
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001288 .. method:: quantize(x, y)
1289
1290 Returns a value equal to *x* (rounded), having the exponent of *y*.
1291
1292
1293 .. method:: radix()
1294
1295 Just returns 10, as this is Decimal, :)
1296
1297
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001298 .. method:: remainder(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001299
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001300 Returns the remainder from integer division.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001301
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001302 The sign of the result, if non-zero, is the same as that of the original
1303 dividend.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001304
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001305 .. method:: remainder_near(x, y)
1306
Georg Brandl734373c2009-01-03 21:55:17 +00001307 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1308 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001309
1310
1311 .. method:: rotate(x, y)
1312
1313 Returns a rotated copy of *x*, *y* times.
1314
1315
1316 .. method:: same_quantum(x, y)
1317
1318 Returns True if the two operands have the same exponent.
1319
1320
1321 .. method:: scaleb (x, y)
1322
1323 Returns the first operand after adding the second value its exp.
1324
1325
1326 .. method:: shift(x, y)
1327
1328 Returns a shifted copy of *x*, *y* times.
1329
1330
1331 .. method:: sqrt(x)
1332
1333 Square root of a non-negative number to context precision.
1334
1335
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001336 .. method:: subtract(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001337
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001338 Return the difference between *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001339
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001340
1341 .. method:: to_eng_string(x)
1342
1343 Converts a number to a string, using scientific notation.
1344
1345
1346 .. method:: to_integral_exact(x)
1347
1348 Rounds to an integer.
1349
1350
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001351 .. method:: to_sci_string(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001352
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001353 Converts a number to a string using scientific notation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001354
Georg Brandlb19be572007-12-29 10:57:00 +00001355.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001356
1357
1358.. _decimal-signals:
1359
1360Signals
1361-------
1362
1363Signals represent conditions that arise during computation. Each corresponds to
1364one context flag and one context trap enabler.
1365
Mark Dickinson1840c1a2008-05-03 18:23:14 +00001366The context flag is set whenever the condition is encountered. After the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001367computation, flags may be checked for informational purposes (for instance, to
1368determine whether a computation was exact). After checking the flags, be sure to
1369clear all flags before starting the next computation.
1370
1371If the context's trap enabler is set for the signal, then the condition causes a
1372Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1373is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1374condition.
1375
1376
1377.. class:: Clamped
1378
1379 Altered an exponent to fit representation constraints.
1380
1381 Typically, clamping occurs when an exponent falls outside the context's
1382 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001383 fit by adding zeros to the coefficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001384
1385
1386.. class:: DecimalException
1387
1388 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1389
1390
1391.. class:: DivisionByZero
1392
1393 Signals the division of a non-infinite number by zero.
1394
1395 Can occur with division, modulo division, or when raising a number to a negative
1396 power. If this signal is not trapped, returns :const:`Infinity` or
1397 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1398
1399
1400.. class:: Inexact
1401
1402 Indicates that rounding occurred and the result is not exact.
1403
1404 Signals when non-zero digits were discarded during rounding. The rounded result
1405 is returned. The signal flag or trap is used to detect when results are
1406 inexact.
1407
1408
1409.. class:: InvalidOperation
1410
1411 An invalid operation was performed.
1412
1413 Indicates that an operation was requested that does not make sense. If not
1414 trapped, returns :const:`NaN`. Possible causes include::
1415
1416 Infinity - Infinity
1417 0 * Infinity
1418 Infinity / Infinity
1419 x % 0
1420 Infinity % x
1421 x._rescale( non-integer )
1422 sqrt(-x) and x > 0
1423 0 ** 0
1424 x ** (non-integer)
Georg Brandl734373c2009-01-03 21:55:17 +00001425 x ** Infinity
Georg Brandl8ec7f652007-08-15 14:28:01 +00001426
1427
1428.. class:: Overflow
1429
1430 Numerical overflow.
1431
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001432 Indicates the exponent is larger than :attr:`Emax` after rounding has
1433 occurred. If not trapped, the result depends on the rounding mode, either
1434 pulling inward to the largest representable finite number or rounding outward
1435 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1436 are also signaled.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001437
1438
1439.. class:: Rounded
1440
1441 Rounding occurred though possibly no information was lost.
1442
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001443 Signaled whenever rounding discards digits; even if those digits are zero
1444 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1445 the result unchanged. This signal is used to detect loss of significant
1446 digits.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001447
1448
1449.. class:: Subnormal
1450
1451 Exponent was lower than :attr:`Emin` prior to rounding.
1452
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001453 Occurs when an operation result is subnormal (the exponent is too small). If
1454 not trapped, returns the result unchanged.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001455
1456
1457.. class:: Underflow
1458
1459 Numerical underflow with result rounded to zero.
1460
1461 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1462 and :class:`Subnormal` are also signaled.
1463
1464The following table summarizes the hierarchy of signals::
1465
1466 exceptions.ArithmeticError(exceptions.StandardError)
1467 DecimalException
1468 Clamped
1469 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1470 Inexact
1471 Overflow(Inexact, Rounded)
1472 Underflow(Inexact, Rounded, Subnormal)
1473 InvalidOperation
1474 Rounded
1475 Subnormal
1476
Georg Brandlb19be572007-12-29 10:57:00 +00001477.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001478
1479
1480.. _decimal-notes:
1481
1482Floating Point Notes
1483--------------------
1484
1485
1486Mitigating round-off error with increased precision
1487^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1488
1489The use of decimal floating point eliminates decimal representation error
1490(making it possible to represent :const:`0.1` exactly); however, some operations
1491can still incur round-off error when non-zero digits exceed the fixed precision.
1492
1493The effects of round-off error can be amplified by the addition or subtraction
1494of nearly offsetting quantities resulting in loss of significance. Knuth
1495provides two instructive examples where rounded floating point arithmetic with
1496insufficient precision causes the breakdown of the associative and distributive
Georg Brandl9f662322008-03-22 11:47:10 +00001497properties of addition:
1498
1499.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001500
1501 # Examples from Seminumerical Algorithms, Section 4.2.2.
1502 >>> from decimal import Decimal, getcontext
1503 >>> getcontext().prec = 8
1504
1505 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1506 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001507 Decimal('9.5111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001508 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001509 Decimal('10')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001510
1511 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1512 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001513 Decimal('0.01')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001514 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001515 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001516
1517The :mod:`decimal` module makes it possible to restore the identities by
Georg Brandl9f662322008-03-22 11:47:10 +00001518expanding the precision sufficiently to avoid loss of significance:
1519
1520.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001521
1522 >>> getcontext().prec = 20
1523 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1524 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001525 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001526 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001527 Decimal('9.51111111')
Georg Brandl734373c2009-01-03 21:55:17 +00001528 >>>
Georg Brandl8ec7f652007-08-15 14:28:01 +00001529 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1530 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001531 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001532 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001533 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001534
1535
1536Special values
1537^^^^^^^^^^^^^^
1538
1539The number system for the :mod:`decimal` module provides special values
1540including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001541and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001542
1543Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1544they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1545not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1546can result from rounding beyond the limits of the largest representable number.
1547
1548The infinities are signed (affine) and can be used in arithmetic operations
1549where they get treated as very large, indeterminate numbers. For instance,
1550adding a constant to infinity gives another infinite result.
1551
1552Some operations are indeterminate and return :const:`NaN`, or if the
1553:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1554``0/0`` returns :const:`NaN` which means "not a number". This variety of
1555:const:`NaN` is quiet and, once created, will flow through other computations
1556always resulting in another :const:`NaN`. This behavior can be useful for a
1557series of computations that occasionally have missing inputs --- it allows the
1558calculation to proceed while flagging specific results as invalid.
1559
1560A variant is :const:`sNaN` which signals rather than remaining quiet after every
1561operation. This is a useful return value when an invalid result needs to
1562interrupt a calculation for special handling.
1563
Mark Dickinson2fc92632008-02-06 22:10:50 +00001564The behavior of Python's comparison operators can be a little surprising where a
1565:const:`NaN` is involved. A test for equality where one of the operands is a
1566quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1567``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
Mark Dickinsonbafa9422008-02-06 22:25:16 +00001568:const:`True`. An attempt to compare two Decimals using any of the ``<``,
Mark Dickinson00c2e652008-02-07 01:42:06 +00001569``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1570if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Mark Dickinson3a94ee02008-02-10 15:19:58 +00001571not trapped. Note that the General Decimal Arithmetic specification does not
Mark Dickinson00c2e652008-02-07 01:42:06 +00001572specify the behavior of direct comparisons; these rules for comparisons
1573involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1574section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
Mark Dickinson2fc92632008-02-06 22:10:50 +00001575and :meth:`compare-signal` methods instead.
1576
Georg Brandl8ec7f652007-08-15 14:28:01 +00001577The signed zeros can result from calculations that underflow. They keep the sign
1578that would have resulted if the calculation had been carried out to greater
1579precision. Since their magnitude is zero, both positive and negative zeros are
1580treated as equal and their sign is informational.
1581
1582In addition to the two signed zeros which are distinct yet equal, there are
1583various representations of zero with differing precisions yet equivalent in
1584value. This takes a bit of getting used to. For an eye accustomed to
1585normalized floating point representations, it is not immediately obvious that
Georg Brandl9f662322008-03-22 11:47:10 +00001586the following calculation returns a value equal to zero:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001587
1588 >>> 1 / Decimal('Infinity')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001589 Decimal('0E-1000000026')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001590
Georg Brandlb19be572007-12-29 10:57:00 +00001591.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001592
1593
1594.. _decimal-threads:
1595
1596Working with threads
1597--------------------
1598
1599The :func:`getcontext` function accesses a different :class:`Context` object for
1600each thread. Having separate thread contexts means that threads may make
1601changes (such as ``getcontext.prec=10``) without interfering with other threads.
1602
1603Likewise, the :func:`setcontext` function automatically assigns its target to
1604the current thread.
1605
1606If :func:`setcontext` has not been called before :func:`getcontext`, then
1607:func:`getcontext` will automatically create a new context for use in the
1608current thread.
1609
1610The new context is copied from a prototype context called *DefaultContext*. To
1611control the defaults so that each thread will use the same values throughout the
1612application, directly modify the *DefaultContext* object. This should be done
1613*before* any threads are started so that there won't be a race condition between
1614threads calling :func:`getcontext`. For example::
1615
1616 # Set applicationwide defaults for all threads about to be launched
1617 DefaultContext.prec = 12
1618 DefaultContext.rounding = ROUND_DOWN
1619 DefaultContext.traps = ExtendedContext.traps.copy()
1620 DefaultContext.traps[InvalidOperation] = 1
1621 setcontext(DefaultContext)
1622
1623 # Afterwards, the threads can be started
1624 t1.start()
1625 t2.start()
1626 t3.start()
1627 . . .
1628
Georg Brandlb19be572007-12-29 10:57:00 +00001629.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001630
1631
1632.. _decimal-recipes:
1633
1634Recipes
1635-------
1636
1637Here are a few recipes that serve as utility functions and that demonstrate ways
1638to work with the :class:`Decimal` class::
1639
1640 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1641 pos='', neg='-', trailneg=''):
1642 """Convert Decimal to a money formatted string.
1643
1644 places: required number of places after the decimal point
1645 curr: optional currency symbol before the sign (may be blank)
1646 sep: optional grouping separator (comma, period, space, or blank)
1647 dp: decimal point indicator (comma or period)
1648 only specify as blank when places is zero
1649 pos: optional sign for positive numbers: '+', space or blank
1650 neg: optional sign for negative numbers: '-', '(', space or blank
1651 trailneg:optional trailing minus indicator: '-', ')', space or blank
1652
1653 >>> d = Decimal('-1234567.8901')
1654 >>> moneyfmt(d, curr='$')
1655 '-$1,234,567.89'
1656 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1657 '1.234.568-'
1658 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1659 '($1,234,567.89)'
1660 >>> moneyfmt(Decimal(123456789), sep=' ')
1661 '123 456 789.00'
1662 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001663 '<0.02>'
Georg Brandl8ec7f652007-08-15 14:28:01 +00001664
1665 """
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001666 q = Decimal(10) ** -places # 2 places --> '0.01'
Georg Brandl734373c2009-01-03 21:55:17 +00001667 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001668 result = []
1669 digits = map(str, digits)
1670 build, next = result.append, digits.pop
1671 if sign:
1672 build(trailneg)
1673 for i in range(places):
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001674 build(next() if digits else '0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001675 build(dp)
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001676 if not digits:
1677 build('0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001678 i = 0
1679 while digits:
1680 build(next())
1681 i += 1
1682 if i == 3 and digits:
1683 i = 0
1684 build(sep)
1685 build(curr)
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001686 build(neg if sign else pos)
1687 return ''.join(reversed(result))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001688
1689 def pi():
1690 """Compute Pi to the current precision.
1691
1692 >>> print pi()
1693 3.141592653589793238462643383
1694
1695 """
1696 getcontext().prec += 2 # extra digits for intermediate steps
1697 three = Decimal(3) # substitute "three=3.0" for regular floats
1698 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1699 while s != lasts:
1700 lasts = s
1701 n, na = n+na, na+8
1702 d, da = d+da, da+32
1703 t = (t * n) / d
1704 s += t
1705 getcontext().prec -= 2
1706 return +s # unary plus applies the new precision
1707
1708 def exp(x):
1709 """Return e raised to the power of x. Result type matches input type.
1710
1711 >>> print exp(Decimal(1))
1712 2.718281828459045235360287471
1713 >>> print exp(Decimal(2))
1714 7.389056098930650227230427461
1715 >>> print exp(2.0)
1716 7.38905609893
1717 >>> print exp(2+0j)
1718 (7.38905609893+0j)
1719
1720 """
1721 getcontext().prec += 2
1722 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1723 while s != lasts:
Georg Brandl734373c2009-01-03 21:55:17 +00001724 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001725 i += 1
1726 fact *= i
Georg Brandl734373c2009-01-03 21:55:17 +00001727 num *= x
1728 s += num / fact
1729 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001730 return +s
1731
1732 def cos(x):
1733 """Return the cosine of x as measured in radians.
1734
1735 >>> print cos(Decimal('0.5'))
1736 0.8775825618903727161162815826
1737 >>> print cos(0.5)
1738 0.87758256189
1739 >>> print cos(0.5+0j)
1740 (0.87758256189+0j)
1741
1742 """
1743 getcontext().prec += 2
1744 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1745 while s != lasts:
Georg Brandl734373c2009-01-03 21:55:17 +00001746 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001747 i += 2
1748 fact *= i * (i-1)
1749 num *= x * x
1750 sign *= -1
Georg Brandl734373c2009-01-03 21:55:17 +00001751 s += num / fact * sign
1752 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001753 return +s
1754
1755 def sin(x):
1756 """Return the sine of x as measured in radians.
1757
1758 >>> print sin(Decimal('0.5'))
1759 0.4794255386042030002732879352
1760 >>> print sin(0.5)
1761 0.479425538604
1762 >>> print sin(0.5+0j)
1763 (0.479425538604+0j)
1764
1765 """
1766 getcontext().prec += 2
1767 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1768 while s != lasts:
Georg Brandl734373c2009-01-03 21:55:17 +00001769 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001770 i += 2
1771 fact *= i * (i-1)
1772 num *= x * x
1773 sign *= -1
Georg Brandl734373c2009-01-03 21:55:17 +00001774 s += num / fact * sign
1775 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001776 return +s
1777
1778
Georg Brandlb19be572007-12-29 10:57:00 +00001779.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001780
1781
1782.. _decimal-faq:
1783
1784Decimal FAQ
1785-----------
1786
1787Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1788minimize typing when using the interactive interpreter?
1789
Georg Brandl9f662322008-03-22 11:47:10 +00001790A. Some users abbreviate the constructor to just a single letter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001791
1792 >>> D = decimal.Decimal
1793 >>> D('1.23') + D('3.45')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001794 Decimal('4.68')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001795
1796Q. In a fixed-point application with two decimal places, some inputs have many
1797places and need to be rounded. Others are not supposed to have excess digits
1798and need to be validated. What methods should be used?
1799
1800A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Georg Brandl9f662322008-03-22 11:47:10 +00001801the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001802
1803 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1804
1805 >>> # Round to two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001806 >>> Decimal('3.214').quantize(TWOPLACES)
1807 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001808
Georg Brandl734373c2009-01-03 21:55:17 +00001809 >>> # Validate that a number does not exceed two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001810 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1811 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001812
Raymond Hettingerabe32372008-02-14 02:41:22 +00001813 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001814 Traceback (most recent call last):
1815 ...
Georg Brandl0b4d9452009-05-26 08:50:50 +00001816 Inexact: None
Georg Brandl8ec7f652007-08-15 14:28:01 +00001817
1818Q. Once I have valid two place inputs, how do I maintain that invariant
1819throughout an application?
1820
Raymond Hettinger46314812008-02-14 10:46:57 +00001821A. Some operations like addition, subtraction, and multiplication by an integer
1822will automatically preserve fixed point. Others operations, like division and
1823non-integer multiplication, will change the number of decimal places and need to
Georg Brandl9f662322008-03-22 11:47:10 +00001824be followed-up with a :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001825
1826 >>> a = Decimal('102.72') # Initial fixed-point values
1827 >>> b = Decimal('3.17')
1828 >>> a + b # Addition preserves fixed-point
1829 Decimal('105.89')
1830 >>> a - b
1831 Decimal('99.55')
1832 >>> a * 42 # So does integer multiplication
1833 Decimal('4314.24')
1834 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1835 Decimal('325.62')
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001836 >>> (b / a).quantize(TWOPLACES) # And quantize division
Raymond Hettinger46314812008-02-14 10:46:57 +00001837 Decimal('0.03')
1838
1839In developing fixed-point applications, it is convenient to define functions
Georg Brandl9f662322008-03-22 11:47:10 +00001840to handle the :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001841
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001842 >>> def mul(x, y, fp=TWOPLACES):
1843 ... return (x * y).quantize(fp)
1844 >>> def div(x, y, fp=TWOPLACES):
1845 ... return (x / y).quantize(fp)
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001846
Raymond Hettinger46314812008-02-14 10:46:57 +00001847 >>> mul(a, b) # Automatically preserve fixed-point
1848 Decimal('325.62')
1849 >>> div(b, a)
1850 Decimal('0.03')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001851
1852Q. There are many ways to express the same value. The numbers :const:`200`,
1853:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1854various precisions. Is there a way to transform them to a single recognizable
1855canonical value?
1856
1857A. The :meth:`normalize` method maps all equivalent values to a single
Georg Brandl9f662322008-03-22 11:47:10 +00001858representative:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001859
1860 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1861 >>> [v.normalize() for v in values]
Raymond Hettingerabe32372008-02-14 02:41:22 +00001862 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001863
1864Q. Some decimal values always print with exponential notation. Is there a way
1865to get a non-exponential representation?
1866
1867A. For some values, exponential notation is the only way to express the number
1868of significant places in the coefficient. For example, expressing
1869:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1870original's two-place significance.
1871
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001872If an application does not care about tracking significance, it is easy to
Georg Brandl907a7202008-02-22 12:31:45 +00001873remove the exponent and trailing zeroes, losing significance, but keeping the
Georg Brandl9f662322008-03-22 11:47:10 +00001874value unchanged:
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001875
1876 >>> def remove_exponent(d):
1877 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1878
1879 >>> remove_exponent(Decimal('5E+3'))
1880 Decimal('5000')
1881
Georg Brandl8ec7f652007-08-15 14:28:01 +00001882Q. Is there a way to convert a regular float to a :class:`Decimal`?
1883
1884A. Yes, all binary floating point numbers can be exactly expressed as a
1885Decimal. An exact conversion may take more precision than intuition would
Georg Brandl9f662322008-03-22 11:47:10 +00001886suggest, so we trap :const:`Inexact` to signal a need for more precision:
1887
Georg Brandl838b4b02008-03-22 13:07:06 +00001888.. testcode::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001889
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001890 def float_to_decimal(f):
1891 "Convert a floating point number to a Decimal with no loss of information"
1892 n, d = f.as_integer_ratio()
Raymond Hettingerb3833dd2009-01-03 07:46:36 +00001893 numerator, denominator = Decimal(n), Decimal(d)
1894 ctx = Context(prec=60)
1895 result = ctx.divide(numerator, denominator)
1896 while ctx.flags[Inexact]:
Raymond Hettingerc921dac2009-01-03 07:50:46 +00001897 ctx.flags[Inexact] = False
Raymond Hettingerb3833dd2009-01-03 07:46:36 +00001898 ctx.prec *= 2
1899 result = ctx.divide(numerator, denominator)
1900 return result
Georg Brandl8ec7f652007-08-15 14:28:01 +00001901
Georg Brandl838b4b02008-03-22 13:07:06 +00001902.. doctest::
Georg Brandl9f662322008-03-22 11:47:10 +00001903
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001904 >>> float_to_decimal(math.pi)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001905 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001906
Raymond Hettinger23bdcc92008-02-07 20:10:49 +00001907Q. Why isn't the :func:`float_to_decimal` routine included in the module?
Georg Brandl8ec7f652007-08-15 14:28:01 +00001908
1909A. There is some question about whether it is advisable to mix binary and
1910decimal floating point. Also, its use requires some care to avoid the
Georg Brandl9f662322008-03-22 11:47:10 +00001911representation issues associated with binary floating point:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001912
Raymond Hettinger23bdcc92008-02-07 20:10:49 +00001913 >>> float_to_decimal(1.1)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001914 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001915
1916Q. Within a complex calculation, how can I make sure that I haven't gotten a
1917spurious result because of insufficient precision or rounding anomalies.
1918
1919A. The decimal module makes it easy to test results. A best practice is to
1920re-run calculations using greater precision and with various rounding modes.
1921Widely differing results indicate insufficient precision, rounding mode issues,
1922ill-conditioned inputs, or a numerically unstable algorithm.
1923
1924Q. I noticed that context precision is applied to the results of operations but
1925not to the inputs. Is there anything to watch out for when mixing values of
1926different precisions?
1927
1928A. Yes. The principle is that all values are considered to be exact and so is
1929the arithmetic on those values. Only the results are rounded. The advantage
1930for inputs is that "what you type is what you get". A disadvantage is that the
Georg Brandl9f662322008-03-22 11:47:10 +00001931results can look odd if you forget that the inputs haven't been rounded:
1932
1933.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001934
1935 >>> getcontext().prec = 3
Georg Brandl9f662322008-03-22 11:47:10 +00001936 >>> Decimal('3.104') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001937 Decimal('5.21')
Georg Brandl9f662322008-03-22 11:47:10 +00001938 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001939 Decimal('5.20')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001940
1941The solution is either to increase precision or to force rounding of inputs
Georg Brandl9f662322008-03-22 11:47:10 +00001942using the unary plus operation:
1943
1944.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001945
1946 >>> getcontext().prec = 3
1947 >>> +Decimal('1.23456789') # unary plus triggers rounding
Raymond Hettingerabe32372008-02-14 02:41:22 +00001948 Decimal('1.23')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001949
1950Alternatively, inputs can be rounded upon creation using the
Georg Brandl9f662322008-03-22 11:47:10 +00001951:meth:`Context.create_decimal` method:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001952
1953 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001954 Decimal('1.2345')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001955