blob: a3325f7abac7b22659824a3244584bd6e3f41e7d [file] [log] [blame]
Christian Heimes3feef612008-02-11 06:19:17 +00001:mod:`decimal` --- Decimal fixed point and floating point arithmetic
2====================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: decimal
5 :synopsis: Implementation of the General Decimal Arithmetic Specification.
6
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
8.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
9.. moduleauthor:: Raymond Hettinger <python at rcn.com>
10.. moduleauthor:: Aahz <aahz at pobox.com>
11.. moduleauthor:: Tim Peters <tim.one at comcast.net>
Georg Brandl116aa622007-08-15 14:28:22 +000012.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
13
Christian Heimesfe337bf2008-03-23 21:54:12 +000014.. import modules for testing inline doctests with the Sphinx doctest builder
15.. testsetup:: *
16
17 import decimal
18 import math
19 from decimal import *
20 # make sure each group gets a fresh context
21 setcontext(Context())
Georg Brandl116aa622007-08-15 14:28:22 +000022
Georg Brandl116aa622007-08-15 14:28:22 +000023The :mod:`decimal` module provides support for decimal floating point
Thomas Wouters1b7f8912007-09-19 03:06:30 +000024arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl116aa622007-08-15 14:28:22 +000025
Christian Heimes3feef612008-02-11 06:19:17 +000026* Decimal "is based on a floating-point model which was designed with people
27 in mind, and necessarily has a paramount guiding principle -- computers must
28 provide an arithmetic that works in the same way as the arithmetic that
29 people learn at school." -- excerpt from the decimal arithmetic specification.
30
Georg Brandl116aa622007-08-15 14:28:22 +000031* Decimal numbers can be represented exactly. In contrast, numbers like
Raymond Hettingerd258d1e2009-04-23 22:06:12 +000032 :const:`1.1` and :const:`2.2` do not have an exact representations in binary
33 floating point. End users typically would not expect ``1.1 + 2.2`` to display
34 as :const:`3.3000000000000003` as it does with binary floating point.
Georg Brandl116aa622007-08-15 14:28:22 +000035
36* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000037 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl116aa622007-08-15 14:28:22 +000038 is :const:`5.5511151231257827e-017`. While near to zero, the differences
39 prevent reliable equality testing and differences can accumulate. For this
Christian Heimes3feef612008-02-11 06:19:17 +000040 reason, decimal is preferred in accounting applications which have strict
Georg Brandl116aa622007-08-15 14:28:22 +000041 equality invariants.
42
43* The decimal module incorporates a notion of significant places so that ``1.30
44 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
45 This is the customary presentation for monetary applications. For
46 multiplication, the "schoolbook" approach uses all the figures in the
47 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
48 1.20`` gives :const:`1.5600`.
49
50* Unlike hardware based binary floating point, the decimal module has a user
Thomas Wouters1b7f8912007-09-19 03:06:30 +000051 alterable precision (defaulting to 28 places) which can be as large as needed for
Christian Heimesfe337bf2008-03-23 21:54:12 +000052 a given problem:
Georg Brandl116aa622007-08-15 14:28:22 +000053
54 >>> getcontext().prec = 6
55 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000056 Decimal('0.142857')
Georg Brandl116aa622007-08-15 14:28:22 +000057 >>> getcontext().prec = 28
58 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000059 Decimal('0.1428571428571428571428571429')
Georg Brandl116aa622007-08-15 14:28:22 +000060
61* Both binary and decimal floating point are implemented in terms of published
62 standards. While the built-in float type exposes only a modest portion of its
63 capabilities, the decimal module exposes all required parts of the standard.
64 When needed, the programmer has full control over rounding and signal handling.
Christian Heimes3feef612008-02-11 06:19:17 +000065 This includes an option to enforce exact arithmetic by using exceptions
66 to block any inexact operations.
67
68* The decimal module was designed to support "without prejudice, both exact
69 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
70 and rounded floating-point arithmetic." -- excerpt from the decimal
71 arithmetic specification.
Georg Brandl116aa622007-08-15 14:28:22 +000072
73The module design is centered around three concepts: the decimal number, the
74context for arithmetic, and signals.
75
76A decimal number is immutable. It has a sign, coefficient digits, and an
77exponent. To preserve significance, the coefficient digits do not truncate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000078trailing zeros. Decimals also include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +000079:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
80differentiates :const:`-0` from :const:`+0`.
81
82The context for arithmetic is an environment specifying precision, rounding
83rules, limits on exponents, flags indicating the results of operations, and trap
84enablers which determine whether signals are treated as exceptions. Rounding
85options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
86:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +000087:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl116aa622007-08-15 14:28:22 +000088
89Signals are groups of exceptional conditions arising during the course of
90computation. Depending on the needs of the application, signals may be ignored,
91considered as informational, or treated as exceptions. The signals in the
92decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
93:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
94:const:`Overflow`, and :const:`Underflow`.
95
96For each signal there is a flag and a trap enabler. When a signal is
Raymond Hettinger86173da2008-02-01 20:38:12 +000097encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl116aa622007-08-15 14:28:22 +000098set to one, an exception is raised. Flags are sticky, so the user needs to
99reset them before monitoring a calculation.
100
101
102.. seealso::
103
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000104 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
Raymond Hettinger960dc362009-04-21 03:43:15 +0000105 Specification <http://speleotrove.com/decimal/decarith.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000106
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000107 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Christian Heimes77c02eb2008-02-09 02:18:51 +0000108 <http://754r.ucbtest.org/standards/854.pdf>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000109
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000110.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000111
112
113.. _decimal-tutorial:
114
115Quick-start Tutorial
116--------------------
117
118The usual start to using decimals is importing the module, viewing the current
119context with :func:`getcontext` and, if necessary, setting new values for
120precision, rounding, or enabled traps::
121
122 >>> from decimal import *
123 >>> getcontext()
124 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000125 capitals=1, flags=[], traps=[Overflow, DivisionByZero,
126 InvalidOperation])
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128 >>> getcontext().prec = 7 # Set a new precision
129
130Decimal instances can be constructed from integers, strings, or tuples. To
131create a Decimal from a :class:`float`, first convert it to a string. This
132serves as an explicit reminder of the details of the conversion (including
133representation error). Decimal numbers include special values such as
134:const:`NaN` which stands for "Not a number", positive and negative
Christian Heimesfe337bf2008-03-23 21:54:12 +0000135:const:`Infinity`, and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000136
Facundo Batista789bdf02008-06-21 17:29:41 +0000137 >>> getcontext().prec = 28
Georg Brandl116aa622007-08-15 14:28:22 +0000138 >>> Decimal(10)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000139 Decimal('10')
140 >>> Decimal('3.14')
141 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000142 >>> Decimal((0, (3, 1, 4), -2))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000143 Decimal('3.14')
Georg Brandl116aa622007-08-15 14:28:22 +0000144 >>> Decimal(str(2.0 ** 0.5))
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000145 Decimal('1.41421356237')
146 >>> Decimal(2) ** Decimal('0.5')
147 Decimal('1.414213562373095048801688724')
148 >>> Decimal('NaN')
149 Decimal('NaN')
150 >>> Decimal('-Infinity')
151 Decimal('-Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153The significance of a new Decimal is determined solely by the number of digits
154input. Context precision and rounding only come into play during arithmetic
Christian Heimesfe337bf2008-03-23 21:54:12 +0000155operations.
156
157.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159 >>> getcontext().prec = 6
160 >>> Decimal('3.0')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000161 Decimal('3.0')
Georg Brandl116aa622007-08-15 14:28:22 +0000162 >>> Decimal('3.1415926535')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000163 Decimal('3.1415926535')
Georg Brandl116aa622007-08-15 14:28:22 +0000164 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000165 Decimal('5.85987')
Georg Brandl116aa622007-08-15 14:28:22 +0000166 >>> getcontext().rounding = ROUND_UP
167 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000168 Decimal('5.85988')
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170Decimals interact well with much of the rest of Python. Here is a small decimal
Christian Heimesfe337bf2008-03-23 21:54:12 +0000171floating point flying circus:
172
173.. doctest::
174 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000175
Facundo Batista789bdf02008-06-21 17:29:41 +0000176 >>> 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 +0000177 >>> max(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000178 Decimal('9.25')
Georg Brandl116aa622007-08-15 14:28:22 +0000179 >>> min(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000180 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +0000181 >>> sorted(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000182 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
183 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl116aa622007-08-15 14:28:22 +0000184 >>> sum(data)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000185 Decimal('19.29')
Georg Brandl116aa622007-08-15 14:28:22 +0000186 >>> a,b,c = data[:3]
187 >>> str(a)
188 '1.34'
189 >>> float(a)
Mark Dickinson8dad7df2009-06-28 20:36:54 +0000190 1.34
191 >>> round(a, 1)
192 Decimal('1.3')
Georg Brandl116aa622007-08-15 14:28:22 +0000193 >>> int(a)
194 1
195 >>> a * 5
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000196 Decimal('6.70')
Georg Brandl116aa622007-08-15 14:28:22 +0000197 >>> a * b
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000198 Decimal('2.5058')
Georg Brandl116aa622007-08-15 14:28:22 +0000199 >>> c % a
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000200 Decimal('0.77')
Georg Brandl116aa622007-08-15 14:28:22 +0000201
Christian Heimesfe337bf2008-03-23 21:54:12 +0000202And some mathematical functions are also available to Decimal:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000203
Facundo Batista789bdf02008-06-21 17:29:41 +0000204 >>> getcontext().prec = 28
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000205 >>> Decimal(2).sqrt()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000206 Decimal('1.414213562373095048801688724')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000207 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000208 Decimal('2.718281828459045235360287471')
209 >>> Decimal('10').ln()
210 Decimal('2.302585092994045684017991455')
211 >>> Decimal('10').log10()
212 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000213
Georg Brandl116aa622007-08-15 14:28:22 +0000214The :meth:`quantize` method rounds a number to a fixed exponent. This method is
215useful for monetary applications that often round results to a fixed number of
Christian Heimesfe337bf2008-03-23 21:54:12 +0000216places:
Georg Brandl116aa622007-08-15 14:28:22 +0000217
218 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000219 Decimal('7.32')
Georg Brandl116aa622007-08-15 14:28:22 +0000220 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000221 Decimal('8')
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223As shown above, the :func:`getcontext` function accesses the current context and
224allows the settings to be changed. This approach meets the needs of most
225applications.
226
227For more advanced work, it may be useful to create alternate contexts using the
228Context() constructor. To make an alternate active, use the :func:`setcontext`
229function.
230
231In accordance with the standard, the :mod:`Decimal` module provides two ready to
232use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
233former is especially useful for debugging because many of the traps are
Christian Heimesfe337bf2008-03-23 21:54:12 +0000234enabled:
235
236.. doctest:: newcontext
237 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000238
239 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
240 >>> setcontext(myothercontext)
241 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000242 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244 >>> ExtendedContext
245 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
246 capitals=1, flags=[], traps=[])
247 >>> setcontext(ExtendedContext)
248 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000249 Decimal('0.142857143')
Georg Brandl116aa622007-08-15 14:28:22 +0000250 >>> Decimal(42) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000251 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000252
253 >>> setcontext(BasicContext)
254 >>> Decimal(42) / Decimal(0)
255 Traceback (most recent call last):
256 File "<pyshell#143>", line 1, in -toplevel-
257 Decimal(42) / Decimal(0)
258 DivisionByZero: x / 0
259
260Contexts also have signal flags for monitoring exceptional conditions
261encountered during computations. The flags remain set until explicitly cleared,
262so it is best to clear the flags before each set of monitored computations by
263using the :meth:`clear_flags` method. ::
264
265 >>> setcontext(ExtendedContext)
266 >>> getcontext().clear_flags()
267 >>> Decimal(355) / Decimal(113)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000268 Decimal('3.14159292')
Georg Brandl116aa622007-08-15 14:28:22 +0000269 >>> getcontext()
270 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Facundo Batista789bdf02008-06-21 17:29:41 +0000271 capitals=1, flags=[Inexact, Rounded], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000272
273The *flags* entry shows that the rational approximation to :const:`Pi` was
274rounded (digits beyond the context precision were thrown away) and that the
275result is inexact (some of the discarded digits were non-zero).
276
277Individual traps are set using the dictionary in the :attr:`traps` field of a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000278context:
Georg Brandl116aa622007-08-15 14:28:22 +0000279
Christian Heimesfe337bf2008-03-23 21:54:12 +0000280.. doctest:: newcontext
281
282 >>> setcontext(ExtendedContext)
Georg Brandl116aa622007-08-15 14:28:22 +0000283 >>> Decimal(1) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000284 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000285 >>> getcontext().traps[DivisionByZero] = 1
286 >>> Decimal(1) / Decimal(0)
287 Traceback (most recent call last):
288 File "<pyshell#112>", line 1, in -toplevel-
289 Decimal(1) / Decimal(0)
290 DivisionByZero: x / 0
291
292Most programs adjust the current context only once, at the beginning of the
293program. And, in many applications, data is converted to :class:`Decimal` with
294a single cast inside a loop. With context set and decimals created, the bulk of
295the program manipulates the data no differently than with other Python numeric
296types.
297
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000298.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000299
300
301.. _decimal-decimal:
302
303Decimal objects
304---------------
305
306
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000307.. class:: Decimal(value="0", context=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000308
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000309 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl116aa622007-08-15 14:28:22 +0000310
Christian Heimesa62da1d2008-01-12 19:39:10 +0000311 *value* can be an integer, string, tuple, or another :class:`Decimal`
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000312 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Christian Heimesa62da1d2008-01-12 19:39:10 +0000313 string, it should conform to the decimal numeric string syntax after leading
314 and trailing whitespace characters are removed::
Georg Brandl116aa622007-08-15 14:28:22 +0000315
316 sign ::= '+' | '-'
317 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
318 indicator ::= 'e' | 'E'
319 digits ::= digit [digit]...
320 decimal-part ::= digits '.' [digits] | ['.'] digits
321 exponent-part ::= indicator [sign] digits
322 infinity ::= 'Infinity' | 'Inf'
323 nan ::= 'NaN' [digits] | 'sNaN' [digits]
324 numeric-value ::= decimal-part [exponent-part] | infinity
Georg Brandl48310cd2009-01-03 21:18:54 +0000325 numeric-string ::= [sign] numeric-value | [sign] nan
Georg Brandl116aa622007-08-15 14:28:22 +0000326
Mark Dickinson345adc42009-08-02 10:14:23 +0000327 Other Unicode decimal digits are also permitted where ``digit``
328 appears above. These include decimal digits from various other
329 alphabets (for example, Arabic-Indic and Devanāgarī digits) along
330 with the fullwidth digits ``'\uff10'`` through ``'\uff19'``.
331
Georg Brandl116aa622007-08-15 14:28:22 +0000332 If *value* is a :class:`tuple`, it should have three components, a sign
333 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
334 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000335 returns ``Decimal('1.414')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337 The *context* precision does not affect how many digits are stored. That is
338 determined exclusively by the number of digits in *value*. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000339 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl116aa622007-08-15 14:28:22 +0000340 only three.
341
342 The purpose of the *context* argument is determining what to do if *value* is a
343 malformed string. If the context traps :const:`InvalidOperation`, an exception
344 is raised; otherwise, the constructor returns a new Decimal with the value of
345 :const:`NaN`.
346
347 Once constructed, :class:`Decimal` objects are immutable.
348
Benjamin Petersone41251e2008-04-25 01:59:09 +0000349 Decimal floating point objects share many properties with the other built-in
350 numeric types such as :class:`float` and :class:`int`. All of the usual math
351 operations and special methods apply. Likewise, decimal objects can be
352 copied, pickled, printed, used as dictionary keys, used as set elements,
353 compared, sorted, and coerced to another type (such as :class:`float` or
354 :class:`long`).
Christian Heimesa62da1d2008-01-12 19:39:10 +0000355
Benjamin Petersone41251e2008-04-25 01:59:09 +0000356 In addition to the standard numeric properties, decimal floating point
357 objects also have a number of specialized methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000358
Georg Brandl116aa622007-08-15 14:28:22 +0000359
Benjamin Petersone41251e2008-04-25 01:59:09 +0000360 .. method:: adjusted()
Georg Brandl116aa622007-08-15 14:28:22 +0000361
Benjamin Petersone41251e2008-04-25 01:59:09 +0000362 Return the adjusted exponent after shifting out the coefficient's
363 rightmost digits until only the lead digit remains:
364 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
365 position of the most significant digit with respect to the decimal point.
Georg Brandl116aa622007-08-15 14:28:22 +0000366
Georg Brandl116aa622007-08-15 14:28:22 +0000367
Benjamin Petersone41251e2008-04-25 01:59:09 +0000368 .. method:: as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Benjamin Petersone41251e2008-04-25 01:59:09 +0000370 Return a :term:`named tuple` representation of the number:
371 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000372
Christian Heimes25bb7832008-01-11 16:17:00 +0000373
Benjamin Petersone41251e2008-04-25 01:59:09 +0000374 .. method:: canonical()
Georg Brandl116aa622007-08-15 14:28:22 +0000375
Benjamin Petersone41251e2008-04-25 01:59:09 +0000376 Return the canonical encoding of the argument. Currently, the encoding of
377 a :class:`Decimal` instance is always canonical, so this operation returns
378 its argument unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000379
Benjamin Petersone41251e2008-04-25 01:59:09 +0000380 .. method:: compare(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000381
Georg Brandl05f5ab72008-09-24 09:11:47 +0000382 Compare the values of two Decimal instances. :meth:`compare` returns a
383 Decimal instance, and if either operand is a NaN then the result is a
384 NaN::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000385
Georg Brandl05f5ab72008-09-24 09:11:47 +0000386 a or b is a NaN ==> Decimal('NaN')
387 a < b ==> Decimal('-1')
388 a == b ==> Decimal('0')
389 a > b ==> Decimal('1')
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Benjamin Petersone41251e2008-04-25 01:59:09 +0000391 .. method:: compare_signal(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000392
Benjamin Petersone41251e2008-04-25 01:59:09 +0000393 This operation is identical to the :meth:`compare` method, except that all
394 NaNs signal. That is, if neither operand is a signaling NaN then any
395 quiet NaN operand is treated as though it were a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000396
Benjamin Petersone41251e2008-04-25 01:59:09 +0000397 .. method:: compare_total(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000398
Benjamin Petersone41251e2008-04-25 01:59:09 +0000399 Compare two operands using their abstract representation rather than their
400 numerical value. Similar to the :meth:`compare` method, but the result
401 gives a total ordering on :class:`Decimal` instances. Two
402 :class:`Decimal` instances with the same numeric value but different
403 representations compare unequal in this ordering:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000404
Benjamin Petersone41251e2008-04-25 01:59:09 +0000405 >>> Decimal('12.0').compare_total(Decimal('12'))
406 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000407
Benjamin Petersone41251e2008-04-25 01:59:09 +0000408 Quiet and signaling NaNs are also included in the total ordering. The
409 result of this function is ``Decimal('0')`` if both operands have the same
410 representation, ``Decimal('-1')`` if the first operand is lower in the
411 total order than the second, and ``Decimal('1')`` if the first operand is
412 higher in the total order than the second operand. See the specification
413 for details of the total order.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000414
Benjamin Petersone41251e2008-04-25 01:59:09 +0000415 .. method:: compare_total_mag(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000416
Benjamin Petersone41251e2008-04-25 01:59:09 +0000417 Compare two operands using their abstract representation rather than their
418 value as in :meth:`compare_total`, but ignoring the sign of each operand.
419 ``x.compare_total_mag(y)`` is equivalent to
420 ``x.copy_abs().compare_total(y.copy_abs())``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000421
Facundo Batista789bdf02008-06-21 17:29:41 +0000422 .. method:: conjugate()
423
Benjamin Petersondcf97b92008-07-02 17:30:14 +0000424 Just returns self, this method is only to comply with the Decimal
Facundo Batista789bdf02008-06-21 17:29:41 +0000425 Specification.
426
Benjamin Petersone41251e2008-04-25 01:59:09 +0000427 .. method:: copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000428
Benjamin Petersone41251e2008-04-25 01:59:09 +0000429 Return the absolute value of the argument. This operation is unaffected
430 by the context and is quiet: no flags are changed and no rounding is
431 performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000432
Benjamin Petersone41251e2008-04-25 01:59:09 +0000433 .. method:: copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000434
Benjamin Petersone41251e2008-04-25 01:59:09 +0000435 Return the negation of the argument. This operation is unaffected by the
436 context and is quiet: no flags are changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000437
Benjamin Petersone41251e2008-04-25 01:59:09 +0000438 .. method:: copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000439
Benjamin Petersone41251e2008-04-25 01:59:09 +0000440 Return a copy of the first operand with the sign set to be the same as the
441 sign of the second operand. For example:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000442
Benjamin Petersone41251e2008-04-25 01:59:09 +0000443 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
444 Decimal('-2.3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000445
Benjamin Petersone41251e2008-04-25 01:59:09 +0000446 This operation is unaffected by the context and is quiet: no flags are
447 changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000448
Benjamin Petersone41251e2008-04-25 01:59:09 +0000449 .. method:: exp([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000450
Benjamin Petersone41251e2008-04-25 01:59:09 +0000451 Return the value of the (natural) exponential function ``e**x`` at the
452 given number. The result is correctly rounded using the
453 :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000454
Benjamin Petersone41251e2008-04-25 01:59:09 +0000455 >>> Decimal(1).exp()
456 Decimal('2.718281828459045235360287471')
457 >>> Decimal(321).exp()
458 Decimal('2.561702493119680037517373933E+139')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000459
Raymond Hettinger771ed762009-01-03 19:20:32 +0000460 .. method:: from_float(f)
461
462 Classmethod that converts a float to a decimal number, exactly.
463
464 Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
465 Since 0.1 is not exactly representable in binary floating point, the
466 value is stored as the nearest representable value which is
467 `0x1.999999999999ap-4`. That equivalent value in decimal is
468 `0.1000000000000000055511151231257827021181583404541015625`.
469
470 .. doctest::
471
472 >>> Decimal.from_float(0.1)
473 Decimal('0.1000000000000000055511151231257827021181583404541015625')
474 >>> Decimal.from_float(float('nan'))
475 Decimal('NaN')
476 >>> Decimal.from_float(float('inf'))
477 Decimal('Infinity')
478 >>> Decimal.from_float(float('-inf'))
479 Decimal('-Infinity')
480
Georg Brandl45f53372009-01-03 21:15:20 +0000481 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000482
Benjamin Petersone41251e2008-04-25 01:59:09 +0000483 .. method:: fma(other, third[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000484
Benjamin Petersone41251e2008-04-25 01:59:09 +0000485 Fused multiply-add. Return self*other+third with no rounding of the
486 intermediate product self*other.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000487
Benjamin Petersone41251e2008-04-25 01:59:09 +0000488 >>> Decimal(2).fma(3, 5)
489 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000490
Benjamin Petersone41251e2008-04-25 01:59:09 +0000491 .. method:: is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000492
Benjamin Petersone41251e2008-04-25 01:59:09 +0000493 Return :const:`True` if the argument is canonical and :const:`False`
494 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
495 this operation always returns :const:`True`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000496
Benjamin Petersone41251e2008-04-25 01:59:09 +0000497 .. method:: is_finite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000498
Benjamin Petersone41251e2008-04-25 01:59:09 +0000499 Return :const:`True` if the argument is a finite number, and
500 :const:`False` if the argument is an infinity or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000501
Benjamin Petersone41251e2008-04-25 01:59:09 +0000502 .. method:: is_infinite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503
Benjamin Petersone41251e2008-04-25 01:59:09 +0000504 Return :const:`True` if the argument is either positive or negative
505 infinity and :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000506
Benjamin Petersone41251e2008-04-25 01:59:09 +0000507 .. method:: is_nan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000508
Benjamin Petersone41251e2008-04-25 01:59:09 +0000509 Return :const:`True` if the argument is a (quiet or signaling) NaN and
510 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000511
Benjamin Petersone41251e2008-04-25 01:59:09 +0000512 .. method:: is_normal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000513
Benjamin Petersone41251e2008-04-25 01:59:09 +0000514 Return :const:`True` if the argument is a *normal* finite number. Return
515 :const:`False` if the argument is zero, subnormal, infinite or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000516
Benjamin Petersone41251e2008-04-25 01:59:09 +0000517 .. method:: is_qnan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000518
Benjamin Petersone41251e2008-04-25 01:59:09 +0000519 Return :const:`True` if the argument is a quiet NaN, and
520 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000521
Benjamin Petersone41251e2008-04-25 01:59:09 +0000522 .. method:: is_signed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000523
Benjamin Petersone41251e2008-04-25 01:59:09 +0000524 Return :const:`True` if the argument has a negative sign and
525 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000526
Benjamin Petersone41251e2008-04-25 01:59:09 +0000527 .. method:: is_snan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000528
Benjamin Petersone41251e2008-04-25 01:59:09 +0000529 Return :const:`True` if the argument is a signaling NaN and :const:`False`
530 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000531
Benjamin Petersone41251e2008-04-25 01:59:09 +0000532 .. method:: is_subnormal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000533
Benjamin Petersone41251e2008-04-25 01:59:09 +0000534 Return :const:`True` if the argument is subnormal, and :const:`False`
535 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000536
Benjamin Petersone41251e2008-04-25 01:59:09 +0000537 .. method:: is_zero()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000538
Benjamin Petersone41251e2008-04-25 01:59:09 +0000539 Return :const:`True` if the argument is a (positive or negative) zero and
540 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000541
Benjamin Petersone41251e2008-04-25 01:59:09 +0000542 .. method:: ln([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000543
Benjamin Petersone41251e2008-04-25 01:59:09 +0000544 Return the natural (base e) logarithm of the operand. The result is
545 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546
Benjamin Petersone41251e2008-04-25 01:59:09 +0000547 .. method:: log10([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000548
Benjamin Petersone41251e2008-04-25 01:59:09 +0000549 Return the base ten logarithm of the operand. The result is correctly
550 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000551
Benjamin Petersone41251e2008-04-25 01:59:09 +0000552 .. method:: logb([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000553
Benjamin Petersone41251e2008-04-25 01:59:09 +0000554 For a nonzero number, return the adjusted exponent of its operand as a
555 :class:`Decimal` instance. If the operand is a zero then
556 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
557 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
558 returned.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000559
Benjamin Petersone41251e2008-04-25 01:59:09 +0000560 .. method:: logical_and(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000561
Benjamin Petersone41251e2008-04-25 01:59:09 +0000562 :meth:`logical_and` is a logical operation which takes two *logical
563 operands* (see :ref:`logical_operands_label`). The result is the
564 digit-wise ``and`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000565
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000566 .. method:: logical_invert([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000567
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000568 :meth:`logical_invert` is a logical operation. The
Benjamin Petersone41251e2008-04-25 01:59:09 +0000569 result is the digit-wise inversion of the operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570
Benjamin Petersone41251e2008-04-25 01:59:09 +0000571 .. method:: logical_or(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000572
Benjamin Petersone41251e2008-04-25 01:59:09 +0000573 :meth:`logical_or` is a logical operation which takes two *logical
574 operands* (see :ref:`logical_operands_label`). The result is the
575 digit-wise ``or`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000576
Benjamin Petersone41251e2008-04-25 01:59:09 +0000577 .. method:: logical_xor(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000578
Benjamin Petersone41251e2008-04-25 01:59:09 +0000579 :meth:`logical_xor` is a logical operation which takes two *logical
580 operands* (see :ref:`logical_operands_label`). The result is the
581 digit-wise exclusive or of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000582
Benjamin Petersone41251e2008-04-25 01:59:09 +0000583 .. method:: max(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000584
Benjamin Petersone41251e2008-04-25 01:59:09 +0000585 Like ``max(self, other)`` except that the context rounding rule is applied
586 before returning and that :const:`NaN` values are either signaled or
587 ignored (depending on the context and whether they are signaling or
588 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000589
Benjamin Petersone41251e2008-04-25 01:59:09 +0000590 .. method:: max_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000591
Georg Brandl502d9a52009-07-26 15:02:41 +0000592 Similar to the :meth:`.max` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000593 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000594
Benjamin Petersone41251e2008-04-25 01:59:09 +0000595 .. method:: min(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000596
Benjamin Petersone41251e2008-04-25 01:59:09 +0000597 Like ``min(self, other)`` except that the context rounding rule is applied
598 before returning and that :const:`NaN` values are either signaled or
599 ignored (depending on the context and whether they are signaling or
600 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000601
Benjamin Petersone41251e2008-04-25 01:59:09 +0000602 .. method:: min_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000603
Georg Brandl502d9a52009-07-26 15:02:41 +0000604 Similar to the :meth:`.min` method, but the comparison is done using the
Benjamin Petersone41251e2008-04-25 01:59:09 +0000605 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000606
Benjamin Petersone41251e2008-04-25 01:59:09 +0000607 .. method:: next_minus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000608
Benjamin Petersone41251e2008-04-25 01:59:09 +0000609 Return the largest number representable in the given context (or in the
610 current thread's context if no context is given) that is smaller than the
611 given operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000612
Benjamin Petersone41251e2008-04-25 01:59:09 +0000613 .. method:: next_plus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000614
Benjamin Petersone41251e2008-04-25 01:59:09 +0000615 Return the smallest number representable in the given context (or in the
616 current thread's context if no context is given) that is larger than the
617 given operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000618
Benjamin Petersone41251e2008-04-25 01:59:09 +0000619 .. method:: next_toward(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000620
Benjamin Petersone41251e2008-04-25 01:59:09 +0000621 If the two operands are unequal, return the number closest to the first
622 operand in the direction of the second operand. If both operands are
623 numerically equal, return a copy of the first operand with the sign set to
624 be the same as the sign of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000625
Benjamin Petersone41251e2008-04-25 01:59:09 +0000626 .. method:: normalize([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000627
Benjamin Petersone41251e2008-04-25 01:59:09 +0000628 Normalize the number by stripping the rightmost trailing zeros and
629 converting any result equal to :const:`Decimal('0')` to
630 :const:`Decimal('0e0')`. Used for producing canonical values for members
631 of an equivalence class. For example, ``Decimal('32.100')`` and
632 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
633 ``Decimal('32.1')``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634
Benjamin Petersone41251e2008-04-25 01:59:09 +0000635 .. method:: number_class([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000636
Benjamin Petersone41251e2008-04-25 01:59:09 +0000637 Return a string describing the *class* of the operand. The returned value
638 is one of the following ten strings.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000639
Benjamin Petersone41251e2008-04-25 01:59:09 +0000640 * ``"-Infinity"``, indicating that the operand is negative infinity.
641 * ``"-Normal"``, indicating that the operand is a negative normal number.
642 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
643 * ``"-Zero"``, indicating that the operand is a negative zero.
644 * ``"+Zero"``, indicating that the operand is a positive zero.
645 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
646 * ``"+Normal"``, indicating that the operand is a positive normal number.
647 * ``"+Infinity"``, indicating that the operand is positive infinity.
648 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
649 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000650
Benjamin Petersone41251e2008-04-25 01:59:09 +0000651 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000652
Benjamin Petersone41251e2008-04-25 01:59:09 +0000653 Return a value equal to the first operand after rounding and having the
654 exponent of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000655
Benjamin Petersone41251e2008-04-25 01:59:09 +0000656 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
657 Decimal('1.414')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658
Benjamin Petersone41251e2008-04-25 01:59:09 +0000659 Unlike other operations, if the length of the coefficient after the
660 quantize operation would be greater than precision, then an
661 :const:`InvalidOperation` is signaled. This guarantees that, unless there
662 is an error condition, the quantized exponent is always equal to that of
663 the right-hand operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000664
Benjamin Petersone41251e2008-04-25 01:59:09 +0000665 Also unlike other operations, quantize never signals Underflow, even if
666 the result is subnormal and inexact.
Georg Brandl116aa622007-08-15 14:28:22 +0000667
Benjamin Petersone41251e2008-04-25 01:59:09 +0000668 If the exponent of the second operand is larger than that of the first
669 then rounding may be necessary. In this case, the rounding mode is
670 determined by the ``rounding`` argument if given, else by the given
671 ``context`` argument; if neither argument is given the rounding mode of
672 the current thread's context is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000673
Benjamin Petersone41251e2008-04-25 01:59:09 +0000674 If *watchexp* is set (default), then an error is returned whenever the
675 resulting exponent is greater than :attr:`Emax` or less than
676 :attr:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +0000677
Benjamin Petersone41251e2008-04-25 01:59:09 +0000678 .. method:: radix()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000679
Benjamin Petersone41251e2008-04-25 01:59:09 +0000680 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
681 class does all its arithmetic. Included for compatibility with the
682 specification.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000683
Benjamin Petersone41251e2008-04-25 01:59:09 +0000684 .. method:: remainder_near(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000685
Benjamin Petersone41251e2008-04-25 01:59:09 +0000686 Compute the modulo as either a positive or negative value depending on
687 which is closest to zero. For instance, ``Decimal(10).remainder_near(6)``
688 returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000689
Benjamin Petersone41251e2008-04-25 01:59:09 +0000690 If both are equally close, the one chosen will have the same sign as
691 *self*.
Georg Brandl116aa622007-08-15 14:28:22 +0000692
Benjamin Petersone41251e2008-04-25 01:59:09 +0000693 .. method:: rotate(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000694
Benjamin Petersone41251e2008-04-25 01:59:09 +0000695 Return the result of rotating the digits of the first operand by an amount
696 specified by the second operand. The second operand must be an integer in
697 the range -precision through precision. The absolute value of the second
698 operand gives the number of places to rotate. If the second operand is
699 positive then rotation is to the left; otherwise rotation is to the right.
700 The coefficient of the first operand is padded on the left with zeros to
701 length precision if necessary. The sign and exponent of the first operand
702 are unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000703
Benjamin Petersone41251e2008-04-25 01:59:09 +0000704 .. method:: same_quantum(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705
Benjamin Petersone41251e2008-04-25 01:59:09 +0000706 Test whether self and other have the same exponent or whether both are
707 :const:`NaN`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000708
Benjamin Petersone41251e2008-04-25 01:59:09 +0000709 .. method:: scaleb(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000710
Benjamin Petersone41251e2008-04-25 01:59:09 +0000711 Return the first operand with exponent adjusted by the second.
712 Equivalently, return the first operand multiplied by ``10**other``. The
713 second operand must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +0000714
Benjamin Petersone41251e2008-04-25 01:59:09 +0000715 .. method:: shift(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000716
Benjamin Petersone41251e2008-04-25 01:59:09 +0000717 Return the result of shifting the digits of the first operand by an amount
718 specified by the second operand. The second operand must be an integer in
719 the range -precision through precision. The absolute value of the second
720 operand gives the number of places to shift. If the second operand is
721 positive then the shift is to the left; otherwise the shift is to the
722 right. Digits shifted into the coefficient are zeros. The sign and
723 exponent of the first operand are unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +0000724
Benjamin Petersone41251e2008-04-25 01:59:09 +0000725 .. method:: sqrt([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000726
Benjamin Petersone41251e2008-04-25 01:59:09 +0000727 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000728
Georg Brandl116aa622007-08-15 14:28:22 +0000729
Benjamin Petersone41251e2008-04-25 01:59:09 +0000730 .. method:: to_eng_string([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000731
Benjamin Petersone41251e2008-04-25 01:59:09 +0000732 Convert to an engineering-type string.
Georg Brandl116aa622007-08-15 14:28:22 +0000733
Benjamin Petersone41251e2008-04-25 01:59:09 +0000734 Engineering notation has an exponent which is a multiple of 3, so there
735 are up to 3 digits left of the decimal place. For example, converts
736 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000737
Benjamin Petersone41251e2008-04-25 01:59:09 +0000738 .. method:: to_integral([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000739
Benjamin Petersone41251e2008-04-25 01:59:09 +0000740 Identical to the :meth:`to_integral_value` method. The ``to_integral``
741 name has been kept for compatibility with older versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000742
Benjamin Petersone41251e2008-04-25 01:59:09 +0000743 .. method:: to_integral_exact([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000744
Benjamin Petersone41251e2008-04-25 01:59:09 +0000745 Round to the nearest integer, signaling :const:`Inexact` or
746 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
747 determined by the ``rounding`` parameter if given, else by the given
748 ``context``. If neither parameter is given then the rounding mode of the
749 current context is used.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000750
Benjamin Petersone41251e2008-04-25 01:59:09 +0000751 .. method:: to_integral_value([rounding[, context]])
Georg Brandl116aa622007-08-15 14:28:22 +0000752
Benjamin Petersone41251e2008-04-25 01:59:09 +0000753 Round to the nearest integer without signaling :const:`Inexact` or
754 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
755 rounding method in either the supplied *context* or the current context.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000756
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000757
758.. _logical_operands_label:
759
760Logical operands
761^^^^^^^^^^^^^^^^
762
763The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
764and :meth:`logical_xor` methods expect their arguments to be *logical
765operands*. A *logical operand* is a :class:`Decimal` instance whose
766exponent and sign are both zero, and whose digits are all either
767:const:`0` or :const:`1`.
768
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000769.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000770
771
772.. _decimal-context:
773
774Context objects
775---------------
776
777Contexts are environments for arithmetic operations. They govern precision, set
778rules for rounding, determine which signals are treated as exceptions, and limit
779the range for exponents.
780
781Each thread has its own current context which is accessed or changed using the
782:func:`getcontext` and :func:`setcontext` functions:
783
784
785.. function:: getcontext()
786
787 Return the current context for the active thread.
788
789
790.. function:: setcontext(c)
791
792 Set the current context for the active thread to *c*.
793
Georg Brandle6bcc912008-05-12 18:05:20 +0000794You can also use the :keyword:`with` statement and the :func:`localcontext`
795function to temporarily change the active context.
Georg Brandl116aa622007-08-15 14:28:22 +0000796
797.. function:: localcontext([c])
798
799 Return a context manager that will set the current context for the active thread
800 to a copy of *c* on entry to the with-statement and restore the previous context
801 when exiting the with-statement. If no context is specified, a copy of the
802 current context is used.
803
Georg Brandl116aa622007-08-15 14:28:22 +0000804 For example, the following code sets the current decimal precision to 42 places,
805 performs a calculation, and then automatically restores the previous context::
806
Georg Brandl116aa622007-08-15 14:28:22 +0000807 from decimal import localcontext
808
809 with localcontext() as ctx:
810 ctx.prec = 42 # Perform a high precision calculation
811 s = calculate_something()
812 s = +s # Round the final result back to the default precision
813
814New contexts can also be created using the :class:`Context` constructor
815described below. In addition, the module provides three pre-made contexts:
816
817
818.. class:: BasicContext
819
820 This is a standard context defined by the General Decimal Arithmetic
821 Specification. Precision is set to nine. Rounding is set to
822 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
823 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
824 :const:`Subnormal`.
825
826 Because many of the traps are enabled, this context is useful for debugging.
827
828
829.. class:: ExtendedContext
830
831 This is a standard context defined by the General Decimal Arithmetic
832 Specification. Precision is set to nine. Rounding is set to
833 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
834 exceptions are not raised during computations).
835
Christian Heimes3feef612008-02-11 06:19:17 +0000836 Because the traps are disabled, this context is useful for applications that
Georg Brandl116aa622007-08-15 14:28:22 +0000837 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
838 raising exceptions. This allows an application to complete a run in the
839 presence of conditions that would otherwise halt the program.
840
841
842.. class:: DefaultContext
843
844 This context is used by the :class:`Context` constructor as a prototype for new
845 contexts. Changing a field (such a precision) has the effect of changing the
846 default for new contexts creating by the :class:`Context` constructor.
847
848 This context is most useful in multi-threaded environments. Changing one of the
849 fields before threads are started has the effect of setting system-wide
850 defaults. Changing the fields after threads have started is not recommended as
851 it would require thread synchronization to prevent race conditions.
852
853 In single threaded environments, it is preferable to not use this context at
854 all. Instead, simply create contexts explicitly as described below.
855
856 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
857 for Overflow, InvalidOperation, and DivisionByZero.
858
859In addition to the three supplied contexts, new contexts can be created with the
860:class:`Context` constructor.
861
862
863.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
864
865 Creates a new context. If a field is not specified or is :const:`None`, the
866 default values are copied from the :const:`DefaultContext`. If the *flags*
867 field is not specified or is :const:`None`, all flags are cleared.
868
869 The *prec* field is a positive integer that sets the precision for arithmetic
870 operations in the context.
871
872 The *rounding* option is one of:
873
874 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
875 * :const:`ROUND_DOWN` (towards zero),
876 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
877 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
878 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
879 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
880 * :const:`ROUND_UP` (away from zero).
Georg Brandl48310cd2009-01-03 21:18:54 +0000881 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000882 would have been 0 or 5; otherwise towards zero)
Georg Brandl116aa622007-08-15 14:28:22 +0000883
884 The *traps* and *flags* fields list any signals to be set. Generally, new
885 contexts should only set traps and leave the flags clear.
886
887 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
888 for exponents.
889
890 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
891 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
892 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
893
Georg Brandl116aa622007-08-15 14:28:22 +0000894
Benjamin Petersone41251e2008-04-25 01:59:09 +0000895 The :class:`Context` class defines several general purpose methods as well as
896 a large number of methods for doing arithmetic directly in a given context.
897 In addition, for each of the :class:`Decimal` methods described above (with
898 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
Mark Dickinson84230a12010-02-18 14:49:50 +0000899 a corresponding :class:`Context` method. For example, for a :class:`Context`
900 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
901 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a
902 Python integer (an instance of :class:`int` or :class:`long`) anywhere that a
903 Decimal instance is accepted.
Georg Brandl116aa622007-08-15 14:28:22 +0000904
905
Benjamin Petersone41251e2008-04-25 01:59:09 +0000906 .. method:: clear_flags()
Georg Brandl116aa622007-08-15 14:28:22 +0000907
Benjamin Petersone41251e2008-04-25 01:59:09 +0000908 Resets all of the flags to :const:`0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000909
Benjamin Petersone41251e2008-04-25 01:59:09 +0000910 .. method:: copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911
Benjamin Petersone41251e2008-04-25 01:59:09 +0000912 Return a duplicate of the context.
Georg Brandl116aa622007-08-15 14:28:22 +0000913
Benjamin Petersone41251e2008-04-25 01:59:09 +0000914 .. method:: copy_decimal(num)
Georg Brandl116aa622007-08-15 14:28:22 +0000915
Benjamin Petersone41251e2008-04-25 01:59:09 +0000916 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +0000917
Benjamin Petersone41251e2008-04-25 01:59:09 +0000918 .. method:: create_decimal(num)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000919
Benjamin Petersone41251e2008-04-25 01:59:09 +0000920 Creates a new Decimal instance from *num* but using *self* as
921 context. Unlike the :class:`Decimal` constructor, the context precision,
922 rounding method, flags, and traps are applied to the conversion.
Georg Brandl116aa622007-08-15 14:28:22 +0000923
Benjamin Petersone41251e2008-04-25 01:59:09 +0000924 This is useful because constants are often given to a greater precision
925 than is needed by the application. Another benefit is that rounding
926 immediately eliminates unintended effects from digits beyond the current
927 precision. In the following example, using unrounded inputs means that
928 adding zero to a sum can change the result:
Georg Brandl116aa622007-08-15 14:28:22 +0000929
Benjamin Petersone41251e2008-04-25 01:59:09 +0000930 .. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000931
Benjamin Petersone41251e2008-04-25 01:59:09 +0000932 >>> getcontext().prec = 3
933 >>> Decimal('3.4445') + Decimal('1.0023')
934 Decimal('4.45')
935 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
936 Decimal('4.44')
Georg Brandl116aa622007-08-15 14:28:22 +0000937
Benjamin Petersone41251e2008-04-25 01:59:09 +0000938 This method implements the to-number operation of the IBM specification.
939 If the argument is a string, no leading or trailing whitespace is
940 permitted.
941
Georg Brandl45f53372009-01-03 21:15:20 +0000942 .. method:: create_decimal_from_float(f)
Raymond Hettinger771ed762009-01-03 19:20:32 +0000943
944 Creates a new Decimal instance from a float *f* but rounding using *self*
Georg Brandl45f53372009-01-03 21:15:20 +0000945 as the context. Unlike the :meth:`Decimal.from_float` class method,
Raymond Hettinger771ed762009-01-03 19:20:32 +0000946 the context precision, rounding method, flags, and traps are applied to
947 the conversion.
948
949 .. doctest::
950
Georg Brandl45f53372009-01-03 21:15:20 +0000951 >>> context = Context(prec=5, rounding=ROUND_DOWN)
952 >>> context.create_decimal_from_float(math.pi)
953 Decimal('3.1415')
954 >>> context = Context(prec=5, traps=[Inexact])
955 >>> context.create_decimal_from_float(math.pi)
956 Traceback (most recent call last):
957 ...
958 decimal.Inexact: None
Raymond Hettinger771ed762009-01-03 19:20:32 +0000959
Georg Brandl45f53372009-01-03 21:15:20 +0000960 .. versionadded:: 3.1
Raymond Hettinger771ed762009-01-03 19:20:32 +0000961
Benjamin Petersone41251e2008-04-25 01:59:09 +0000962 .. method:: Etiny()
963
964 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
965 value for subnormal results. When underflow occurs, the exponent is set
966 to :const:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +0000967
968
Benjamin Petersone41251e2008-04-25 01:59:09 +0000969 .. method:: Etop()
Georg Brandl116aa622007-08-15 14:28:22 +0000970
Benjamin Petersone41251e2008-04-25 01:59:09 +0000971 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000972
Benjamin Petersone41251e2008-04-25 01:59:09 +0000973 The usual approach to working with decimals is to create :class:`Decimal`
974 instances and then apply arithmetic operations which take place within the
975 current context for the active thread. An alternative approach is to use
976 context methods for calculating within a specific context. The methods are
977 similar to those for the :class:`Decimal` class and are only briefly
978 recounted here.
Georg Brandl116aa622007-08-15 14:28:22 +0000979
980
Benjamin Petersone41251e2008-04-25 01:59:09 +0000981 .. method:: abs(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000982
Benjamin Petersone41251e2008-04-25 01:59:09 +0000983 Returns the absolute value of *x*.
Georg Brandl116aa622007-08-15 14:28:22 +0000984
985
Benjamin Petersone41251e2008-04-25 01:59:09 +0000986 .. method:: add(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +0000987
Benjamin Petersone41251e2008-04-25 01:59:09 +0000988 Return the sum of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +0000989
990
Facundo Batista789bdf02008-06-21 17:29:41 +0000991 .. method:: canonical(x)
992
993 Returns the same Decimal object *x*.
994
995
996 .. method:: compare(x, y)
997
998 Compares *x* and *y* numerically.
999
1000
1001 .. method:: compare_signal(x, y)
1002
1003 Compares the values of the two operands numerically.
1004
1005
1006 .. method:: compare_total(x, y)
1007
1008 Compares two operands using their abstract representation.
1009
1010
1011 .. method:: compare_total_mag(x, y)
1012
1013 Compares two operands using their abstract representation, ignoring sign.
1014
1015
1016 .. method:: copy_abs(x)
1017
1018 Returns a copy of *x* with the sign set to 0.
1019
1020
1021 .. method:: copy_negate(x)
1022
1023 Returns a copy of *x* with the sign inverted.
1024
1025
1026 .. method:: copy_sign(x, y)
1027
1028 Copies the sign from *y* to *x*.
1029
1030
Benjamin Petersone41251e2008-04-25 01:59:09 +00001031 .. method:: divide(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001032
Benjamin Petersone41251e2008-04-25 01:59:09 +00001033 Return *x* divided by *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001034
1035
Benjamin Petersone41251e2008-04-25 01:59:09 +00001036 .. method:: divide_int(x, y)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001037
Benjamin Petersone41251e2008-04-25 01:59:09 +00001038 Return *x* divided by *y*, truncated to an integer.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001039
1040
Benjamin Petersone41251e2008-04-25 01:59:09 +00001041 .. method:: divmod(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001042
Benjamin Petersone41251e2008-04-25 01:59:09 +00001043 Divides two numbers and returns the integer part of the result.
Georg Brandl116aa622007-08-15 14:28:22 +00001044
1045
Facundo Batista789bdf02008-06-21 17:29:41 +00001046 .. method:: exp(x)
1047
1048 Returns `e ** x`.
1049
1050
1051 .. method:: fma(x, y, z)
1052
1053 Returns *x* multiplied by *y*, plus *z*.
1054
1055
1056 .. method:: is_canonical(x)
1057
1058 Returns True if *x* is canonical; otherwise returns False.
1059
1060
1061 .. method:: is_finite(x)
1062
1063 Returns True if *x* is finite; otherwise returns False.
1064
1065
1066 .. method:: is_infinite(x)
1067
1068 Returns True if *x* is infinite; otherwise returns False.
1069
1070
1071 .. method:: is_nan(x)
1072
1073 Returns True if *x* is a qNaN or sNaN; otherwise returns False.
1074
1075
1076 .. method:: is_normal(x)
1077
1078 Returns True if *x* is a normal number; otherwise returns False.
1079
1080
1081 .. method:: is_qnan(x)
1082
1083 Returns True if *x* is a quiet NaN; otherwise returns False.
1084
1085
1086 .. method:: is_signed(x)
1087
1088 Returns True if *x* is negative; otherwise returns False.
1089
1090
1091 .. method:: is_snan(x)
1092
1093 Returns True if *x* is a signaling NaN; otherwise returns False.
1094
1095
1096 .. method:: is_subnormal(x)
1097
1098 Returns True if *x* is subnormal; otherwise returns False.
1099
1100
1101 .. method:: is_zero(x)
1102
1103 Returns True if *x* is a zero; otherwise returns False.
1104
1105
1106 .. method:: ln(x)
1107
1108 Returns the natural (base e) logarithm of *x*.
1109
1110
1111 .. method:: log10(x)
1112
1113 Returns the base 10 logarithm of *x*.
1114
1115
1116 .. method:: logb(x)
1117
1118 Returns the exponent of the magnitude of the operand's MSD.
1119
1120
1121 .. method:: logical_and(x, y)
1122
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001123 Applies the logical operation *and* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001124
1125
1126 .. method:: logical_invert(x)
1127
1128 Invert all the digits in *x*.
1129
1130
1131 .. method:: logical_or(x, y)
1132
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001133 Applies the logical operation *or* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001134
1135
1136 .. method:: logical_xor(x, y)
1137
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001138 Applies the logical operation *xor* between each operand's digits.
Facundo Batista789bdf02008-06-21 17:29:41 +00001139
1140
1141 .. method:: max(x, y)
1142
1143 Compares two values numerically and returns the maximum.
1144
1145
1146 .. method:: max_mag(x, y)
1147
1148 Compares the values numerically with their sign ignored.
1149
1150
1151 .. method:: min(x, y)
1152
1153 Compares two values numerically and returns the minimum.
1154
1155
1156 .. method:: min_mag(x, y)
1157
1158 Compares the values numerically with their sign ignored.
1159
1160
Benjamin Petersone41251e2008-04-25 01:59:09 +00001161 .. method:: minus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001162
Benjamin Petersone41251e2008-04-25 01:59:09 +00001163 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl116aa622007-08-15 14:28:22 +00001164
1165
Benjamin Petersone41251e2008-04-25 01:59:09 +00001166 .. method:: multiply(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001167
Benjamin Petersone41251e2008-04-25 01:59:09 +00001168 Return the product of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001169
1170
Facundo Batista789bdf02008-06-21 17:29:41 +00001171 .. method:: next_minus(x)
1172
1173 Returns the largest representable number smaller than *x*.
1174
1175
1176 .. method:: next_plus(x)
1177
1178 Returns the smallest representable number larger than *x*.
1179
1180
1181 .. method:: next_toward(x, y)
1182
1183 Returns the number closest to *x*, in direction towards *y*.
1184
1185
1186 .. method:: normalize(x)
1187
1188 Reduces *x* to its simplest form.
1189
1190
1191 .. method:: number_class(x)
1192
1193 Returns an indication of the class of *x*.
1194
1195
Benjamin Petersone41251e2008-04-25 01:59:09 +00001196 .. method:: plus(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001197
Benjamin Petersone41251e2008-04-25 01:59:09 +00001198 Plus corresponds to the unary prefix plus operator in Python. This
1199 operation applies the context precision and rounding, so it is *not* an
1200 identity operation.
Georg Brandl116aa622007-08-15 14:28:22 +00001201
1202
Benjamin Petersone41251e2008-04-25 01:59:09 +00001203 .. method:: power(x, y[, modulo])
Georg Brandl116aa622007-08-15 14:28:22 +00001204
Benjamin Petersone41251e2008-04-25 01:59:09 +00001205 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl116aa622007-08-15 14:28:22 +00001206
Benjamin Petersone41251e2008-04-25 01:59:09 +00001207 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
1208 must be integral. The result will be inexact unless ``y`` is integral and
1209 the result is finite and can be expressed exactly in 'precision' digits.
1210 The result should always be correctly rounded, using the rounding mode of
1211 the current thread's context.
Georg Brandl116aa622007-08-15 14:28:22 +00001212
Benjamin Petersone41251e2008-04-25 01:59:09 +00001213 With three arguments, compute ``(x**y) % modulo``. For the three argument
1214 form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +00001215
Benjamin Petersone41251e2008-04-25 01:59:09 +00001216 - all three arguments must be integral
1217 - ``y`` must be nonnegative
1218 - at least one of ``x`` or ``y`` must be nonzero
1219 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +00001220
Benjamin Petersone41251e2008-04-25 01:59:09 +00001221 The result of ``Context.power(x, y, modulo)`` is identical to the result
1222 that would be obtained by computing ``(x**y) % modulo`` with unbounded
1223 precision, but is computed more efficiently. It is always exact.
Georg Brandl116aa622007-08-15 14:28:22 +00001224
Facundo Batista789bdf02008-06-21 17:29:41 +00001225
1226 .. method:: quantize(x, y)
1227
1228 Returns a value equal to *x* (rounded), having the exponent of *y*.
1229
1230
1231 .. method:: radix()
1232
1233 Just returns 10, as this is Decimal, :)
1234
1235
Benjamin Petersone41251e2008-04-25 01:59:09 +00001236 .. method:: remainder(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001237
Benjamin Petersone41251e2008-04-25 01:59:09 +00001238 Returns the remainder from integer division.
Georg Brandl116aa622007-08-15 14:28:22 +00001239
Benjamin Petersone41251e2008-04-25 01:59:09 +00001240 The sign of the result, if non-zero, is the same as that of the original
1241 dividend.
Georg Brandl116aa622007-08-15 14:28:22 +00001242
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001243
Facundo Batista789bdf02008-06-21 17:29:41 +00001244 .. method:: remainder_near(x, y)
1245
Georg Brandl36ab1ef2009-01-03 21:17:04 +00001246 Returns ``x - y * n``, where *n* is the integer nearest the exact value
1247 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).
Facundo Batista789bdf02008-06-21 17:29:41 +00001248
1249
1250 .. method:: rotate(x, y)
1251
1252 Returns a rotated copy of *x*, *y* times.
1253
1254
1255 .. method:: same_quantum(x, y)
1256
1257 Returns True if the two operands have the same exponent.
1258
1259
1260 .. method:: scaleb (x, y)
1261
1262 Returns the first operand after adding the second value its exp.
1263
1264
1265 .. method:: shift(x, y)
1266
1267 Returns a shifted copy of *x*, *y* times.
1268
1269
1270 .. method:: sqrt(x)
1271
1272 Square root of a non-negative number to context precision.
1273
1274
Benjamin Petersone41251e2008-04-25 01:59:09 +00001275 .. method:: subtract(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001276
Benjamin Petersone41251e2008-04-25 01:59:09 +00001277 Return the difference between *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001278
Facundo Batista789bdf02008-06-21 17:29:41 +00001279
1280 .. method:: to_eng_string(x)
1281
1282 Converts a number to a string, using scientific notation.
1283
1284
1285 .. method:: to_integral_exact(x)
1286
1287 Rounds to an integer.
1288
1289
Benjamin Petersone41251e2008-04-25 01:59:09 +00001290 .. method:: to_sci_string(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001291
Benjamin Petersone41251e2008-04-25 01:59:09 +00001292 Converts a number to a string using scientific notation.
Georg Brandl116aa622007-08-15 14:28:22 +00001293
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001294.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001295
1296
1297.. _decimal-signals:
1298
1299Signals
1300-------
1301
1302Signals represent conditions that arise during computation. Each corresponds to
1303one context flag and one context trap enabler.
1304
Raymond Hettinger86173da2008-02-01 20:38:12 +00001305The context flag is set whenever the condition is encountered. After the
Georg Brandl116aa622007-08-15 14:28:22 +00001306computation, flags may be checked for informational purposes (for instance, to
1307determine whether a computation was exact). After checking the flags, be sure to
1308clear all flags before starting the next computation.
1309
1310If the context's trap enabler is set for the signal, then the condition causes a
1311Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1312is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1313condition.
1314
1315
1316.. class:: Clamped
1317
1318 Altered an exponent to fit representation constraints.
1319
1320 Typically, clamping occurs when an exponent falls outside the context's
1321 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001322 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001323
1324
1325.. class:: DecimalException
1326
1327 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1328
1329
1330.. class:: DivisionByZero
1331
1332 Signals the division of a non-infinite number by zero.
1333
1334 Can occur with division, modulo division, or when raising a number to a negative
1335 power. If this signal is not trapped, returns :const:`Infinity` or
1336 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1337
1338
1339.. class:: Inexact
1340
1341 Indicates that rounding occurred and the result is not exact.
1342
1343 Signals when non-zero digits were discarded during rounding. The rounded result
1344 is returned. The signal flag or trap is used to detect when results are
1345 inexact.
1346
1347
1348.. class:: InvalidOperation
1349
1350 An invalid operation was performed.
1351
1352 Indicates that an operation was requested that does not make sense. If not
1353 trapped, returns :const:`NaN`. Possible causes include::
1354
1355 Infinity - Infinity
1356 0 * Infinity
1357 Infinity / Infinity
1358 x % 0
1359 Infinity % x
1360 x._rescale( non-integer )
1361 sqrt(-x) and x > 0
1362 0 ** 0
1363 x ** (non-integer)
Georg Brandl48310cd2009-01-03 21:18:54 +00001364 x ** Infinity
Georg Brandl116aa622007-08-15 14:28:22 +00001365
1366
1367.. class:: Overflow
1368
1369 Numerical overflow.
1370
Benjamin Petersone41251e2008-04-25 01:59:09 +00001371 Indicates the exponent is larger than :attr:`Emax` after rounding has
1372 occurred. If not trapped, the result depends on the rounding mode, either
1373 pulling inward to the largest representable finite number or rounding outward
1374 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1375 are also signaled.
Georg Brandl116aa622007-08-15 14:28:22 +00001376
1377
1378.. class:: Rounded
1379
1380 Rounding occurred though possibly no information was lost.
1381
Benjamin Petersone41251e2008-04-25 01:59:09 +00001382 Signaled whenever rounding discards digits; even if those digits are zero
1383 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1384 the result unchanged. This signal is used to detect loss of significant
1385 digits.
Georg Brandl116aa622007-08-15 14:28:22 +00001386
1387
1388.. class:: Subnormal
1389
1390 Exponent was lower than :attr:`Emin` prior to rounding.
1391
Benjamin Petersone41251e2008-04-25 01:59:09 +00001392 Occurs when an operation result is subnormal (the exponent is too small). If
1393 not trapped, returns the result unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +00001394
1395
1396.. class:: Underflow
1397
1398 Numerical underflow with result rounded to zero.
1399
1400 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1401 and :class:`Subnormal` are also signaled.
1402
1403The following table summarizes the hierarchy of signals::
1404
1405 exceptions.ArithmeticError(exceptions.Exception)
1406 DecimalException
1407 Clamped
1408 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1409 Inexact
1410 Overflow(Inexact, Rounded)
1411 Underflow(Inexact, Rounded, Subnormal)
1412 InvalidOperation
1413 Rounded
1414 Subnormal
1415
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001416.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001417
1418
1419.. _decimal-notes:
1420
1421Floating Point Notes
1422--------------------
1423
1424
1425Mitigating round-off error with increased precision
1426^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1427
1428The use of decimal floating point eliminates decimal representation error
1429(making it possible to represent :const:`0.1` exactly); however, some operations
1430can still incur round-off error when non-zero digits exceed the fixed precision.
1431
1432The effects of round-off error can be amplified by the addition or subtraction
1433of nearly offsetting quantities resulting in loss of significance. Knuth
1434provides two instructive examples where rounded floating point arithmetic with
1435insufficient precision causes the breakdown of the associative and distributive
Christian Heimesfe337bf2008-03-23 21:54:12 +00001436properties of addition:
1437
1438.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001439
1440 # Examples from Seminumerical Algorithms, Section 4.2.2.
1441 >>> from decimal import Decimal, getcontext
1442 >>> getcontext().prec = 8
1443
1444 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1445 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001446 Decimal('9.5111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001447 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001448 Decimal('10')
Georg Brandl116aa622007-08-15 14:28:22 +00001449
1450 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1451 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001452 Decimal('0.01')
Georg Brandl116aa622007-08-15 14:28:22 +00001453 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001454 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001455
1456The :mod:`decimal` module makes it possible to restore the identities by
Christian Heimesfe337bf2008-03-23 21:54:12 +00001457expanding the precision sufficiently to avoid loss of significance:
1458
1459.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001460
1461 >>> getcontext().prec = 20
1462 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1463 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001464 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001465 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001466 Decimal('9.51111111')
Georg Brandl48310cd2009-01-03 21:18:54 +00001467 >>>
Georg Brandl116aa622007-08-15 14:28:22 +00001468 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1469 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001470 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001471 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001472 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001473
1474
1475Special values
1476^^^^^^^^^^^^^^
1477
1478The number system for the :mod:`decimal` module provides special values
1479including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001480and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001481
1482Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1483they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1484not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1485can result from rounding beyond the limits of the largest representable number.
1486
1487The infinities are signed (affine) and can be used in arithmetic operations
1488where they get treated as very large, indeterminate numbers. For instance,
1489adding a constant to infinity gives another infinite result.
1490
1491Some operations are indeterminate and return :const:`NaN`, or if the
1492:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1493``0/0`` returns :const:`NaN` which means "not a number". This variety of
1494:const:`NaN` is quiet and, once created, will flow through other computations
1495always resulting in another :const:`NaN`. This behavior can be useful for a
1496series of computations that occasionally have missing inputs --- it allows the
1497calculation to proceed while flagging specific results as invalid.
1498
1499A variant is :const:`sNaN` which signals rather than remaining quiet after every
1500operation. This is a useful return value when an invalid result needs to
1501interrupt a calculation for special handling.
1502
Christian Heimes77c02eb2008-02-09 02:18:51 +00001503The behavior of Python's comparison operators can be a little surprising where a
1504:const:`NaN` is involved. A test for equality where one of the operands is a
1505quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1506``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1507:const:`True`. An attempt to compare two Decimals using any of the ``<``,
1508``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1509if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes3feef612008-02-11 06:19:17 +00001510not trapped. Note that the General Decimal Arithmetic specification does not
Christian Heimes77c02eb2008-02-09 02:18:51 +00001511specify the behavior of direct comparisons; these rules for comparisons
1512involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1513section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1514and :meth:`compare-signal` methods instead.
1515
Georg Brandl116aa622007-08-15 14:28:22 +00001516The signed zeros can result from calculations that underflow. They keep the sign
1517that would have resulted if the calculation had been carried out to greater
1518precision. Since their magnitude is zero, both positive and negative zeros are
1519treated as equal and their sign is informational.
1520
1521In addition to the two signed zeros which are distinct yet equal, there are
1522various representations of zero with differing precisions yet equivalent in
1523value. This takes a bit of getting used to. For an eye accustomed to
1524normalized floating point representations, it is not immediately obvious that
Christian Heimesfe337bf2008-03-23 21:54:12 +00001525the following calculation returns a value equal to zero:
Georg Brandl116aa622007-08-15 14:28:22 +00001526
1527 >>> 1 / Decimal('Infinity')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001528 Decimal('0E-1000000026')
Georg Brandl116aa622007-08-15 14:28:22 +00001529
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001530.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001531
1532
1533.. _decimal-threads:
1534
1535Working with threads
1536--------------------
1537
1538The :func:`getcontext` function accesses a different :class:`Context` object for
1539each thread. Having separate thread contexts means that threads may make
1540changes (such as ``getcontext.prec=10``) without interfering with other threads.
1541
1542Likewise, the :func:`setcontext` function automatically assigns its target to
1543the current thread.
1544
1545If :func:`setcontext` has not been called before :func:`getcontext`, then
1546:func:`getcontext` will automatically create a new context for use in the
1547current thread.
1548
1549The new context is copied from a prototype context called *DefaultContext*. To
1550control the defaults so that each thread will use the same values throughout the
1551application, directly modify the *DefaultContext* object. This should be done
1552*before* any threads are started so that there won't be a race condition between
1553threads calling :func:`getcontext`. For example::
1554
1555 # Set applicationwide defaults for all threads about to be launched
1556 DefaultContext.prec = 12
1557 DefaultContext.rounding = ROUND_DOWN
1558 DefaultContext.traps = ExtendedContext.traps.copy()
1559 DefaultContext.traps[InvalidOperation] = 1
1560 setcontext(DefaultContext)
1561
1562 # Afterwards, the threads can be started
1563 t1.start()
1564 t2.start()
1565 t3.start()
1566 . . .
1567
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001568.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001569
1570
1571.. _decimal-recipes:
1572
1573Recipes
1574-------
1575
1576Here are a few recipes that serve as utility functions and that demonstrate ways
1577to work with the :class:`Decimal` class::
1578
1579 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1580 pos='', neg='-', trailneg=''):
1581 """Convert Decimal to a money formatted string.
1582
1583 places: required number of places after the decimal point
1584 curr: optional currency symbol before the sign (may be blank)
1585 sep: optional grouping separator (comma, period, space, or blank)
1586 dp: decimal point indicator (comma or period)
1587 only specify as blank when places is zero
1588 pos: optional sign for positive numbers: '+', space or blank
1589 neg: optional sign for negative numbers: '-', '(', space or blank
1590 trailneg:optional trailing minus indicator: '-', ')', space or blank
1591
1592 >>> d = Decimal('-1234567.8901')
1593 >>> moneyfmt(d, curr='$')
1594 '-$1,234,567.89'
1595 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1596 '1.234.568-'
1597 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1598 '($1,234,567.89)'
1599 >>> moneyfmt(Decimal(123456789), sep=' ')
1600 '123 456 789.00'
1601 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Christian Heimesdae2a892008-04-19 00:55:37 +00001602 '<0.02>'
Georg Brandl116aa622007-08-15 14:28:22 +00001603
1604 """
Christian Heimesa156e092008-02-16 07:38:31 +00001605 q = Decimal(10) ** -places # 2 places --> '0.01'
Georg Brandl48310cd2009-01-03 21:18:54 +00001606 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +00001607 result = []
Facundo Batista789bdf02008-06-21 17:29:41 +00001608 digits = list(map(str, digits))
Georg Brandl116aa622007-08-15 14:28:22 +00001609 build, next = result.append, digits.pop
1610 if sign:
1611 build(trailneg)
1612 for i in range(places):
Christian Heimesa156e092008-02-16 07:38:31 +00001613 build(next() if digits else '0')
Georg Brandl116aa622007-08-15 14:28:22 +00001614 build(dp)
Christian Heimesdae2a892008-04-19 00:55:37 +00001615 if not digits:
1616 build('0')
Georg Brandl116aa622007-08-15 14:28:22 +00001617 i = 0
1618 while digits:
1619 build(next())
1620 i += 1
1621 if i == 3 and digits:
1622 i = 0
1623 build(sep)
1624 build(curr)
Christian Heimesa156e092008-02-16 07:38:31 +00001625 build(neg if sign else pos)
1626 return ''.join(reversed(result))
Georg Brandl116aa622007-08-15 14:28:22 +00001627
1628 def pi():
1629 """Compute Pi to the current precision.
1630
Georg Brandl6911e3c2007-09-04 07:15:32 +00001631 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001632 3.141592653589793238462643383
1633
1634 """
1635 getcontext().prec += 2 # extra digits for intermediate steps
1636 three = Decimal(3) # substitute "three=3.0" for regular floats
1637 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1638 while s != lasts:
1639 lasts = s
1640 n, na = n+na, na+8
1641 d, da = d+da, da+32
1642 t = (t * n) / d
1643 s += t
1644 getcontext().prec -= 2
1645 return +s # unary plus applies the new precision
1646
1647 def exp(x):
1648 """Return e raised to the power of x. Result type matches input type.
1649
Georg Brandl6911e3c2007-09-04 07:15:32 +00001650 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001651 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001652 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001653 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001654 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001655 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001656 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001657 (7.38905609893+0j)
1658
1659 """
1660 getcontext().prec += 2
1661 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1662 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001663 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001664 i += 1
1665 fact *= i
Georg Brandl48310cd2009-01-03 21:18:54 +00001666 num *= x
1667 s += num / fact
1668 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001669 return +s
1670
1671 def cos(x):
1672 """Return the cosine of x as measured in radians.
1673
Georg Brandl6911e3c2007-09-04 07:15:32 +00001674 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001675 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001676 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001677 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001678 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001679 (0.87758256189+0j)
1680
1681 """
1682 getcontext().prec += 2
1683 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1684 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001685 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001686 i += 2
1687 fact *= i * (i-1)
1688 num *= x * x
1689 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001690 s += num / fact * sign
1691 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001692 return +s
1693
1694 def sin(x):
1695 """Return the sine of x as measured in radians.
1696
Georg Brandl6911e3c2007-09-04 07:15:32 +00001697 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001698 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001699 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001700 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001701 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001702 (0.479425538604+0j)
1703
1704 """
1705 getcontext().prec += 2
1706 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1707 while s != lasts:
Georg Brandl48310cd2009-01-03 21:18:54 +00001708 lasts = s
Georg Brandl116aa622007-08-15 14:28:22 +00001709 i += 2
1710 fact *= i * (i-1)
1711 num *= x * x
1712 sign *= -1
Georg Brandl48310cd2009-01-03 21:18:54 +00001713 s += num / fact * sign
1714 getcontext().prec -= 2
Georg Brandl116aa622007-08-15 14:28:22 +00001715 return +s
1716
1717
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001718.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001719
1720
1721.. _decimal-faq:
1722
1723Decimal FAQ
1724-----------
1725
1726Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1727minimize typing when using the interactive interpreter?
1728
Christian Heimesfe337bf2008-03-23 21:54:12 +00001729A. Some users abbreviate the constructor to just a single letter:
Georg Brandl116aa622007-08-15 14:28:22 +00001730
1731 >>> D = decimal.Decimal
1732 >>> D('1.23') + D('3.45')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001733 Decimal('4.68')
Georg Brandl116aa622007-08-15 14:28:22 +00001734
1735Q. In a fixed-point application with two decimal places, some inputs have many
1736places and need to be rounded. Others are not supposed to have excess digits
1737and need to be validated. What methods should be used?
1738
1739A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Christian Heimesfe337bf2008-03-23 21:54:12 +00001740the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl116aa622007-08-15 14:28:22 +00001741
1742 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1743
1744 >>> # Round to two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001745 >>> Decimal('3.214').quantize(TWOPLACES)
1746 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001747
Georg Brandl48310cd2009-01-03 21:18:54 +00001748 >>> # Validate that a number does not exceed two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001749 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1750 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001751
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001752 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl116aa622007-08-15 14:28:22 +00001753 Traceback (most recent call last):
1754 ...
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001755 Inexact: None
Georg Brandl116aa622007-08-15 14:28:22 +00001756
1757Q. Once I have valid two place inputs, how do I maintain that invariant
1758throughout an application?
1759
Christian Heimesa156e092008-02-16 07:38:31 +00001760A. Some operations like addition, subtraction, and multiplication by an integer
1761will automatically preserve fixed point. Others operations, like division and
1762non-integer multiplication, will change the number of decimal places and need to
Christian Heimesfe337bf2008-03-23 21:54:12 +00001763be followed-up with a :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001764
1765 >>> a = Decimal('102.72') # Initial fixed-point values
1766 >>> b = Decimal('3.17')
1767 >>> a + b # Addition preserves fixed-point
1768 Decimal('105.89')
1769 >>> a - b
1770 Decimal('99.55')
1771 >>> a * 42 # So does integer multiplication
1772 Decimal('4314.24')
1773 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1774 Decimal('325.62')
1775 >>> (b / a).quantize(TWOPLACES) # And quantize division
1776 Decimal('0.03')
1777
1778In developing fixed-point applications, it is convenient to define functions
Christian Heimesfe337bf2008-03-23 21:54:12 +00001779to handle the :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001780
1781 >>> def mul(x, y, fp=TWOPLACES):
1782 ... return (x * y).quantize(fp)
1783 >>> def div(x, y, fp=TWOPLACES):
1784 ... return (x / y).quantize(fp)
1785
1786 >>> mul(a, b) # Automatically preserve fixed-point
1787 Decimal('325.62')
1788 >>> div(b, a)
1789 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +00001790
1791Q. There are many ways to express the same value. The numbers :const:`200`,
1792:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1793various precisions. Is there a way to transform them to a single recognizable
1794canonical value?
1795
1796A. The :meth:`normalize` method maps all equivalent values to a single
Christian Heimesfe337bf2008-03-23 21:54:12 +00001797representative:
Georg Brandl116aa622007-08-15 14:28:22 +00001798
1799 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1800 >>> [v.normalize() for v in values]
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001801 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl116aa622007-08-15 14:28:22 +00001802
1803Q. Some decimal values always print with exponential notation. Is there a way
1804to get a non-exponential representation?
1805
1806A. For some values, exponential notation is the only way to express the number
1807of significant places in the coefficient. For example, expressing
1808:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1809original's two-place significance.
1810
Christian Heimesa156e092008-02-16 07:38:31 +00001811If an application does not care about tracking significance, it is easy to
Christian Heimesc3f30c42008-02-22 16:37:40 +00001812remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001813value unchanged:
Christian Heimesa156e092008-02-16 07:38:31 +00001814
1815 >>> def remove_exponent(d):
1816 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1817
1818 >>> remove_exponent(Decimal('5E+3'))
1819 Decimal('5000')
1820
Georg Brandl116aa622007-08-15 14:28:22 +00001821Q. Is there a way to convert a regular float to a :class:`Decimal`?
1822
1823A. Yes, all binary floating point numbers can be exactly expressed as a
1824Decimal. An exact conversion may take more precision than intuition would
Christian Heimesfe337bf2008-03-23 21:54:12 +00001825suggest, so we trap :const:`Inexact` to signal a need for more precision:
1826
1827.. testcode::
Georg Brandl116aa622007-08-15 14:28:22 +00001828
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001829 def float_to_decimal(f):
1830 "Convert a floating point number to a Decimal with no loss of information"
1831 n, d = f.as_integer_ratio()
1832 with localcontext() as ctx:
1833 ctx.traps[Inexact] = True
1834 while True:
1835 try:
1836 return Decimal(n) / Decimal(d)
1837 except Inexact:
1838 ctx.prec += 1
Georg Brandl116aa622007-08-15 14:28:22 +00001839
Christian Heimesfe337bf2008-03-23 21:54:12 +00001840.. doctest::
1841
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001842 >>> float_to_decimal(math.pi)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001843 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl116aa622007-08-15 14:28:22 +00001844
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001845Q. Why isn't the :func:`float_to_decimal` routine included in the module?
Georg Brandl116aa622007-08-15 14:28:22 +00001846
1847A. There is some question about whether it is advisable to mix binary and
1848decimal floating point. Also, its use requires some care to avoid the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001849representation issues associated with binary floating point:
Georg Brandl116aa622007-08-15 14:28:22 +00001850
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001851 >>> float_to_decimal(1.1)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001852 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl116aa622007-08-15 14:28:22 +00001853
1854Q. Within a complex calculation, how can I make sure that I haven't gotten a
1855spurious result because of insufficient precision or rounding anomalies.
1856
1857A. The decimal module makes it easy to test results. A best practice is to
1858re-run calculations using greater precision and with various rounding modes.
1859Widely differing results indicate insufficient precision, rounding mode issues,
1860ill-conditioned inputs, or a numerically unstable algorithm.
1861
1862Q. I noticed that context precision is applied to the results of operations but
1863not to the inputs. Is there anything to watch out for when mixing values of
1864different precisions?
1865
1866A. Yes. The principle is that all values are considered to be exact and so is
1867the arithmetic on those values. Only the results are rounded. The advantage
1868for inputs is that "what you type is what you get". A disadvantage is that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001869results can look odd if you forget that the inputs haven't been rounded:
1870
1871.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001872
1873 >>> getcontext().prec = 3
Christian Heimesfe337bf2008-03-23 21:54:12 +00001874 >>> Decimal('3.104') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001875 Decimal('5.21')
Christian Heimesfe337bf2008-03-23 21:54:12 +00001876 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001877 Decimal('5.20')
Georg Brandl116aa622007-08-15 14:28:22 +00001878
1879The solution is either to increase precision or to force rounding of inputs
Christian Heimesfe337bf2008-03-23 21:54:12 +00001880using the unary plus operation:
1881
1882.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001883
1884 >>> getcontext().prec = 3
1885 >>> +Decimal('1.23456789') # unary plus triggers rounding
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001886 Decimal('1.23')
Georg Brandl116aa622007-08-15 14:28:22 +00001887
1888Alternatively, inputs can be rounded upon creation using the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001889:meth:`Context.create_decimal` method:
Georg Brandl116aa622007-08-15 14:28:22 +00001890
1891 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001892 Decimal('1.2345')
Georg Brandl116aa622007-08-15 14:28:22 +00001893