blob: aea1c01419fcded15ddb0189eadb591c102f6808 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
Christian Heimes3feef612008-02-11 06:19:17 +00002:mod:`decimal` --- Decimal fixed point and floating point arithmetic
3====================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00004
5.. module:: decimal
6 :synopsis: Implementation of the General Decimal Arithmetic Specification.
7
Georg Brandl116aa622007-08-15 14:28:22 +00008.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
9.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
10.. moduleauthor:: Raymond Hettinger <python at rcn.com>
11.. moduleauthor:: Aahz <aahz at pobox.com>
12.. moduleauthor:: Tim Peters <tim.one at comcast.net>
Georg Brandl116aa622007-08-15 14:28:22 +000013.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
14
Christian Heimesfe337bf2008-03-23 21:54:12 +000015.. import modules for testing inline doctests with the Sphinx doctest builder
16.. testsetup:: *
17
18 import decimal
19 import math
20 from decimal import *
21 # make sure each group gets a fresh context
22 setcontext(Context())
Georg Brandl116aa622007-08-15 14:28:22 +000023
Georg Brandl116aa622007-08-15 14:28:22 +000024The :mod:`decimal` module provides support for decimal floating point
Thomas Wouters1b7f8912007-09-19 03:06:30 +000025arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl116aa622007-08-15 14:28:22 +000026
Christian Heimes3feef612008-02-11 06:19:17 +000027* Decimal "is based on a floating-point model which was designed with people
28 in mind, and necessarily has a paramount guiding principle -- computers must
29 provide an arithmetic that works in the same way as the arithmetic that
30 people learn at school." -- excerpt from the decimal arithmetic specification.
31
Georg Brandl116aa622007-08-15 14:28:22 +000032* Decimal numbers can be represented exactly. In contrast, numbers like
33 :const:`1.1` do not have an exact representation in binary floating point. End
34 users typically would not expect :const:`1.1` to display as
35 :const:`1.1000000000000001` as it does with binary floating point.
36
37* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000038 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl116aa622007-08-15 14:28:22 +000039 is :const:`5.5511151231257827e-017`. While near to zero, the differences
40 prevent reliable equality testing and differences can accumulate. For this
Christian Heimes3feef612008-02-11 06:19:17 +000041 reason, decimal is preferred in accounting applications which have strict
Georg Brandl116aa622007-08-15 14:28:22 +000042 equality invariants.
43
44* The decimal module incorporates a notion of significant places so that ``1.30
45 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
46 This is the customary presentation for monetary applications. For
47 multiplication, the "schoolbook" approach uses all the figures in the
48 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
49 1.20`` gives :const:`1.5600`.
50
51* Unlike hardware based binary floating point, the decimal module has a user
Thomas Wouters1b7f8912007-09-19 03:06:30 +000052 alterable precision (defaulting to 28 places) which can be as large as needed for
Christian Heimesfe337bf2008-03-23 21:54:12 +000053 a given problem:
Georg Brandl116aa622007-08-15 14:28:22 +000054
55 >>> getcontext().prec = 6
56 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000057 Decimal('0.142857')
Georg Brandl116aa622007-08-15 14:28:22 +000058 >>> getcontext().prec = 28
59 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000060 Decimal('0.1428571428571428571428571429')
Georg Brandl116aa622007-08-15 14:28:22 +000061
62* Both binary and decimal floating point are implemented in terms of published
63 standards. While the built-in float type exposes only a modest portion of its
64 capabilities, the decimal module exposes all required parts of the standard.
65 When needed, the programmer has full control over rounding and signal handling.
Christian Heimes3feef612008-02-11 06:19:17 +000066 This includes an option to enforce exact arithmetic by using exceptions
67 to block any inexact operations.
68
69* The decimal module was designed to support "without prejudice, both exact
70 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
71 and rounded floating-point arithmetic." -- excerpt from the decimal
72 arithmetic specification.
Georg Brandl116aa622007-08-15 14:28:22 +000073
74The module design is centered around three concepts: the decimal number, the
75context for arithmetic, and signals.
76
77A decimal number is immutable. It has a sign, coefficient digits, and an
78exponent. To preserve significance, the coefficient digits do not truncate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000079trailing zeros. Decimals also include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +000080:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
81differentiates :const:`-0` from :const:`+0`.
82
83The context for arithmetic is an environment specifying precision, rounding
84rules, limits on exponents, flags indicating the results of operations, and trap
85enablers which determine whether signals are treated as exceptions. Rounding
86options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
87:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +000088:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl116aa622007-08-15 14:28:22 +000089
90Signals are groups of exceptional conditions arising during the course of
91computation. Depending on the needs of the application, signals may be ignored,
92considered as informational, or treated as exceptions. The signals in the
93decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
94:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
95:const:`Overflow`, and :const:`Underflow`.
96
97For each signal there is a flag and a trap enabler. When a signal is
Raymond Hettinger86173da2008-02-01 20:38:12 +000098encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl116aa622007-08-15 14:28:22 +000099set to one, an exception is raised. Flags are sticky, so the user needs to
100reset them before monitoring a calculation.
101
102
103.. seealso::
104
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000105 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
106 Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000108 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Christian Heimes77c02eb2008-02-09 02:18:51 +0000109 <http://754r.ucbtest.org/standards/854.pdf>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000111.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113
114.. _decimal-tutorial:
115
116Quick-start Tutorial
117--------------------
118
119The usual start to using decimals is importing the module, viewing the current
120context with :func:`getcontext` and, if necessary, setting new values for
121precision, rounding, or enabled traps::
122
123 >>> from decimal import *
124 >>> getcontext()
125 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000126 capitals=1, flags=[], traps=[Overflow, DivisionByZero,
127 InvalidOperation])
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129 >>> getcontext().prec = 7 # Set a new precision
130
131Decimal instances can be constructed from integers, strings, or tuples. To
132create a Decimal from a :class:`float`, first convert it to a string. This
133serves as an explicit reminder of the details of the conversion (including
134representation error). Decimal numbers include special values such as
135:const:`NaN` which stands for "Not a number", positive and negative
Christian Heimesfe337bf2008-03-23 21:54:12 +0000136:const:`Infinity`, and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000137
Facundo Batista789bdf02008-06-21 17:29:41 +0000138 >>> getcontext().prec = 28
Georg Brandl116aa622007-08-15 14:28:22 +0000139 >>> Decimal(10)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000140 Decimal('10')
141 >>> Decimal('3.14')
142 Decimal('3.14')
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)
191 1.3400000000000001
192 >>> round(a, 1) # round() first converts to binary floating point
193 1.3
194 >>> 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,
247 capitals=1, flags=[], traps=[])
248 >>> 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,
Facundo Batista789bdf02008-06-21 17:29:41 +0000272 capitals=1, 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
308.. class:: Decimal([value [, context]])
309
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
Christian Heimesa62da1d2008-01-12 19:39:10 +0000312 *value* can be an integer, string, tuple, 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
326 numeric-string ::= [sign] numeric-value | [sign] nan
327
328 If *value* is a :class:`tuple`, it should have three components, a sign
329 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
330 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000331 returns ``Decimal('1.414')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000332
333 The *context* precision does not affect how many digits are stored. That is
334 determined exclusively by the number of digits in *value*. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000335 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl116aa622007-08-15 14:28:22 +0000336 only three.
337
338 The purpose of the *context* argument is determining what to do if *value* is a
339 malformed string. If the context traps :const:`InvalidOperation`, an exception
340 is raised; otherwise, the constructor returns a new Decimal with the value of
341 :const:`NaN`.
342
343 Once constructed, :class:`Decimal` objects are immutable.
344
Benjamin Petersone41251e2008-04-25 01:59:09 +0000345 Decimal floating point objects share many properties with the other built-in
346 numeric types such as :class:`float` and :class:`int`. All of the usual math
347 operations and special methods apply. Likewise, decimal objects can be
348 copied, pickled, printed, used as dictionary keys, used as set elements,
349 compared, sorted, and coerced to another type (such as :class:`float` or
350 :class:`long`).
Christian Heimesa62da1d2008-01-12 19:39:10 +0000351
Benjamin Petersone41251e2008-04-25 01:59:09 +0000352 In addition to the standard numeric properties, decimal floating point
353 objects also have a number of specialized methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000354
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Benjamin Petersone41251e2008-04-25 01:59:09 +0000356 .. method:: adjusted()
Georg Brandl116aa622007-08-15 14:28:22 +0000357
Benjamin Petersone41251e2008-04-25 01:59:09 +0000358 Return the adjusted exponent after shifting out the coefficient's
359 rightmost digits until only the lead digit remains:
360 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
361 position of the most significant digit with respect to the decimal point.
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Benjamin Petersone41251e2008-04-25 01:59:09 +0000364 .. method:: as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +0000365
Benjamin Petersone41251e2008-04-25 01:59:09 +0000366 Return a :term:`named tuple` representation of the number:
367 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000368
Christian Heimes25bb7832008-01-11 16:17:00 +0000369
Benjamin Petersone41251e2008-04-25 01:59:09 +0000370 .. method:: canonical()
Georg Brandl116aa622007-08-15 14:28:22 +0000371
Benjamin Petersone41251e2008-04-25 01:59:09 +0000372 Return the canonical encoding of the argument. Currently, the encoding of
373 a :class:`Decimal` instance is always canonical, so this operation returns
374 its argument unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000375
Benjamin Petersone41251e2008-04-25 01:59:09 +0000376 .. method:: compare(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000377
Benjamin Petersone41251e2008-04-25 01:59:09 +0000378 Compare the values of two Decimal instances. This operation behaves in
379 the same way as the usual comparison method :meth:`__cmp__`, except that
380 :meth:`compare` returns a Decimal instance rather than an integer, and if
381 either operand is a NaN then the result is a NaN::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000382
Benjamin Petersone41251e2008-04-25 01:59:09 +0000383 a or b is a NaN ==> Decimal('NaN')
384 a < b ==> Decimal('-1')
385 a == b ==> Decimal('0')
386 a > b ==> Decimal('1')
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Benjamin Petersone41251e2008-04-25 01:59:09 +0000388 .. method:: compare_signal(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000389
Benjamin Petersone41251e2008-04-25 01:59:09 +0000390 This operation is identical to the :meth:`compare` method, except that all
391 NaNs signal. That is, if neither operand is a signaling NaN then any
392 quiet NaN operand is treated as though it were a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000393
Benjamin Petersone41251e2008-04-25 01:59:09 +0000394 .. method:: compare_total(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000395
Benjamin Petersone41251e2008-04-25 01:59:09 +0000396 Compare two operands using their abstract representation rather than their
397 numerical value. Similar to the :meth:`compare` method, but the result
398 gives a total ordering on :class:`Decimal` instances. Two
399 :class:`Decimal` instances with the same numeric value but different
400 representations compare unequal in this ordering:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000401
Benjamin Petersone41251e2008-04-25 01:59:09 +0000402 >>> Decimal('12.0').compare_total(Decimal('12'))
403 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000404
Benjamin Petersone41251e2008-04-25 01:59:09 +0000405 Quiet and signaling NaNs are also included in the total ordering. The
406 result of this function is ``Decimal('0')`` if both operands have the same
407 representation, ``Decimal('-1')`` if the first operand is lower in the
408 total order than the second, and ``Decimal('1')`` if the first operand is
409 higher in the total order than the second operand. See the specification
410 for details of the total order.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000411
Benjamin Petersone41251e2008-04-25 01:59:09 +0000412 .. method:: compare_total_mag(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000413
Benjamin Petersone41251e2008-04-25 01:59:09 +0000414 Compare two operands using their abstract representation rather than their
415 value as in :meth:`compare_total`, but ignoring the sign of each operand.
416 ``x.compare_total_mag(y)`` is equivalent to
417 ``x.copy_abs().compare_total(y.copy_abs())``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000418
Facundo Batista789bdf02008-06-21 17:29:41 +0000419 .. method:: conjugate()
420
421 Just returns itself, this method is only to comply with the Decimal
422 Specification.
423
Benjamin Petersone41251e2008-04-25 01:59:09 +0000424 .. method:: copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000425
Benjamin Petersone41251e2008-04-25 01:59:09 +0000426 Return the absolute value of the argument. This operation is unaffected
427 by the context and is quiet: no flags are changed and no rounding is
428 performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000429
Benjamin Petersone41251e2008-04-25 01:59:09 +0000430 .. method:: copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000431
Benjamin Petersone41251e2008-04-25 01:59:09 +0000432 Return the negation of the argument. This operation is unaffected by the
433 context and is quiet: no flags are changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000434
Benjamin Petersone41251e2008-04-25 01:59:09 +0000435 .. method:: copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000436
Benjamin Petersone41251e2008-04-25 01:59:09 +0000437 Return a copy of the first operand with the sign set to be the same as the
438 sign of the second operand. For example:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000439
Benjamin Petersone41251e2008-04-25 01:59:09 +0000440 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
441 Decimal('-2.3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000442
Benjamin Petersone41251e2008-04-25 01:59:09 +0000443 This operation is unaffected by the context and is quiet: no flags are
444 changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000445
Benjamin Petersone41251e2008-04-25 01:59:09 +0000446 .. method:: exp([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000447
Benjamin Petersone41251e2008-04-25 01:59:09 +0000448 Return the value of the (natural) exponential function ``e**x`` at the
449 given number. The result is correctly rounded using the
450 :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000451
Benjamin Petersone41251e2008-04-25 01:59:09 +0000452 >>> Decimal(1).exp()
453 Decimal('2.718281828459045235360287471')
454 >>> Decimal(321).exp()
455 Decimal('2.561702493119680037517373933E+139')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000456
Benjamin Petersone41251e2008-04-25 01:59:09 +0000457 .. method:: fma(other, third[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000458
Benjamin Petersone41251e2008-04-25 01:59:09 +0000459 Fused multiply-add. Return self*other+third with no rounding of the
460 intermediate product self*other.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000461
Benjamin Petersone41251e2008-04-25 01:59:09 +0000462 >>> Decimal(2).fma(3, 5)
463 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000464
Benjamin Petersone41251e2008-04-25 01:59:09 +0000465 .. method:: is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000466
Benjamin Petersone41251e2008-04-25 01:59:09 +0000467 Return :const:`True` if the argument is canonical and :const:`False`
468 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
469 this operation always returns :const:`True`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000470
Benjamin Petersone41251e2008-04-25 01:59:09 +0000471 .. method:: is_finite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000472
Benjamin Petersone41251e2008-04-25 01:59:09 +0000473 Return :const:`True` if the argument is a finite number, and
474 :const:`False` if the argument is an infinity or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000475
Benjamin Petersone41251e2008-04-25 01:59:09 +0000476 .. method:: is_infinite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000477
Benjamin Petersone41251e2008-04-25 01:59:09 +0000478 Return :const:`True` if the argument is either positive or negative
479 infinity and :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000480
Benjamin Petersone41251e2008-04-25 01:59:09 +0000481 .. method:: is_nan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000482
Benjamin Petersone41251e2008-04-25 01:59:09 +0000483 Return :const:`True` if the argument is a (quiet or signaling) NaN and
484 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000485
Benjamin Petersone41251e2008-04-25 01:59:09 +0000486 .. method:: is_normal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000487
Benjamin Petersone41251e2008-04-25 01:59:09 +0000488 Return :const:`True` if the argument is a *normal* finite number. Return
489 :const:`False` if the argument is zero, subnormal, infinite or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000490
Benjamin Petersone41251e2008-04-25 01:59:09 +0000491 .. method:: is_qnan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000492
Benjamin Petersone41251e2008-04-25 01:59:09 +0000493 Return :const:`True` if the argument is a quiet NaN, and
494 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000495
Benjamin Petersone41251e2008-04-25 01:59:09 +0000496 .. method:: is_signed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000497
Benjamin Petersone41251e2008-04-25 01:59:09 +0000498 Return :const:`True` if the argument has a negative sign and
499 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000500
Benjamin Petersone41251e2008-04-25 01:59:09 +0000501 .. method:: is_snan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000502
Benjamin Petersone41251e2008-04-25 01:59:09 +0000503 Return :const:`True` if the argument is a signaling NaN and :const:`False`
504 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000505
Benjamin Petersone41251e2008-04-25 01:59:09 +0000506 .. method:: is_subnormal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000507
Benjamin Petersone41251e2008-04-25 01:59:09 +0000508 Return :const:`True` if the argument is subnormal, and :const:`False`
509 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510
Benjamin Petersone41251e2008-04-25 01:59:09 +0000511 .. method:: is_zero()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000512
Benjamin Petersone41251e2008-04-25 01:59:09 +0000513 Return :const:`True` if the argument is a (positive or negative) zero and
514 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000515
Benjamin Petersone41251e2008-04-25 01:59:09 +0000516 .. method:: ln([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000517
Benjamin Petersone41251e2008-04-25 01:59:09 +0000518 Return the natural (base e) logarithm of the operand. The result is
519 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000520
Benjamin Petersone41251e2008-04-25 01:59:09 +0000521 .. method:: log10([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000522
Benjamin Petersone41251e2008-04-25 01:59:09 +0000523 Return the base ten logarithm of the operand. The result is correctly
524 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000525
Benjamin Petersone41251e2008-04-25 01:59:09 +0000526 .. method:: logb([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000527
Benjamin Petersone41251e2008-04-25 01:59:09 +0000528 For a nonzero number, return the adjusted exponent of its operand as a
529 :class:`Decimal` instance. If the operand is a zero then
530 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
531 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
532 returned.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000533
Benjamin Petersone41251e2008-04-25 01:59:09 +0000534 .. method:: logical_and(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000535
Benjamin Petersone41251e2008-04-25 01:59:09 +0000536 :meth:`logical_and` is a logical operation which takes two *logical
537 operands* (see :ref:`logical_operands_label`). The result is the
538 digit-wise ``and`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000539
Benjamin Petersone41251e2008-04-25 01:59:09 +0000540 .. method:: logical_invert(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000541
Benjamin Petersone41251e2008-04-25 01:59:09 +0000542 :meth:`logical_invert` is a logical operation. The argument must
543 be a *logical operand* (see :ref:`logical_operands_label`). The
544 result is the digit-wise inversion of the operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000545
Benjamin Petersone41251e2008-04-25 01:59:09 +0000546 .. method:: logical_or(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000547
Benjamin Petersone41251e2008-04-25 01:59:09 +0000548 :meth:`logical_or` is a logical operation which takes two *logical
549 operands* (see :ref:`logical_operands_label`). The result is the
550 digit-wise ``or`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000551
Benjamin Petersone41251e2008-04-25 01:59:09 +0000552 .. method:: logical_xor(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000553
Benjamin Petersone41251e2008-04-25 01:59:09 +0000554 :meth:`logical_xor` is a logical operation which takes two *logical
555 operands* (see :ref:`logical_operands_label`). The result is the
556 digit-wise exclusive or of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000557
Benjamin Petersone41251e2008-04-25 01:59:09 +0000558 .. method:: max(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000559
Benjamin Petersone41251e2008-04-25 01:59:09 +0000560 Like ``max(self, other)`` except that the context rounding rule is applied
561 before returning and that :const:`NaN` values are either signaled or
562 ignored (depending on the context and whether they are signaling or
563 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000564
Benjamin Petersone41251e2008-04-25 01:59:09 +0000565 .. method:: max_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000566
Benjamin Petersone41251e2008-04-25 01:59:09 +0000567 Similar to the :meth:`max` method, but the comparison is done using the
568 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000569
Benjamin Petersone41251e2008-04-25 01:59:09 +0000570 .. method:: min(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000571
Benjamin Petersone41251e2008-04-25 01:59:09 +0000572 Like ``min(self, other)`` except that the context rounding rule is applied
573 before returning and that :const:`NaN` values are either signaled or
574 ignored (depending on the context and whether they are signaling or
575 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000576
Benjamin Petersone41251e2008-04-25 01:59:09 +0000577 .. method:: min_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000578
Benjamin Petersone41251e2008-04-25 01:59:09 +0000579 Similar to the :meth:`min` method, but the comparison is done using the
580 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000581
Benjamin Petersone41251e2008-04-25 01:59:09 +0000582 .. method:: next_minus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000583
Benjamin Petersone41251e2008-04-25 01:59:09 +0000584 Return the largest number representable in the given context (or in the
585 current thread's context if no context is given) that is smaller than the
586 given operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000587
Benjamin Petersone41251e2008-04-25 01:59:09 +0000588 .. method:: next_plus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000589
Benjamin Petersone41251e2008-04-25 01:59:09 +0000590 Return the smallest number representable in the given context (or in the
591 current thread's context if no context is given) that is larger than the
592 given operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000593
Benjamin Petersone41251e2008-04-25 01:59:09 +0000594 .. method:: next_toward(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000595
Benjamin Petersone41251e2008-04-25 01:59:09 +0000596 If the two operands are unequal, return the number closest to the first
597 operand in the direction of the second operand. If both operands are
598 numerically equal, return a copy of the first operand with the sign set to
599 be the same as the sign of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000600
Benjamin Petersone41251e2008-04-25 01:59:09 +0000601 .. method:: normalize([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602
Benjamin Petersone41251e2008-04-25 01:59:09 +0000603 Normalize the number by stripping the rightmost trailing zeros and
604 converting any result equal to :const:`Decimal('0')` to
605 :const:`Decimal('0e0')`. Used for producing canonical values for members
606 of an equivalence class. For example, ``Decimal('32.100')`` and
607 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
608 ``Decimal('32.1')``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000609
Benjamin Petersone41251e2008-04-25 01:59:09 +0000610 .. method:: number_class([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000611
Benjamin Petersone41251e2008-04-25 01:59:09 +0000612 Return a string describing the *class* of the operand. The returned value
613 is one of the following ten strings.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000614
Benjamin Petersone41251e2008-04-25 01:59:09 +0000615 * ``"-Infinity"``, indicating that the operand is negative infinity.
616 * ``"-Normal"``, indicating that the operand is a negative normal number.
617 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
618 * ``"-Zero"``, indicating that the operand is a negative zero.
619 * ``"+Zero"``, indicating that the operand is a positive zero.
620 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
621 * ``"+Normal"``, indicating that the operand is a positive normal number.
622 * ``"+Infinity"``, indicating that the operand is positive infinity.
623 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
624 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000625
Benjamin Petersone41251e2008-04-25 01:59:09 +0000626 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000627
Benjamin Petersone41251e2008-04-25 01:59:09 +0000628 Return a value equal to the first operand after rounding and having the
629 exponent of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000630
Benjamin Petersone41251e2008-04-25 01:59:09 +0000631 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
632 Decimal('1.414')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000633
Benjamin Petersone41251e2008-04-25 01:59:09 +0000634 Unlike other operations, if the length of the coefficient after the
635 quantize operation would be greater than precision, then an
636 :const:`InvalidOperation` is signaled. This guarantees that, unless there
637 is an error condition, the quantized exponent is always equal to that of
638 the right-hand operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000639
Benjamin Petersone41251e2008-04-25 01:59:09 +0000640 Also unlike other operations, quantize never signals Underflow, even if
641 the result is subnormal and inexact.
Georg Brandl116aa622007-08-15 14:28:22 +0000642
Benjamin Petersone41251e2008-04-25 01:59:09 +0000643 If the exponent of the second operand is larger than that of the first
644 then rounding may be necessary. In this case, the rounding mode is
645 determined by the ``rounding`` argument if given, else by the given
646 ``context`` argument; if neither argument is given the rounding mode of
647 the current thread's context is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000648
Benjamin Petersone41251e2008-04-25 01:59:09 +0000649 If *watchexp* is set (default), then an error is returned whenever the
650 resulting exponent is greater than :attr:`Emax` or less than
651 :attr:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +0000652
Benjamin Petersone41251e2008-04-25 01:59:09 +0000653 .. method:: radix()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000654
Benjamin Petersone41251e2008-04-25 01:59:09 +0000655 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
656 class does all its arithmetic. Included for compatibility with the
657 specification.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658
Benjamin Petersone41251e2008-04-25 01:59:09 +0000659 .. method:: remainder_near(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000660
Benjamin Petersone41251e2008-04-25 01:59:09 +0000661 Compute the modulo as either a positive or negative value depending on
662 which is closest to zero. For instance, ``Decimal(10).remainder_near(6)``
663 returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000664
Benjamin Petersone41251e2008-04-25 01:59:09 +0000665 If both are equally close, the one chosen will have the same sign as
666 *self*.
Georg Brandl116aa622007-08-15 14:28:22 +0000667
Benjamin Petersone41251e2008-04-25 01:59:09 +0000668 .. method:: rotate(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000669
Benjamin Petersone41251e2008-04-25 01:59:09 +0000670 Return the result of rotating the digits of the first operand by an amount
671 specified by the second operand. The second operand must be an integer in
672 the range -precision through precision. The absolute value of the second
673 operand gives the number of places to rotate. If the second operand is
674 positive then rotation is to the left; otherwise rotation is to the right.
675 The coefficient of the first operand is padded on the left with zeros to
676 length precision if necessary. The sign and exponent of the first operand
677 are unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000678
Benjamin Petersone41251e2008-04-25 01:59:09 +0000679 .. method:: same_quantum(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000680
Benjamin Petersone41251e2008-04-25 01:59:09 +0000681 Test whether self and other have the same exponent or whether both are
682 :const:`NaN`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000683
Benjamin Petersone41251e2008-04-25 01:59:09 +0000684 .. method:: scaleb(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685
Benjamin Petersone41251e2008-04-25 01:59:09 +0000686 Return the first operand with exponent adjusted by the second.
687 Equivalently, return the first operand multiplied by ``10**other``. The
688 second operand must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +0000689
Benjamin Petersone41251e2008-04-25 01:59:09 +0000690 .. method:: shift(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000691
Benjamin Petersone41251e2008-04-25 01:59:09 +0000692 Return the result of shifting the digits of the first operand by an amount
693 specified by the second operand. The second operand must be an integer in
694 the range -precision through precision. The absolute value of the second
695 operand gives the number of places to shift. If the second operand is
696 positive then the shift is to the left; otherwise the shift is to the
697 right. Digits shifted into the coefficient are zeros. The sign and
698 exponent of the first operand are unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +0000699
Benjamin Petersone41251e2008-04-25 01:59:09 +0000700 .. method:: sqrt([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000701
Benjamin Petersone41251e2008-04-25 01:59:09 +0000702 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000703
Georg Brandl116aa622007-08-15 14:28:22 +0000704
Benjamin Petersone41251e2008-04-25 01:59:09 +0000705 .. method:: to_eng_string([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000706
Benjamin Petersone41251e2008-04-25 01:59:09 +0000707 Convert to an engineering-type string.
Georg Brandl116aa622007-08-15 14:28:22 +0000708
Benjamin Petersone41251e2008-04-25 01:59:09 +0000709 Engineering notation has an exponent which is a multiple of 3, so there
710 are up to 3 digits left of the decimal place. For example, converts
711 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000712
Benjamin Petersone41251e2008-04-25 01:59:09 +0000713 .. method:: to_integral([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000714
Benjamin Petersone41251e2008-04-25 01:59:09 +0000715 Identical to the :meth:`to_integral_value` method. The ``to_integral``
716 name has been kept for compatibility with older versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000717
Benjamin Petersone41251e2008-04-25 01:59:09 +0000718 .. method:: to_integral_exact([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000719
Benjamin Petersone41251e2008-04-25 01:59:09 +0000720 Round to the nearest integer, signaling :const:`Inexact` or
721 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
722 determined by the ``rounding`` parameter if given, else by the given
723 ``context``. If neither parameter is given then the rounding mode of the
724 current context is used.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000725
Benjamin Petersone41251e2008-04-25 01:59:09 +0000726 .. method:: to_integral_value([rounding[, context]])
Georg Brandl116aa622007-08-15 14:28:22 +0000727
Benjamin Petersone41251e2008-04-25 01:59:09 +0000728 Round to the nearest integer without signaling :const:`Inexact` or
729 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
730 rounding method in either the supplied *context* or the current context.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000731
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000732
733.. _logical_operands_label:
734
735Logical operands
736^^^^^^^^^^^^^^^^
737
738The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
739and :meth:`logical_xor` methods expect their arguments to be *logical
740operands*. A *logical operand* is a :class:`Decimal` instance whose
741exponent and sign are both zero, and whose digits are all either
742:const:`0` or :const:`1`.
743
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000744.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000745
746
747.. _decimal-context:
748
749Context objects
750---------------
751
752Contexts are environments for arithmetic operations. They govern precision, set
753rules for rounding, determine which signals are treated as exceptions, and limit
754the range for exponents.
755
756Each thread has its own current context which is accessed or changed using the
757:func:`getcontext` and :func:`setcontext` functions:
758
759
760.. function:: getcontext()
761
762 Return the current context for the active thread.
763
764
765.. function:: setcontext(c)
766
767 Set the current context for the active thread to *c*.
768
Georg Brandle6bcc912008-05-12 18:05:20 +0000769You can also use the :keyword:`with` statement and the :func:`localcontext`
770function to temporarily change the active context.
Georg Brandl116aa622007-08-15 14:28:22 +0000771
772.. function:: localcontext([c])
773
774 Return a context manager that will set the current context for the active thread
775 to a copy of *c* on entry to the with-statement and restore the previous context
776 when exiting the with-statement. If no context is specified, a copy of the
777 current context is used.
778
Georg Brandl116aa622007-08-15 14:28:22 +0000779 For example, the following code sets the current decimal precision to 42 places,
780 performs a calculation, and then automatically restores the previous context::
781
Georg Brandl116aa622007-08-15 14:28:22 +0000782 from decimal import localcontext
783
784 with localcontext() as ctx:
785 ctx.prec = 42 # Perform a high precision calculation
786 s = calculate_something()
787 s = +s # Round the final result back to the default precision
788
789New contexts can also be created using the :class:`Context` constructor
790described below. In addition, the module provides three pre-made contexts:
791
792
793.. class:: BasicContext
794
795 This is a standard context defined by the General Decimal Arithmetic
796 Specification. Precision is set to nine. Rounding is set to
797 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
798 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
799 :const:`Subnormal`.
800
801 Because many of the traps are enabled, this context is useful for debugging.
802
803
804.. class:: ExtendedContext
805
806 This is a standard context defined by the General Decimal Arithmetic
807 Specification. Precision is set to nine. Rounding is set to
808 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
809 exceptions are not raised during computations).
810
Christian Heimes3feef612008-02-11 06:19:17 +0000811 Because the traps are disabled, this context is useful for applications that
Georg Brandl116aa622007-08-15 14:28:22 +0000812 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
813 raising exceptions. This allows an application to complete a run in the
814 presence of conditions that would otherwise halt the program.
815
816
817.. class:: DefaultContext
818
819 This context is used by the :class:`Context` constructor as a prototype for new
820 contexts. Changing a field (such a precision) has the effect of changing the
821 default for new contexts creating by the :class:`Context` constructor.
822
823 This context is most useful in multi-threaded environments. Changing one of the
824 fields before threads are started has the effect of setting system-wide
825 defaults. Changing the fields after threads have started is not recommended as
826 it would require thread synchronization to prevent race conditions.
827
828 In single threaded environments, it is preferable to not use this context at
829 all. Instead, simply create contexts explicitly as described below.
830
831 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
832 for Overflow, InvalidOperation, and DivisionByZero.
833
834In addition to the three supplied contexts, new contexts can be created with the
835:class:`Context` constructor.
836
837
838.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
839
840 Creates a new context. If a field is not specified or is :const:`None`, the
841 default values are copied from the :const:`DefaultContext`. If the *flags*
842 field is not specified or is :const:`None`, all flags are cleared.
843
844 The *prec* field is a positive integer that sets the precision for arithmetic
845 operations in the context.
846
847 The *rounding* option is one of:
848
849 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
850 * :const:`ROUND_DOWN` (towards zero),
851 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
852 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
853 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
854 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
855 * :const:`ROUND_UP` (away from zero).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000856 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
857 would have been 0 or 5; otherwise towards zero)
Georg Brandl116aa622007-08-15 14:28:22 +0000858
859 The *traps* and *flags* fields list any signals to be set. Generally, new
860 contexts should only set traps and leave the flags clear.
861
862 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
863 for exponents.
864
865 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
866 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
867 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
868
Georg Brandl116aa622007-08-15 14:28:22 +0000869
Benjamin Petersone41251e2008-04-25 01:59:09 +0000870 The :class:`Context` class defines several general purpose methods as well as
871 a large number of methods for doing arithmetic directly in a given context.
872 In addition, for each of the :class:`Decimal` methods described above (with
873 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
874 a corresponding :class:`Context` method. For example, ``C.exp(x)`` is
875 equivalent to ``x.exp(context=C)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000876
877
Benjamin Petersone41251e2008-04-25 01:59:09 +0000878 .. method:: clear_flags()
Georg Brandl116aa622007-08-15 14:28:22 +0000879
Benjamin Petersone41251e2008-04-25 01:59:09 +0000880 Resets all of the flags to :const:`0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000881
Benjamin Petersone41251e2008-04-25 01:59:09 +0000882 .. method:: copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883
Benjamin Petersone41251e2008-04-25 01:59:09 +0000884 Return a duplicate of the context.
Georg Brandl116aa622007-08-15 14:28:22 +0000885
Benjamin Petersone41251e2008-04-25 01:59:09 +0000886 .. method:: copy_decimal(num)
Georg Brandl116aa622007-08-15 14:28:22 +0000887
Benjamin Petersone41251e2008-04-25 01:59:09 +0000888 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +0000889
Benjamin Petersone41251e2008-04-25 01:59:09 +0000890 .. method:: create_decimal(num)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000891
Benjamin Petersone41251e2008-04-25 01:59:09 +0000892 Creates a new Decimal instance from *num* but using *self* as
893 context. Unlike the :class:`Decimal` constructor, the context precision,
894 rounding method, flags, and traps are applied to the conversion.
Georg Brandl116aa622007-08-15 14:28:22 +0000895
Benjamin Petersone41251e2008-04-25 01:59:09 +0000896 This is useful because constants are often given to a greater precision
897 than is needed by the application. Another benefit is that rounding
898 immediately eliminates unintended effects from digits beyond the current
899 precision. In the following example, using unrounded inputs means that
900 adding zero to a sum can change the result:
Georg Brandl116aa622007-08-15 14:28:22 +0000901
Benjamin Petersone41251e2008-04-25 01:59:09 +0000902 .. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000903
Benjamin Petersone41251e2008-04-25 01:59:09 +0000904 >>> getcontext().prec = 3
905 >>> Decimal('3.4445') + Decimal('1.0023')
906 Decimal('4.45')
907 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
908 Decimal('4.44')
Georg Brandl116aa622007-08-15 14:28:22 +0000909
Benjamin Petersone41251e2008-04-25 01:59:09 +0000910 This method implements the to-number operation of the IBM specification.
911 If the argument is a string, no leading or trailing whitespace is
912 permitted.
913
914 .. method:: Etiny()
915
916 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
917 value for subnormal results. When underflow occurs, the exponent is set
918 to :const:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +0000919
920
Benjamin Petersone41251e2008-04-25 01:59:09 +0000921 .. method:: Etop()
Georg Brandl116aa622007-08-15 14:28:22 +0000922
Benjamin Petersone41251e2008-04-25 01:59:09 +0000923 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000924
Benjamin Petersone41251e2008-04-25 01:59:09 +0000925 The usual approach to working with decimals is to create :class:`Decimal`
926 instances and then apply arithmetic operations which take place within the
927 current context for the active thread. An alternative approach is to use
928 context methods for calculating within a specific context. The methods are
929 similar to those for the :class:`Decimal` class and are only briefly
930 recounted here.
Georg Brandl116aa622007-08-15 14:28:22 +0000931
932
Benjamin Petersone41251e2008-04-25 01:59:09 +0000933 .. method:: abs(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000934
Benjamin Petersone41251e2008-04-25 01:59:09 +0000935 Returns the absolute value of *x*.
Georg Brandl116aa622007-08-15 14:28:22 +0000936
937
Benjamin Petersone41251e2008-04-25 01:59:09 +0000938 .. method:: add(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +0000939
Benjamin Petersone41251e2008-04-25 01:59:09 +0000940 Return the sum of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +0000941
942
Facundo Batista789bdf02008-06-21 17:29:41 +0000943 .. method:: canonical(x)
944
945 Returns the same Decimal object *x*.
946
947
948 .. method:: compare(x, y)
949
950 Compares *x* and *y* numerically.
951
952
953 .. method:: compare_signal(x, y)
954
955 Compares the values of the two operands numerically.
956
957
958 .. method:: compare_total(x, y)
959
960 Compares two operands using their abstract representation.
961
962
963 .. method:: compare_total_mag(x, y)
964
965 Compares two operands using their abstract representation, ignoring sign.
966
967
968 .. method:: copy_abs(x)
969
970 Returns a copy of *x* with the sign set to 0.
971
972
973 .. method:: copy_negate(x)
974
975 Returns a copy of *x* with the sign inverted.
976
977
978 .. method:: copy_sign(x, y)
979
980 Copies the sign from *y* to *x*.
981
982
Benjamin Petersone41251e2008-04-25 01:59:09 +0000983 .. method:: divide(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +0000984
Benjamin Petersone41251e2008-04-25 01:59:09 +0000985 Return *x* divided by *y*.
Georg Brandl116aa622007-08-15 14:28:22 +0000986
987
Benjamin Petersone41251e2008-04-25 01:59:09 +0000988 .. method:: divide_int(x, y)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000989
Benjamin Petersone41251e2008-04-25 01:59:09 +0000990 Return *x* divided by *y*, truncated to an integer.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000991
992
Benjamin Petersone41251e2008-04-25 01:59:09 +0000993 .. method:: divmod(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +0000994
Benjamin Petersone41251e2008-04-25 01:59:09 +0000995 Divides two numbers and returns the integer part of the result.
Georg Brandl116aa622007-08-15 14:28:22 +0000996
997
Facundo Batista789bdf02008-06-21 17:29:41 +0000998 .. method:: exp(x)
999
1000 Returns `e ** x`.
1001
1002
1003 .. method:: fma(x, y, z)
1004
1005 Returns *x* multiplied by *y*, plus *z*.
1006
1007
1008 .. method:: is_canonical(x)
1009
1010 Returns True if *x* is canonical; otherwise returns False.
1011
1012
1013 .. method:: is_finite(x)
1014
1015 Returns True if *x* is finite; otherwise returns False.
1016
1017
1018 .. method:: is_infinite(x)
1019
1020 Returns True if *x* is infinite; otherwise returns False.
1021
1022
1023 .. method:: is_nan(x)
1024
1025 Returns True if *x* is a qNaN or sNaN; otherwise returns False.
1026
1027
1028 .. method:: is_normal(x)
1029
1030 Returns True if *x* is a normal number; otherwise returns False.
1031
1032
1033 .. method:: is_qnan(x)
1034
1035 Returns True if *x* is a quiet NaN; otherwise returns False.
1036
1037
1038 .. method:: is_signed(x)
1039
1040 Returns True if *x* is negative; otherwise returns False.
1041
1042
1043 .. method:: is_snan(x)
1044
1045 Returns True if *x* is a signaling NaN; otherwise returns False.
1046
1047
1048 .. method:: is_subnormal(x)
1049
1050 Returns True if *x* is subnormal; otherwise returns False.
1051
1052
1053 .. method:: is_zero(x)
1054
1055 Returns True if *x* is a zero; otherwise returns False.
1056
1057
1058 .. method:: ln(x)
1059
1060 Returns the natural (base e) logarithm of *x*.
1061
1062
1063 .. method:: log10(x)
1064
1065 Returns the base 10 logarithm of *x*.
1066
1067
1068 .. method:: logb(x)
1069
1070 Returns the exponent of the magnitude of the operand's MSD.
1071
1072
1073 .. method:: logical_and(x, y)
1074
1075 Applies the logical operation `and` between each operand's digits.
1076
1077
1078 .. method:: logical_invert(x)
1079
1080 Invert all the digits in *x*.
1081
1082
1083 .. method:: logical_or(x, y)
1084
1085 Applies the logical operation `or` between each operand's digits.
1086
1087
1088 .. method:: logical_xor(x, y)
1089
1090 Applies the logical operation `xor` between each operand's digits.
1091
1092
1093 .. method:: max(x, y)
1094
1095 Compares two values numerically and returns the maximum.
1096
1097
1098 .. method:: max_mag(x, y)
1099
1100 Compares the values numerically with their sign ignored.
1101
1102
1103 .. method:: min(x, y)
1104
1105 Compares two values numerically and returns the minimum.
1106
1107
1108 .. method:: min_mag(x, y)
1109
1110 Compares the values numerically with their sign ignored.
1111
1112
Benjamin Petersone41251e2008-04-25 01:59:09 +00001113 .. method:: minus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001114
Benjamin Petersone41251e2008-04-25 01:59:09 +00001115 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001116
1117
Benjamin Petersone41251e2008-04-25 01:59:09 +00001118 .. method:: multiply(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001119
Benjamin Petersone41251e2008-04-25 01:59:09 +00001120 Return the product of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001121
1122
Facundo Batista789bdf02008-06-21 17:29:41 +00001123 .. method:: next_minus(x)
1124
1125 Returns the largest representable number smaller than *x*.
1126
1127
1128 .. method:: next_plus(x)
1129
1130 Returns the smallest representable number larger than *x*.
1131
1132
1133 .. method:: next_toward(x, y)
1134
1135 Returns the number closest to *x*, in direction towards *y*.
1136
1137
1138 .. method:: normalize(x)
1139
1140 Reduces *x* to its simplest form.
1141
1142
1143 .. method:: number_class(x)
1144
1145 Returns an indication of the class of *x*.
1146
1147
Benjamin Petersone41251e2008-04-25 01:59:09 +00001148 .. method:: plus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001149
Benjamin Petersone41251e2008-04-25 01:59:09 +00001150 Plus corresponds to the unary prefix plus operator in Python. This
1151 operation applies the context precision and rounding, so it is *not* an
1152 identity operation.
Georg Brandl116aa622007-08-15 14:28:22 +00001153
1154
Benjamin Petersone41251e2008-04-25 01:59:09 +00001155 .. method:: power(x, y[, modulo])
Georg Brandl116aa622007-08-15 14:28:22 +00001156
Benjamin Petersone41251e2008-04-25 01:59:09 +00001157 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl116aa622007-08-15 14:28:22 +00001158
Benjamin Petersone41251e2008-04-25 01:59:09 +00001159 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1160 must be integral. The result will be inexact unless ``y`` is integral and
1161 the result is finite and can be expressed exactly in 'precision' digits.
1162 The result should always be correctly rounded, using the rounding mode of
1163 the current thread's context.
Georg Brandl116aa622007-08-15 14:28:22 +00001164
Benjamin Petersone41251e2008-04-25 01:59:09 +00001165 With three arguments, compute ``(x**y) % modulo``. For the three argument
1166 form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +00001167
Benjamin Petersone41251e2008-04-25 01:59:09 +00001168 - all three arguments must be integral
1169 - ``y`` must be nonnegative
1170 - at least one of ``x`` or ``y`` must be nonzero
1171 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +00001172
Benjamin Petersone41251e2008-04-25 01:59:09 +00001173 The result of ``Context.power(x, y, modulo)`` is identical to the result
1174 that would be obtained by computing ``(x**y) % modulo`` with unbounded
1175 precision, but is computed more efficiently. It is always exact.
Georg Brandl116aa622007-08-15 14:28:22 +00001176
Facundo Batista789bdf02008-06-21 17:29:41 +00001177
1178 .. method:: quantize(x, y)
1179
1180 Returns a value equal to *x* (rounded), having the exponent of *y*.
1181
1182
1183 .. method:: radix()
1184
1185 Just returns 10, as this is Decimal, :)
1186
1187
Benjamin Petersone41251e2008-04-25 01:59:09 +00001188 .. method:: remainder(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001189
Benjamin Petersone41251e2008-04-25 01:59:09 +00001190 Returns the remainder from integer division.
Georg Brandl116aa622007-08-15 14:28:22 +00001191
Benjamin Petersone41251e2008-04-25 01:59:09 +00001192 The sign of the result, if non-zero, is the same as that of the original
1193 dividend.
Georg Brandl116aa622007-08-15 14:28:22 +00001194
Facundo Batista789bdf02008-06-21 17:29:41 +00001195 .. method:: remainder_near(x, y)
1196
1197 Returns `x - y * n`, where *n* is the integer nearest the exact value
1198 of `x / y` (if the result is `0` then its sign will be the sign of *x*).
1199
1200
1201 .. method:: rotate(x, y)
1202
1203 Returns a rotated copy of *x*, *y* times.
1204
1205
1206 .. method:: same_quantum(x, y)
1207
1208 Returns True if the two operands have the same exponent.
1209
1210
1211 .. method:: scaleb (x, y)
1212
1213 Returns the first operand after adding the second value its exp.
1214
1215
1216 .. method:: shift(x, y)
1217
1218 Returns a shifted copy of *x*, *y* times.
1219
1220
1221 .. method:: sqrt(x)
1222
1223 Square root of a non-negative number to context precision.
1224
1225
Benjamin Petersone41251e2008-04-25 01:59:09 +00001226 .. method:: subtract(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001227
Benjamin Petersone41251e2008-04-25 01:59:09 +00001228 Return the difference between *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001229
Facundo Batista789bdf02008-06-21 17:29:41 +00001230
1231 .. method:: to_eng_string(x)
1232
1233 Converts a number to a string, using scientific notation.
1234
1235
1236 .. method:: to_integral_exact(x)
1237
1238 Rounds to an integer.
1239
1240
Benjamin Petersone41251e2008-04-25 01:59:09 +00001241 .. method:: to_sci_string(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001242
Benjamin Petersone41251e2008-04-25 01:59:09 +00001243 Converts a number to a string using scientific notation.
Georg Brandl116aa622007-08-15 14:28:22 +00001244
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001245.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001246
1247
1248.. _decimal-signals:
1249
1250Signals
1251-------
1252
1253Signals represent conditions that arise during computation. Each corresponds to
1254one context flag and one context trap enabler.
1255
Raymond Hettinger86173da2008-02-01 20:38:12 +00001256The context flag is set whenever the condition is encountered. After the
Georg Brandl116aa622007-08-15 14:28:22 +00001257computation, flags may be checked for informational purposes (for instance, to
1258determine whether a computation was exact). After checking the flags, be sure to
1259clear all flags before starting the next computation.
1260
1261If the context's trap enabler is set for the signal, then the condition causes a
1262Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1263is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1264condition.
1265
1266
1267.. class:: Clamped
1268
1269 Altered an exponent to fit representation constraints.
1270
1271 Typically, clamping occurs when an exponent falls outside the context's
1272 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001273 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001274
1275
1276.. class:: DecimalException
1277
1278 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1279
1280
1281.. class:: DivisionByZero
1282
1283 Signals the division of a non-infinite number by zero.
1284
1285 Can occur with division, modulo division, or when raising a number to a negative
1286 power. If this signal is not trapped, returns :const:`Infinity` or
1287 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1288
1289
1290.. class:: Inexact
1291
1292 Indicates that rounding occurred and the result is not exact.
1293
1294 Signals when non-zero digits were discarded during rounding. The rounded result
1295 is returned. The signal flag or trap is used to detect when results are
1296 inexact.
1297
1298
1299.. class:: InvalidOperation
1300
1301 An invalid operation was performed.
1302
1303 Indicates that an operation was requested that does not make sense. If not
1304 trapped, returns :const:`NaN`. Possible causes include::
1305
1306 Infinity - Infinity
1307 0 * Infinity
1308 Infinity / Infinity
1309 x % 0
1310 Infinity % x
1311 x._rescale( non-integer )
1312 sqrt(-x) and x > 0
1313 0 ** 0
1314 x ** (non-integer)
1315 x ** Infinity
1316
1317
1318.. class:: Overflow
1319
1320 Numerical overflow.
1321
Benjamin Petersone41251e2008-04-25 01:59:09 +00001322 Indicates the exponent is larger than :attr:`Emax` after rounding has
1323 occurred. If not trapped, the result depends on the rounding mode, either
1324 pulling inward to the largest representable finite number or rounding outward
1325 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1326 are also signaled.
Georg Brandl116aa622007-08-15 14:28:22 +00001327
1328
1329.. class:: Rounded
1330
1331 Rounding occurred though possibly no information was lost.
1332
Benjamin Petersone41251e2008-04-25 01:59:09 +00001333 Signaled whenever rounding discards digits; even if those digits are zero
1334 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1335 the result unchanged. This signal is used to detect loss of significant
1336 digits.
Georg Brandl116aa622007-08-15 14:28:22 +00001337
1338
1339.. class:: Subnormal
1340
1341 Exponent was lower than :attr:`Emin` prior to rounding.
1342
Benjamin Petersone41251e2008-04-25 01:59:09 +00001343 Occurs when an operation result is subnormal (the exponent is too small). If
1344 not trapped, returns the result unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +00001345
1346
1347.. class:: Underflow
1348
1349 Numerical underflow with result rounded to zero.
1350
1351 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1352 and :class:`Subnormal` are also signaled.
1353
1354The following table summarizes the hierarchy of signals::
1355
1356 exceptions.ArithmeticError(exceptions.Exception)
1357 DecimalException
1358 Clamped
1359 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1360 Inexact
1361 Overflow(Inexact, Rounded)
1362 Underflow(Inexact, Rounded, Subnormal)
1363 InvalidOperation
1364 Rounded
1365 Subnormal
1366
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001367.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001368
1369
1370.. _decimal-notes:
1371
1372Floating Point Notes
1373--------------------
1374
1375
1376Mitigating round-off error with increased precision
1377^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1378
1379The use of decimal floating point eliminates decimal representation error
1380(making it possible to represent :const:`0.1` exactly); however, some operations
1381can still incur round-off error when non-zero digits exceed the fixed precision.
1382
1383The effects of round-off error can be amplified by the addition or subtraction
1384of nearly offsetting quantities resulting in loss of significance. Knuth
1385provides two instructive examples where rounded floating point arithmetic with
1386insufficient precision causes the breakdown of the associative and distributive
Christian Heimesfe337bf2008-03-23 21:54:12 +00001387properties of addition:
1388
1389.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001390
1391 # Examples from Seminumerical Algorithms, Section 4.2.2.
1392 >>> from decimal import Decimal, getcontext
1393 >>> getcontext().prec = 8
1394
1395 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1396 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001397 Decimal('9.5111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001398 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001399 Decimal('10')
Georg Brandl116aa622007-08-15 14:28:22 +00001400
1401 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1402 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001403 Decimal('0.01')
Georg Brandl116aa622007-08-15 14:28:22 +00001404 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001405 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001406
1407The :mod:`decimal` module makes it possible to restore the identities by
Christian Heimesfe337bf2008-03-23 21:54:12 +00001408expanding the precision sufficiently to avoid loss of significance:
1409
1410.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001411
1412 >>> getcontext().prec = 20
1413 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1414 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001415 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001416 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001417 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001418 >>>
1419 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1420 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001421 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001422 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001423 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001424
1425
1426Special values
1427^^^^^^^^^^^^^^
1428
1429The number system for the :mod:`decimal` module provides special values
1430including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001431and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001432
1433Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1434they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1435not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1436can result from rounding beyond the limits of the largest representable number.
1437
1438The infinities are signed (affine) and can be used in arithmetic operations
1439where they get treated as very large, indeterminate numbers. For instance,
1440adding a constant to infinity gives another infinite result.
1441
1442Some operations are indeterminate and return :const:`NaN`, or if the
1443:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1444``0/0`` returns :const:`NaN` which means "not a number". This variety of
1445:const:`NaN` is quiet and, once created, will flow through other computations
1446always resulting in another :const:`NaN`. This behavior can be useful for a
1447series of computations that occasionally have missing inputs --- it allows the
1448calculation to proceed while flagging specific results as invalid.
1449
1450A variant is :const:`sNaN` which signals rather than remaining quiet after every
1451operation. This is a useful return value when an invalid result needs to
1452interrupt a calculation for special handling.
1453
Christian Heimes77c02eb2008-02-09 02:18:51 +00001454The behavior of Python's comparison operators can be a little surprising where a
1455:const:`NaN` is involved. A test for equality where one of the operands is a
1456quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1457``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1458:const:`True`. An attempt to compare two Decimals using any of the ``<``,
1459``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1460if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes3feef612008-02-11 06:19:17 +00001461not trapped. Note that the General Decimal Arithmetic specification does not
Christian Heimes77c02eb2008-02-09 02:18:51 +00001462specify the behavior of direct comparisons; these rules for comparisons
1463involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1464section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1465and :meth:`compare-signal` methods instead.
1466
Georg Brandl116aa622007-08-15 14:28:22 +00001467The signed zeros can result from calculations that underflow. They keep the sign
1468that would have resulted if the calculation had been carried out to greater
1469precision. Since their magnitude is zero, both positive and negative zeros are
1470treated as equal and their sign is informational.
1471
1472In addition to the two signed zeros which are distinct yet equal, there are
1473various representations of zero with differing precisions yet equivalent in
1474value. This takes a bit of getting used to. For an eye accustomed to
1475normalized floating point representations, it is not immediately obvious that
Christian Heimesfe337bf2008-03-23 21:54:12 +00001476the following calculation returns a value equal to zero:
Georg Brandl116aa622007-08-15 14:28:22 +00001477
1478 >>> 1 / Decimal('Infinity')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001479 Decimal('0E-1000000026')
Georg Brandl116aa622007-08-15 14:28:22 +00001480
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001481.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001482
1483
1484.. _decimal-threads:
1485
1486Working with threads
1487--------------------
1488
1489The :func:`getcontext` function accesses a different :class:`Context` object for
1490each thread. Having separate thread contexts means that threads may make
1491changes (such as ``getcontext.prec=10``) without interfering with other threads.
1492
1493Likewise, the :func:`setcontext` function automatically assigns its target to
1494the current thread.
1495
1496If :func:`setcontext` has not been called before :func:`getcontext`, then
1497:func:`getcontext` will automatically create a new context for use in the
1498current thread.
1499
1500The new context is copied from a prototype context called *DefaultContext*. To
1501control the defaults so that each thread will use the same values throughout the
1502application, directly modify the *DefaultContext* object. This should be done
1503*before* any threads are started so that there won't be a race condition between
1504threads calling :func:`getcontext`. For example::
1505
1506 # Set applicationwide defaults for all threads about to be launched
1507 DefaultContext.prec = 12
1508 DefaultContext.rounding = ROUND_DOWN
1509 DefaultContext.traps = ExtendedContext.traps.copy()
1510 DefaultContext.traps[InvalidOperation] = 1
1511 setcontext(DefaultContext)
1512
1513 # Afterwards, the threads can be started
1514 t1.start()
1515 t2.start()
1516 t3.start()
1517 . . .
1518
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001519.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001520
1521
1522.. _decimal-recipes:
1523
1524Recipes
1525-------
1526
1527Here are a few recipes that serve as utility functions and that demonstrate ways
1528to work with the :class:`Decimal` class::
1529
1530 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1531 pos='', neg='-', trailneg=''):
1532 """Convert Decimal to a money formatted string.
1533
1534 places: required number of places after the decimal point
1535 curr: optional currency symbol before the sign (may be blank)
1536 sep: optional grouping separator (comma, period, space, or blank)
1537 dp: decimal point indicator (comma or period)
1538 only specify as blank when places is zero
1539 pos: optional sign for positive numbers: '+', space or blank
1540 neg: optional sign for negative numbers: '-', '(', space or blank
1541 trailneg:optional trailing minus indicator: '-', ')', space or blank
1542
1543 >>> d = Decimal('-1234567.8901')
1544 >>> moneyfmt(d, curr='$')
1545 '-$1,234,567.89'
1546 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1547 '1.234.568-'
1548 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1549 '($1,234,567.89)'
1550 >>> moneyfmt(Decimal(123456789), sep=' ')
1551 '123 456 789.00'
1552 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Christian Heimesdae2a892008-04-19 00:55:37 +00001553 '<0.02>'
Georg Brandl116aa622007-08-15 14:28:22 +00001554
1555 """
Christian Heimesa156e092008-02-16 07:38:31 +00001556 q = Decimal(10) ** -places # 2 places --> '0.01'
1557 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +00001558 result = []
Facundo Batista789bdf02008-06-21 17:29:41 +00001559 digits = list(map(str, digits))
Georg Brandl116aa622007-08-15 14:28:22 +00001560 build, next = result.append, digits.pop
1561 if sign:
1562 build(trailneg)
1563 for i in range(places):
Christian Heimesa156e092008-02-16 07:38:31 +00001564 build(next() if digits else '0')
Georg Brandl116aa622007-08-15 14:28:22 +00001565 build(dp)
Christian Heimesdae2a892008-04-19 00:55:37 +00001566 if not digits:
1567 build('0')
Georg Brandl116aa622007-08-15 14:28:22 +00001568 i = 0
1569 while digits:
1570 build(next())
1571 i += 1
1572 if i == 3 and digits:
1573 i = 0
1574 build(sep)
1575 build(curr)
Christian Heimesa156e092008-02-16 07:38:31 +00001576 build(neg if sign else pos)
1577 return ''.join(reversed(result))
Georg Brandl116aa622007-08-15 14:28:22 +00001578
1579 def pi():
1580 """Compute Pi to the current precision.
1581
Georg Brandl6911e3c2007-09-04 07:15:32 +00001582 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001583 3.141592653589793238462643383
1584
1585 """
1586 getcontext().prec += 2 # extra digits for intermediate steps
1587 three = Decimal(3) # substitute "three=3.0" for regular floats
1588 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1589 while s != lasts:
1590 lasts = s
1591 n, na = n+na, na+8
1592 d, da = d+da, da+32
1593 t = (t * n) / d
1594 s += t
1595 getcontext().prec -= 2
1596 return +s # unary plus applies the new precision
1597
1598 def exp(x):
1599 """Return e raised to the power of x. Result type matches input type.
1600
Georg Brandl6911e3c2007-09-04 07:15:32 +00001601 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001602 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001603 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001604 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001605 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001606 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001607 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001608 (7.38905609893+0j)
1609
1610 """
1611 getcontext().prec += 2
1612 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1613 while s != lasts:
1614 lasts = s
1615 i += 1
1616 fact *= i
1617 num *= x
1618 s += num / fact
1619 getcontext().prec -= 2
1620 return +s
1621
1622 def cos(x):
1623 """Return the cosine of x as measured in radians.
1624
Georg Brandl6911e3c2007-09-04 07:15:32 +00001625 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001626 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001627 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001628 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001629 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001630 (0.87758256189+0j)
1631
1632 """
1633 getcontext().prec += 2
1634 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1635 while s != lasts:
1636 lasts = s
1637 i += 2
1638 fact *= i * (i-1)
1639 num *= x * x
1640 sign *= -1
1641 s += num / fact * sign
1642 getcontext().prec -= 2
1643 return +s
1644
1645 def sin(x):
1646 """Return the sine of x as measured in radians.
1647
Georg Brandl6911e3c2007-09-04 07:15:32 +00001648 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001649 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001650 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001651 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001652 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001653 (0.479425538604+0j)
1654
1655 """
1656 getcontext().prec += 2
1657 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1658 while s != lasts:
1659 lasts = s
1660 i += 2
1661 fact *= i * (i-1)
1662 num *= x * x
1663 sign *= -1
1664 s += num / fact * sign
1665 getcontext().prec -= 2
1666 return +s
1667
1668
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001669.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001670
1671
1672.. _decimal-faq:
1673
1674Decimal FAQ
1675-----------
1676
1677Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1678minimize typing when using the interactive interpreter?
1679
Christian Heimesfe337bf2008-03-23 21:54:12 +00001680A. Some users abbreviate the constructor to just a single letter:
Georg Brandl116aa622007-08-15 14:28:22 +00001681
1682 >>> D = decimal.Decimal
1683 >>> D('1.23') + D('3.45')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001684 Decimal('4.68')
Georg Brandl116aa622007-08-15 14:28:22 +00001685
1686Q. In a fixed-point application with two decimal places, some inputs have many
1687places and need to be rounded. Others are not supposed to have excess digits
1688and need to be validated. What methods should be used?
1689
1690A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Christian Heimesfe337bf2008-03-23 21:54:12 +00001691the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl116aa622007-08-15 14:28:22 +00001692
1693 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1694
1695 >>> # Round to two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001696 >>> Decimal('3.214').quantize(TWOPLACES)
1697 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001698
1699 >>> # Validate that a number does not exceed two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001700 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1701 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001702
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001703 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl116aa622007-08-15 14:28:22 +00001704 Traceback (most recent call last):
1705 ...
Christian Heimesfe337bf2008-03-23 21:54:12 +00001706 Inexact
Georg Brandl116aa622007-08-15 14:28:22 +00001707
1708Q. Once I have valid two place inputs, how do I maintain that invariant
1709throughout an application?
1710
Christian Heimesa156e092008-02-16 07:38:31 +00001711A. Some operations like addition, subtraction, and multiplication by an integer
1712will automatically preserve fixed point. Others operations, like division and
1713non-integer multiplication, will change the number of decimal places and need to
Christian Heimesfe337bf2008-03-23 21:54:12 +00001714be followed-up with a :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001715
1716 >>> a = Decimal('102.72') # Initial fixed-point values
1717 >>> b = Decimal('3.17')
1718 >>> a + b # Addition preserves fixed-point
1719 Decimal('105.89')
1720 >>> a - b
1721 Decimal('99.55')
1722 >>> a * 42 # So does integer multiplication
1723 Decimal('4314.24')
1724 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1725 Decimal('325.62')
1726 >>> (b / a).quantize(TWOPLACES) # And quantize division
1727 Decimal('0.03')
1728
1729In developing fixed-point applications, it is convenient to define functions
Christian Heimesfe337bf2008-03-23 21:54:12 +00001730to handle the :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001731
1732 >>> def mul(x, y, fp=TWOPLACES):
1733 ... return (x * y).quantize(fp)
1734 >>> def div(x, y, fp=TWOPLACES):
1735 ... return (x / y).quantize(fp)
1736
1737 >>> mul(a, b) # Automatically preserve fixed-point
1738 Decimal('325.62')
1739 >>> div(b, a)
1740 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +00001741
1742Q. There are many ways to express the same value. The numbers :const:`200`,
1743:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1744various precisions. Is there a way to transform them to a single recognizable
1745canonical value?
1746
1747A. The :meth:`normalize` method maps all equivalent values to a single
Christian Heimesfe337bf2008-03-23 21:54:12 +00001748representative:
Georg Brandl116aa622007-08-15 14:28:22 +00001749
1750 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1751 >>> [v.normalize() for v in values]
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001752 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl116aa622007-08-15 14:28:22 +00001753
1754Q. Some decimal values always print with exponential notation. Is there a way
1755to get a non-exponential representation?
1756
1757A. For some values, exponential notation is the only way to express the number
1758of significant places in the coefficient. For example, expressing
1759:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1760original's two-place significance.
1761
Christian Heimesa156e092008-02-16 07:38:31 +00001762If an application does not care about tracking significance, it is easy to
Christian Heimesc3f30c42008-02-22 16:37:40 +00001763remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001764value unchanged:
Christian Heimesa156e092008-02-16 07:38:31 +00001765
1766 >>> def remove_exponent(d):
1767 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1768
1769 >>> remove_exponent(Decimal('5E+3'))
1770 Decimal('5000')
1771
Georg Brandl116aa622007-08-15 14:28:22 +00001772Q. Is there a way to convert a regular float to a :class:`Decimal`?
1773
1774A. Yes, all binary floating point numbers can be exactly expressed as a
1775Decimal. An exact conversion may take more precision than intuition would
Christian Heimesfe337bf2008-03-23 21:54:12 +00001776suggest, so we trap :const:`Inexact` to signal a need for more precision:
1777
1778.. testcode::
Georg Brandl116aa622007-08-15 14:28:22 +00001779
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001780 def float_to_decimal(f):
1781 "Convert a floating point number to a Decimal with no loss of information"
1782 n, d = f.as_integer_ratio()
1783 with localcontext() as ctx:
1784 ctx.traps[Inexact] = True
1785 while True:
1786 try:
1787 return Decimal(n) / Decimal(d)
1788 except Inexact:
1789 ctx.prec += 1
Georg Brandl116aa622007-08-15 14:28:22 +00001790
Christian Heimesfe337bf2008-03-23 21:54:12 +00001791.. doctest::
1792
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001793 >>> float_to_decimal(math.pi)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001794 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl116aa622007-08-15 14:28:22 +00001795
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001796Q. Why isn't the :func:`float_to_decimal` routine included in the module?
Georg Brandl116aa622007-08-15 14:28:22 +00001797
1798A. There is some question about whether it is advisable to mix binary and
1799decimal floating point. Also, its use requires some care to avoid the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001800representation issues associated with binary floating point:
Georg Brandl116aa622007-08-15 14:28:22 +00001801
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001802 >>> float_to_decimal(1.1)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001803 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl116aa622007-08-15 14:28:22 +00001804
1805Q. Within a complex calculation, how can I make sure that I haven't gotten a
1806spurious result because of insufficient precision or rounding anomalies.
1807
1808A. The decimal module makes it easy to test results. A best practice is to
1809re-run calculations using greater precision and with various rounding modes.
1810Widely differing results indicate insufficient precision, rounding mode issues,
1811ill-conditioned inputs, or a numerically unstable algorithm.
1812
1813Q. I noticed that context precision is applied to the results of operations but
1814not to the inputs. Is there anything to watch out for when mixing values of
1815different precisions?
1816
1817A. Yes. The principle is that all values are considered to be exact and so is
1818the arithmetic on those values. Only the results are rounded. The advantage
1819for inputs is that "what you type is what you get". A disadvantage is that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001820results can look odd if you forget that the inputs haven't been rounded:
1821
1822.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001823
1824 >>> getcontext().prec = 3
Christian Heimesfe337bf2008-03-23 21:54:12 +00001825 >>> Decimal('3.104') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001826 Decimal('5.21')
Christian Heimesfe337bf2008-03-23 21:54:12 +00001827 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001828 Decimal('5.20')
Georg Brandl116aa622007-08-15 14:28:22 +00001829
1830The solution is either to increase precision or to force rounding of inputs
Christian Heimesfe337bf2008-03-23 21:54:12 +00001831using the unary plus operation:
1832
1833.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001834
1835 >>> getcontext().prec = 3
1836 >>> +Decimal('1.23456789') # unary plus triggers rounding
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001837 Decimal('1.23')
Georg Brandl116aa622007-08-15 14:28:22 +00001838
1839Alternatively, inputs can be rounded upon creation using the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001840:meth:`Context.create_decimal` method:
Georg Brandl116aa622007-08-15 14:28:22 +00001841
1842 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001843 Decimal('1.2345')
Georg Brandl116aa622007-08-15 14:28:22 +00001844