blob: 7c03b6a47c02be653ecafa202e567e58997d7805 [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
Mark Dickinson6b87f112009-11-24 14:27:02 +000038 :const:`1.1` and :const:`2.2` do not have an exact representations in binary
39 floating point. End users typically would not expect ``1.1 + 2.2`` to display
40 as :const:`3.3000000000000003` as it does with binary floating point.
Georg Brandl8ec7f652007-08-15 14:28:01 +000041
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
Raymond Hettingerf345a212009-03-10 01:07:30 +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)
Mark Dickinson6b87f112009-11-24 14:27:02 +0000196 1.34
Georg Brandl8ec7f652007-08-15 14:28:01 +0000197 >>> 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 Brandlc62ef8b2009-01-03 20:55:06 +0000331 numeric-string ::= [sign] numeric-value | [sign] nan
Georg Brandl8ec7f652007-08-15 14:28:01 +0000332
Mark Dickinson4326ad82009-08-02 10:59:36 +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
Mark Dickinson99d80962010-04-02 08:53:22 +0000367 Decimal objects cannot generally be combined with floats in
368 arithmetic operations: an attempt to add a :class:`Decimal` to a
369 :class:`float`, for example, will raise a :exc:`TypeError`.
370 There's one exception to this rule: it's possible to use Python's
371 comparison operators to compare a :class:`float` instance ``x``
372 with a :class:`Decimal` instance ``y``. Without this exception,
373 comparisons between :class:`Decimal` and :class:`float` instances
374 would follow the general rules for comparing objects of different
375 types described in the :ref:`expressions` section of the reference
376 manual, leading to confusing results.
377
378 .. versionchanged:: 2.7
379 A comparison between a :class:`float` instance ``x`` and a
380 :class:`Decimal` instance ``y`` now returns a result based on
381 the values of ``x`` and ``y``. In earlier versions ``x < y``
382 returned the same (arbitrary) result for any :class:`Decimal`
383 instance ``x`` and any :class:`float` instance ``y``.
384
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000385 In addition to the standard numeric properties, decimal floating point
386 objects also have a number of specialized methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000387
388
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000389 .. method:: adjusted()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000390
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000391 Return the adjusted exponent after shifting out the coefficient's
392 rightmost digits until only the lead digit remains:
393 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
394 position of the most significant digit with respect to the decimal point.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000395
396
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000397 .. method:: as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000398
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000399 Return a :term:`named tuple` representation of the number:
400 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandle3c3db52008-01-11 09:55:53 +0000401
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000402 .. versionchanged:: 2.6
403 Use a named tuple.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000404
405
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000406 .. method:: canonical()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000407
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000408 Return the canonical encoding of the argument. Currently, the encoding of
409 a :class:`Decimal` instance is always canonical, so this operation returns
410 its argument unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000411
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000412 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000413
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000414 .. method:: compare(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000415
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000416 Compare the values of two Decimal instances. This operation behaves in
417 the same way as the usual comparison method :meth:`__cmp__`, except that
418 :meth:`compare` returns a Decimal instance rather than an integer, and if
419 either operand is a NaN then the result is a NaN::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000420
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000421 a or b is a NaN ==> Decimal('NaN')
422 a < b ==> Decimal('-1')
423 a == b ==> Decimal('0')
424 a > b ==> Decimal('1')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000425
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000426 .. method:: compare_signal(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000427
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000428 This operation is identical to the :meth:`compare` method, except that all
429 NaNs signal. That is, if neither operand is a signaling NaN then any
430 quiet NaN operand is treated as though it were a signaling NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000431
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000432 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000433
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000434 .. method:: compare_total(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000435
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000436 Compare two operands using their abstract representation rather than their
437 numerical value. Similar to the :meth:`compare` method, but the result
438 gives a total ordering on :class:`Decimal` instances. Two
439 :class:`Decimal` instances with the same numeric value but different
440 representations compare unequal in this ordering:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000441
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000442 >>> Decimal('12.0').compare_total(Decimal('12'))
443 Decimal('-1')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000444
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000445 Quiet and signaling NaNs are also included in the total ordering. The
446 result of this function is ``Decimal('0')`` if both operands have the same
447 representation, ``Decimal('-1')`` if the first operand is lower in the
448 total order than the second, and ``Decimal('1')`` if the first operand is
449 higher in the total order than the second operand. See the specification
450 for details of the total order.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000451
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000452 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000453
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000454 .. method:: compare_total_mag(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000455
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000456 Compare two operands using their abstract representation rather than their
457 value as in :meth:`compare_total`, but ignoring the sign of each operand.
458 ``x.compare_total_mag(y)`` is equivalent to
459 ``x.copy_abs().compare_total(y.copy_abs())``.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000460
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000461 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000462
Facundo Batista8e1c52a2008-06-21 17:30:06 +0000463 .. method:: conjugate()
464
465 Just returns self, this method is only to comply with the Decimal
466 Specification.
467
468 .. versionadded:: 2.6
469
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000470 .. method:: copy_abs()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000471
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000472 Return the absolute value of the argument. This operation is unaffected
473 by the context and is quiet: no flags are changed and no rounding is
474 performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000475
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000476 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000477
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000478 .. method:: copy_negate()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000479
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000480 Return the negation of the argument. This operation is unaffected by the
481 context and is quiet: no flags are changed and no rounding is performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000482
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000483 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000484
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000485 .. method:: copy_sign(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000486
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000487 Return a copy of the first operand with the sign set to be the same as the
488 sign of the second operand. For example:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000489
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000490 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
491 Decimal('-2.3')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000492
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000493 This operation is unaffected by the context and is quiet: no flags are
494 changed and no rounding is performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000495
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000496 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000497
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000498 .. method:: exp([context])
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000499
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000500 Return the value of the (natural) exponential function ``e**x`` at the
501 given number. The result is correctly rounded using the
502 :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000503
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000504 >>> Decimal(1).exp()
505 Decimal('2.718281828459045235360287471')
506 >>> Decimal(321).exp()
507 Decimal('2.561702493119680037517373933E+139')
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
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000511 .. method:: from_float(f)
512
513 Classmethod that converts a float to a decimal number, exactly.
514
515 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
516 Since 0.1 is not exactly representable in binary floating point, the
517 value is stored as the nearest representable value which is
518 `0x1.999999999999ap-4`. That equivalent value in decimal is
519 `0.1000000000000000055511151231257827021181583404541015625`.
520
521 .. doctest::
522
523 >>> Decimal.from_float(0.1)
524 Decimal('0.1000000000000000055511151231257827021181583404541015625')
525 >>> Decimal.from_float(float('nan'))
526 Decimal('NaN')
527 >>> Decimal.from_float(float('inf'))
528 Decimal('Infinity')
529 >>> Decimal.from_float(float('-inf'))
530 Decimal('-Infinity')
531
532 .. versionadded:: 2.7
533
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000534 .. method:: fma(other, third[, context])
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000535
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000536 Fused multiply-add. Return self*other+third with no rounding of the
537 intermediate product self*other.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000538
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000539 >>> Decimal(2).fma(3, 5)
540 Decimal('11')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000541
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000542 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000543
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000544 .. method:: is_canonical()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000545
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000546 Return :const:`True` if the argument is canonical and :const:`False`
547 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
548 this operation always returns :const:`True`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000549
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000550 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000551
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000552 .. method:: is_finite()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000553
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000554 Return :const:`True` if the argument is a finite number, and
555 :const:`False` if the argument is an infinity or a NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000556
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000557 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000558
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000559 .. method:: is_infinite()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000560
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000561 Return :const:`True` if the argument is either positive or negative
562 infinity and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000563
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000564 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000565
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000566 .. method:: is_nan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000567
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000568 Return :const:`True` if the argument is a (quiet or signaling) NaN and
569 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000570
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000571 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000572
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000573 .. method:: is_normal()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000574
Raymond Hettingereecd1dc62009-03-10 04:40:24 +0000575 Return :const:`True` if the argument is a *normal* finite non-zero
576 number with an adjusted exponent greater than or equal to *Emin*.
577 Return :const:`False` if the argument is zero, subnormal, infinite or a
578 NaN. Note, the term *normal* is used here in a different sense with
579 the :meth:`normalize` method which is used to create canonical values.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000580
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000581 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000582
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000583 .. method:: is_qnan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000584
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000585 Return :const:`True` if the argument is a quiet NaN, and
586 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000587
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000588 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000589
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000590 .. method:: is_signed()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000591
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000592 Return :const:`True` if the argument has a negative sign and
593 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000594
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000595 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000596
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000597 .. method:: is_snan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000598
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000599 Return :const:`True` if the argument is a signaling NaN and :const:`False`
600 otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000601
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000602 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000603
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000604 .. method:: is_subnormal()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000605
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000606 Return :const:`True` if the argument is subnormal, and :const:`False`
Raymond Hettingereecd1dc62009-03-10 04:40:24 +0000607 otherwise. A number is subnormal is if it is nonzero, finite, and has an
608 adjusted exponent less than *Emin*.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000609
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000610 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000611
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000612 .. method:: is_zero()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000613
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000614 Return :const:`True` if the argument is a (positive or negative) zero and
615 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000616
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000617 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000618
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000619 .. method:: ln([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000620
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000621 Return the natural (base e) logarithm of the operand. The result is
622 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
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:: log10([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000627
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000628 Return the base ten logarithm of the operand. The result is correctly
629 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000630
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000631 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000632
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000633 .. method:: logb([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000634
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000635 For a nonzero number, return the adjusted exponent of its operand as a
636 :class:`Decimal` instance. If the operand is a zero then
637 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
638 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
639 returned.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000640
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000641 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000642
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000643 .. method:: logical_and(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000644
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000645 :meth:`logical_and` is a logical operation which takes two *logical
646 operands* (see :ref:`logical_operands_label`). The result is the
647 digit-wise ``and`` of the two operands.
648
649 .. versionadded:: 2.6
650
Georg Brandl3d5c87a2009-06-30 16:15:43 +0000651 .. method:: logical_invert([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000652
Georg Brandl3d5c87a2009-06-30 16:15:43 +0000653 :meth:`logical_invert` is a logical operation. The
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000654 result is the digit-wise inversion of the operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000655
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000656 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000657
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000658 .. method:: logical_or(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000659
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000660 :meth:`logical_or` is a logical operation which takes two *logical
661 operands* (see :ref:`logical_operands_label`). The result is the
662 digit-wise ``or`` of the two operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000663
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000664 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000665
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000666 .. method:: logical_xor(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000667
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000668 :meth:`logical_xor` is a logical operation which takes two *logical
669 operands* (see :ref:`logical_operands_label`). The result is the
670 digit-wise exclusive or of the two operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000671
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000672 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000673
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000674 .. method:: max(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000675
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000676 Like ``max(self, other)`` except that the context rounding rule is applied
677 before returning and that :const:`NaN` values are either signaled or
678 ignored (depending on the context and whether they are signaling or
679 quiet).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000680
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000681 .. method:: max_mag(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000682
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000683 Similar to the :meth:`.max` method, but the comparison is done using the
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000684 absolute values of the operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000685
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000686 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000687
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000688 .. method:: min(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000689
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000690 Like ``min(self, other)`` except that the context rounding rule is applied
691 before returning and that :const:`NaN` values are either signaled or
692 ignored (depending on the context and whether they are signaling or
693 quiet).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000694
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000695 .. method:: min_mag(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000696
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000697 Similar to the :meth:`.min` method, but the comparison is done using the
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000698 absolute values of the operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000699
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000700 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000701
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000702 .. method:: next_minus([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000703
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000704 Return the largest number representable in the given context (or in the
705 current thread's context if no context is given) that is smaller than the
706 given operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000707
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000708 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000709
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000710 .. method:: next_plus([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000711
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000712 Return the smallest number representable in the given context (or in the
713 current thread's context if no context is given) that is larger than the
714 given operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000715
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000716 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000717
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000718 .. method:: next_toward(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000719
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000720 If the two operands are unequal, return the number closest to the first
721 operand in the direction of the second operand. If both operands are
722 numerically equal, return a copy of the first operand with the sign set to
723 be the same as the sign of the second operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000724
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000725 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000726
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000727 .. method:: normalize([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000728
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000729 Normalize the number by stripping the rightmost trailing zeros and
730 converting any result equal to :const:`Decimal('0')` to
731 :const:`Decimal('0e0')`. Used for producing canonical values for members
732 of an equivalence class. For example, ``Decimal('32.100')`` and
733 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
734 ``Decimal('32.1')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000735
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000736 .. method:: number_class([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000737
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000738 Return a string describing the *class* of the operand. The returned value
739 is one of the following ten strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000740
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000741 * ``"-Infinity"``, indicating that the operand is negative infinity.
742 * ``"-Normal"``, indicating that the operand is a negative normal number.
743 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
744 * ``"-Zero"``, indicating that the operand is a negative zero.
745 * ``"+Zero"``, indicating that the operand is a positive zero.
746 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
747 * ``"+Normal"``, indicating that the operand is a positive normal number.
748 * ``"+Infinity"``, indicating that the operand is positive infinity.
749 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
750 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000752 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000753
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000754 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000755
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000756 Return a value equal to the first operand after rounding and having the
757 exponent of the second operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000758
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000759 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
760 Decimal('1.414')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000761
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000762 Unlike other operations, if the length of the coefficient after the
763 quantize operation would be greater than precision, then an
764 :const:`InvalidOperation` is signaled. This guarantees that, unless there
765 is an error condition, the quantized exponent is always equal to that of
766 the right-hand operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000767
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000768 Also unlike other operations, quantize never signals Underflow, even if
769 the result is subnormal and inexact.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000770
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000771 If the exponent of the second operand is larger than that of the first
772 then rounding may be necessary. In this case, the rounding mode is
773 determined by the ``rounding`` argument if given, else by the given
774 ``context`` argument; if neither argument is given the rounding mode of
775 the current thread's context is used.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000776
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000777 If *watchexp* is set (default), then an error is returned whenever the
778 resulting exponent is greater than :attr:`Emax` or less than
779 :attr:`Etiny`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000780
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000781 .. method:: radix()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000782
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000783 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
784 class does all its arithmetic. Included for compatibility with the
785 specification.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000786
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000787 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000788
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000789 .. method:: remainder_near(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000790
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000791 Compute the modulo as either a positive or negative value depending on
792 which is closest to zero. For instance, ``Decimal(10).remainder_near(6)``
793 returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000794
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000795 If both are equally close, the one chosen will have the same sign as
796 *self*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000797
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000798 .. method:: rotate(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000799
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000800 Return the result of rotating the digits of the first operand by an amount
801 specified by the second operand. The second operand must be an integer in
802 the range -precision through precision. The absolute value of the second
803 operand gives the number of places to rotate. If the second operand is
804 positive then rotation is to the left; otherwise rotation is to the right.
805 The coefficient of the first operand is padded on the left with zeros to
806 length precision if necessary. The sign and exponent of the first operand
807 are unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000808
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000809 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000810
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000811 .. method:: same_quantum(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000812
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000813 Test whether self and other have the same exponent or whether both are
814 :const:`NaN`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000815
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000816 .. method:: scaleb(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000817
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000818 Return the first operand with exponent adjusted by the second.
819 Equivalently, return the first operand multiplied by ``10**other``. The
820 second operand must be an integer.
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:: shift(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000825
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000826 Return the result of shifting the digits of the first operand by an amount
827 specified by the second operand. The second operand must be an integer in
828 the range -precision through precision. The absolute value of the second
829 operand gives the number of places to shift. If the second operand is
830 positive then the shift is to the left; otherwise the shift is to the
831 right. Digits shifted into the coefficient are zeros. The sign and
832 exponent of the first operand are unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000833
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000834 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000835
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000836 .. method:: sqrt([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000837
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000838 Return the square root of the argument to full precision.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000839
840
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000841 .. method:: to_eng_string([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000842
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000843 Convert to an engineering-type string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000844
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000845 Engineering notation has an exponent which is a multiple of 3, so there
846 are up to 3 digits left of the decimal place. For example, converts
847 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000848
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000849 .. method:: to_integral([rounding[, context]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000850
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000851 Identical to the :meth:`to_integral_value` method. The ``to_integral``
852 name has been kept for compatibility with older versions.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000853
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000854 .. method:: to_integral_exact([rounding[, context]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000855
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000856 Round to the nearest integer, signaling :const:`Inexact` or
857 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
858 determined by the ``rounding`` parameter if given, else by the given
859 ``context``. If neither parameter is given then the rounding mode of the
860 current context is used.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000861
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000862 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000863
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000864 .. method:: to_integral_value([rounding[, context]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000865
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000866 Round to the nearest integer without signaling :const:`Inexact` or
867 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
868 rounding method in either the supplied *context* or the current context.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000869
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000870 .. versionchanged:: 2.6
871 renamed from ``to_integral`` to ``to_integral_value``. The old name
872 remains valid for compatibility.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000873
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000874.. _logical_operands_label:
875
876Logical operands
877^^^^^^^^^^^^^^^^
878
879The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
880and :meth:`logical_xor` methods expect their arguments to be *logical
881operands*. A *logical operand* is a :class:`Decimal` instance whose
882exponent and sign are both zero, and whose digits are all either
883:const:`0` or :const:`1`.
884
Georg Brandlb19be572007-12-29 10:57:00 +0000885.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000886
887
888.. _decimal-context:
889
890Context objects
891---------------
892
893Contexts are environments for arithmetic operations. They govern precision, set
894rules for rounding, determine which signals are treated as exceptions, and limit
895the range for exponents.
896
897Each thread has its own current context which is accessed or changed using the
898:func:`getcontext` and :func:`setcontext` functions:
899
900
901.. function:: getcontext()
902
903 Return the current context for the active thread.
904
905
906.. function:: setcontext(c)
907
908 Set the current context for the active thread to *c*.
909
910Beginning with Python 2.5, you can also use the :keyword:`with` statement and
911the :func:`localcontext` function to temporarily change the active context.
912
913
914.. function:: localcontext([c])
915
916 Return a context manager that will set the current context for the active thread
917 to a copy of *c* on entry to the with-statement and restore the previous context
918 when exiting the with-statement. If no context is specified, a copy of the
919 current context is used.
920
921 .. versionadded:: 2.5
922
923 For example, the following code sets the current decimal precision to 42 places,
924 performs a calculation, and then automatically restores the previous context::
925
Georg Brandl8ec7f652007-08-15 14:28:01 +0000926 from decimal import localcontext
927
928 with localcontext() as ctx:
929 ctx.prec = 42 # Perform a high precision calculation
930 s = calculate_something()
931 s = +s # Round the final result back to the default precision
932
933New contexts can also be created using the :class:`Context` constructor
934described below. In addition, the module provides three pre-made contexts:
935
936
937.. class:: BasicContext
938
939 This is a standard context defined by the General Decimal Arithmetic
940 Specification. Precision is set to nine. Rounding is set to
941 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
942 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
943 :const:`Subnormal`.
944
945 Because many of the traps are enabled, this context is useful for debugging.
946
947
948.. class:: ExtendedContext
949
950 This is a standard context defined by the General Decimal Arithmetic
951 Specification. Precision is set to nine. Rounding is set to
952 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
953 exceptions are not raised during computations).
954
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000955 Because the traps are disabled, this context is useful for applications that
Georg Brandl8ec7f652007-08-15 14:28:01 +0000956 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
957 raising exceptions. This allows an application to complete a run in the
958 presence of conditions that would otherwise halt the program.
959
960
961.. class:: DefaultContext
962
963 This context is used by the :class:`Context` constructor as a prototype for new
964 contexts. Changing a field (such a precision) has the effect of changing the
965 default for new contexts creating by the :class:`Context` constructor.
966
967 This context is most useful in multi-threaded environments. Changing one of the
968 fields before threads are started has the effect of setting system-wide
969 defaults. Changing the fields after threads have started is not recommended as
970 it would require thread synchronization to prevent race conditions.
971
972 In single threaded environments, it is preferable to not use this context at
973 all. Instead, simply create contexts explicitly as described below.
974
975 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
976 for Overflow, InvalidOperation, and DivisionByZero.
977
978In addition to the three supplied contexts, new contexts can be created with the
979:class:`Context` constructor.
980
981
982.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
983
984 Creates a new context. If a field is not specified or is :const:`None`, the
985 default values are copied from the :const:`DefaultContext`. If the *flags*
986 field is not specified or is :const:`None`, all flags are cleared.
987
988 The *prec* field is a positive integer that sets the precision for arithmetic
989 operations in the context.
990
991 The *rounding* option is one of:
992
993 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
994 * :const:`ROUND_DOWN` (towards zero),
995 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
996 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
997 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
998 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
999 * :const:`ROUND_UP` (away from zero).
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001000 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001001 would have been 0 or 5; otherwise towards zero)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001002
1003 The *traps* and *flags* fields list any signals to be set. Generally, new
1004 contexts should only set traps and leave the flags clear.
1005
1006 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
1007 for exponents.
1008
1009 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
1010 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
1011 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
1012
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001013 .. versionchanged:: 2.6
1014 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001015
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001016 The :class:`Context` class defines several general purpose methods as well as
1017 a large number of methods for doing arithmetic directly in a given context.
1018 In addition, for each of the :class:`Decimal` methods described above (with
1019 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
Mark Dickinson6d8effb2010-02-18 14:27:02 +00001020 a corresponding :class:`Context` method. For example, for a :class:`Context`
1021 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
1022 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a
1023 Python integer (an instance of :class:`int` or :class:`long`) anywhere that a
1024 Decimal instance is accepted.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001025
1026
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001027 .. method:: clear_flags()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001028
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001029 Resets all of the flags to :const:`0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001030
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001031 .. method:: copy()
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001032
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001033 Return a duplicate of the context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001034
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001035 .. method:: copy_decimal(num)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001036
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001037 Return a copy of the Decimal instance num.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001038
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001039 .. method:: create_decimal(num)
Georg Brandl9f662322008-03-22 11:47:10 +00001040
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001041 Creates a new Decimal instance from *num* but using *self* as
1042 context. Unlike the :class:`Decimal` constructor, the context precision,
1043 rounding method, flags, and traps are applied to the conversion.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001044
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001045 This is useful because constants are often given to a greater precision
1046 than is needed by the application. Another benefit is that rounding
1047 immediately eliminates unintended effects from digits beyond the current
1048 precision. In the following example, using unrounded inputs means that
1049 adding zero to a sum can change the result:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001050
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001051 .. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001052
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001053 >>> getcontext().prec = 3
1054 >>> Decimal('3.4445') + Decimal('1.0023')
1055 Decimal('4.45')
1056 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1057 Decimal('4.44')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001058
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001059 This method implements the to-number operation of the IBM specification.
1060 If the argument is a string, no leading or trailing whitespace is
1061 permitted.
1062
Georg Brandlaa5bb322009-01-03 19:44:48 +00001063 .. method:: create_decimal_from_float(f)
Raymond Hettingerf4d85972009-01-03 19:02:23 +00001064
1065 Creates a new Decimal instance from a float *f* but rounding using *self*
Georg Brandla24067e2009-01-03 20:15:14 +00001066 as the context. Unlike the :meth:`Decimal.from_float` class method,
Raymond Hettingerf4d85972009-01-03 19:02:23 +00001067 the context precision, rounding method, flags, and traps are applied to
1068 the conversion.
1069
1070 .. doctest::
1071
Georg Brandlaa5bb322009-01-03 19:44:48 +00001072 >>> context = Context(prec=5, rounding=ROUND_DOWN)
1073 >>> context.create_decimal_from_float(math.pi)
1074 Decimal('3.1415')
1075 >>> context = Context(prec=5, traps=[Inexact])
1076 >>> context.create_decimal_from_float(math.pi)
1077 Traceback (most recent call last):
1078 ...
1079 Inexact: None
Raymond Hettingerf4d85972009-01-03 19:02:23 +00001080
1081 .. versionadded:: 2.7
1082
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001083 .. method:: Etiny()
1084
1085 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
1086 value for subnormal results. When underflow occurs, the exponent is set
1087 to :const:`Etiny`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001088
1089
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001090 .. method:: Etop()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001091
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001092 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001093
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001094 The usual approach to working with decimals is to create :class:`Decimal`
1095 instances and then apply arithmetic operations which take place within the
1096 current context for the active thread. An alternative approach is to use
1097 context methods for calculating within a specific context. The methods are
1098 similar to those for the :class:`Decimal` class and are only briefly
1099 recounted here.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001100
1101
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001102 .. method:: abs(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001103
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001104 Returns the absolute value of *x*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001105
1106
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001107 .. method:: add(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001108
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001109 Return the sum of *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001110
1111
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001112 .. method:: canonical(x)
1113
1114 Returns the same Decimal object *x*.
1115
1116
1117 .. method:: compare(x, y)
1118
1119 Compares *x* and *y* numerically.
1120
1121
1122 .. method:: compare_signal(x, y)
1123
1124 Compares the values of the two operands numerically.
1125
1126
1127 .. method:: compare_total(x, y)
1128
1129 Compares two operands using their abstract representation.
1130
1131
1132 .. method:: compare_total_mag(x, y)
1133
1134 Compares two operands using their abstract representation, ignoring sign.
1135
1136
1137 .. method:: copy_abs(x)
1138
1139 Returns a copy of *x* with the sign set to 0.
1140
1141
1142 .. method:: copy_negate(x)
1143
1144 Returns a copy of *x* with the sign inverted.
1145
1146
1147 .. method:: copy_sign(x, y)
1148
1149 Copies the sign from *y* to *x*.
1150
1151
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001152 .. method:: divide(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001153
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001154 Return *x* divided by *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001155
1156
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001157 .. method:: divide_int(x, y)
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001158
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001159 Return *x* divided by *y*, truncated to an integer.
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001160
1161
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001162 .. method:: divmod(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001163
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001164 Divides two numbers and returns the integer part of the result.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001165
1166
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001167 .. method:: exp(x)
1168
1169 Returns `e ** x`.
1170
1171
1172 .. method:: fma(x, y, z)
1173
1174 Returns *x* multiplied by *y*, plus *z*.
1175
1176
1177 .. method:: is_canonical(x)
1178
1179 Returns True if *x* is canonical; otherwise returns False.
1180
1181
1182 .. method:: is_finite(x)
1183
1184 Returns True if *x* is finite; otherwise returns False.
1185
1186
1187 .. method:: is_infinite(x)
1188
1189 Returns True if *x* is infinite; otherwise returns False.
1190
1191
1192 .. method:: is_nan(x)
1193
1194 Returns True if *x* is a qNaN or sNaN; otherwise returns False.
1195
1196
1197 .. method:: is_normal(x)
1198
1199 Returns True if *x* is a normal number; otherwise returns False.
1200
1201
1202 .. method:: is_qnan(x)
1203
1204 Returns True if *x* is a quiet NaN; otherwise returns False.
1205
1206
1207 .. method:: is_signed(x)
1208
1209 Returns True if *x* is negative; otherwise returns False.
1210
1211
1212 .. method:: is_snan(x)
1213
1214 Returns True if *x* is a signaling NaN; otherwise returns False.
1215
1216
1217 .. method:: is_subnormal(x)
1218
1219 Returns True if *x* is subnormal; otherwise returns False.
1220
1221
1222 .. method:: is_zero(x)
1223
1224 Returns True if *x* is a zero; otherwise returns False.
1225
1226
1227 .. method:: ln(x)
1228
1229 Returns the natural (base e) logarithm of *x*.
1230
1231
1232 .. method:: log10(x)
1233
1234 Returns the base 10 logarithm of *x*.
1235
1236
1237 .. method:: logb(x)
1238
1239 Returns the exponent of the magnitude of the operand's MSD.
1240
1241
1242 .. method:: logical_and(x, y)
1243
Georg Brandle92818f2009-01-03 20:47:01 +00001244 Applies the logical operation *and* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001245
1246
1247 .. method:: logical_invert(x)
1248
1249 Invert all the digits in *x*.
1250
1251
1252 .. method:: logical_or(x, y)
1253
Georg Brandle92818f2009-01-03 20:47:01 +00001254 Applies the logical operation *or* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001255
1256
1257 .. method:: logical_xor(x, y)
1258
Georg Brandle92818f2009-01-03 20:47:01 +00001259 Applies the logical operation *xor* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001260
1261
1262 .. method:: max(x, y)
1263
1264 Compares two values numerically and returns the maximum.
1265
1266
1267 .. method:: max_mag(x, y)
1268
1269 Compares the values numerically with their sign ignored.
1270
1271
1272 .. method:: min(x, y)
1273
1274 Compares two values numerically and returns the minimum.
1275
1276
1277 .. method:: min_mag(x, y)
1278
1279 Compares the values numerically with their sign ignored.
1280
1281
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001282 .. method:: minus(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001283
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001284 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001285
1286
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001287 .. method:: multiply(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001288
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001289 Return the product of *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001290
1291
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001292 .. method:: next_minus(x)
1293
1294 Returns the largest representable number smaller than *x*.
1295
1296
1297 .. method:: next_plus(x)
1298
1299 Returns the smallest representable number larger than *x*.
1300
1301
1302 .. method:: next_toward(x, y)
1303
1304 Returns the number closest to *x*, in direction towards *y*.
1305
1306
1307 .. method:: normalize(x)
1308
1309 Reduces *x* to its simplest form.
1310
1311
1312 .. method:: number_class(x)
1313
1314 Returns an indication of the class of *x*.
1315
1316
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001317 .. method:: plus(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001318
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001319 Plus corresponds to the unary prefix plus operator in Python. This
1320 operation applies the context precision and rounding, so it is *not* an
1321 identity operation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001322
1323
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001324 .. method:: power(x, y[, modulo])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001325
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001326 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001327
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001328 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1329 must be integral. The result will be inexact unless ``y`` is integral and
1330 the result is finite and can be expressed exactly in 'precision' digits.
1331 The result should always be correctly rounded, using the rounding mode of
1332 the current thread's context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001333
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001334 With three arguments, compute ``(x**y) % modulo``. For the three argument
1335 form, the following restrictions on the arguments hold:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001336
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001337 - all three arguments must be integral
1338 - ``y`` must be nonnegative
1339 - at least one of ``x`` or ``y`` must be nonzero
1340 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl8ec7f652007-08-15 14:28:01 +00001341
Mark Dickinsonf5be4e62010-02-22 15:40:28 +00001342 The value resulting from ``Context.power(x, y, modulo)`` is
1343 equal to the value that would be obtained by computing ``(x**y)
1344 % modulo`` with unbounded precision, but is computed more
1345 efficiently. The exponent of the result is zero, regardless of
1346 the exponents of ``x``, ``y`` and ``modulo``. The result is
1347 always exact.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001348
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001349 .. versionchanged:: 2.6
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001350 ``y`` may now be nonintegral in ``x**y``.
1351 Stricter requirements for the three-argument version.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001352
1353
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001354 .. method:: quantize(x, y)
1355
1356 Returns a value equal to *x* (rounded), having the exponent of *y*.
1357
1358
1359 .. method:: radix()
1360
1361 Just returns 10, as this is Decimal, :)
1362
1363
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001364 .. method:: remainder(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001365
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001366 Returns the remainder from integer division.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001367
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001368 The sign of the result, if non-zero, is the same as that of the original
1369 dividend.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001370
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001371 .. method:: remainder_near(x, y)
1372
Georg Brandle92818f2009-01-03 20:47:01 +00001373 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1374 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001375
1376
1377 .. method:: rotate(x, y)
1378
1379 Returns a rotated copy of *x*, *y* times.
1380
1381
1382 .. method:: same_quantum(x, y)
1383
1384 Returns True if the two operands have the same exponent.
1385
1386
1387 .. method:: scaleb (x, y)
1388
1389 Returns the first operand after adding the second value its exp.
1390
1391
1392 .. method:: shift(x, y)
1393
1394 Returns a shifted copy of *x*, *y* times.
1395
1396
1397 .. method:: sqrt(x)
1398
1399 Square root of a non-negative number to context precision.
1400
1401
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001402 .. method:: subtract(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001403
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001404 Return the difference between *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001405
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001406
1407 .. method:: to_eng_string(x)
1408
1409 Converts a number to a string, using scientific notation.
1410
1411
1412 .. method:: to_integral_exact(x)
1413
1414 Rounds to an integer.
1415
1416
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001417 .. method:: to_sci_string(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001418
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001419 Converts a number to a string using scientific notation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001420
Georg Brandlb19be572007-12-29 10:57:00 +00001421.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001422
1423
1424.. _decimal-signals:
1425
1426Signals
1427-------
1428
1429Signals represent conditions that arise during computation. Each corresponds to
1430one context flag and one context trap enabler.
1431
Mark Dickinson1840c1a2008-05-03 18:23:14 +00001432The context flag is set whenever the condition is encountered. After the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001433computation, flags may be checked for informational purposes (for instance, to
1434determine whether a computation was exact). After checking the flags, be sure to
1435clear all flags before starting the next computation.
1436
1437If the context's trap enabler is set for the signal, then the condition causes a
1438Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1439is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1440condition.
1441
1442
1443.. class:: Clamped
1444
1445 Altered an exponent to fit representation constraints.
1446
1447 Typically, clamping occurs when an exponent falls outside the context's
1448 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001449 fit by adding zeros to the coefficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001450
1451
1452.. class:: DecimalException
1453
1454 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1455
1456
1457.. class:: DivisionByZero
1458
1459 Signals the division of a non-infinite number by zero.
1460
1461 Can occur with division, modulo division, or when raising a number to a negative
1462 power. If this signal is not trapped, returns :const:`Infinity` or
1463 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1464
1465
1466.. class:: Inexact
1467
1468 Indicates that rounding occurred and the result is not exact.
1469
1470 Signals when non-zero digits were discarded during rounding. The rounded result
1471 is returned. The signal flag or trap is used to detect when results are
1472 inexact.
1473
1474
1475.. class:: InvalidOperation
1476
1477 An invalid operation was performed.
1478
1479 Indicates that an operation was requested that does not make sense. If not
1480 trapped, returns :const:`NaN`. Possible causes include::
1481
1482 Infinity - Infinity
1483 0 * Infinity
1484 Infinity / Infinity
1485 x % 0
1486 Infinity % x
1487 x._rescale( non-integer )
1488 sqrt(-x) and x > 0
1489 0 ** 0
1490 x ** (non-integer)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001491 x ** Infinity
Georg Brandl8ec7f652007-08-15 14:28:01 +00001492
1493
1494.. class:: Overflow
1495
1496 Numerical overflow.
1497
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001498 Indicates the exponent is larger than :attr:`Emax` after rounding has
1499 occurred. If not trapped, the result depends on the rounding mode, either
1500 pulling inward to the largest representable finite number or rounding outward
1501 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1502 are also signaled.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001503
1504
1505.. class:: Rounded
1506
1507 Rounding occurred though possibly no information was lost.
1508
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001509 Signaled whenever rounding discards digits; even if those digits are zero
1510 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1511 the result unchanged. This signal is used to detect loss of significant
1512 digits.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001513
1514
1515.. class:: Subnormal
1516
1517 Exponent was lower than :attr:`Emin` prior to rounding.
1518
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001519 Occurs when an operation result is subnormal (the exponent is too small). If
1520 not trapped, returns the result unchanged.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001521
1522
1523.. class:: Underflow
1524
1525 Numerical underflow with result rounded to zero.
1526
1527 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1528 and :class:`Subnormal` are also signaled.
1529
1530The following table summarizes the hierarchy of signals::
1531
1532 exceptions.ArithmeticError(exceptions.StandardError)
1533 DecimalException
1534 Clamped
1535 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1536 Inexact
1537 Overflow(Inexact, Rounded)
1538 Underflow(Inexact, Rounded, Subnormal)
1539 InvalidOperation
1540 Rounded
1541 Subnormal
1542
Georg Brandlb19be572007-12-29 10:57:00 +00001543.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001544
1545
1546.. _decimal-notes:
1547
1548Floating Point Notes
1549--------------------
1550
1551
1552Mitigating round-off error with increased precision
1553^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1554
1555The use of decimal floating point eliminates decimal representation error
1556(making it possible to represent :const:`0.1` exactly); however, some operations
1557can still incur round-off error when non-zero digits exceed the fixed precision.
1558
1559The effects of round-off error can be amplified by the addition or subtraction
1560of nearly offsetting quantities resulting in loss of significance. Knuth
1561provides two instructive examples where rounded floating point arithmetic with
1562insufficient precision causes the breakdown of the associative and distributive
Georg Brandl9f662322008-03-22 11:47:10 +00001563properties of addition:
1564
1565.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001566
1567 # Examples from Seminumerical Algorithms, Section 4.2.2.
1568 >>> from decimal import Decimal, getcontext
1569 >>> getcontext().prec = 8
1570
1571 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1572 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001573 Decimal('9.5111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001574 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001575 Decimal('10')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001576
1577 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1578 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001579 Decimal('0.01')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001580 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001581 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001582
1583The :mod:`decimal` module makes it possible to restore the identities by
Georg Brandl9f662322008-03-22 11:47:10 +00001584expanding the precision sufficiently to avoid loss of significance:
1585
1586.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001587
1588 >>> getcontext().prec = 20
1589 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1590 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001591 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001592 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001593 Decimal('9.51111111')
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001594 >>>
Georg Brandl8ec7f652007-08-15 14:28:01 +00001595 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1596 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001597 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001598 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001599 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001600
1601
1602Special values
1603^^^^^^^^^^^^^^
1604
1605The number system for the :mod:`decimal` module provides special values
1606including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001607and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001608
1609Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1610they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1611not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1612can result from rounding beyond the limits of the largest representable number.
1613
1614The infinities are signed (affine) and can be used in arithmetic operations
1615where they get treated as very large, indeterminate numbers. For instance,
1616adding a constant to infinity gives another infinite result.
1617
1618Some operations are indeterminate and return :const:`NaN`, or if the
1619:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1620``0/0`` returns :const:`NaN` which means "not a number". This variety of
1621:const:`NaN` is quiet and, once created, will flow through other computations
1622always resulting in another :const:`NaN`. This behavior can be useful for a
1623series of computations that occasionally have missing inputs --- it allows the
1624calculation to proceed while flagging specific results as invalid.
1625
1626A variant is :const:`sNaN` which signals rather than remaining quiet after every
1627operation. This is a useful return value when an invalid result needs to
1628interrupt a calculation for special handling.
1629
Mark Dickinson2fc92632008-02-06 22:10:50 +00001630The behavior of Python's comparison operators can be a little surprising where a
1631:const:`NaN` is involved. A test for equality where one of the operands is a
1632quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1633``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
Mark Dickinsonbafa9422008-02-06 22:25:16 +00001634:const:`True`. An attempt to compare two Decimals using any of the ``<``,
Mark Dickinson00c2e652008-02-07 01:42:06 +00001635``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1636if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Mark Dickinson3a94ee02008-02-10 15:19:58 +00001637not trapped. Note that the General Decimal Arithmetic specification does not
Mark Dickinson00c2e652008-02-07 01:42:06 +00001638specify the behavior of direct comparisons; these rules for comparisons
1639involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1640section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
Mark Dickinson2fc92632008-02-06 22:10:50 +00001641and :meth:`compare-signal` methods instead.
1642
Georg Brandl8ec7f652007-08-15 14:28:01 +00001643The signed zeros can result from calculations that underflow. They keep the sign
1644that would have resulted if the calculation had been carried out to greater
1645precision. Since their magnitude is zero, both positive and negative zeros are
1646treated as equal and their sign is informational.
1647
1648In addition to the two signed zeros which are distinct yet equal, there are
1649various representations of zero with differing precisions yet equivalent in
1650value. This takes a bit of getting used to. For an eye accustomed to
1651normalized floating point representations, it is not immediately obvious that
Georg Brandl9f662322008-03-22 11:47:10 +00001652the following calculation returns a value equal to zero:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001653
1654 >>> 1 / Decimal('Infinity')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001655 Decimal('0E-1000000026')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001656
Georg Brandlb19be572007-12-29 10:57:00 +00001657.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001658
1659
1660.. _decimal-threads:
1661
1662Working with threads
1663--------------------
1664
1665The :func:`getcontext` function accesses a different :class:`Context` object for
1666each thread. Having separate thread contexts means that threads may make
1667changes (such as ``getcontext.prec=10``) without interfering with other threads.
1668
1669Likewise, the :func:`setcontext` function automatically assigns its target to
1670the current thread.
1671
1672If :func:`setcontext` has not been called before :func:`getcontext`, then
1673:func:`getcontext` will automatically create a new context for use in the
1674current thread.
1675
1676The new context is copied from a prototype context called *DefaultContext*. To
1677control the defaults so that each thread will use the same values throughout the
1678application, directly modify the *DefaultContext* object. This should be done
1679*before* any threads are started so that there won't be a race condition between
1680threads calling :func:`getcontext`. For example::
1681
1682 # Set applicationwide defaults for all threads about to be launched
1683 DefaultContext.prec = 12
1684 DefaultContext.rounding = ROUND_DOWN
1685 DefaultContext.traps = ExtendedContext.traps.copy()
1686 DefaultContext.traps[InvalidOperation] = 1
1687 setcontext(DefaultContext)
1688
1689 # Afterwards, the threads can be started
1690 t1.start()
1691 t2.start()
1692 t3.start()
1693 . . .
1694
Georg Brandlb19be572007-12-29 10:57:00 +00001695.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001696
1697
1698.. _decimal-recipes:
1699
1700Recipes
1701-------
1702
1703Here are a few recipes that serve as utility functions and that demonstrate ways
1704to work with the :class:`Decimal` class::
1705
1706 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1707 pos='', neg='-', trailneg=''):
1708 """Convert Decimal to a money formatted string.
1709
1710 places: required number of places after the decimal point
1711 curr: optional currency symbol before the sign (may be blank)
1712 sep: optional grouping separator (comma, period, space, or blank)
1713 dp: decimal point indicator (comma or period)
1714 only specify as blank when places is zero
1715 pos: optional sign for positive numbers: '+', space or blank
1716 neg: optional sign for negative numbers: '-', '(', space or blank
1717 trailneg:optional trailing minus indicator: '-', ')', space or blank
1718
1719 >>> d = Decimal('-1234567.8901')
1720 >>> moneyfmt(d, curr='$')
1721 '-$1,234,567.89'
1722 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1723 '1.234.568-'
1724 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1725 '($1,234,567.89)'
1726 >>> moneyfmt(Decimal(123456789), sep=' ')
1727 '123 456 789.00'
1728 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001729 '<0.02>'
Georg Brandl8ec7f652007-08-15 14:28:01 +00001730
1731 """
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001732 q = Decimal(10) ** -places # 2 places --> '0.01'
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001733 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001734 result = []
1735 digits = map(str, digits)
1736 build, next = result.append, digits.pop
1737 if sign:
1738 build(trailneg)
1739 for i in range(places):
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001740 build(next() if digits else '0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001741 build(dp)
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001742 if not digits:
1743 build('0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001744 i = 0
1745 while digits:
1746 build(next())
1747 i += 1
1748 if i == 3 and digits:
1749 i = 0
1750 build(sep)
1751 build(curr)
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001752 build(neg if sign else pos)
1753 return ''.join(reversed(result))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001754
1755 def pi():
1756 """Compute Pi to the current precision.
1757
1758 >>> print pi()
1759 3.141592653589793238462643383
1760
1761 """
1762 getcontext().prec += 2 # extra digits for intermediate steps
1763 three = Decimal(3) # substitute "three=3.0" for regular floats
1764 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1765 while s != lasts:
1766 lasts = s
1767 n, na = n+na, na+8
1768 d, da = d+da, da+32
1769 t = (t * n) / d
1770 s += t
1771 getcontext().prec -= 2
1772 return +s # unary plus applies the new precision
1773
1774 def exp(x):
1775 """Return e raised to the power of x. Result type matches input type.
1776
1777 >>> print exp(Decimal(1))
1778 2.718281828459045235360287471
1779 >>> print exp(Decimal(2))
1780 7.389056098930650227230427461
1781 >>> print exp(2.0)
1782 7.38905609893
1783 >>> print exp(2+0j)
1784 (7.38905609893+0j)
1785
1786 """
1787 getcontext().prec += 2
1788 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1789 while s != lasts:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001790 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001791 i += 1
1792 fact *= i
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001793 num *= x
1794 s += num / fact
1795 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001796 return +s
1797
1798 def cos(x):
1799 """Return the cosine of x as measured in radians.
1800
1801 >>> print cos(Decimal('0.5'))
1802 0.8775825618903727161162815826
1803 >>> print cos(0.5)
1804 0.87758256189
1805 >>> print cos(0.5+0j)
1806 (0.87758256189+0j)
1807
1808 """
1809 getcontext().prec += 2
1810 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1811 while s != lasts:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001812 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001813 i += 2
1814 fact *= i * (i-1)
1815 num *= x * x
1816 sign *= -1
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001817 s += num / fact * sign
1818 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001819 return +s
1820
1821 def sin(x):
1822 """Return the sine of x as measured in radians.
1823
1824 >>> print sin(Decimal('0.5'))
1825 0.4794255386042030002732879352
1826 >>> print sin(0.5)
1827 0.479425538604
1828 >>> print sin(0.5+0j)
1829 (0.479425538604+0j)
1830
1831 """
1832 getcontext().prec += 2
1833 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1834 while s != lasts:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001835 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001836 i += 2
1837 fact *= i * (i-1)
1838 num *= x * x
1839 sign *= -1
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001840 s += num / fact * sign
1841 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001842 return +s
1843
1844
Georg Brandlb19be572007-12-29 10:57:00 +00001845.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001846
1847
1848.. _decimal-faq:
1849
1850Decimal FAQ
1851-----------
1852
1853Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1854minimize typing when using the interactive interpreter?
1855
Georg Brandl9f662322008-03-22 11:47:10 +00001856A. Some users abbreviate the constructor to just a single letter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001857
1858 >>> D = decimal.Decimal
1859 >>> D('1.23') + D('3.45')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001860 Decimal('4.68')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001861
1862Q. In a fixed-point application with two decimal places, some inputs have many
1863places and need to be rounded. Others are not supposed to have excess digits
1864and need to be validated. What methods should be used?
1865
1866A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Georg Brandl9f662322008-03-22 11:47:10 +00001867the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001868
1869 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1870
1871 >>> # Round to two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001872 >>> Decimal('3.214').quantize(TWOPLACES)
1873 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001874
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001875 >>> # Validate that a number does not exceed two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001876 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1877 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001878
Raymond Hettingerabe32372008-02-14 02:41:22 +00001879 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001880 Traceback (most recent call last):
1881 ...
Georg Brandlf6dab952009-04-28 21:48:35 +00001882 Inexact: None
Georg Brandl8ec7f652007-08-15 14:28:01 +00001883
1884Q. Once I have valid two place inputs, how do I maintain that invariant
1885throughout an application?
1886
Raymond Hettinger46314812008-02-14 10:46:57 +00001887A. Some operations like addition, subtraction, and multiplication by an integer
1888will automatically preserve fixed point. Others operations, like division and
1889non-integer multiplication, will change the number of decimal places and need to
Georg Brandl9f662322008-03-22 11:47:10 +00001890be followed-up with a :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001891
1892 >>> a = Decimal('102.72') # Initial fixed-point values
1893 >>> b = Decimal('3.17')
1894 >>> a + b # Addition preserves fixed-point
1895 Decimal('105.89')
1896 >>> a - b
1897 Decimal('99.55')
1898 >>> a * 42 # So does integer multiplication
1899 Decimal('4314.24')
1900 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1901 Decimal('325.62')
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001902 >>> (b / a).quantize(TWOPLACES) # And quantize division
Raymond Hettinger46314812008-02-14 10:46:57 +00001903 Decimal('0.03')
1904
1905In developing fixed-point applications, it is convenient to define functions
Georg Brandl9f662322008-03-22 11:47:10 +00001906to handle the :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001907
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001908 >>> def mul(x, y, fp=TWOPLACES):
1909 ... return (x * y).quantize(fp)
1910 >>> def div(x, y, fp=TWOPLACES):
1911 ... return (x / y).quantize(fp)
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001912
Raymond Hettinger46314812008-02-14 10:46:57 +00001913 >>> mul(a, b) # Automatically preserve fixed-point
1914 Decimal('325.62')
1915 >>> div(b, a)
1916 Decimal('0.03')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001917
1918Q. There are many ways to express the same value. The numbers :const:`200`,
1919:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1920various precisions. Is there a way to transform them to a single recognizable
1921canonical value?
1922
1923A. The :meth:`normalize` method maps all equivalent values to a single
Georg Brandl9f662322008-03-22 11:47:10 +00001924representative:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001925
1926 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1927 >>> [v.normalize() for v in values]
Raymond Hettingerabe32372008-02-14 02:41:22 +00001928 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001929
1930Q. Some decimal values always print with exponential notation. Is there a way
1931to get a non-exponential representation?
1932
1933A. For some values, exponential notation is the only way to express the number
1934of significant places in the coefficient. For example, expressing
1935:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1936original's two-place significance.
1937
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001938If an application does not care about tracking significance, it is easy to
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001939remove the exponent and trailing zeros, losing significance, but keeping the
1940value unchanged::
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001941
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001942 def remove_exponent(d):
1943 '''Remove exponent and trailing zeros.
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001944
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001945 >>> remove_exponent(Decimal('5E+3'))
1946 Decimal('5000')
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001947
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001948 '''
1949 return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001950
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001951Q. Is there a way to convert a regular float to a Decimal?
Georg Brandl9f662322008-03-22 11:47:10 +00001952
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001953A. Yes, the classmethod :meth:`from_float` makes an exact conversion.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001954
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001955The regular decimal constructor does not do this by default because there is
1956some question about whether it is advisable to mix binary and decimal floating
1957point. Also, its use requires some care to avoid the representation issues
1958associated with binary floating point:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001959
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001960 >>> Decimal.from_float(1.1)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001961 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001962
1963Q. Within a complex calculation, how can I make sure that I haven't gotten a
1964spurious result because of insufficient precision or rounding anomalies.
1965
1966A. The decimal module makes it easy to test results. A best practice is to
1967re-run calculations using greater precision and with various rounding modes.
1968Widely differing results indicate insufficient precision, rounding mode issues,
1969ill-conditioned inputs, or a numerically unstable algorithm.
1970
1971Q. I noticed that context precision is applied to the results of operations but
1972not to the inputs. Is there anything to watch out for when mixing values of
1973different precisions?
1974
1975A. Yes. The principle is that all values are considered to be exact and so is
1976the arithmetic on those values. Only the results are rounded. The advantage
1977for inputs is that "what you type is what you get". A disadvantage is that the
Georg Brandl9f662322008-03-22 11:47:10 +00001978results can look odd if you forget that the inputs haven't been rounded:
1979
1980.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001981
1982 >>> getcontext().prec = 3
Georg Brandl9f662322008-03-22 11:47:10 +00001983 >>> Decimal('3.104') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001984 Decimal('5.21')
Georg Brandl9f662322008-03-22 11:47:10 +00001985 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001986 Decimal('5.20')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001987
1988The solution is either to increase precision or to force rounding of inputs
Georg Brandl9f662322008-03-22 11:47:10 +00001989using the unary plus operation:
1990
1991.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001992
1993 >>> getcontext().prec = 3
1994 >>> +Decimal('1.23456789') # unary plus triggers rounding
Raymond Hettingerabe32372008-02-14 02:41:22 +00001995 Decimal('1.23')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001996
1997Alternatively, inputs can be rounded upon creation using the
Georg Brandl9f662322008-03-22 11:47:10 +00001998:meth:`Context.create_decimal` method:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001999
2000 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Raymond Hettingerabe32372008-02-14 02:41:22 +00002001 Decimal('1.2345')
Georg Brandl8ec7f652007-08-15 14:28:01 +00002002