blob: e82929cd6cbc148d206d92bbb6bce7c021d2ac75 [file] [log] [blame]
Christian Heimes3feef612008-02-11 06:19:17 +00001:mod:`decimal` --- Decimal fixed point and floating point arithmetic
2====================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: decimal
5 :synopsis: Implementation of the General Decimal Arithmetic Specification.
6
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
8.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
9.. moduleauthor:: Raymond Hettinger <python at rcn.com>
10.. moduleauthor:: Aahz <aahz at pobox.com>
11.. moduleauthor:: Tim Peters <tim.one at comcast.net>
Georg Brandl116aa622007-08-15 14:28:22 +000012.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
13
Christian Heimesfe337bf2008-03-23 21:54:12 +000014.. import modules for testing inline doctests with the Sphinx doctest builder
15.. testsetup:: *
16
17 import decimal
18 import math
19 from decimal import *
20 # make sure each group gets a fresh context
21 setcontext(Context())
Georg Brandl116aa622007-08-15 14:28:22 +000022
Georg Brandl116aa622007-08-15 14:28:22 +000023The :mod:`decimal` module provides support for decimal floating point
Thomas Wouters1b7f8912007-09-19 03:06:30 +000024arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl116aa622007-08-15 14:28:22 +000025
Christian Heimes3feef612008-02-11 06:19:17 +000026* Decimal "is based on a floating-point model which was designed with people
27 in mind, and necessarily has a paramount guiding principle -- computers must
28 provide an arithmetic that works in the same way as the arithmetic that
29 people learn at school." -- excerpt from the decimal arithmetic specification.
30
Georg Brandl116aa622007-08-15 14:28:22 +000031* Decimal numbers can be represented exactly. In contrast, numbers like
Raymond Hettingerd258d1e2009-04-23 22:06:12 +000032 :const:`1.1` and :const:`2.2` do not have an exact representations in binary
33 floating point. End users typically would not expect ``1.1 + 2.2`` to display
34 as :const:`3.3000000000000003` as it does with binary floating point.
Georg Brandl116aa622007-08-15 14:28:22 +000035
36* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000037 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl116aa622007-08-15 14:28:22 +000038 is :const:`5.5511151231257827e-017`. While near to zero, the differences
39 prevent reliable equality testing and differences can accumulate. For this
Christian Heimes3feef612008-02-11 06:19:17 +000040 reason, decimal is preferred in accounting applications which have strict
Georg Brandl116aa622007-08-15 14:28:22 +000041 equality invariants.
42
43* The decimal module incorporates a notion of significant places so that ``1.30
44 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
45 This is the customary presentation for monetary applications. For
46 multiplication, the "schoolbook" approach uses all the figures in the
47 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
48 1.20`` gives :const:`1.5600`.
49
50* Unlike hardware based binary floating point, the decimal module has a user
Thomas Wouters1b7f8912007-09-19 03:06:30 +000051 alterable precision (defaulting to 28 places) which can be as large as needed for
Christian Heimesfe337bf2008-03-23 21:54:12 +000052 a given problem:
Georg Brandl116aa622007-08-15 14:28:22 +000053
54 >>> getcontext().prec = 6
55 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000056 Decimal('0.142857')
Georg Brandl116aa622007-08-15 14:28:22 +000057 >>> getcontext().prec = 28
58 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000059 Decimal('0.1428571428571428571428571429')
Georg Brandl116aa622007-08-15 14:28:22 +000060
61* Both binary and decimal floating point are implemented in terms of published
62 standards. While the built-in float type exposes only a modest portion of its
63 capabilities, the decimal module exposes all required parts of the standard.
64 When needed, the programmer has full control over rounding and signal handling.
Christian Heimes3feef612008-02-11 06:19:17 +000065 This includes an option to enforce exact arithmetic by using exceptions
66 to block any inexact operations.
67
68* The decimal module was designed to support "without prejudice, both exact
69 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
70 and rounded floating-point arithmetic." -- excerpt from the decimal
71 arithmetic specification.
Georg Brandl116aa622007-08-15 14:28:22 +000072
73The module design is centered around three concepts: the decimal number, the
74context for arithmetic, and signals.
75
76A decimal number is immutable. It has a sign, coefficient digits, and an
77exponent. To preserve significance, the coefficient digits do not truncate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000078trailing zeros. Decimals also include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +000079:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
80differentiates :const:`-0` from :const:`+0`.
81
82The context for arithmetic is an environment specifying precision, rounding
83rules, limits on exponents, flags indicating the results of operations, and trap
84enablers which determine whether signals are treated as exceptions. Rounding
85options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
86:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +000087:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl116aa622007-08-15 14:28:22 +000088
89Signals are groups of exceptional conditions arising during the course of
90computation. Depending on the needs of the application, signals may be ignored,
91considered as informational, or treated as exceptions. The signals in the
92decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
93:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
94:const:`Overflow`, and :const:`Underflow`.
95
96For each signal there is a flag and a trap enabler. When a signal is
Raymond Hettinger86173da2008-02-01 20:38:12 +000097encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl116aa622007-08-15 14:28:22 +000098set to one, an exception is raised. Flags are sticky, so the user needs to
99reset them before monitoring a calculation.
100
101
102.. seealso::
103
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000104 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
Raymond Hettinger960dc362009-04-21 03:43:15 +0000105 Specification <http://speleotrove.com/decimal/decarith.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000106
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000107 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Christian Heimes77c02eb2008-02-09 02:18:51 +0000108 <http://754r.ucbtest.org/standards/854.pdf>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000109
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000110.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112
113.. _decimal-tutorial:
114
115Quick-start Tutorial
116--------------------
117
118The usual start to using decimals is importing the module, viewing the current
119context with :func:`getcontext` and, if necessary, setting new values for
120precision, rounding, or enabled traps::
121
122 >>> from decimal import *
123 >>> getcontext()
124 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000125 capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000126 InvalidOperation])
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128 >>> getcontext().prec = 7 # Set a new precision
129
Mark Dickinsone534a072010-04-04 22:13:14 +0000130Decimal instances can be constructed from integers, strings, floats, or tuples.
131Construction from an integer or a float performs an exact conversion of the
132value of that integer or float. Decimal numbers include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +0000133:const:`NaN` which stands for "Not a number", positive and negative
Christian Heimesfe337bf2008-03-23 21:54:12 +0000134:const:`Infinity`, and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000135
Facundo Batista789bdf02008-06-21 17:29:41 +0000136 >>> getcontext().prec = 28
Georg Brandl116aa622007-08-15 14:28:22 +0000137 >>> Decimal(10)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000138 Decimal('10')
139 >>> Decimal('3.14')
140 Decimal('3.14')
Mark Dickinsone534a072010-04-04 22:13:14 +0000141 >>> Decimal(3.14)
142 Decimal('3.140000000000000124344978758017532527446746826171875')
Georg Brandl116aa622007-08-15 14:28:22 +0000143 >>> Decimal((0, (3, 1, 4), -2))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000144 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000145 >>> Decimal(str(2.0 ** 0.5))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000146 Decimal('1.41421356237')
147 >>> Decimal(2) ** Decimal('0.5')
148 Decimal('1.414213562373095048801688724')
149 >>> Decimal('NaN')
150 Decimal('NaN')
151 >>> Decimal('-Infinity')
152 Decimal('-Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154The significance of a new Decimal is determined solely by the number of digits
155input. Context precision and rounding only come into play during arithmetic
Christian Heimesfe337bf2008-03-23 21:54:12 +0000156operations.
157
158.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000159
160 >>> getcontext().prec = 6
161 >>> Decimal('3.0')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000162 Decimal('3.0')
Georg Brandl116aa622007-08-15 14:28:22 +0000163 >>> Decimal('3.1415926535')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000164 Decimal('3.1415926535')
Georg Brandl116aa622007-08-15 14:28:22 +0000165 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000166 Decimal('5.85987')
Georg Brandl116aa622007-08-15 14:28:22 +0000167 >>> getcontext().rounding = ROUND_UP
168 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000169 Decimal('5.85988')
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171Decimals interact well with much of the rest of Python. Here is a small decimal
Christian Heimesfe337bf2008-03-23 21:54:12 +0000172floating point flying circus:
173
174.. doctest::
175 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000176
Facundo Batista789bdf02008-06-21 17:29:41 +0000177 >>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
Georg Brandl116aa622007-08-15 14:28:22 +0000178 >>> max(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000179 Decimal('9.25')
Georg Brandl116aa622007-08-15 14:28:22 +0000180 >>> min(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000181 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +0000182 >>> sorted(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000183 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
184 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl116aa622007-08-15 14:28:22 +0000185 >>> sum(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000186 Decimal('19.29')
Georg Brandl116aa622007-08-15 14:28:22 +0000187 >>> a,b,c = data[:3]
188 >>> str(a)
189 '1.34'
190 >>> float(a)
Mark Dickinson8dad7df2009-06-28 20:36:54 +0000191 1.34
192 >>> round(a, 1)
193 Decimal('1.3')
Georg Brandl116aa622007-08-15 14:28:22 +0000194 >>> int(a)
195 1
196 >>> a * 5
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000197 Decimal('6.70')
Georg Brandl116aa622007-08-15 14:28:22 +0000198 >>> a * b
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000199 Decimal('2.5058')
Georg Brandl116aa622007-08-15 14:28:22 +0000200 >>> c % a
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000201 Decimal('0.77')
Georg Brandl116aa622007-08-15 14:28:22 +0000202
Christian Heimesfe337bf2008-03-23 21:54:12 +0000203And some mathematical functions are also available to Decimal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000204
Facundo Batista789bdf02008-06-21 17:29:41 +0000205 >>> getcontext().prec = 28
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000206 >>> Decimal(2).sqrt()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000207 Decimal('1.414213562373095048801688724')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000208 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000209 Decimal('2.718281828459045235360287471')
210 >>> Decimal('10').ln()
211 Decimal('2.302585092994045684017991455')
212 >>> Decimal('10').log10()
213 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000214
Georg Brandl116aa622007-08-15 14:28:22 +0000215The :meth:`quantize` method rounds a number to a fixed exponent. This method is
216useful for monetary applications that often round results to a fixed number of
Christian Heimesfe337bf2008-03-23 21:54:12 +0000217places:
Georg Brandl116aa622007-08-15 14:28:22 +0000218
219 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000220 Decimal('7.32')
Georg Brandl116aa622007-08-15 14:28:22 +0000221 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000222 Decimal('8')
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224As shown above, the :func:`getcontext` function accesses the current context and
225allows the settings to be changed. This approach meets the needs of most
226applications.
227
228For more advanced work, it may be useful to create alternate contexts using the
229Context() constructor. To make an alternate active, use the :func:`setcontext`
230function.
231
232In accordance with the standard, the :mod:`Decimal` module provides two ready to
233use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
234former is especially useful for debugging because many of the traps are
Christian Heimesfe337bf2008-03-23 21:54:12 +0000235enabled:
236
237.. doctest:: newcontext
238 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000239
240 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
241 >>> setcontext(myothercontext)
242 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000243 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245 >>> ExtendedContext
246 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000247 capitals=1, clamp=0, flags=[], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000248 >>> setcontext(ExtendedContext)
249 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000250 Decimal('0.142857143')
Georg Brandl116aa622007-08-15 14:28:22 +0000251 >>> Decimal(42) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000252 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000253
254 >>> setcontext(BasicContext)
255 >>> Decimal(42) / Decimal(0)
256 Traceback (most recent call last):
257 File "<pyshell#143>", line 1, in -toplevel-
258 Decimal(42) / Decimal(0)
259 DivisionByZero: x / 0
260
261Contexts also have signal flags for monitoring exceptional conditions
262encountered during computations. The flags remain set until explicitly cleared,
263so it is best to clear the flags before each set of monitored computations by
264using the :meth:`clear_flags` method. ::
265
266 >>> setcontext(ExtendedContext)
267 >>> getcontext().clear_flags()
268 >>> Decimal(355) / Decimal(113)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000269 Decimal('3.14159292')
Georg Brandl116aa622007-08-15 14:28:22 +0000270 >>> getcontext()
271 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000272 capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000273
274The *flags* entry shows that the rational approximation to :const:`Pi` was
275rounded (digits beyond the context precision were thrown away) and that the
276result is inexact (some of the discarded digits were non-zero).
277
278Individual traps are set using the dictionary in the :attr:`traps` field of a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000279context:
Georg Brandl116aa622007-08-15 14:28:22 +0000280
Christian Heimesfe337bf2008-03-23 21:54:12 +0000281.. doctest:: newcontext
282
283 >>> setcontext(ExtendedContext)
Georg Brandl116aa622007-08-15 14:28:22 +0000284 >>> Decimal(1) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000285 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000286 >>> getcontext().traps[DivisionByZero] = 1
287 >>> Decimal(1) / Decimal(0)
288 Traceback (most recent call last):
289 File "<pyshell#112>", line 1, in -toplevel-
290 Decimal(1) / Decimal(0)
291 DivisionByZero: x / 0
292
293Most programs adjust the current context only once, at the beginning of the
294program. And, in many applications, data is converted to :class:`Decimal` with
295a single cast inside a loop. With context set and decimals created, the bulk of
296the program manipulates the data no differently than with other Python numeric
297types.
298
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000299.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000300
301
302.. _decimal-decimal:
303
304Decimal objects
305---------------
306
307
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000308.. class:: Decimal(value="0", context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000309
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000310 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl116aa622007-08-15 14:28:22 +0000311
Raymond Hettinger96798592010-04-02 16:58:27 +0000312 *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal`
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000313 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Christian Heimesa62da1d2008-01-12 19:39:10 +0000314 string, it should conform to the decimal numeric string syntax after leading
315 and trailing whitespace characters are removed::
Georg Brandl116aa622007-08-15 14:28:22 +0000316
317 sign ::= '+' | '-'
318 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
319 indicator ::= 'e' | 'E'
320 digits ::= digit [digit]...
321 decimal-part ::= digits '.' [digits] | ['.'] digits
322 exponent-part ::= indicator [sign] digits
323 infinity ::= 'Infinity' | 'Inf'
324 nan ::= 'NaN' [digits] | 'sNaN' [digits]
325 numeric-value ::= decimal-part [exponent-part] | infinity
Georg Brandl48310cd2009-01-03 21:18:54 +0000326 numeric-string ::= [sign] numeric-value | [sign] nan
Georg Brandl116aa622007-08-15 14:28:22 +0000327
Mark Dickinson345adc42009-08-02 10:14:23 +0000328 Other Unicode decimal digits are also permitted where ``digit``
329 appears above. These include decimal digits from various other
330 alphabets (for example, Arabic-Indic and Devanāgarī digits) along
331 with the fullwidth digits ``'\uff10'`` through ``'\uff19'``.
332
Georg Brandl116aa622007-08-15 14:28:22 +0000333 If *value* is a :class:`tuple`, it should have three components, a sign
334 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
335 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000336 returns ``Decimal('1.414')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000337
Raymond Hettinger96798592010-04-02 16:58:27 +0000338 If *value* is a :class:`float`, the binary floating point value is losslessly
339 converted to its exact decimal equivalent. This conversion can often require
Mark Dickinsone534a072010-04-04 22:13:14 +0000340 53 or more digits of precision. For example, ``Decimal(float('1.1'))``
341 converts to
342 ``Decimal('1.100000000000000088817841970012523233890533447265625')``.
Raymond Hettinger96798592010-04-02 16:58:27 +0000343
Georg Brandl116aa622007-08-15 14:28:22 +0000344 The *context* precision does not affect how many digits are stored. That is
345 determined exclusively by the number of digits in *value*. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000346 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl116aa622007-08-15 14:28:22 +0000347 only three.
348
349 The purpose of the *context* argument is determining what to do if *value* is a
350 malformed string. If the context traps :const:`InvalidOperation`, an exception
351 is raised; otherwise, the constructor returns a new Decimal with the value of
352 :const:`NaN`.
353
354 Once constructed, :class:`Decimal` objects are immutable.
355
Mark Dickinsone534a072010-04-04 22:13:14 +0000356 .. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000357 The argument to the constructor is now permitted to be a :class:`float`
358 instance.
Mark Dickinsone534a072010-04-04 22:13:14 +0000359
Benjamin Petersone41251e2008-04-25 01:59:09 +0000360 Decimal floating point objects share many properties with the other built-in
361 numeric types such as :class:`float` and :class:`int`. All of the usual math
362 operations and special methods apply. Likewise, decimal objects can be
363 copied, pickled, printed, used as dictionary keys, used as set elements,
364 compared, sorted, and coerced to another type (such as :class:`float` or
Mark Dickinson5d233fd2010-02-18 14:54:37 +0000365 :class:`int`).
Christian Heimesa62da1d2008-01-12 19:39:10 +0000366
Mark Dickinson08ade6f2010-06-11 10:44:52 +0000367 Decimal objects cannot generally be combined with floats or
368 instances of :class:`fractions.Fraction` in arithmetic operations:
369 an attempt to add a :class:`Decimal` to a :class:`float`, for
370 example, will raise a :exc:`TypeError`. However, it is possible to
371 use Python's comparison operators to compare a :class:`Decimal`
372 instance ``x`` with another number ``y``. This avoids confusing results
373 when doing equality comparisons between numbers of different types.
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000374
Ezio Melotti993a5ee2010-04-04 06:30:08 +0000375 .. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000376 Mixed-type comparisons between :class:`Decimal` instances and other
377 numeric types are now fully supported.
Mark Dickinsonac256ab2010-04-03 11:08:14 +0000378
Benjamin Petersone41251e2008-04-25 01:59:09 +0000379 In addition to the standard numeric properties, decimal floating point
380 objects also have a number of specialized methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Georg Brandl116aa622007-08-15 14:28:22 +0000382
Benjamin Petersone41251e2008-04-25 01:59:09 +0000383 .. method:: adjusted()
Georg Brandl116aa622007-08-15 14:28:22 +0000384
Benjamin Petersone41251e2008-04-25 01:59:09 +0000385 Return the adjusted exponent after shifting out the coefficient's
386 rightmost digits until only the lead digit remains:
387 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
388 position of the most significant digit with respect to the decimal point.
Georg Brandl116aa622007-08-15 14:28:22 +0000389
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Benjamin Petersone41251e2008-04-25 01:59:09 +0000391 .. method:: as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +0000392
Benjamin Petersone41251e2008-04-25 01:59:09 +0000393 Return a :term:`named tuple` representation of the number:
394 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000395
Christian Heimes25bb7832008-01-11 16:17:00 +0000396
Benjamin Petersone41251e2008-04-25 01:59:09 +0000397 .. method:: canonical()
Georg Brandl116aa622007-08-15 14:28:22 +0000398
Benjamin Petersone41251e2008-04-25 01:59:09 +0000399 Return the canonical encoding of the argument. Currently, the encoding of
400 a :class:`Decimal` instance is always canonical, so this operation returns
401 its argument unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000402
Benjamin Petersone41251e2008-04-25 01:59:09 +0000403 .. method:: compare(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000404
Georg Brandl05f5ab72008-09-24 09:11:47 +0000405 Compare the values of two Decimal instances. :meth:`compare` returns a
406 Decimal instance, and if either operand is a NaN then the result is a
407 NaN::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000408
Georg Brandl05f5ab72008-09-24 09:11:47 +0000409 a or b is a NaN ==> Decimal('NaN')
410 a < b ==> Decimal('-1')
411 a == b ==> Decimal('0')
412 a > b ==> Decimal('1')
Georg Brandl116aa622007-08-15 14:28:22 +0000413
Benjamin Petersone41251e2008-04-25 01:59:09 +0000414 .. method:: compare_signal(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000415
Benjamin Petersone41251e2008-04-25 01:59:09 +0000416 This operation is identical to the :meth:`compare` method, except that all
417 NaNs signal. That is, if neither operand is a signaling NaN then any
418 quiet NaN operand is treated as though it were a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Benjamin Petersone41251e2008-04-25 01:59:09 +0000420 .. method:: compare_total(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000421
Benjamin Petersone41251e2008-04-25 01:59:09 +0000422 Compare two operands using their abstract representation rather than their
423 numerical value. Similar to the :meth:`compare` method, but the result
424 gives a total ordering on :class:`Decimal` instances. Two
425 :class:`Decimal` instances with the same numeric value but different
426 representations compare unequal in this ordering:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000427
Benjamin Petersone41251e2008-04-25 01:59:09 +0000428 >>> Decimal('12.0').compare_total(Decimal('12'))
429 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000430
Benjamin Petersone41251e2008-04-25 01:59:09 +0000431 Quiet and signaling NaNs are also included in the total ordering. The
432 result of this function is ``Decimal('0')`` if both operands have the same
433 representation, ``Decimal('-1')`` if the first operand is lower in the
434 total order than the second, and ``Decimal('1')`` if the first operand is
435 higher in the total order than the second operand. See the specification
436 for details of the total order.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000437
Benjamin Petersone41251e2008-04-25 01:59:09 +0000438 .. method:: compare_total_mag(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000439
Benjamin Petersone41251e2008-04-25 01:59:09 +0000440 Compare two operands using their abstract representation rather than their
441 value as in :meth:`compare_total`, but ignoring the sign of each operand.
442 ``x.compare_total_mag(y)`` is equivalent to
443 ``x.copy_abs().compare_total(y.copy_abs())``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000444
Facundo Batista789bdf02008-06-21 17:29:41 +0000445 .. method:: conjugate()
446
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000447 Just returns self, this method is only to comply with the Decimal
Facundo Batista789bdf02008-06-21 17:29:41 +0000448 Specification.
449
Benjamin Petersone41251e2008-04-25 01:59:09 +0000450 .. method:: copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000451
Benjamin Petersone41251e2008-04-25 01:59:09 +0000452 Return the absolute value of the argument. This operation is unaffected
453 by the context and is quiet: no flags are changed and no rounding is
454 performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000455
Benjamin Petersone41251e2008-04-25 01:59:09 +0000456 .. method:: copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000457
Benjamin Petersone41251e2008-04-25 01:59:09 +0000458 Return the negation of the argument. This operation is unaffected by the
459 context and is quiet: no flags are changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000460
Benjamin Petersone41251e2008-04-25 01:59:09 +0000461 .. method:: copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000462
Benjamin Petersone41251e2008-04-25 01:59:09 +0000463 Return a copy of the first operand with the sign set to be the same as the
464 sign of the second operand. For example:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000465
Benjamin Petersone41251e2008-04-25 01:59:09 +0000466 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
467 Decimal('-2.3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000468
Benjamin Petersone41251e2008-04-25 01:59:09 +0000469 This operation is unaffected by the context and is quiet: no flags are
470 changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000471
Benjamin Petersone41251e2008-04-25 01:59:09 +0000472 .. method:: exp([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000473
Benjamin Petersone41251e2008-04-25 01:59:09 +0000474 Return the value of the (natural) exponential function ``e**x`` at the
475 given number. The result is correctly rounded using the
476 :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000477
Benjamin Petersone41251e2008-04-25 01:59:09 +0000478 >>> Decimal(1).exp()
479 Decimal('2.718281828459045235360287471')
480 >>> Decimal(321).exp()
481 Decimal('2.561702493119680037517373933E+139')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000482
Raymond Hettinger771ed762009-01-03 19:20:32 +0000483 .. method:: from_float(f)
484
485 Classmethod that converts a float to a decimal number, exactly.
486
487 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
488 Since 0.1 is not exactly representable in binary floating point, the
489 value is stored as the nearest representable value which is
490 `0x1.999999999999ap-4`. That equivalent value in decimal is
491 `0.1000000000000000055511151231257827021181583404541015625`.
492
Mark Dickinsone534a072010-04-04 22:13:14 +0000493 .. note:: From Python 3.2 onwards, a :class:`Decimal` instance
494 can also be constructed directly from a :class:`float`.
495
Raymond Hettinger771ed762009-01-03 19:20:32 +0000496 .. doctest::
497
498 >>> Decimal.from_float(0.1)
499 Decimal('0.1000000000000000055511151231257827021181583404541015625')
500 >>> Decimal.from_float(float('nan'))
501 Decimal('NaN')
502 >>> Decimal.from_float(float('inf'))
503 Decimal('Infinity')
504 >>> Decimal.from_float(float('-inf'))
505 Decimal('-Infinity')
506
Georg Brandl45f53372009-01-03 21:15:20 +0000507 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000508
Benjamin Petersone41251e2008-04-25 01:59:09 +0000509 .. method:: fma(other, third[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510
Benjamin Petersone41251e2008-04-25 01:59:09 +0000511 Fused multiply-add. Return self*other+third with no rounding of the
512 intermediate product self*other.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000513
Benjamin Petersone41251e2008-04-25 01:59:09 +0000514 >>> Decimal(2).fma(3, 5)
515 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000516
Benjamin Petersone41251e2008-04-25 01:59:09 +0000517 .. method:: is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000518
Benjamin Petersone41251e2008-04-25 01:59:09 +0000519 Return :const:`True` if the argument is canonical and :const:`False`
520 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
521 this operation always returns :const:`True`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522
Benjamin Petersone41251e2008-04-25 01:59:09 +0000523 .. method:: is_finite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000524
Benjamin Petersone41251e2008-04-25 01:59:09 +0000525 Return :const:`True` if the argument is a finite number, and
526 :const:`False` if the argument is an infinity or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000527
Benjamin Petersone41251e2008-04-25 01:59:09 +0000528 .. method:: is_infinite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000529
Benjamin Petersone41251e2008-04-25 01:59:09 +0000530 Return :const:`True` if the argument is either positive or negative
531 infinity and :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000532
Benjamin Petersone41251e2008-04-25 01:59:09 +0000533 .. method:: is_nan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000534
Benjamin Petersone41251e2008-04-25 01:59:09 +0000535 Return :const:`True` if the argument is a (quiet or signaling) NaN and
536 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000537
Benjamin Petersone41251e2008-04-25 01:59:09 +0000538 .. method:: is_normal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000539
Benjamin Petersone41251e2008-04-25 01:59:09 +0000540 Return :const:`True` if the argument is a *normal* finite number. Return
541 :const:`False` if the argument is zero, subnormal, infinite or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000542
Benjamin Petersone41251e2008-04-25 01:59:09 +0000543 .. method:: is_qnan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000544
Benjamin Petersone41251e2008-04-25 01:59:09 +0000545 Return :const:`True` if the argument is a quiet NaN, and
546 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000547
Benjamin Petersone41251e2008-04-25 01:59:09 +0000548 .. method:: is_signed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000549
Benjamin Petersone41251e2008-04-25 01:59:09 +0000550 Return :const:`True` if the argument has a negative sign and
551 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000552
Benjamin Petersone41251e2008-04-25 01:59:09 +0000553 .. method:: is_snan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000554
Benjamin Petersone41251e2008-04-25 01:59:09 +0000555 Return :const:`True` if the argument is a signaling NaN and :const:`False`
556 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000557
Benjamin Petersone41251e2008-04-25 01:59:09 +0000558 .. method:: is_subnormal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000559
Benjamin Petersone41251e2008-04-25 01:59:09 +0000560 Return :const:`True` if the argument is subnormal, and :const:`False`
561 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000562
Benjamin Petersone41251e2008-04-25 01:59:09 +0000563 .. method:: is_zero()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000564
Benjamin Petersone41251e2008-04-25 01:59:09 +0000565 Return :const:`True` if the argument is a (positive or negative) zero and
566 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000567
Benjamin Petersone41251e2008-04-25 01:59:09 +0000568 .. method:: ln([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000569
Benjamin Petersone41251e2008-04-25 01:59:09 +0000570 Return the natural (base e) logarithm of the operand. The result is
571 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000572
Benjamin Petersone41251e2008-04-25 01:59:09 +0000573 .. method:: log10([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000574
Benjamin Petersone41251e2008-04-25 01:59:09 +0000575 Return the base ten logarithm of the operand. The result is correctly
576 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000577
Benjamin Petersone41251e2008-04-25 01:59:09 +0000578 .. method:: logb([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000579
Benjamin Petersone41251e2008-04-25 01:59:09 +0000580 For a nonzero number, return the adjusted exponent of its operand as a
581 :class:`Decimal` instance. If the operand is a zero then
582 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
583 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
584 returned.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000585
Benjamin Petersone41251e2008-04-25 01:59:09 +0000586 .. method:: logical_and(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000587
Benjamin Petersone41251e2008-04-25 01:59:09 +0000588 :meth:`logical_and` is a logical operation which takes two *logical
589 operands* (see :ref:`logical_operands_label`). The result is the
590 digit-wise ``and`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000591
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000592 .. method:: logical_invert([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000593
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000594 :meth:`logical_invert` is a logical operation. The
Benjamin Petersone41251e2008-04-25 01:59:09 +0000595 result is the digit-wise inversion of the operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000596
Benjamin Petersone41251e2008-04-25 01:59:09 +0000597 .. method:: logical_or(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000598
Benjamin Petersone41251e2008-04-25 01:59:09 +0000599 :meth:`logical_or` is a logical operation which takes two *logical
600 operands* (see :ref:`logical_operands_label`). The result is the
601 digit-wise ``or`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602
Benjamin Petersone41251e2008-04-25 01:59:09 +0000603 .. method:: logical_xor(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
Benjamin Petersone41251e2008-04-25 01:59:09 +0000605 :meth:`logical_xor` is a logical operation which takes two *logical
606 operands* (see :ref:`logical_operands_label`). The result is the
607 digit-wise exclusive or of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000608
Benjamin Petersone41251e2008-04-25 01:59:09 +0000609 .. method:: max(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000610
Benjamin Petersone41251e2008-04-25 01:59:09 +0000611 Like ``max(self, other)`` except that the context rounding rule is applied
612 before returning and that :const:`NaN` values are either signaled or
613 ignored (depending on the context and whether they are signaling or
614 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000615
Benjamin Petersone41251e2008-04-25 01:59:09 +0000616 .. method:: max_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000617
Georg Brandl502d9a52009-07-26 15:02:41 +0000618 Similar to the :meth:`.max` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000619 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000620
Benjamin Petersone41251e2008-04-25 01:59:09 +0000621 .. method:: min(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000622
Benjamin Petersone41251e2008-04-25 01:59:09 +0000623 Like ``min(self, other)`` except that the context rounding rule is applied
624 before returning and that :const:`NaN` values are either signaled or
625 ignored (depending on the context and whether they are signaling or
626 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000627
Benjamin Petersone41251e2008-04-25 01:59:09 +0000628 .. method:: min_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000629
Georg Brandl502d9a52009-07-26 15:02:41 +0000630 Similar to the :meth:`.min` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000631 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000632
Benjamin Petersone41251e2008-04-25 01:59:09 +0000633 .. method:: next_minus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634
Benjamin Petersone41251e2008-04-25 01:59:09 +0000635 Return the largest number representable in the given context (or in the
636 current thread's context if no context is given) that is smaller than the
637 given operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000638
Benjamin Petersone41251e2008-04-25 01:59:09 +0000639 .. method:: next_plus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000640
Benjamin Petersone41251e2008-04-25 01:59:09 +0000641 Return the smallest number representable in the given context (or in the
642 current thread's context if no context is given) that is larger than the
643 given operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000644
Benjamin Petersone41251e2008-04-25 01:59:09 +0000645 .. method:: next_toward(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000646
Benjamin Petersone41251e2008-04-25 01:59:09 +0000647 If the two operands are unequal, return the number closest to the first
648 operand in the direction of the second operand. If both operands are
649 numerically equal, return a copy of the first operand with the sign set to
650 be the same as the sign of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000651
Benjamin Petersone41251e2008-04-25 01:59:09 +0000652 .. method:: normalize([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653
Benjamin Petersone41251e2008-04-25 01:59:09 +0000654 Normalize the number by stripping the rightmost trailing zeros and
655 converting any result equal to :const:`Decimal('0')` to
656 :const:`Decimal('0e0')`. Used for producing canonical values for members
657 of an equivalence class. For example, ``Decimal('32.100')`` and
658 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
659 ``Decimal('32.1')``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000660
Benjamin Petersone41251e2008-04-25 01:59:09 +0000661 .. method:: number_class([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662
Benjamin Petersone41251e2008-04-25 01:59:09 +0000663 Return a string describing the *class* of the operand. The returned value
664 is one of the following ten strings.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665
Benjamin Petersone41251e2008-04-25 01:59:09 +0000666 * ``"-Infinity"``, indicating that the operand is negative infinity.
667 * ``"-Normal"``, indicating that the operand is a negative normal number.
668 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
669 * ``"-Zero"``, indicating that the operand is a negative zero.
670 * ``"+Zero"``, indicating that the operand is a positive zero.
671 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
672 * ``"+Normal"``, indicating that the operand is a positive normal number.
673 * ``"+Infinity"``, indicating that the operand is positive infinity.
674 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
675 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676
Benjamin Petersone41251e2008-04-25 01:59:09 +0000677 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000678
Benjamin Petersone41251e2008-04-25 01:59:09 +0000679 Return a value equal to the first operand after rounding and having the
680 exponent of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000681
Benjamin Petersone41251e2008-04-25 01:59:09 +0000682 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
683 Decimal('1.414')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000684
Benjamin Petersone41251e2008-04-25 01:59:09 +0000685 Unlike other operations, if the length of the coefficient after the
686 quantize operation would be greater than precision, then an
687 :const:`InvalidOperation` is signaled. This guarantees that, unless there
688 is an error condition, the quantized exponent is always equal to that of
689 the right-hand operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000690
Benjamin Petersone41251e2008-04-25 01:59:09 +0000691 Also unlike other operations, quantize never signals Underflow, even if
692 the result is subnormal and inexact.
Georg Brandl116aa622007-08-15 14:28:22 +0000693
Benjamin Petersone41251e2008-04-25 01:59:09 +0000694 If the exponent of the second operand is larger than that of the first
695 then rounding may be necessary. In this case, the rounding mode is
696 determined by the ``rounding`` argument if given, else by the given
697 ``context`` argument; if neither argument is given the rounding mode of
698 the current thread's context is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000699
Benjamin Petersone41251e2008-04-25 01:59:09 +0000700 If *watchexp* is set (default), then an error is returned whenever the
701 resulting exponent is greater than :attr:`Emax` or less than
702 :attr:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Benjamin Petersone41251e2008-04-25 01:59:09 +0000704 .. method:: radix()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705
Benjamin Petersone41251e2008-04-25 01:59:09 +0000706 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
707 class does all its arithmetic. Included for compatibility with the
708 specification.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000709
Benjamin Petersone41251e2008-04-25 01:59:09 +0000710 .. method:: remainder_near(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000711
Benjamin Petersone41251e2008-04-25 01:59:09 +0000712 Compute the modulo as either a positive or negative value depending on
713 which is closest to zero. For instance, ``Decimal(10).remainder_near(6)``
714 returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000715
Benjamin Petersone41251e2008-04-25 01:59:09 +0000716 If both are equally close, the one chosen will have the same sign as
717 *self*.
Georg Brandl116aa622007-08-15 14:28:22 +0000718
Benjamin Petersone41251e2008-04-25 01:59:09 +0000719 .. method:: rotate(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000720
Benjamin Petersone41251e2008-04-25 01:59:09 +0000721 Return the result of rotating the digits of the first operand by an amount
722 specified by the second operand. The second operand must be an integer in
723 the range -precision through precision. The absolute value of the second
724 operand gives the number of places to rotate. If the second operand is
725 positive then rotation is to the left; otherwise rotation is to the right.
726 The coefficient of the first operand is padded on the left with zeros to
727 length precision if necessary. The sign and exponent of the first operand
728 are unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000729
Benjamin Petersone41251e2008-04-25 01:59:09 +0000730 .. method:: same_quantum(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000731
Benjamin Petersone41251e2008-04-25 01:59:09 +0000732 Test whether self and other have the same exponent or whether both are
733 :const:`NaN`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000734
Benjamin Petersone41251e2008-04-25 01:59:09 +0000735 .. method:: scaleb(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000736
Benjamin Petersone41251e2008-04-25 01:59:09 +0000737 Return the first operand with exponent adjusted by the second.
738 Equivalently, return the first operand multiplied by ``10**other``. The
739 second operand must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +0000740
Benjamin Petersone41251e2008-04-25 01:59:09 +0000741 .. method:: shift(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000742
Benjamin Petersone41251e2008-04-25 01:59:09 +0000743 Return the result of shifting the digits of the first operand by an amount
744 specified by the second operand. The second operand must be an integer in
745 the range -precision through precision. The absolute value of the second
746 operand gives the number of places to shift. If the second operand is
747 positive then the shift is to the left; otherwise the shift is to the
748 right. Digits shifted into the coefficient are zeros. The sign and
749 exponent of the first operand are unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +0000750
Benjamin Petersone41251e2008-04-25 01:59:09 +0000751 .. method:: sqrt([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000752
Benjamin Petersone41251e2008-04-25 01:59:09 +0000753 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000754
Georg Brandl116aa622007-08-15 14:28:22 +0000755
Benjamin Petersone41251e2008-04-25 01:59:09 +0000756 .. method:: to_eng_string([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000757
Benjamin Petersone41251e2008-04-25 01:59:09 +0000758 Convert to an engineering-type string.
Georg Brandl116aa622007-08-15 14:28:22 +0000759
Benjamin Petersone41251e2008-04-25 01:59:09 +0000760 Engineering notation has an exponent which is a multiple of 3, so there
761 are up to 3 digits left of the decimal place. For example, converts
762 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000763
Benjamin Petersone41251e2008-04-25 01:59:09 +0000764 .. method:: to_integral([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000765
Benjamin Petersone41251e2008-04-25 01:59:09 +0000766 Identical to the :meth:`to_integral_value` method. The ``to_integral``
767 name has been kept for compatibility with older versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000768
Benjamin Petersone41251e2008-04-25 01:59:09 +0000769 .. method:: to_integral_exact([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000770
Benjamin Petersone41251e2008-04-25 01:59:09 +0000771 Round to the nearest integer, signaling :const:`Inexact` or
772 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
773 determined by the ``rounding`` parameter if given, else by the given
774 ``context``. If neither parameter is given then the rounding mode of the
775 current context is used.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000776
Benjamin Petersone41251e2008-04-25 01:59:09 +0000777 .. method:: to_integral_value([rounding[, context]])
Georg Brandl116aa622007-08-15 14:28:22 +0000778
Benjamin Petersone41251e2008-04-25 01:59:09 +0000779 Round to the nearest integer without signaling :const:`Inexact` or
780 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
781 rounding method in either the supplied *context* or the current context.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000782
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000783
784.. _logical_operands_label:
785
786Logical operands
787^^^^^^^^^^^^^^^^
788
789The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
790and :meth:`logical_xor` methods expect their arguments to be *logical
791operands*. A *logical operand* is a :class:`Decimal` instance whose
792exponent and sign are both zero, and whose digits are all either
793:const:`0` or :const:`1`.
794
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000795.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000796
797
798.. _decimal-context:
799
800Context objects
801---------------
802
803Contexts are environments for arithmetic operations. They govern precision, set
804rules for rounding, determine which signals are treated as exceptions, and limit
805the range for exponents.
806
807Each thread has its own current context which is accessed or changed using the
808:func:`getcontext` and :func:`setcontext` functions:
809
810
811.. function:: getcontext()
812
813 Return the current context for the active thread.
814
815
816.. function:: setcontext(c)
817
818 Set the current context for the active thread to *c*.
819
Georg Brandle6bcc912008-05-12 18:05:20 +0000820You can also use the :keyword:`with` statement and the :func:`localcontext`
821function to temporarily change the active context.
Georg Brandl116aa622007-08-15 14:28:22 +0000822
823.. function:: localcontext([c])
824
825 Return a context manager that will set the current context for the active thread
826 to a copy of *c* on entry to the with-statement and restore the previous context
827 when exiting the with-statement. If no context is specified, a copy of the
828 current context is used.
829
Georg Brandl116aa622007-08-15 14:28:22 +0000830 For example, the following code sets the current decimal precision to 42 places,
831 performs a calculation, and then automatically restores the previous context::
832
Georg Brandl116aa622007-08-15 14:28:22 +0000833 from decimal import localcontext
834
835 with localcontext() as ctx:
836 ctx.prec = 42 # Perform a high precision calculation
837 s = calculate_something()
838 s = +s # Round the final result back to the default precision
839
840New contexts can also be created using the :class:`Context` constructor
841described below. In addition, the module provides three pre-made contexts:
842
843
844.. class:: BasicContext
845
846 This is a standard context defined by the General Decimal Arithmetic
847 Specification. Precision is set to nine. Rounding is set to
848 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
849 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
850 :const:`Subnormal`.
851
852 Because many of the traps are enabled, this context is useful for debugging.
853
854
855.. class:: ExtendedContext
856
857 This is a standard context defined by the General Decimal Arithmetic
858 Specification. Precision is set to nine. Rounding is set to
859 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
860 exceptions are not raised during computations).
861
Christian Heimes3feef612008-02-11 06:19:17 +0000862 Because the traps are disabled, this context is useful for applications that
Georg Brandl116aa622007-08-15 14:28:22 +0000863 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
864 raising exceptions. This allows an application to complete a run in the
865 presence of conditions that would otherwise halt the program.
866
867
868.. class:: DefaultContext
869
870 This context is used by the :class:`Context` constructor as a prototype for new
871 contexts. Changing a field (such a precision) has the effect of changing the
Stefan Kraha1193932010-05-29 12:59:18 +0000872 default for new contexts created by the :class:`Context` constructor.
Georg Brandl116aa622007-08-15 14:28:22 +0000873
874 This context is most useful in multi-threaded environments. Changing one of the
875 fields before threads are started has the effect of setting system-wide
876 defaults. Changing the fields after threads have started is not recommended as
877 it would require thread synchronization to prevent race conditions.
878
879 In single threaded environments, it is preferable to not use this context at
880 all. Instead, simply create contexts explicitly as described below.
881
882 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
883 for Overflow, InvalidOperation, and DivisionByZero.
884
885In addition to the three supplied contexts, new contexts can be created with the
886:class:`Context` constructor.
887
888
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000889.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=None, clamp=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000890
891 Creates a new context. If a field is not specified or is :const:`None`, the
892 default values are copied from the :const:`DefaultContext`. If the *flags*
893 field is not specified or is :const:`None`, all flags are cleared.
894
895 The *prec* field is a positive integer that sets the precision for arithmetic
896 operations in the context.
897
898 The *rounding* option is one of:
899
900 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
901 * :const:`ROUND_DOWN` (towards zero),
902 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
903 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
904 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
905 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
906 * :const:`ROUND_UP` (away from zero).
Georg Brandl48310cd2009-01-03 21:18:54 +0000907 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000908 would have been 0 or 5; otherwise towards zero)
Georg Brandl116aa622007-08-15 14:28:22 +0000909
910 The *traps* and *flags* fields list any signals to be set. Generally, new
911 contexts should only set traps and leave the flags clear.
912
913 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
914 for exponents.
915
916 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
917 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
918 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
919
Mark Dickinsonb1d8e322010-05-22 18:35:36 +0000920 The *clamp* field is either :const:`0` (the default) or :const:`1`.
921 If set to :const:`1`, the exponent ``e`` of a :class:`Decimal`
922 instance representable in this context is strictly limited to the
923 range ``Emin - prec + 1 <= e <= Emax - prec + 1``. If *clamp* is
924 :const:`0` then a weaker condition holds: the adjusted exponent of
925 the :class:`Decimal` instance is at most ``Emax``. When *clamp* is
926 :const:`1`, a large normal number will, where possible, have its
927 exponent reduced and a corresponding number of zeros added to its
928 coefficient, in order to fit the exponent constraints; this
929 preserves the value of the number but loses information about
930 significant trailing zeros. For example::
931
932 >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
933 Decimal('1.23000E+999')
934
935 A *clamp* value of :const:`1` allows compatibility with the
936 fixed-width decimal interchange formats specified in IEEE 754.
Georg Brandl116aa622007-08-15 14:28:22 +0000937
Benjamin Petersone41251e2008-04-25 01:59:09 +0000938 The :class:`Context` class defines several general purpose methods as well as
939 a large number of methods for doing arithmetic directly in a given context.
940 In addition, for each of the :class:`Decimal` methods described above (with
941 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
Mark Dickinson84230a12010-02-18 14:49:50 +0000942 a corresponding :class:`Context` method. For example, for a :class:`Context`
943 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
944 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a
Mark Dickinson5d233fd2010-02-18 14:54:37 +0000945 Python integer (an instance of :class:`int`) anywhere that a
Mark Dickinson84230a12010-02-18 14:49:50 +0000946 Decimal instance is accepted.
Georg Brandl116aa622007-08-15 14:28:22 +0000947
948
Benjamin Petersone41251e2008-04-25 01:59:09 +0000949 .. method:: clear_flags()
Georg Brandl116aa622007-08-15 14:28:22 +0000950
Benjamin Petersone41251e2008-04-25 01:59:09 +0000951 Resets all of the flags to :const:`0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000952
Benjamin Petersone41251e2008-04-25 01:59:09 +0000953 .. method:: copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000954
Benjamin Petersone41251e2008-04-25 01:59:09 +0000955 Return a duplicate of the context.
Georg Brandl116aa622007-08-15 14:28:22 +0000956
Benjamin Petersone41251e2008-04-25 01:59:09 +0000957 .. method:: copy_decimal(num)
Georg Brandl116aa622007-08-15 14:28:22 +0000958
Benjamin Petersone41251e2008-04-25 01:59:09 +0000959 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +0000960
Benjamin Petersone41251e2008-04-25 01:59:09 +0000961 .. method:: create_decimal(num)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000962
Benjamin Petersone41251e2008-04-25 01:59:09 +0000963 Creates a new Decimal instance from *num* but using *self* as
964 context. Unlike the :class:`Decimal` constructor, the context precision,
965 rounding method, flags, and traps are applied to the conversion.
Georg Brandl116aa622007-08-15 14:28:22 +0000966
Benjamin Petersone41251e2008-04-25 01:59:09 +0000967 This is useful because constants are often given to a greater precision
968 than is needed by the application. Another benefit is that rounding
969 immediately eliminates unintended effects from digits beyond the current
970 precision. In the following example, using unrounded inputs means that
971 adding zero to a sum can change the result:
Georg Brandl116aa622007-08-15 14:28:22 +0000972
Benjamin Petersone41251e2008-04-25 01:59:09 +0000973 .. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000974
Benjamin Petersone41251e2008-04-25 01:59:09 +0000975 >>> getcontext().prec = 3
976 >>> Decimal('3.4445') + Decimal('1.0023')
977 Decimal('4.45')
978 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
979 Decimal('4.44')
Georg Brandl116aa622007-08-15 14:28:22 +0000980
Benjamin Petersone41251e2008-04-25 01:59:09 +0000981 This method implements the to-number operation of the IBM specification.
982 If the argument is a string, no leading or trailing whitespace is
983 permitted.
984
Georg Brandl45f53372009-01-03 21:15:20 +0000985 .. method:: create_decimal_from_float(f)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000986
987 Creates a new Decimal instance from a float *f* but rounding using *self*
Georg Brandl45f53372009-01-03 21:15:20 +0000988 as the context. Unlike the :meth:`Decimal.from_float` class method,
Raymond Hettinger771ed762009-01-03 19:20:32 +0000989 the context precision, rounding method, flags, and traps are applied to
990 the conversion.
991
992 .. doctest::
993
Georg Brandl45f53372009-01-03 21:15:20 +0000994 >>> context = Context(prec=5, rounding=ROUND_DOWN)
995 >>> context.create_decimal_from_float(math.pi)
996 Decimal('3.1415')
997 >>> context = Context(prec=5, traps=[Inexact])
998 >>> context.create_decimal_from_float(math.pi)
999 Traceback (most recent call last):
1000 ...
1001 decimal.Inexact: None
Raymond Hettinger771ed762009-01-03 19:20:32 +00001002
Georg Brandl45f53372009-01-03 21:15:20 +00001003 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +00001004
Benjamin Petersone41251e2008-04-25 01:59:09 +00001005 .. method:: Etiny()
1006
1007 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
1008 value for subnormal results. When underflow occurs, the exponent is set
1009 to :const:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +00001010
Benjamin Petersone41251e2008-04-25 01:59:09 +00001011 .. method:: Etop()
Georg Brandl116aa622007-08-15 14:28:22 +00001012
Benjamin Petersone41251e2008-04-25 01:59:09 +00001013 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl116aa622007-08-15 14:28:22 +00001014
Benjamin Petersone41251e2008-04-25 01:59:09 +00001015 The usual approach to working with decimals is to create :class:`Decimal`
1016 instances and then apply arithmetic operations which take place within the
1017 current context for the active thread. An alternative approach is to use
1018 context methods for calculating within a specific context. The methods are
1019 similar to those for the :class:`Decimal` class and are only briefly
1020 recounted here.
Georg Brandl116aa622007-08-15 14:28:22 +00001021
1022
Benjamin Petersone41251e2008-04-25 01:59:09 +00001023 .. method:: abs(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001024
Benjamin Petersone41251e2008-04-25 01:59:09 +00001025 Returns the absolute value of *x*.
Georg Brandl116aa622007-08-15 14:28:22 +00001026
1027
Benjamin Petersone41251e2008-04-25 01:59:09 +00001028 .. method:: add(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001029
Benjamin Petersone41251e2008-04-25 01:59:09 +00001030 Return the sum of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001031
1032
Facundo Batista789bdf02008-06-21 17:29:41 +00001033 .. method:: canonical(x)
1034
1035 Returns the same Decimal object *x*.
1036
1037
1038 .. method:: compare(x, y)
1039
1040 Compares *x* and *y* numerically.
1041
1042
1043 .. method:: compare_signal(x, y)
1044
1045 Compares the values of the two operands numerically.
1046
1047
1048 .. method:: compare_total(x, y)
1049
1050 Compares two operands using their abstract representation.
1051
1052
1053 .. method:: compare_total_mag(x, y)
1054
1055 Compares two operands using their abstract representation, ignoring sign.
1056
1057
1058 .. method:: copy_abs(x)
1059
1060 Returns a copy of *x* with the sign set to 0.
1061
1062
1063 .. method:: copy_negate(x)
1064
1065 Returns a copy of *x* with the sign inverted.
1066
1067
1068 .. method:: copy_sign(x, y)
1069
1070 Copies the sign from *y* to *x*.
1071
1072
Benjamin Petersone41251e2008-04-25 01:59:09 +00001073 .. method:: divide(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001074
Benjamin Petersone41251e2008-04-25 01:59:09 +00001075 Return *x* divided by *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001076
1077
Benjamin Petersone41251e2008-04-25 01:59:09 +00001078 .. method:: divide_int(x, y)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001079
Benjamin Petersone41251e2008-04-25 01:59:09 +00001080 Return *x* divided by *y*, truncated to an integer.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001081
1082
Benjamin Petersone41251e2008-04-25 01:59:09 +00001083 .. method:: divmod(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001084
Benjamin Petersone41251e2008-04-25 01:59:09 +00001085 Divides two numbers and returns the integer part of the result.
Georg Brandl116aa622007-08-15 14:28:22 +00001086
1087
Facundo Batista789bdf02008-06-21 17:29:41 +00001088 .. method:: exp(x)
1089
1090 Returns `e ** x`.
1091
1092
1093 .. method:: fma(x, y, z)
1094
1095 Returns *x* multiplied by *y*, plus *z*.
1096
1097
1098 .. method:: is_canonical(x)
1099
1100 Returns True if *x* is canonical; otherwise returns False.
1101
1102
1103 .. method:: is_finite(x)
1104
1105 Returns True if *x* is finite; otherwise returns False.
1106
1107
1108 .. method:: is_infinite(x)
1109
1110 Returns True if *x* is infinite; otherwise returns False.
1111
1112
1113 .. method:: is_nan(x)
1114
1115 Returns True if *x* is a qNaN or sNaN; otherwise returns False.
1116
1117
1118 .. method:: is_normal(x)
1119
1120 Returns True if *x* is a normal number; otherwise returns False.
1121
1122
1123 .. method:: is_qnan(x)
1124
1125 Returns True if *x* is a quiet NaN; otherwise returns False.
1126
1127
1128 .. method:: is_signed(x)
1129
1130 Returns True if *x* is negative; otherwise returns False.
1131
1132
1133 .. method:: is_snan(x)
1134
1135 Returns True if *x* is a signaling NaN; otherwise returns False.
1136
1137
1138 .. method:: is_subnormal(x)
1139
1140 Returns True if *x* is subnormal; otherwise returns False.
1141
1142
1143 .. method:: is_zero(x)
1144
1145 Returns True if *x* is a zero; otherwise returns False.
1146
1147
1148 .. method:: ln(x)
1149
1150 Returns the natural (base e) logarithm of *x*.
1151
1152
1153 .. method:: log10(x)
1154
1155 Returns the base 10 logarithm of *x*.
1156
1157
1158 .. method:: logb(x)
1159
1160 Returns the exponent of the magnitude of the operand's MSD.
1161
1162
1163 .. method:: logical_and(x, y)
1164
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001165 Applies the logical operation *and* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001166
1167
1168 .. method:: logical_invert(x)
1169
1170 Invert all the digits in *x*.
1171
1172
1173 .. method:: logical_or(x, y)
1174
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001175 Applies the logical operation *or* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001176
1177
1178 .. method:: logical_xor(x, y)
1179
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001180 Applies the logical operation *xor* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001181
1182
1183 .. method:: max(x, y)
1184
1185 Compares two values numerically and returns the maximum.
1186
1187
1188 .. method:: max_mag(x, y)
1189
1190 Compares the values numerically with their sign ignored.
1191
1192
1193 .. method:: min(x, y)
1194
1195 Compares two values numerically and returns the minimum.
1196
1197
1198 .. method:: min_mag(x, y)
1199
1200 Compares the values numerically with their sign ignored.
1201
1202
Benjamin Petersone41251e2008-04-25 01:59:09 +00001203 .. method:: minus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001204
Benjamin Petersone41251e2008-04-25 01:59:09 +00001205 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001206
1207
Benjamin Petersone41251e2008-04-25 01:59:09 +00001208 .. method:: multiply(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001209
Benjamin Petersone41251e2008-04-25 01:59:09 +00001210 Return the product of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001211
1212
Facundo Batista789bdf02008-06-21 17:29:41 +00001213 .. method:: next_minus(x)
1214
1215 Returns the largest representable number smaller than *x*.
1216
1217
1218 .. method:: next_plus(x)
1219
1220 Returns the smallest representable number larger than *x*.
1221
1222
1223 .. method:: next_toward(x, y)
1224
1225 Returns the number closest to *x*, in direction towards *y*.
1226
1227
1228 .. method:: normalize(x)
1229
1230 Reduces *x* to its simplest form.
1231
1232
1233 .. method:: number_class(x)
1234
1235 Returns an indication of the class of *x*.
1236
1237
Benjamin Petersone41251e2008-04-25 01:59:09 +00001238 .. method:: plus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001239
Benjamin Petersone41251e2008-04-25 01:59:09 +00001240 Plus corresponds to the unary prefix plus operator in Python. This
1241 operation applies the context precision and rounding, so it is *not* an
1242 identity operation.
Georg Brandl116aa622007-08-15 14:28:22 +00001243
1244
Benjamin Petersone41251e2008-04-25 01:59:09 +00001245 .. method:: power(x, y[, modulo])
Georg Brandl116aa622007-08-15 14:28:22 +00001246
Benjamin Petersone41251e2008-04-25 01:59:09 +00001247 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl116aa622007-08-15 14:28:22 +00001248
Benjamin Petersone41251e2008-04-25 01:59:09 +00001249 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1250 must be integral. The result will be inexact unless ``y`` is integral and
1251 the result is finite and can be expressed exactly in 'precision' digits.
1252 The result should always be correctly rounded, using the rounding mode of
1253 the current thread's context.
Georg Brandl116aa622007-08-15 14:28:22 +00001254
Benjamin Petersone41251e2008-04-25 01:59:09 +00001255 With three arguments, compute ``(x**y) % modulo``. For the three argument
1256 form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +00001257
Benjamin Petersone41251e2008-04-25 01:59:09 +00001258 - all three arguments must be integral
1259 - ``y`` must be nonnegative
1260 - at least one of ``x`` or ``y`` must be nonzero
1261 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +00001262
Mark Dickinson5961b0e2010-02-22 15:41:48 +00001263 The value resulting from ``Context.power(x, y, modulo)`` is
1264 equal to the value that would be obtained by computing ``(x**y)
1265 % modulo`` with unbounded precision, but is computed more
1266 efficiently. The exponent of the result is zero, regardless of
1267 the exponents of ``x``, ``y`` and ``modulo``. The result is
1268 always exact.
Georg Brandl116aa622007-08-15 14:28:22 +00001269
Facundo Batista789bdf02008-06-21 17:29:41 +00001270
1271 .. method:: quantize(x, y)
1272
1273 Returns a value equal to *x* (rounded), having the exponent of *y*.
1274
1275
1276 .. method:: radix()
1277
1278 Just returns 10, as this is Decimal, :)
1279
1280
Benjamin Petersone41251e2008-04-25 01:59:09 +00001281 .. method:: remainder(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001282
Benjamin Petersone41251e2008-04-25 01:59:09 +00001283 Returns the remainder from integer division.
Georg Brandl116aa622007-08-15 14:28:22 +00001284
Benjamin Petersone41251e2008-04-25 01:59:09 +00001285 The sign of the result, if non-zero, is the same as that of the original
1286 dividend.
Georg Brandl116aa622007-08-15 14:28:22 +00001287
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001288
Facundo Batista789bdf02008-06-21 17:29:41 +00001289 .. method:: remainder_near(x, y)
1290
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001291 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1292 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
Facundo Batista789bdf02008-06-21 17:29:41 +00001293
1294
1295 .. method:: rotate(x, y)
1296
1297 Returns a rotated copy of *x*, *y* times.
1298
1299
1300 .. method:: same_quantum(x, y)
1301
1302 Returns True if the two operands have the same exponent.
1303
1304
1305 .. method:: scaleb (x, y)
1306
1307 Returns the first operand after adding the second value its exp.
1308
1309
1310 .. method:: shift(x, y)
1311
1312 Returns a shifted copy of *x*, *y* times.
1313
1314
1315 .. method:: sqrt(x)
1316
1317 Square root of a non-negative number to context precision.
1318
1319
Benjamin Petersone41251e2008-04-25 01:59:09 +00001320 .. method:: subtract(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001321
Benjamin Petersone41251e2008-04-25 01:59:09 +00001322 Return the difference between *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001323
Facundo Batista789bdf02008-06-21 17:29:41 +00001324
1325 .. method:: to_eng_string(x)
1326
1327 Converts a number to a string, using scientific notation.
1328
1329
1330 .. method:: to_integral_exact(x)
1331
1332 Rounds to an integer.
1333
1334
Benjamin Petersone41251e2008-04-25 01:59:09 +00001335 .. method:: to_sci_string(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001336
Benjamin Petersone41251e2008-04-25 01:59:09 +00001337 Converts a number to a string using scientific notation.
Georg Brandl116aa622007-08-15 14:28:22 +00001338
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001339.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001340
1341
1342.. _decimal-signals:
1343
1344Signals
1345-------
1346
1347Signals represent conditions that arise during computation. Each corresponds to
1348one context flag and one context trap enabler.
1349
Raymond Hettinger86173da2008-02-01 20:38:12 +00001350The context flag is set whenever the condition is encountered. After the
Georg Brandl116aa622007-08-15 14:28:22 +00001351computation, flags may be checked for informational purposes (for instance, to
1352determine whether a computation was exact). After checking the flags, be sure to
1353clear all flags before starting the next computation.
1354
1355If the context's trap enabler is set for the signal, then the condition causes a
1356Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1357is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1358condition.
1359
1360
1361.. class:: Clamped
1362
1363 Altered an exponent to fit representation constraints.
1364
1365 Typically, clamping occurs when an exponent falls outside the context's
1366 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001367 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001368
1369
1370.. class:: DecimalException
1371
1372 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1373
1374
1375.. class:: DivisionByZero
1376
1377 Signals the division of a non-infinite number by zero.
1378
1379 Can occur with division, modulo division, or when raising a number to a negative
1380 power. If this signal is not trapped, returns :const:`Infinity` or
1381 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1382
1383
1384.. class:: Inexact
1385
1386 Indicates that rounding occurred and the result is not exact.
1387
1388 Signals when non-zero digits were discarded during rounding. The rounded result
1389 is returned. The signal flag or trap is used to detect when results are
1390 inexact.
1391
1392
1393.. class:: InvalidOperation
1394
1395 An invalid operation was performed.
1396
1397 Indicates that an operation was requested that does not make sense. If not
1398 trapped, returns :const:`NaN`. Possible causes include::
1399
1400 Infinity - Infinity
1401 0 * Infinity
1402 Infinity / Infinity
1403 x % 0
1404 Infinity % x
1405 x._rescale( non-integer )
1406 sqrt(-x) and x > 0
1407 0 ** 0
1408 x ** (non-integer)
Georg Brandl48310cd2009-01-03 21:18:54 +00001409 x ** Infinity
Georg Brandl116aa622007-08-15 14:28:22 +00001410
1411
1412.. class:: Overflow
1413
1414 Numerical overflow.
1415
Benjamin Petersone41251e2008-04-25 01:59:09 +00001416 Indicates the exponent is larger than :attr:`Emax` after rounding has
1417 occurred. If not trapped, the result depends on the rounding mode, either
1418 pulling inward to the largest representable finite number or rounding outward
1419 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1420 are also signaled.
Georg Brandl116aa622007-08-15 14:28:22 +00001421
1422
1423.. class:: Rounded
1424
1425 Rounding occurred though possibly no information was lost.
1426
Benjamin Petersone41251e2008-04-25 01:59:09 +00001427 Signaled whenever rounding discards digits; even if those digits are zero
1428 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1429 the result unchanged. This signal is used to detect loss of significant
1430 digits.
Georg Brandl116aa622007-08-15 14:28:22 +00001431
1432
1433.. class:: Subnormal
1434
1435 Exponent was lower than :attr:`Emin` prior to rounding.
1436
Benjamin Petersone41251e2008-04-25 01:59:09 +00001437 Occurs when an operation result is subnormal (the exponent is too small). If
1438 not trapped, returns the result unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +00001439
1440
1441.. class:: Underflow
1442
1443 Numerical underflow with result rounded to zero.
1444
1445 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1446 and :class:`Subnormal` are also signaled.
1447
1448The following table summarizes the hierarchy of signals::
1449
1450 exceptions.ArithmeticError(exceptions.Exception)
1451 DecimalException
1452 Clamped
1453 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1454 Inexact
1455 Overflow(Inexact, Rounded)
1456 Underflow(Inexact, Rounded, Subnormal)
1457 InvalidOperation
1458 Rounded
1459 Subnormal
1460
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001461.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001462
1463
1464.. _decimal-notes:
1465
1466Floating Point Notes
1467--------------------
1468
1469
1470Mitigating round-off error with increased precision
1471^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1472
1473The use of decimal floating point eliminates decimal representation error
1474(making it possible to represent :const:`0.1` exactly); however, some operations
1475can still incur round-off error when non-zero digits exceed the fixed precision.
1476
1477The effects of round-off error can be amplified by the addition or subtraction
1478of nearly offsetting quantities resulting in loss of significance. Knuth
1479provides two instructive examples where rounded floating point arithmetic with
1480insufficient precision causes the breakdown of the associative and distributive
Christian Heimesfe337bf2008-03-23 21:54:12 +00001481properties of addition:
1482
1483.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001484
1485 # Examples from Seminumerical Algorithms, Section 4.2.2.
1486 >>> from decimal import Decimal, getcontext
1487 >>> getcontext().prec = 8
1488
1489 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1490 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001491 Decimal('9.5111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001492 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001493 Decimal('10')
Georg Brandl116aa622007-08-15 14:28:22 +00001494
1495 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1496 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001497 Decimal('0.01')
Georg Brandl116aa622007-08-15 14:28:22 +00001498 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001499 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001500
1501The :mod:`decimal` module makes it possible to restore the identities by
Christian Heimesfe337bf2008-03-23 21:54:12 +00001502expanding the precision sufficiently to avoid loss of significance:
1503
1504.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001505
1506 >>> getcontext().prec = 20
1507 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1508 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001509 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001510 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001511 Decimal('9.51111111')
Georg Brandl48310cd2009-01-03 21:18:54 +00001512 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001513 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1514 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001515 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001516 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001517 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001518
1519
1520Special values
1521^^^^^^^^^^^^^^
1522
1523The number system for the :mod:`decimal` module provides special values
1524including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001525and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001526
1527Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1528they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1529not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1530can result from rounding beyond the limits of the largest representable number.
1531
1532The infinities are signed (affine) and can be used in arithmetic operations
1533where they get treated as very large, indeterminate numbers. For instance,
1534adding a constant to infinity gives another infinite result.
1535
1536Some operations are indeterminate and return :const:`NaN`, or if the
1537:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1538``0/0`` returns :const:`NaN` which means "not a number". This variety of
1539:const:`NaN` is quiet and, once created, will flow through other computations
1540always resulting in another :const:`NaN`. This behavior can be useful for a
1541series of computations that occasionally have missing inputs --- it allows the
1542calculation to proceed while flagging specific results as invalid.
1543
1544A variant is :const:`sNaN` which signals rather than remaining quiet after every
1545operation. This is a useful return value when an invalid result needs to
1546interrupt a calculation for special handling.
1547
Christian Heimes77c02eb2008-02-09 02:18:51 +00001548The behavior of Python's comparison operators can be a little surprising where a
1549:const:`NaN` is involved. A test for equality where one of the operands is a
1550quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1551``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1552:const:`True`. An attempt to compare two Decimals using any of the ``<``,
1553``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1554if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes3feef612008-02-11 06:19:17 +00001555not trapped. Note that the General Decimal Arithmetic specification does not
Christian Heimes77c02eb2008-02-09 02:18:51 +00001556specify the behavior of direct comparisons; these rules for comparisons
1557involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1558section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1559and :meth:`compare-signal` methods instead.
1560
Georg Brandl116aa622007-08-15 14:28:22 +00001561The signed zeros can result from calculations that underflow. They keep the sign
1562that would have resulted if the calculation had been carried out to greater
1563precision. Since their magnitude is zero, both positive and negative zeros are
1564treated as equal and their sign is informational.
1565
1566In addition to the two signed zeros which are distinct yet equal, there are
1567various representations of zero with differing precisions yet equivalent in
1568value. This takes a bit of getting used to. For an eye accustomed to
1569normalized floating point representations, it is not immediately obvious that
Christian Heimesfe337bf2008-03-23 21:54:12 +00001570the following calculation returns a value equal to zero:
Georg Brandl116aa622007-08-15 14:28:22 +00001571
1572 >>> 1 / Decimal('Infinity')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001573 Decimal('0E-1000000026')
Georg Brandl116aa622007-08-15 14:28:22 +00001574
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001575.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001576
1577
1578.. _decimal-threads:
1579
1580Working with threads
1581--------------------
1582
1583The :func:`getcontext` function accesses a different :class:`Context` object for
1584each thread. Having separate thread contexts means that threads may make
1585changes (such as ``getcontext.prec=10``) without interfering with other threads.
1586
1587Likewise, the :func:`setcontext` function automatically assigns its target to
1588the current thread.
1589
1590If :func:`setcontext` has not been called before :func:`getcontext`, then
1591:func:`getcontext` will automatically create a new context for use in the
1592current thread.
1593
1594The new context is copied from a prototype context called *DefaultContext*. To
1595control the defaults so that each thread will use the same values throughout the
1596application, directly modify the *DefaultContext* object. This should be done
1597*before* any threads are started so that there won't be a race condition between
1598threads calling :func:`getcontext`. For example::
1599
1600 # Set applicationwide defaults for all threads about to be launched
1601 DefaultContext.prec = 12
1602 DefaultContext.rounding = ROUND_DOWN
1603 DefaultContext.traps = ExtendedContext.traps.copy()
1604 DefaultContext.traps[InvalidOperation] = 1
1605 setcontext(DefaultContext)
1606
1607 # Afterwards, the threads can be started
1608 t1.start()
1609 t2.start()
1610 t3.start()
1611 . . .
1612
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001613.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001614
1615
1616.. _decimal-recipes:
1617
1618Recipes
1619-------
1620
1621Here are a few recipes that serve as utility functions and that demonstrate ways
1622to work with the :class:`Decimal` class::
1623
1624 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1625 pos='', neg='-', trailneg=''):
1626 """Convert Decimal to a money formatted string.
1627
1628 places: required number of places after the decimal point
1629 curr: optional currency symbol before the sign (may be blank)
1630 sep: optional grouping separator (comma, period, space, or blank)
1631 dp: decimal point indicator (comma or period)
1632 only specify as blank when places is zero
1633 pos: optional sign for positive numbers: '+', space or blank
1634 neg: optional sign for negative numbers: '-', '(', space or blank
1635 trailneg:optional trailing minus indicator: '-', ')', space or blank
1636
1637 >>> d = Decimal('-1234567.8901')
1638 >>> moneyfmt(d, curr='$')
1639 '-$1,234,567.89'
1640 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1641 '1.234.568-'
1642 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1643 '($1,234,567.89)'
1644 >>> moneyfmt(Decimal(123456789), sep=' ')
1645 '123 456 789.00'
1646 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Christian Heimesdae2a892008-04-19 00:55:37 +00001647 '<0.02>'
Georg Brandl116aa622007-08-15 14:28:22 +00001648
1649 """
Christian Heimesa156e092008-02-16 07:38:31 +00001650 q = Decimal(10) ** -places # 2 places --> '0.01'
Georg Brandl48310cd2009-01-03 21:18:54 +00001651 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +00001652 result = []
Facundo Batista789bdf02008-06-21 17:29:41 +00001653 digits = list(map(str, digits))
Georg Brandl116aa622007-08-15 14:28:22 +00001654 build, next = result.append, digits.pop
1655 if sign:
1656 build(trailneg)
1657 for i in range(places):
Christian Heimesa156e092008-02-16 07:38:31 +00001658 build(next() if digits else '0')
Georg Brandl116aa622007-08-15 14:28:22 +00001659 build(dp)
Christian Heimesdae2a892008-04-19 00:55:37 +00001660 if not digits:
1661 build('0')
Georg Brandl116aa622007-08-15 14:28:22 +00001662 i = 0
1663 while digits:
1664 build(next())
1665 i += 1
1666 if i == 3 and digits:
1667 i = 0
1668 build(sep)
1669 build(curr)
Christian Heimesa156e092008-02-16 07:38:31 +00001670 build(neg if sign else pos)
1671 return ''.join(reversed(result))
Georg Brandl116aa622007-08-15 14:28:22 +00001672
1673 def pi():
1674 """Compute Pi to the current precision.
1675
Georg Brandl6911e3c2007-09-04 07:15:32 +00001676 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001677 3.141592653589793238462643383
1678
1679 """
1680 getcontext().prec += 2 # extra digits for intermediate steps
1681 three = Decimal(3) # substitute "three=3.0" for regular floats
1682 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1683 while s != lasts:
1684 lasts = s
1685 n, na = n+na, na+8
1686 d, da = d+da, da+32
1687 t = (t * n) / d
1688 s += t
1689 getcontext().prec -= 2
1690 return +s # unary plus applies the new precision
1691
1692 def exp(x):
1693 """Return e raised to the power of x. Result type matches input type.
1694
Georg Brandl6911e3c2007-09-04 07:15:32 +00001695 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001696 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001697 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001698 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001699 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001700 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001701 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001702 (7.38905609893+0j)
1703
1704 """
1705 getcontext().prec += 2
1706 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1707 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001708 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001709 i += 1
1710 fact *= i
Georg Brandl48310cd2009-01-03 21:18:54 +00001711 num *= x
1712 s += num / fact
1713 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001714 return +s
1715
1716 def cos(x):
1717 """Return the cosine of x as measured in radians.
1718
Georg Brandl6911e3c2007-09-04 07:15:32 +00001719 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001720 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001721 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001722 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001723 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001724 (0.87758256189+0j)
1725
1726 """
1727 getcontext().prec += 2
1728 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1729 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001730 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001731 i += 2
1732 fact *= i * (i-1)
1733 num *= x * x
1734 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001735 s += num / fact * sign
1736 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001737 return +s
1738
1739 def sin(x):
1740 """Return the sine of x as measured in radians.
1741
Georg Brandl6911e3c2007-09-04 07:15:32 +00001742 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001743 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001744 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001745 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001746 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001747 (0.479425538604+0j)
1748
1749 """
1750 getcontext().prec += 2
1751 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1752 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001753 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001754 i += 2
1755 fact *= i * (i-1)
1756 num *= x * x
1757 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001758 s += num / fact * sign
1759 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001760 return +s
1761
1762
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001763.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001764
1765
1766.. _decimal-faq:
1767
1768Decimal FAQ
1769-----------
1770
1771Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1772minimize typing when using the interactive interpreter?
1773
Christian Heimesfe337bf2008-03-23 21:54:12 +00001774A. Some users abbreviate the constructor to just a single letter:
Georg Brandl116aa622007-08-15 14:28:22 +00001775
1776 >>> D = decimal.Decimal
1777 >>> D('1.23') + D('3.45')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001778 Decimal('4.68')
Georg Brandl116aa622007-08-15 14:28:22 +00001779
1780Q. In a fixed-point application with two decimal places, some inputs have many
1781places and need to be rounded. Others are not supposed to have excess digits
1782and need to be validated. What methods should be used?
1783
1784A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Christian Heimesfe337bf2008-03-23 21:54:12 +00001785the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl116aa622007-08-15 14:28:22 +00001786
1787 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1788
1789 >>> # Round to two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001790 >>> Decimal('3.214').quantize(TWOPLACES)
1791 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001792
Georg Brandl48310cd2009-01-03 21:18:54 +00001793 >>> # Validate that a number does not exceed two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001794 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1795 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001796
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001797 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl116aa622007-08-15 14:28:22 +00001798 Traceback (most recent call last):
1799 ...
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001800 Inexact: None
Georg Brandl116aa622007-08-15 14:28:22 +00001801
1802Q. Once I have valid two place inputs, how do I maintain that invariant
1803throughout an application?
1804
Christian Heimesa156e092008-02-16 07:38:31 +00001805A. Some operations like addition, subtraction, and multiplication by an integer
1806will automatically preserve fixed point. Others operations, like division and
1807non-integer multiplication, will change the number of decimal places and need to
Christian Heimesfe337bf2008-03-23 21:54:12 +00001808be followed-up with a :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001809
1810 >>> a = Decimal('102.72') # Initial fixed-point values
1811 >>> b = Decimal('3.17')
1812 >>> a + b # Addition preserves fixed-point
1813 Decimal('105.89')
1814 >>> a - b
1815 Decimal('99.55')
1816 >>> a * 42 # So does integer multiplication
1817 Decimal('4314.24')
1818 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1819 Decimal('325.62')
1820 >>> (b / a).quantize(TWOPLACES) # And quantize division
1821 Decimal('0.03')
1822
1823In developing fixed-point applications, it is convenient to define functions
Christian Heimesfe337bf2008-03-23 21:54:12 +00001824to handle the :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001825
1826 >>> def mul(x, y, fp=TWOPLACES):
1827 ... return (x * y).quantize(fp)
1828 >>> def div(x, y, fp=TWOPLACES):
1829 ... return (x / y).quantize(fp)
1830
1831 >>> mul(a, b) # Automatically preserve fixed-point
1832 Decimal('325.62')
1833 >>> div(b, a)
1834 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +00001835
1836Q. There are many ways to express the same value. The numbers :const:`200`,
1837:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1838various precisions. Is there a way to transform them to a single recognizable
1839canonical value?
1840
1841A. The :meth:`normalize` method maps all equivalent values to a single
Christian Heimesfe337bf2008-03-23 21:54:12 +00001842representative:
Georg Brandl116aa622007-08-15 14:28:22 +00001843
1844 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1845 >>> [v.normalize() for v in values]
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001846 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl116aa622007-08-15 14:28:22 +00001847
1848Q. Some decimal values always print with exponential notation. Is there a way
1849to get a non-exponential representation?
1850
1851A. For some values, exponential notation is the only way to express the number
1852of significant places in the coefficient. For example, expressing
1853:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1854original's two-place significance.
1855
Christian Heimesa156e092008-02-16 07:38:31 +00001856If an application does not care about tracking significance, it is easy to
Christian Heimesc3f30c42008-02-22 16:37:40 +00001857remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001858value unchanged:
Christian Heimesa156e092008-02-16 07:38:31 +00001859
1860 >>> def remove_exponent(d):
1861 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1862
1863 >>> remove_exponent(Decimal('5E+3'))
1864 Decimal('5000')
1865
Georg Brandl116aa622007-08-15 14:28:22 +00001866Q. Is there a way to convert a regular float to a :class:`Decimal`?
1867
Mark Dickinsone534a072010-04-04 22:13:14 +00001868A. Yes, any binary floating point number can be exactly expressed as a
Raymond Hettinger96798592010-04-02 16:58:27 +00001869Decimal though an exact conversion may take more precision than intuition would
1870suggest:
Georg Brandl116aa622007-08-15 14:28:22 +00001871
Christian Heimesfe337bf2008-03-23 21:54:12 +00001872.. doctest::
1873
Raymond Hettinger96798592010-04-02 16:58:27 +00001874 >>> Decimal(math.pi)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001875 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl116aa622007-08-15 14:28:22 +00001876
Georg Brandl116aa622007-08-15 14:28:22 +00001877Q. Within a complex calculation, how can I make sure that I haven't gotten a
1878spurious result because of insufficient precision or rounding anomalies.
1879
1880A. The decimal module makes it easy to test results. A best practice is to
1881re-run calculations using greater precision and with various rounding modes.
1882Widely differing results indicate insufficient precision, rounding mode issues,
1883ill-conditioned inputs, or a numerically unstable algorithm.
1884
1885Q. I noticed that context precision is applied to the results of operations but
1886not to the inputs. Is there anything to watch out for when mixing values of
1887different precisions?
1888
1889A. Yes. The principle is that all values are considered to be exact and so is
1890the arithmetic on those values. Only the results are rounded. The advantage
1891for inputs is that "what you type is what you get". A disadvantage is that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001892results can look odd if you forget that the inputs haven't been rounded:
1893
1894.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001895
1896 >>> getcontext().prec = 3
Christian Heimesfe337bf2008-03-23 21:54:12 +00001897 >>> Decimal('3.104') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001898 Decimal('5.21')
Christian Heimesfe337bf2008-03-23 21:54:12 +00001899 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001900 Decimal('5.20')
Georg Brandl116aa622007-08-15 14:28:22 +00001901
1902The solution is either to increase precision or to force rounding of inputs
Christian Heimesfe337bf2008-03-23 21:54:12 +00001903using the unary plus operation:
1904
1905.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001906
1907 >>> getcontext().prec = 3
1908 >>> +Decimal('1.23456789') # unary plus triggers rounding
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001909 Decimal('1.23')
Georg Brandl116aa622007-08-15 14:28:22 +00001910
1911Alternatively, inputs can be rounded upon creation using the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001912:meth:`Context.create_decimal` method:
Georg Brandl116aa622007-08-15 14:28:22 +00001913
1914 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001915 Decimal('1.2345')
Georg Brandl116aa622007-08-15 14:28:22 +00001916