blob: 2697026f05857fa69e5a2bf0fbd708c1f957feed [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
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000136Decimal instances can be constructed from integers, strings, floats, or tuples.
137Construction from an integer or a float performs an exact conversion of the
138value of that integer or float. Decimal numbers include special values such as
Georg Brandl8ec7f652007-08-15 14:28:01 +0000139:const:`NaN` which stands for "Not a number", positive and negative
Georg Brandl17baef02008-03-22 10:56:23 +0000140:const:`Infinity`, and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000141
Facundo Batista8e1c52a2008-06-21 17:30:06 +0000142 >>> getcontext().prec = 28
Georg Brandl8ec7f652007-08-15 14:28:01 +0000143 >>> Decimal(10)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000144 Decimal('10')
145 >>> Decimal('3.14')
146 Decimal('3.14')
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000147 >>> Decimal(3.14)
148 Decimal('3.140000000000000124344978758017532527446746826171875')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000149 >>> Decimal((0, (3, 1, 4), -2))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000150 Decimal('3.14')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000151 >>> Decimal(str(2.0 ** 0.5))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000152 Decimal('1.41421356237')
153 >>> Decimal(2) ** Decimal('0.5')
154 Decimal('1.414213562373095048801688724')
155 >>> Decimal('NaN')
156 Decimal('NaN')
157 >>> Decimal('-Infinity')
158 Decimal('-Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000159
160The significance of a new Decimal is determined solely by the number of digits
161input. Context precision and rounding only come into play during arithmetic
Georg Brandl17baef02008-03-22 10:56:23 +0000162operations.
163
164.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +0000165
166 >>> getcontext().prec = 6
167 >>> Decimal('3.0')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000168 Decimal('3.0')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000169 >>> Decimal('3.1415926535')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000170 Decimal('3.1415926535')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000171 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000172 Decimal('5.85987')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000173 >>> getcontext().rounding = ROUND_UP
174 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000175 Decimal('5.85988')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000176
177Decimals interact well with much of the rest of Python. Here is a small decimal
Georg Brandl9f662322008-03-22 11:47:10 +0000178floating point flying circus:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000179
Georg Brandl838b4b02008-03-22 13:07:06 +0000180.. doctest::
181 :options: +NORMALIZE_WHITESPACE
182
Georg Brandl8ec7f652007-08-15 14:28:01 +0000183 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
184 >>> max(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000185 Decimal('9.25')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000186 >>> min(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000187 Decimal('0.03')
Georg Brandl838b4b02008-03-22 13:07:06 +0000188 >>> sorted(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000189 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
190 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000191 >>> sum(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000192 Decimal('19.29')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000193 >>> a,b,c = data[:3]
194 >>> str(a)
195 '1.34'
196 >>> float(a)
Mark Dickinson6b87f112009-11-24 14:27:02 +0000197 1.34
Georg Brandl8ec7f652007-08-15 14:28:01 +0000198 >>> round(a, 1) # round() first converts to binary floating point
199 1.3
200 >>> int(a)
201 1
202 >>> a * 5
Raymond Hettingerabe32372008-02-14 02:41:22 +0000203 Decimal('6.70')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000204 >>> a * b
Raymond Hettingerabe32372008-02-14 02:41:22 +0000205 Decimal('2.5058')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000206 >>> c % a
Raymond Hettingerabe32372008-02-14 02:41:22 +0000207 Decimal('0.77')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000208
Georg Brandl9f662322008-03-22 11:47:10 +0000209And some mathematical functions are also available to Decimal:
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000210
Facundo Batista8e1c52a2008-06-21 17:30:06 +0000211 >>> getcontext().prec = 28
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000212 >>> Decimal(2).sqrt()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000213 Decimal('1.414213562373095048801688724')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000214 >>> Decimal(1).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000215 Decimal('2.718281828459045235360287471')
216 >>> Decimal('10').ln()
217 Decimal('2.302585092994045684017991455')
218 >>> Decimal('10').log10()
219 Decimal('1')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000220
Georg Brandl8ec7f652007-08-15 14:28:01 +0000221The :meth:`quantize` method rounds a number to a fixed exponent. This method is
222useful for monetary applications that often round results to a fixed number of
Georg Brandl9f662322008-03-22 11:47:10 +0000223places:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000224
225 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000226 Decimal('7.32')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000227 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000228 Decimal('8')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000229
230As shown above, the :func:`getcontext` function accesses the current context and
231allows the settings to be changed. This approach meets the needs of most
232applications.
233
234For more advanced work, it may be useful to create alternate contexts using the
235Context() constructor. To make an alternate active, use the :func:`setcontext`
236function.
237
238In accordance with the standard, the :mod:`Decimal` module provides two ready to
239use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
240former is especially useful for debugging because many of the traps are
Georg Brandl9f662322008-03-22 11:47:10 +0000241enabled:
242
243.. doctest:: newcontext
244 :options: +NORMALIZE_WHITESPACE
Georg Brandl8ec7f652007-08-15 14:28:01 +0000245
246 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
247 >>> setcontext(myothercontext)
248 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000249 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000250
251 >>> ExtendedContext
252 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
253 capitals=1, flags=[], traps=[])
254 >>> setcontext(ExtendedContext)
255 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000256 Decimal('0.142857143')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000257 >>> Decimal(42) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000258 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000259
260 >>> setcontext(BasicContext)
261 >>> Decimal(42) / Decimal(0)
262 Traceback (most recent call last):
263 File "<pyshell#143>", line 1, in -toplevel-
264 Decimal(42) / Decimal(0)
265 DivisionByZero: x / 0
266
267Contexts also have signal flags for monitoring exceptional conditions
268encountered during computations. The flags remain set until explicitly cleared,
269so it is best to clear the flags before each set of monitored computations by
270using the :meth:`clear_flags` method. ::
271
272 >>> setcontext(ExtendedContext)
273 >>> getcontext().clear_flags()
274 >>> Decimal(355) / Decimal(113)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000275 Decimal('3.14159292')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000276 >>> getcontext()
277 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Georg Brandl9f662322008-03-22 11:47:10 +0000278 capitals=1, flags=[Rounded, Inexact], traps=[])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000279
280The *flags* entry shows that the rational approximation to :const:`Pi` was
281rounded (digits beyond the context precision were thrown away) and that the
282result is inexact (some of the discarded digits were non-zero).
283
284Individual traps are set using the dictionary in the :attr:`traps` field of a
Georg Brandl9f662322008-03-22 11:47:10 +0000285context:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000286
Georg Brandl9f662322008-03-22 11:47:10 +0000287.. doctest:: newcontext
288
289 >>> setcontext(ExtendedContext)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000290 >>> Decimal(1) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000291 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000292 >>> getcontext().traps[DivisionByZero] = 1
293 >>> Decimal(1) / Decimal(0)
294 Traceback (most recent call last):
295 File "<pyshell#112>", line 1, in -toplevel-
296 Decimal(1) / Decimal(0)
297 DivisionByZero: x / 0
298
299Most programs adjust the current context only once, at the beginning of the
300program. And, in many applications, data is converted to :class:`Decimal` with
301a single cast inside a loop. With context set and decimals created, the bulk of
302the program manipulates the data no differently than with other Python numeric
303types.
304
Georg Brandlb19be572007-12-29 10:57:00 +0000305.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000306
307
308.. _decimal-decimal:
309
310Decimal objects
311---------------
312
313
314.. class:: Decimal([value [, context]])
315
Georg Brandlb19be572007-12-29 10:57:00 +0000316 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000317
Raymond Hettingered171ab2010-04-02 18:39:24 +0000318 *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal`
Raymond Hettingerabe32372008-02-14 02:41:22 +0000319 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000320 string, it should conform to the decimal numeric string syntax after leading
321 and trailing whitespace characters are removed::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000322
323 sign ::= '+' | '-'
324 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
325 indicator ::= 'e' | 'E'
326 digits ::= digit [digit]...
327 decimal-part ::= digits '.' [digits] | ['.'] digits
328 exponent-part ::= indicator [sign] digits
329 infinity ::= 'Infinity' | 'Inf'
330 nan ::= 'NaN' [digits] | 'sNaN' [digits]
331 numeric-value ::= decimal-part [exponent-part] | infinity
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000332 numeric-string ::= [sign] numeric-value | [sign] nan
Georg Brandl8ec7f652007-08-15 14:28:01 +0000333
Mark Dickinson4326ad82009-08-02 10:59:36 +0000334 If *value* is a unicode string then other Unicode decimal digits
335 are also permitted where ``digit`` appears above. These include
336 decimal digits from various other alphabets (for example,
337 Arabic-Indic and Devanāgarī digits) along with the fullwidth digits
338 ``u'\uff10'`` through ``u'\uff19'``.
339
Georg Brandl8ec7f652007-08-15 14:28:01 +0000340 If *value* is a :class:`tuple`, it should have three components, a sign
341 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
342 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Raymond Hettingerabe32372008-02-14 02:41:22 +0000343 returns ``Decimal('1.414')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000344
Raymond Hettingered171ab2010-04-02 18:39:24 +0000345 If *value* is a :class:`float`, the binary floating point value is losslessly
346 converted to its exact decimal equivalent. This conversion can often require
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000347 53 or more digits of precision. For example, ``Decimal(float('1.1'))``
348 converts to
349 ``Decimal('1.100000000000000088817841970012523233890533447265625')``.
Raymond Hettingered171ab2010-04-02 18:39:24 +0000350
Georg Brandl8ec7f652007-08-15 14:28:01 +0000351 The *context* precision does not affect how many digits are stored. That is
352 determined exclusively by the number of digits in *value*. For example,
Raymond Hettingerabe32372008-02-14 02:41:22 +0000353 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000354 only three.
355
356 The purpose of the *context* argument is determining what to do if *value* is a
357 malformed string. If the context traps :const:`InvalidOperation`, an exception
358 is raised; otherwise, the constructor returns a new Decimal with the value of
359 :const:`NaN`.
360
361 Once constructed, :class:`Decimal` objects are immutable.
362
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000363 .. versionchanged:: 2.6
364 leading and trailing whitespace characters are permitted when
365 creating a Decimal instance from a string.
366
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000367 .. versionchanged:: 2.7
368 The argument to the constructor is now permitted to be a :float:`instance`.
369
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000370 Decimal floating point objects share many properties with the other built-in
371 numeric types such as :class:`float` and :class:`int`. All of the usual math
372 operations and special methods apply. Likewise, decimal objects can be
373 copied, pickled, printed, used as dictionary keys, used as set elements,
374 compared, sorted, and coerced to another type (such as :class:`float` or
375 :class:`long`).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000376
Mark Dickinson99d80962010-04-02 08:53:22 +0000377 Decimal objects cannot generally be combined with floats in
378 arithmetic operations: an attempt to add a :class:`Decimal` to a
379 :class:`float`, for example, will raise a :exc:`TypeError`.
380 There's one exception to this rule: it's possible to use Python's
381 comparison operators to compare a :class:`float` instance ``x``
382 with a :class:`Decimal` instance ``y``. Without this exception,
383 comparisons between :class:`Decimal` and :class:`float` instances
384 would follow the general rules for comparing objects of different
385 types described in the :ref:`expressions` section of the reference
386 manual, leading to confusing results.
387
388 .. versionchanged:: 2.7
389 A comparison between a :class:`float` instance ``x`` and a
390 :class:`Decimal` instance ``y`` now returns a result based on
391 the values of ``x`` and ``y``. In earlier versions ``x < y``
392 returned the same (arbitrary) result for any :class:`Decimal`
393 instance ``x`` and any :class:`float` instance ``y``.
394
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000395 In addition to the standard numeric properties, decimal floating point
396 objects also have a number of specialized methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000397
398
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000399 .. method:: adjusted()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000400
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000401 Return the adjusted exponent after shifting out the coefficient's
402 rightmost digits until only the lead digit remains:
403 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
404 position of the most significant digit with respect to the decimal point.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000405
406
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000407 .. method:: as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000408
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000409 Return a :term:`named tuple` representation of the number:
410 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandle3c3db52008-01-11 09:55:53 +0000411
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000412 .. versionchanged:: 2.6
413 Use a named tuple.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000414
415
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000416 .. method:: canonical()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000417
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000418 Return the canonical encoding of the argument. Currently, the encoding of
419 a :class:`Decimal` instance is always canonical, so this operation returns
420 its argument unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000421
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000422 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000423
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000424 .. method:: compare(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000425
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000426 Compare the values of two Decimal instances. This operation behaves in
427 the same way as the usual comparison method :meth:`__cmp__`, except that
428 :meth:`compare` returns a Decimal instance rather than an integer, and if
429 either operand is a NaN then the result is a NaN::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000430
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000431 a or b is a NaN ==> Decimal('NaN')
432 a < b ==> Decimal('-1')
433 a == b ==> Decimal('0')
434 a > b ==> Decimal('1')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000435
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000436 .. method:: compare_signal(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000437
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000438 This operation is identical to the :meth:`compare` method, except that all
439 NaNs signal. That is, if neither operand is a signaling NaN then any
440 quiet NaN operand is treated as though it were a signaling NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000441
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000442 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000443
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000444 .. method:: compare_total(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000445
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000446 Compare two operands using their abstract representation rather than their
447 numerical value. Similar to the :meth:`compare` method, but the result
448 gives a total ordering on :class:`Decimal` instances. Two
449 :class:`Decimal` instances with the same numeric value but different
450 representations compare unequal in this ordering:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000451
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000452 >>> Decimal('12.0').compare_total(Decimal('12'))
453 Decimal('-1')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000454
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000455 Quiet and signaling NaNs are also included in the total ordering. The
456 result of this function is ``Decimal('0')`` if both operands have the same
457 representation, ``Decimal('-1')`` if the first operand is lower in the
458 total order than the second, and ``Decimal('1')`` if the first operand is
459 higher in the total order than the second operand. See the specification
460 for details of the total order.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000461
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000462 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000463
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000464 .. method:: compare_total_mag(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000465
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000466 Compare two operands using their abstract representation rather than their
467 value as in :meth:`compare_total`, but ignoring the sign of each operand.
468 ``x.compare_total_mag(y)`` is equivalent to
469 ``x.copy_abs().compare_total(y.copy_abs())``.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000470
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000471 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000472
Facundo Batista8e1c52a2008-06-21 17:30:06 +0000473 .. method:: conjugate()
474
475 Just returns self, this method is only to comply with the Decimal
476 Specification.
477
478 .. versionadded:: 2.6
479
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000480 .. method:: copy_abs()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000481
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000482 Return the absolute value of the argument. This operation is unaffected
483 by the context and is quiet: no flags are changed and no rounding is
484 performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000485
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000486 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000487
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000488 .. method:: copy_negate()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000489
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000490 Return the negation of the argument. This operation is unaffected by the
491 context and is quiet: no flags are changed and no rounding is performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000492
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000493 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000494
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000495 .. method:: copy_sign(other)
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000496
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000497 Return a copy of the first operand with the sign set to be the same as the
498 sign of the second operand. For example:
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000499
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000500 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
501 Decimal('-2.3')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000502
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000503 This operation is unaffected by the context and is quiet: no flags are
504 changed and no rounding is performed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000505
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000506 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000507
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000508 .. method:: exp([context])
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000509
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000510 Return the value of the (natural) exponential function ``e**x`` at the
511 given number. The result is correctly rounded using the
512 :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000513
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000514 >>> Decimal(1).exp()
515 Decimal('2.718281828459045235360287471')
516 >>> Decimal(321).exp()
517 Decimal('2.561702493119680037517373933E+139')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000518
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000519 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000520
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000521 .. method:: from_float(f)
522
523 Classmethod that converts a float to a decimal number, exactly.
524
525 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
526 Since 0.1 is not exactly representable in binary floating point, the
527 value is stored as the nearest representable value which is
528 `0x1.999999999999ap-4`. That equivalent value in decimal is
529 `0.1000000000000000055511151231257827021181583404541015625`.
530
Mark Dickinsonb1affc52010-04-04 22:09:21 +0000531 .. note:: From Python 2.7 onwards, a :class:`Decimal` instance
532 can also be constructed directly from a :class:`float`.
533
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000534 .. doctest::
535
536 >>> Decimal.from_float(0.1)
537 Decimal('0.1000000000000000055511151231257827021181583404541015625')
538 >>> Decimal.from_float(float('nan'))
539 Decimal('NaN')
540 >>> Decimal.from_float(float('inf'))
541 Decimal('Infinity')
542 >>> Decimal.from_float(float('-inf'))
543 Decimal('-Infinity')
544
545 .. versionadded:: 2.7
546
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000547 .. method:: fma(other, third[, context])
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000548
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000549 Fused multiply-add. Return self*other+third with no rounding of the
550 intermediate product self*other.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000551
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000552 >>> Decimal(2).fma(3, 5)
553 Decimal('11')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000554
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000555 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000556
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000557 .. method:: is_canonical()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000558
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000559 Return :const:`True` if the argument is canonical and :const:`False`
560 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
561 this operation always returns :const:`True`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000562
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000563 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000564
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000565 .. method:: is_finite()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000566
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000567 Return :const:`True` if the argument is a finite number, and
568 :const:`False` if the argument is an infinity or a NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000569
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000570 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000571
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000572 .. method:: is_infinite()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000573
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000574 Return :const:`True` if the argument is either positive or negative
575 infinity and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000576
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000577 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000578
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000579 .. method:: is_nan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000580
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000581 Return :const:`True` if the argument is a (quiet or signaling) NaN and
582 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000583
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000584 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000585
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000586 .. method:: is_normal()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000587
Raymond Hettingereecd1dc62009-03-10 04:40:24 +0000588 Return :const:`True` if the argument is a *normal* finite non-zero
589 number with an adjusted exponent greater than or equal to *Emin*.
590 Return :const:`False` if the argument is zero, subnormal, infinite or a
591 NaN. Note, the term *normal* is used here in a different sense with
592 the :meth:`normalize` method which is used to create canonical values.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000593
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000594 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000595
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000596 .. method:: is_qnan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000597
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000598 Return :const:`True` if the argument is a quiet NaN, and
599 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000600
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000601 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000602
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000603 .. method:: is_signed()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000604
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000605 Return :const:`True` if the argument has a negative sign and
606 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000607
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000608 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000609
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000610 .. method:: is_snan()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000611
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000612 Return :const:`True` if the argument is a signaling NaN and :const:`False`
613 otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000614
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000615 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000616
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000617 .. method:: is_subnormal()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000618
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000619 Return :const:`True` if the argument is subnormal, and :const:`False`
Raymond Hettingereecd1dc62009-03-10 04:40:24 +0000620 otherwise. A number is subnormal is if it is nonzero, finite, and has an
621 adjusted exponent less than *Emin*.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000622
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000623 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000624
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000625 .. method:: is_zero()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000626
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000627 Return :const:`True` if the argument is a (positive or negative) zero and
628 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000629
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000630 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000631
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000632 .. method:: ln([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000633
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000634 Return the natural (base e) logarithm of the operand. The result is
635 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000636
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000637 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000638
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000639 .. method:: log10([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000640
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000641 Return the base ten logarithm of the operand. The result is correctly
642 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000643
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000644 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000645
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000646 .. method:: logb([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000647
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000648 For a nonzero number, return the adjusted exponent of its operand as a
649 :class:`Decimal` instance. If the operand is a zero then
650 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
651 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
652 returned.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000653
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000654 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000655
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000656 .. method:: logical_and(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000657
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000658 :meth:`logical_and` is a logical operation which takes two *logical
659 operands* (see :ref:`logical_operands_label`). The result is the
660 digit-wise ``and`` of the two operands.
661
662 .. versionadded:: 2.6
663
Georg Brandl3d5c87a2009-06-30 16:15:43 +0000664 .. method:: logical_invert([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000665
Georg Brandl3d5c87a2009-06-30 16:15:43 +0000666 :meth:`logical_invert` is a logical operation. The
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000667 result is the digit-wise inversion of the operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000668
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000669 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000670
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000671 .. method:: logical_or(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000672
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000673 :meth:`logical_or` is a logical operation which takes two *logical
674 operands* (see :ref:`logical_operands_label`). The result is the
675 digit-wise ``or`` of the two operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000676
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000677 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000678
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000679 .. method:: logical_xor(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000680
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000681 :meth:`logical_xor` is a logical operation which takes two *logical
682 operands* (see :ref:`logical_operands_label`). The result is the
683 digit-wise exclusive or of the two operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000684
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000685 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000686
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000687 .. method:: max(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000688
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000689 Like ``max(self, other)`` except that the context rounding rule is applied
690 before returning and that :const:`NaN` values are either signaled or
691 ignored (depending on the context and whether they are signaling or
692 quiet).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000693
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000694 .. method:: max_mag(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000695
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000696 Similar to the :meth:`.max` method, but the comparison is done using the
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000697 absolute values of the operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000698
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000699 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000700
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000701 .. method:: min(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000702
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000703 Like ``min(self, other)`` except that the context rounding rule is applied
704 before returning and that :const:`NaN` values are either signaled or
705 ignored (depending on the context and whether they are signaling or
706 quiet).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000707
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000708 .. method:: min_mag(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000709
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000710 Similar to the :meth:`.min` method, but the comparison is done using the
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000711 absolute values of the operands.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000712
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000713 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000714
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000715 .. method:: next_minus([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000716
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000717 Return the largest number representable in the given context (or in the
718 current thread's context if no context is given) that is smaller than the
719 given operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000720
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000721 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000722
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000723 .. method:: next_plus([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000724
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000725 Return the smallest number representable in the given context (or in the
726 current thread's context if no context is given) that is larger than the
727 given operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000728
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000729 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000730
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000731 .. method:: next_toward(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000732
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000733 If the two operands are unequal, return the number closest to the first
734 operand in the direction of the second operand. If both operands are
735 numerically equal, return a copy of the first operand with the sign set to
736 be the same as the sign of the second operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000737
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000738 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000739
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000740 .. method:: normalize([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000741
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000742 Normalize the number by stripping the rightmost trailing zeros and
743 converting any result equal to :const:`Decimal('0')` to
744 :const:`Decimal('0e0')`. Used for producing canonical values for members
745 of an equivalence class. For example, ``Decimal('32.100')`` and
746 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
747 ``Decimal('32.1')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000748
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000749 .. method:: number_class([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000750
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000751 Return a string describing the *class* of the operand. The returned value
752 is one of the following ten strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000753
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000754 * ``"-Infinity"``, indicating that the operand is negative infinity.
755 * ``"-Normal"``, indicating that the operand is a negative normal number.
756 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
757 * ``"-Zero"``, indicating that the operand is a negative zero.
758 * ``"+Zero"``, indicating that the operand is a positive zero.
759 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
760 * ``"+Normal"``, indicating that the operand is a positive normal number.
761 * ``"+Infinity"``, indicating that the operand is positive infinity.
762 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
763 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000764
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000765 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000766
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000767 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000768
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000769 Return a value equal to the first operand after rounding and having the
770 exponent of the second operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000771
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000772 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
773 Decimal('1.414')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000774
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000775 Unlike other operations, if the length of the coefficient after the
776 quantize operation would be greater than precision, then an
777 :const:`InvalidOperation` is signaled. This guarantees that, unless there
778 is an error condition, the quantized exponent is always equal to that of
779 the right-hand operand.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000780
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000781 Also unlike other operations, quantize never signals Underflow, even if
782 the result is subnormal and inexact.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000783
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000784 If the exponent of the second operand is larger than that of the first
785 then rounding may be necessary. In this case, the rounding mode is
786 determined by the ``rounding`` argument if given, else by the given
787 ``context`` argument; if neither argument is given the rounding mode of
788 the current thread's context is used.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000789
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000790 If *watchexp* is set (default), then an error is returned whenever the
791 resulting exponent is greater than :attr:`Emax` or less than
792 :attr:`Etiny`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000793
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000794 .. method:: radix()
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000795
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000796 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
797 class does all its arithmetic. Included for compatibility with the
798 specification.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000799
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000800 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000801
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000802 .. method:: remainder_near(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000803
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000804 Compute the modulo as either a positive or negative value depending on
805 which is closest to zero. For instance, ``Decimal(10).remainder_near(6)``
806 returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000807
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000808 If both are equally close, the one chosen will have the same sign as
809 *self*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000810
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000811 .. method:: rotate(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000812
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000813 Return the result of rotating the digits of the first operand by an amount
814 specified by the second operand. The second operand must be an integer in
815 the range -precision through precision. The absolute value of the second
816 operand gives the number of places to rotate. If the second operand is
817 positive then rotation is to the left; otherwise rotation is to the right.
818 The coefficient of the first operand is padded on the left with zeros to
819 length precision if necessary. The sign and exponent of the first operand
820 are unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000821
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000822 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000823
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000824 .. method:: same_quantum(other[, context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000825
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000826 Test whether self and other have the same exponent or whether both are
827 :const:`NaN`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000828
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000829 .. method:: scaleb(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000830
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000831 Return the first operand with exponent adjusted by the second.
832 Equivalently, return the first operand multiplied by ``10**other``. The
833 second operand must be an integer.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000834
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000835 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000836
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000837 .. method:: shift(other[, context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000838
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000839 Return the result of shifting the digits of the first operand by an amount
840 specified by the second operand. The second operand must be an integer in
841 the range -precision through precision. The absolute value of the second
842 operand gives the number of places to shift. If the second operand is
843 positive then the shift is to the left; otherwise the shift is to the
844 right. Digits shifted into the coefficient are zeros. The sign and
845 exponent of the first operand are unchanged.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000846
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000847 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000848
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000849 .. method:: sqrt([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000850
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000851 Return the square root of the argument to full precision.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000852
853
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000854 .. method:: to_eng_string([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000855
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000856 Convert to an engineering-type string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000857
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000858 Engineering notation has an exponent which is a multiple of 3, so there
859 are up to 3 digits left of the decimal place. For example, converts
860 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000861
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000862 .. method:: to_integral([rounding[, context]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000863
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000864 Identical to the :meth:`to_integral_value` method. The ``to_integral``
865 name has been kept for compatibility with older versions.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000866
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000867 .. method:: to_integral_exact([rounding[, context]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000868
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000869 Round to the nearest integer, signaling :const:`Inexact` or
870 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
871 determined by the ``rounding`` parameter if given, else by the given
872 ``context``. If neither parameter is given then the rounding mode of the
873 current context is used.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000874
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000875 .. versionadded:: 2.6
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000876
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000877 .. method:: to_integral_value([rounding[, context]])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000878
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000879 Round to the nearest integer without signaling :const:`Inexact` or
880 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
881 rounding method in either the supplied *context* or the current context.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000882
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000883 .. versionchanged:: 2.6
884 renamed from ``to_integral`` to ``to_integral_value``. The old name
885 remains valid for compatibility.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000886
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000887.. _logical_operands_label:
888
889Logical operands
890^^^^^^^^^^^^^^^^
891
892The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
893and :meth:`logical_xor` methods expect their arguments to be *logical
894operands*. A *logical operand* is a :class:`Decimal` instance whose
895exponent and sign are both zero, and whose digits are all either
896:const:`0` or :const:`1`.
897
Georg Brandlb19be572007-12-29 10:57:00 +0000898.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000899
900
901.. _decimal-context:
902
903Context objects
904---------------
905
906Contexts are environments for arithmetic operations. They govern precision, set
907rules for rounding, determine which signals are treated as exceptions, and limit
908the range for exponents.
909
910Each thread has its own current context which is accessed or changed using the
911:func:`getcontext` and :func:`setcontext` functions:
912
913
914.. function:: getcontext()
915
916 Return the current context for the active thread.
917
918
919.. function:: setcontext(c)
920
921 Set the current context for the active thread to *c*.
922
923Beginning with Python 2.5, you can also use the :keyword:`with` statement and
924the :func:`localcontext` function to temporarily change the active context.
925
926
927.. function:: localcontext([c])
928
929 Return a context manager that will set the current context for the active thread
930 to a copy of *c* on entry to the with-statement and restore the previous context
931 when exiting the with-statement. If no context is specified, a copy of the
932 current context is used.
933
934 .. versionadded:: 2.5
935
936 For example, the following code sets the current decimal precision to 42 places,
937 performs a calculation, and then automatically restores the previous context::
938
Georg Brandl8ec7f652007-08-15 14:28:01 +0000939 from decimal import localcontext
940
941 with localcontext() as ctx:
942 ctx.prec = 42 # Perform a high precision calculation
943 s = calculate_something()
944 s = +s # Round the final result back to the default precision
945
946New contexts can also be created using the :class:`Context` constructor
947described below. In addition, the module provides three pre-made contexts:
948
949
950.. class:: BasicContext
951
952 This is a standard context defined by the General Decimal Arithmetic
953 Specification. Precision is set to nine. Rounding is set to
954 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
955 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
956 :const:`Subnormal`.
957
958 Because many of the traps are enabled, this context is useful for debugging.
959
960
961.. class:: ExtendedContext
962
963 This is a standard context defined by the General Decimal Arithmetic
964 Specification. Precision is set to nine. Rounding is set to
965 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
966 exceptions are not raised during computations).
967
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000968 Because the traps are disabled, this context is useful for applications that
Georg Brandl8ec7f652007-08-15 14:28:01 +0000969 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
970 raising exceptions. This allows an application to complete a run in the
971 presence of conditions that would otherwise halt the program.
972
973
974.. class:: DefaultContext
975
976 This context is used by the :class:`Context` constructor as a prototype for new
977 contexts. Changing a field (such a precision) has the effect of changing the
978 default for new contexts creating by the :class:`Context` constructor.
979
980 This context is most useful in multi-threaded environments. Changing one of the
981 fields before threads are started has the effect of setting system-wide
982 defaults. Changing the fields after threads have started is not recommended as
983 it would require thread synchronization to prevent race conditions.
984
985 In single threaded environments, it is preferable to not use this context at
986 all. Instead, simply create contexts explicitly as described below.
987
988 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
989 for Overflow, InvalidOperation, and DivisionByZero.
990
991In addition to the three supplied contexts, new contexts can be created with the
992:class:`Context` constructor.
993
994
995.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
996
997 Creates a new context. If a field is not specified or is :const:`None`, the
998 default values are copied from the :const:`DefaultContext`. If the *flags*
999 field is not specified or is :const:`None`, all flags are cleared.
1000
1001 The *prec* field is a positive integer that sets the precision for arithmetic
1002 operations in the context.
1003
1004 The *rounding* option is one of:
1005
1006 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
1007 * :const:`ROUND_DOWN` (towards zero),
1008 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
1009 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
1010 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
1011 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
1012 * :const:`ROUND_UP` (away from zero).
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001013 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001014 would have been 0 or 5; otherwise towards zero)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001015
1016 The *traps* and *flags* fields list any signals to be set. Generally, new
1017 contexts should only set traps and leave the flags clear.
1018
1019 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
1020 for exponents.
1021
1022 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
1023 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
1024 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
1025
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001026 .. versionchanged:: 2.6
1027 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001028
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001029 The :class:`Context` class defines several general purpose methods as well as
1030 a large number of methods for doing arithmetic directly in a given context.
1031 In addition, for each of the :class:`Decimal` methods described above (with
1032 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
Mark Dickinson6d8effb2010-02-18 14:27:02 +00001033 a corresponding :class:`Context` method. For example, for a :class:`Context`
1034 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
1035 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a
1036 Python integer (an instance of :class:`int` or :class:`long`) anywhere that a
1037 Decimal instance is accepted.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001038
1039
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001040 .. method:: clear_flags()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001041
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001042 Resets all of the flags to :const:`0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001043
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001044 .. method:: copy()
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001045
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001046 Return a duplicate of the context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001047
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001048 .. method:: copy_decimal(num)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001049
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001050 Return a copy of the Decimal instance num.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001051
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001052 .. method:: create_decimal(num)
Georg Brandl9f662322008-03-22 11:47:10 +00001053
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001054 Creates a new Decimal instance from *num* but using *self* as
1055 context. Unlike the :class:`Decimal` constructor, the context precision,
1056 rounding method, flags, and traps are applied to the conversion.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001057
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001058 This is useful because constants are often given to a greater precision
1059 than is needed by the application. Another benefit is that rounding
1060 immediately eliminates unintended effects from digits beyond the current
1061 precision. In the following example, using unrounded inputs means that
1062 adding zero to a sum can change the result:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001063
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001064 .. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001065
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001066 >>> getcontext().prec = 3
1067 >>> Decimal('3.4445') + Decimal('1.0023')
1068 Decimal('4.45')
1069 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
1070 Decimal('4.44')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001071
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001072 This method implements the to-number operation of the IBM specification.
1073 If the argument is a string, no leading or trailing whitespace is
1074 permitted.
1075
Georg Brandlaa5bb322009-01-03 19:44:48 +00001076 .. method:: create_decimal_from_float(f)
Raymond Hettingerf4d85972009-01-03 19:02:23 +00001077
1078 Creates a new Decimal instance from a float *f* but rounding using *self*
Georg Brandla24067e2009-01-03 20:15:14 +00001079 as the context. Unlike the :meth:`Decimal.from_float` class method,
Raymond Hettingerf4d85972009-01-03 19:02:23 +00001080 the context precision, rounding method, flags, and traps are applied to
1081 the conversion.
1082
1083 .. doctest::
1084
Georg Brandlaa5bb322009-01-03 19:44:48 +00001085 >>> context = Context(prec=5, rounding=ROUND_DOWN)
1086 >>> context.create_decimal_from_float(math.pi)
1087 Decimal('3.1415')
1088 >>> context = Context(prec=5, traps=[Inexact])
1089 >>> context.create_decimal_from_float(math.pi)
1090 Traceback (most recent call last):
1091 ...
1092 Inexact: None
Raymond Hettingerf4d85972009-01-03 19:02:23 +00001093
1094 .. versionadded:: 2.7
1095
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001096 .. method:: Etiny()
1097
1098 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
1099 value for subnormal results. When underflow occurs, the exponent is set
1100 to :const:`Etiny`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001101
1102
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001103 .. method:: Etop()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001104
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001105 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001106
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001107 The usual approach to working with decimals is to create :class:`Decimal`
1108 instances and then apply arithmetic operations which take place within the
1109 current context for the active thread. An alternative approach is to use
1110 context methods for calculating within a specific context. The methods are
1111 similar to those for the :class:`Decimal` class and are only briefly
1112 recounted here.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001113
1114
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001115 .. method:: abs(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001116
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001117 Returns the absolute value of *x*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001118
1119
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001120 .. method:: add(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001121
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001122 Return the sum of *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001123
1124
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001125 .. method:: canonical(x)
1126
1127 Returns the same Decimal object *x*.
1128
1129
1130 .. method:: compare(x, y)
1131
1132 Compares *x* and *y* numerically.
1133
1134
1135 .. method:: compare_signal(x, y)
1136
1137 Compares the values of the two operands numerically.
1138
1139
1140 .. method:: compare_total(x, y)
1141
1142 Compares two operands using their abstract representation.
1143
1144
1145 .. method:: compare_total_mag(x, y)
1146
1147 Compares two operands using their abstract representation, ignoring sign.
1148
1149
1150 .. method:: copy_abs(x)
1151
1152 Returns a copy of *x* with the sign set to 0.
1153
1154
1155 .. method:: copy_negate(x)
1156
1157 Returns a copy of *x* with the sign inverted.
1158
1159
1160 .. method:: copy_sign(x, y)
1161
1162 Copies the sign from *y* to *x*.
1163
1164
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001165 .. method:: divide(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001166
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001167 Return *x* divided by *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001168
1169
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001170 .. method:: divide_int(x, y)
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001171
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001172 Return *x* divided by *y*, truncated to an integer.
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001173
1174
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001175 .. method:: divmod(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001176
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001177 Divides two numbers and returns the integer part of the result.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001178
1179
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001180 .. method:: exp(x)
1181
1182 Returns `e ** x`.
1183
1184
1185 .. method:: fma(x, y, z)
1186
1187 Returns *x* multiplied by *y*, plus *z*.
1188
1189
1190 .. method:: is_canonical(x)
1191
1192 Returns True if *x* is canonical; otherwise returns False.
1193
1194
1195 .. method:: is_finite(x)
1196
1197 Returns True if *x* is finite; otherwise returns False.
1198
1199
1200 .. method:: is_infinite(x)
1201
1202 Returns True if *x* is infinite; otherwise returns False.
1203
1204
1205 .. method:: is_nan(x)
1206
1207 Returns True if *x* is a qNaN or sNaN; otherwise returns False.
1208
1209
1210 .. method:: is_normal(x)
1211
1212 Returns True if *x* is a normal number; otherwise returns False.
1213
1214
1215 .. method:: is_qnan(x)
1216
1217 Returns True if *x* is a quiet NaN; otherwise returns False.
1218
1219
1220 .. method:: is_signed(x)
1221
1222 Returns True if *x* is negative; otherwise returns False.
1223
1224
1225 .. method:: is_snan(x)
1226
1227 Returns True if *x* is a signaling NaN; otherwise returns False.
1228
1229
1230 .. method:: is_subnormal(x)
1231
1232 Returns True if *x* is subnormal; otherwise returns False.
1233
1234
1235 .. method:: is_zero(x)
1236
1237 Returns True if *x* is a zero; otherwise returns False.
1238
1239
1240 .. method:: ln(x)
1241
1242 Returns the natural (base e) logarithm of *x*.
1243
1244
1245 .. method:: log10(x)
1246
1247 Returns the base 10 logarithm of *x*.
1248
1249
1250 .. method:: logb(x)
1251
1252 Returns the exponent of the magnitude of the operand's MSD.
1253
1254
1255 .. method:: logical_and(x, y)
1256
Georg Brandle92818f2009-01-03 20:47:01 +00001257 Applies the logical operation *and* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001258
1259
1260 .. method:: logical_invert(x)
1261
1262 Invert all the digits in *x*.
1263
1264
1265 .. method:: logical_or(x, y)
1266
Georg Brandle92818f2009-01-03 20:47:01 +00001267 Applies the logical operation *or* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001268
1269
1270 .. method:: logical_xor(x, y)
1271
Georg Brandle92818f2009-01-03 20:47:01 +00001272 Applies the logical operation *xor* between each operand's digits.
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001273
1274
1275 .. method:: max(x, y)
1276
1277 Compares two values numerically and returns the maximum.
1278
1279
1280 .. method:: max_mag(x, y)
1281
1282 Compares the values numerically with their sign ignored.
1283
1284
1285 .. method:: min(x, y)
1286
1287 Compares two values numerically and returns the minimum.
1288
1289
1290 .. method:: min_mag(x, y)
1291
1292 Compares the values numerically with their sign ignored.
1293
1294
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001295 .. method:: minus(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001296
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001297 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001298
1299
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001300 .. method:: multiply(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001301
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001302 Return the product of *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001303
1304
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001305 .. method:: next_minus(x)
1306
1307 Returns the largest representable number smaller than *x*.
1308
1309
1310 .. method:: next_plus(x)
1311
1312 Returns the smallest representable number larger than *x*.
1313
1314
1315 .. method:: next_toward(x, y)
1316
1317 Returns the number closest to *x*, in direction towards *y*.
1318
1319
1320 .. method:: normalize(x)
1321
1322 Reduces *x* to its simplest form.
1323
1324
1325 .. method:: number_class(x)
1326
1327 Returns an indication of the class of *x*.
1328
1329
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001330 .. method:: plus(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001331
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001332 Plus corresponds to the unary prefix plus operator in Python. This
1333 operation applies the context precision and rounding, so it is *not* an
1334 identity operation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001335
1336
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001337 .. method:: power(x, y[, modulo])
Georg Brandl8ec7f652007-08-15 14:28:01 +00001338
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001339 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001340
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001341 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1342 must be integral. The result will be inexact unless ``y`` is integral and
1343 the result is finite and can be expressed exactly in 'precision' digits.
1344 The result should always be correctly rounded, using the rounding mode of
1345 the current thread's context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001346
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001347 With three arguments, compute ``(x**y) % modulo``. For the three argument
1348 form, the following restrictions on the arguments hold:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001349
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001350 - all three arguments must be integral
1351 - ``y`` must be nonnegative
1352 - at least one of ``x`` or ``y`` must be nonzero
1353 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl8ec7f652007-08-15 14:28:01 +00001354
Mark Dickinsonf5be4e62010-02-22 15:40:28 +00001355 The value resulting from ``Context.power(x, y, modulo)`` is
1356 equal to the value that would be obtained by computing ``(x**y)
1357 % modulo`` with unbounded precision, but is computed more
1358 efficiently. The exponent of the result is zero, regardless of
1359 the exponents of ``x``, ``y`` and ``modulo``. The result is
1360 always exact.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001361
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001362 .. versionchanged:: 2.6
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001363 ``y`` may now be nonintegral in ``x**y``.
1364 Stricter requirements for the three-argument version.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001365
1366
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001367 .. method:: quantize(x, y)
1368
1369 Returns a value equal to *x* (rounded), having the exponent of *y*.
1370
1371
1372 .. method:: radix()
1373
1374 Just returns 10, as this is Decimal, :)
1375
1376
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001377 .. method:: remainder(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001378
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001379 Returns the remainder from integer division.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001380
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001381 The sign of the result, if non-zero, is the same as that of the original
1382 dividend.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001383
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001384 .. method:: remainder_near(x, y)
1385
Georg Brandle92818f2009-01-03 20:47:01 +00001386 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1387 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001388
1389
1390 .. method:: rotate(x, y)
1391
1392 Returns a rotated copy of *x*, *y* times.
1393
1394
1395 .. method:: same_quantum(x, y)
1396
1397 Returns True if the two operands have the same exponent.
1398
1399
1400 .. method:: scaleb (x, y)
1401
1402 Returns the first operand after adding the second value its exp.
1403
1404
1405 .. method:: shift(x, y)
1406
1407 Returns a shifted copy of *x*, *y* times.
1408
1409
1410 .. method:: sqrt(x)
1411
1412 Square root of a non-negative number to context precision.
1413
1414
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001415 .. method:: subtract(x, y)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001416
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001417 Return the difference between *x* and *y*.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001418
Facundo Batista8e1c52a2008-06-21 17:30:06 +00001419
1420 .. method:: to_eng_string(x)
1421
1422 Converts a number to a string, using scientific notation.
1423
1424
1425 .. method:: to_integral_exact(x)
1426
1427 Rounds to an integer.
1428
1429
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001430 .. method:: to_sci_string(x)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001431
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001432 Converts a number to a string using scientific notation.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001433
Georg Brandlb19be572007-12-29 10:57:00 +00001434.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001435
1436
1437.. _decimal-signals:
1438
1439Signals
1440-------
1441
1442Signals represent conditions that arise during computation. Each corresponds to
1443one context flag and one context trap enabler.
1444
Mark Dickinson1840c1a2008-05-03 18:23:14 +00001445The context flag is set whenever the condition is encountered. After the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001446computation, flags may be checked for informational purposes (for instance, to
1447determine whether a computation was exact). After checking the flags, be sure to
1448clear all flags before starting the next computation.
1449
1450If the context's trap enabler is set for the signal, then the condition causes a
1451Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1452is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1453condition.
1454
1455
1456.. class:: Clamped
1457
1458 Altered an exponent to fit representation constraints.
1459
1460 Typically, clamping occurs when an exponent falls outside the context's
1461 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001462 fit by adding zeros to the coefficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001463
1464
1465.. class:: DecimalException
1466
1467 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1468
1469
1470.. class:: DivisionByZero
1471
1472 Signals the division of a non-infinite number by zero.
1473
1474 Can occur with division, modulo division, or when raising a number to a negative
1475 power. If this signal is not trapped, returns :const:`Infinity` or
1476 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1477
1478
1479.. class:: Inexact
1480
1481 Indicates that rounding occurred and the result is not exact.
1482
1483 Signals when non-zero digits were discarded during rounding. The rounded result
1484 is returned. The signal flag or trap is used to detect when results are
1485 inexact.
1486
1487
1488.. class:: InvalidOperation
1489
1490 An invalid operation was performed.
1491
1492 Indicates that an operation was requested that does not make sense. If not
1493 trapped, returns :const:`NaN`. Possible causes include::
1494
1495 Infinity - Infinity
1496 0 * Infinity
1497 Infinity / Infinity
1498 x % 0
1499 Infinity % x
1500 x._rescale( non-integer )
1501 sqrt(-x) and x > 0
1502 0 ** 0
1503 x ** (non-integer)
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001504 x ** Infinity
Georg Brandl8ec7f652007-08-15 14:28:01 +00001505
1506
1507.. class:: Overflow
1508
1509 Numerical overflow.
1510
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001511 Indicates the exponent is larger than :attr:`Emax` after rounding has
1512 occurred. If not trapped, the result depends on the rounding mode, either
1513 pulling inward to the largest representable finite number or rounding outward
1514 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1515 are also signaled.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001516
1517
1518.. class:: Rounded
1519
1520 Rounding occurred though possibly no information was lost.
1521
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001522 Signaled whenever rounding discards digits; even if those digits are zero
1523 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1524 the result unchanged. This signal is used to detect loss of significant
1525 digits.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001526
1527
1528.. class:: Subnormal
1529
1530 Exponent was lower than :attr:`Emin` prior to rounding.
1531
Benjamin Petersonc7b05922008-04-25 01:29:10 +00001532 Occurs when an operation result is subnormal (the exponent is too small). If
1533 not trapped, returns the result unchanged.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001534
1535
1536.. class:: Underflow
1537
1538 Numerical underflow with result rounded to zero.
1539
1540 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1541 and :class:`Subnormal` are also signaled.
1542
1543The following table summarizes the hierarchy of signals::
1544
1545 exceptions.ArithmeticError(exceptions.StandardError)
1546 DecimalException
1547 Clamped
1548 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1549 Inexact
1550 Overflow(Inexact, Rounded)
1551 Underflow(Inexact, Rounded, Subnormal)
1552 InvalidOperation
1553 Rounded
1554 Subnormal
1555
Georg Brandlb19be572007-12-29 10:57:00 +00001556.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001557
1558
1559.. _decimal-notes:
1560
1561Floating Point Notes
1562--------------------
1563
1564
1565Mitigating round-off error with increased precision
1566^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1567
1568The use of decimal floating point eliminates decimal representation error
1569(making it possible to represent :const:`0.1` exactly); however, some operations
1570can still incur round-off error when non-zero digits exceed the fixed precision.
1571
1572The effects of round-off error can be amplified by the addition or subtraction
1573of nearly offsetting quantities resulting in loss of significance. Knuth
1574provides two instructive examples where rounded floating point arithmetic with
1575insufficient precision causes the breakdown of the associative and distributive
Georg Brandl9f662322008-03-22 11:47:10 +00001576properties of addition:
1577
1578.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001579
1580 # Examples from Seminumerical Algorithms, Section 4.2.2.
1581 >>> from decimal import Decimal, getcontext
1582 >>> getcontext().prec = 8
1583
1584 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1585 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001586 Decimal('9.5111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001587 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001588 Decimal('10')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001589
1590 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1591 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001592 Decimal('0.01')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001593 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001594 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001595
1596The :mod:`decimal` module makes it possible to restore the identities by
Georg Brandl9f662322008-03-22 11:47:10 +00001597expanding the precision sufficiently to avoid loss of significance:
1598
1599.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001600
1601 >>> getcontext().prec = 20
1602 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1603 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001604 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001605 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001606 Decimal('9.51111111')
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001607 >>>
Georg Brandl8ec7f652007-08-15 14:28:01 +00001608 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1609 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001610 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001611 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001612 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001613
1614
1615Special values
1616^^^^^^^^^^^^^^
1617
1618The number system for the :mod:`decimal` module provides special values
1619including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001620and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001621
1622Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1623they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1624not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1625can result from rounding beyond the limits of the largest representable number.
1626
1627The infinities are signed (affine) and can be used in arithmetic operations
1628where they get treated as very large, indeterminate numbers. For instance,
1629adding a constant to infinity gives another infinite result.
1630
1631Some operations are indeterminate and return :const:`NaN`, or if the
1632:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1633``0/0`` returns :const:`NaN` which means "not a number". This variety of
1634:const:`NaN` is quiet and, once created, will flow through other computations
1635always resulting in another :const:`NaN`. This behavior can be useful for a
1636series of computations that occasionally have missing inputs --- it allows the
1637calculation to proceed while flagging specific results as invalid.
1638
1639A variant is :const:`sNaN` which signals rather than remaining quiet after every
1640operation. This is a useful return value when an invalid result needs to
1641interrupt a calculation for special handling.
1642
Mark Dickinson2fc92632008-02-06 22:10:50 +00001643The behavior of Python's comparison operators can be a little surprising where a
1644:const:`NaN` is involved. A test for equality where one of the operands is a
1645quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1646``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
Mark Dickinsonbafa9422008-02-06 22:25:16 +00001647:const:`True`. An attempt to compare two Decimals using any of the ``<``,
Mark Dickinson00c2e652008-02-07 01:42:06 +00001648``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1649if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Mark Dickinson3a94ee02008-02-10 15:19:58 +00001650not trapped. Note that the General Decimal Arithmetic specification does not
Mark Dickinson00c2e652008-02-07 01:42:06 +00001651specify the behavior of direct comparisons; these rules for comparisons
1652involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1653section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
Mark Dickinson2fc92632008-02-06 22:10:50 +00001654and :meth:`compare-signal` methods instead.
1655
Georg Brandl8ec7f652007-08-15 14:28:01 +00001656The signed zeros can result from calculations that underflow. They keep the sign
1657that would have resulted if the calculation had been carried out to greater
1658precision. Since their magnitude is zero, both positive and negative zeros are
1659treated as equal and their sign is informational.
1660
1661In addition to the two signed zeros which are distinct yet equal, there are
1662various representations of zero with differing precisions yet equivalent in
1663value. This takes a bit of getting used to. For an eye accustomed to
1664normalized floating point representations, it is not immediately obvious that
Georg Brandl9f662322008-03-22 11:47:10 +00001665the following calculation returns a value equal to zero:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001666
1667 >>> 1 / Decimal('Infinity')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001668 Decimal('0E-1000000026')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001669
Georg Brandlb19be572007-12-29 10:57:00 +00001670.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001671
1672
1673.. _decimal-threads:
1674
1675Working with threads
1676--------------------
1677
1678The :func:`getcontext` function accesses a different :class:`Context` object for
1679each thread. Having separate thread contexts means that threads may make
1680changes (such as ``getcontext.prec=10``) without interfering with other threads.
1681
1682Likewise, the :func:`setcontext` function automatically assigns its target to
1683the current thread.
1684
1685If :func:`setcontext` has not been called before :func:`getcontext`, then
1686:func:`getcontext` will automatically create a new context for use in the
1687current thread.
1688
1689The new context is copied from a prototype context called *DefaultContext*. To
1690control the defaults so that each thread will use the same values throughout the
1691application, directly modify the *DefaultContext* object. This should be done
1692*before* any threads are started so that there won't be a race condition between
1693threads calling :func:`getcontext`. For example::
1694
1695 # Set applicationwide defaults for all threads about to be launched
1696 DefaultContext.prec = 12
1697 DefaultContext.rounding = ROUND_DOWN
1698 DefaultContext.traps = ExtendedContext.traps.copy()
1699 DefaultContext.traps[InvalidOperation] = 1
1700 setcontext(DefaultContext)
1701
1702 # Afterwards, the threads can be started
1703 t1.start()
1704 t2.start()
1705 t3.start()
1706 . . .
1707
Georg Brandlb19be572007-12-29 10:57:00 +00001708.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001709
1710
1711.. _decimal-recipes:
1712
1713Recipes
1714-------
1715
1716Here are a few recipes that serve as utility functions and that demonstrate ways
1717to work with the :class:`Decimal` class::
1718
1719 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1720 pos='', neg='-', trailneg=''):
1721 """Convert Decimal to a money formatted string.
1722
1723 places: required number of places after the decimal point
1724 curr: optional currency symbol before the sign (may be blank)
1725 sep: optional grouping separator (comma, period, space, or blank)
1726 dp: decimal point indicator (comma or period)
1727 only specify as blank when places is zero
1728 pos: optional sign for positive numbers: '+', space or blank
1729 neg: optional sign for negative numbers: '-', '(', space or blank
1730 trailneg:optional trailing minus indicator: '-', ')', space or blank
1731
1732 >>> d = Decimal('-1234567.8901')
1733 >>> moneyfmt(d, curr='$')
1734 '-$1,234,567.89'
1735 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1736 '1.234.568-'
1737 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1738 '($1,234,567.89)'
1739 >>> moneyfmt(Decimal(123456789), sep=' ')
1740 '123 456 789.00'
1741 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001742 '<0.02>'
Georg Brandl8ec7f652007-08-15 14:28:01 +00001743
1744 """
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001745 q = Decimal(10) ** -places # 2 places --> '0.01'
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001746 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001747 result = []
1748 digits = map(str, digits)
1749 build, next = result.append, digits.pop
1750 if sign:
1751 build(trailneg)
1752 for i in range(places):
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001753 build(next() if digits else '0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001754 build(dp)
Raymond Hettinger5eaffc42008-04-17 10:48:31 +00001755 if not digits:
1756 build('0')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001757 i = 0
1758 while digits:
1759 build(next())
1760 i += 1
1761 if i == 3 and digits:
1762 i = 0
1763 build(sep)
1764 build(curr)
Raymond Hettinger0cd71702008-02-14 12:49:37 +00001765 build(neg if sign else pos)
1766 return ''.join(reversed(result))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001767
1768 def pi():
1769 """Compute Pi to the current precision.
1770
1771 >>> print pi()
1772 3.141592653589793238462643383
1773
1774 """
1775 getcontext().prec += 2 # extra digits for intermediate steps
1776 three = Decimal(3) # substitute "three=3.0" for regular floats
1777 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1778 while s != lasts:
1779 lasts = s
1780 n, na = n+na, na+8
1781 d, da = d+da, da+32
1782 t = (t * n) / d
1783 s += t
1784 getcontext().prec -= 2
1785 return +s # unary plus applies the new precision
1786
1787 def exp(x):
1788 """Return e raised to the power of x. Result type matches input type.
1789
1790 >>> print exp(Decimal(1))
1791 2.718281828459045235360287471
1792 >>> print exp(Decimal(2))
1793 7.389056098930650227230427461
1794 >>> print exp(2.0)
1795 7.38905609893
1796 >>> print exp(2+0j)
1797 (7.38905609893+0j)
1798
1799 """
1800 getcontext().prec += 2
1801 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1802 while s != lasts:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001803 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001804 i += 1
1805 fact *= i
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001806 num *= x
1807 s += num / fact
1808 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001809 return +s
1810
1811 def cos(x):
1812 """Return the cosine of x as measured in radians.
1813
1814 >>> print cos(Decimal('0.5'))
1815 0.8775825618903727161162815826
1816 >>> print cos(0.5)
1817 0.87758256189
1818 >>> print cos(0.5+0j)
1819 (0.87758256189+0j)
1820
1821 """
1822 getcontext().prec += 2
1823 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1824 while s != lasts:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001825 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001826 i += 2
1827 fact *= i * (i-1)
1828 num *= x * x
1829 sign *= -1
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001830 s += num / fact * sign
1831 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001832 return +s
1833
1834 def sin(x):
1835 """Return the sine of x as measured in radians.
1836
1837 >>> print sin(Decimal('0.5'))
1838 0.4794255386042030002732879352
1839 >>> print sin(0.5)
1840 0.479425538604
1841 >>> print sin(0.5+0j)
1842 (0.479425538604+0j)
1843
1844 """
1845 getcontext().prec += 2
1846 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1847 while s != lasts:
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001848 lasts = s
Georg Brandl8ec7f652007-08-15 14:28:01 +00001849 i += 2
1850 fact *= i * (i-1)
1851 num *= x * x
1852 sign *= -1
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001853 s += num / fact * sign
1854 getcontext().prec -= 2
Georg Brandl8ec7f652007-08-15 14:28:01 +00001855 return +s
1856
1857
Georg Brandlb19be572007-12-29 10:57:00 +00001858.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001859
1860
1861.. _decimal-faq:
1862
1863Decimal FAQ
1864-----------
1865
1866Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1867minimize typing when using the interactive interpreter?
1868
Georg Brandl9f662322008-03-22 11:47:10 +00001869A. Some users abbreviate the constructor to just a single letter:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001870
1871 >>> D = decimal.Decimal
1872 >>> D('1.23') + D('3.45')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001873 Decimal('4.68')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001874
1875Q. In a fixed-point application with two decimal places, some inputs have many
1876places and need to be rounded. Others are not supposed to have excess digits
1877and need to be validated. What methods should be used?
1878
1879A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Georg Brandl9f662322008-03-22 11:47:10 +00001880the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001881
1882 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1883
1884 >>> # Round to two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001885 >>> Decimal('3.214').quantize(TWOPLACES)
1886 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001887
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001888 >>> # Validate that a number does not exceed two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001889 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1890 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001891
Raymond Hettingerabe32372008-02-14 02:41:22 +00001892 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001893 Traceback (most recent call last):
1894 ...
Georg Brandlf6dab952009-04-28 21:48:35 +00001895 Inexact: None
Georg Brandl8ec7f652007-08-15 14:28:01 +00001896
1897Q. Once I have valid two place inputs, how do I maintain that invariant
1898throughout an application?
1899
Raymond Hettinger46314812008-02-14 10:46:57 +00001900A. Some operations like addition, subtraction, and multiplication by an integer
1901will automatically preserve fixed point. Others operations, like division and
1902non-integer multiplication, will change the number of decimal places and need to
Georg Brandl9f662322008-03-22 11:47:10 +00001903be followed-up with a :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001904
1905 >>> a = Decimal('102.72') # Initial fixed-point values
1906 >>> b = Decimal('3.17')
1907 >>> a + b # Addition preserves fixed-point
1908 Decimal('105.89')
1909 >>> a - b
1910 Decimal('99.55')
1911 >>> a * 42 # So does integer multiplication
1912 Decimal('4314.24')
1913 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1914 Decimal('325.62')
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001915 >>> (b / a).quantize(TWOPLACES) # And quantize division
Raymond Hettinger46314812008-02-14 10:46:57 +00001916 Decimal('0.03')
1917
1918In developing fixed-point applications, it is convenient to define functions
Georg Brandl9f662322008-03-22 11:47:10 +00001919to handle the :meth:`quantize` step:
Raymond Hettinger46314812008-02-14 10:46:57 +00001920
Raymond Hettinger27a90d92008-02-14 11:01:10 +00001921 >>> def mul(x, y, fp=TWOPLACES):
1922 ... return (x * y).quantize(fp)
1923 >>> def div(x, y, fp=TWOPLACES):
1924 ... return (x / y).quantize(fp)
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001925
Raymond Hettinger46314812008-02-14 10:46:57 +00001926 >>> mul(a, b) # Automatically preserve fixed-point
1927 Decimal('325.62')
1928 >>> div(b, a)
1929 Decimal('0.03')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001930
1931Q. There are many ways to express the same value. The numbers :const:`200`,
1932:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1933various precisions. Is there a way to transform them to a single recognizable
1934canonical value?
1935
1936A. The :meth:`normalize` method maps all equivalent values to a single
Georg Brandl9f662322008-03-22 11:47:10 +00001937representative:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001938
1939 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1940 >>> [v.normalize() for v in values]
Raymond Hettingerabe32372008-02-14 02:41:22 +00001941 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001942
1943Q. Some decimal values always print with exponential notation. Is there a way
1944to get a non-exponential representation?
1945
1946A. For some values, exponential notation is the only way to express the number
1947of significant places in the coefficient. For example, expressing
1948:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1949original's two-place significance.
1950
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001951If an application does not care about tracking significance, it is easy to
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001952remove the exponent and trailing zeros, losing significance, but keeping the
1953value unchanged::
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001954
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001955 def remove_exponent(d):
1956 '''Remove exponent and trailing zeros.
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001957
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001958 >>> remove_exponent(Decimal('5E+3'))
1959 Decimal('5000')
Raymond Hettingerd68bf022008-02-14 11:57:25 +00001960
Raymond Hettingerced6b1d2009-03-10 08:16:05 +00001961 '''
1962 return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
Georg Brandl8ec7f652007-08-15 14:28:01 +00001963
Raymond Hettingered171ab2010-04-02 18:39:24 +00001964Q. Is there a way to convert a regular float to a :class:`Decimal`?
Georg Brandl9f662322008-03-22 11:47:10 +00001965
Mark Dickinsonb1affc52010-04-04 22:09:21 +00001966A. Yes, any binary floating point number can be exactly expressed as a
Raymond Hettingered171ab2010-04-02 18:39:24 +00001967Decimal though an exact conversion may take more precision than intuition would
1968suggest:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001969
Raymond Hettingered171ab2010-04-02 18:39:24 +00001970.. doctest::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001971
Raymond Hettingered171ab2010-04-02 18:39:24 +00001972 >>> Decimal(math.pi)
1973 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001974
1975Q. Within a complex calculation, how can I make sure that I haven't gotten a
1976spurious result because of insufficient precision or rounding anomalies.
1977
1978A. The decimal module makes it easy to test results. A best practice is to
1979re-run calculations using greater precision and with various rounding modes.
1980Widely differing results indicate insufficient precision, rounding mode issues,
1981ill-conditioned inputs, or a numerically unstable algorithm.
1982
1983Q. I noticed that context precision is applied to the results of operations but
1984not to the inputs. Is there anything to watch out for when mixing values of
1985different precisions?
1986
1987A. Yes. The principle is that all values are considered to be exact and so is
1988the arithmetic on those values. Only the results are rounded. The advantage
1989for inputs is that "what you type is what you get". A disadvantage is that the
Georg Brandl9f662322008-03-22 11:47:10 +00001990results can look odd if you forget that the inputs haven't been rounded:
1991
1992.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00001993
1994 >>> getcontext().prec = 3
Georg Brandl9f662322008-03-22 11:47:10 +00001995 >>> Decimal('3.104') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001996 Decimal('5.21')
Georg Brandl9f662322008-03-22 11:47:10 +00001997 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001998 Decimal('5.20')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001999
2000The solution is either to increase precision or to force rounding of inputs
Georg Brandl9f662322008-03-22 11:47:10 +00002001using the unary plus operation:
2002
2003.. doctest:: newcontext
Georg Brandl8ec7f652007-08-15 14:28:01 +00002004
2005 >>> getcontext().prec = 3
2006 >>> +Decimal('1.23456789') # unary plus triggers rounding
Raymond Hettingerabe32372008-02-14 02:41:22 +00002007 Decimal('1.23')
Georg Brandl8ec7f652007-08-15 14:28:01 +00002008
2009Alternatively, inputs can be rounded upon creation using the
Georg Brandl9f662322008-03-22 11:47:10 +00002010:meth:`Context.create_decimal` method:
Georg Brandl8ec7f652007-08-15 14:28:01 +00002011
2012 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Raymond Hettingerabe32372008-02-14 02:41:22 +00002013 Decimal('1.2345')
Georg Brandl8ec7f652007-08-15 14:28:01 +00002014