blob: b7dd32f90623140232d651063cf88b0dc36f45c0 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
Christian Heimes3feef612008-02-11 06:19:17 +00002:mod:`decimal` --- Decimal fixed point and floating point arithmetic
3====================================================================
Georg Brandl116aa622007-08-15 14:28:22 +00004
5.. module:: decimal
6 :synopsis: Implementation of the General Decimal Arithmetic Specification.
7
Georg Brandl116aa622007-08-15 14:28:22 +00008.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
9.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
10.. moduleauthor:: Raymond Hettinger <python at rcn.com>
11.. moduleauthor:: Aahz <aahz at pobox.com>
12.. moduleauthor:: Tim Peters <tim.one at comcast.net>
Georg Brandl116aa622007-08-15 14:28:22 +000013.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
14
Christian Heimesfe337bf2008-03-23 21:54:12 +000015.. import modules for testing inline doctests with the Sphinx doctest builder
16.. testsetup:: *
17
18 import decimal
19 import math
20 from decimal import *
21 # make sure each group gets a fresh context
22 setcontext(Context())
Georg Brandl116aa622007-08-15 14:28:22 +000023
Georg Brandl116aa622007-08-15 14:28:22 +000024The :mod:`decimal` module provides support for decimal floating point
Thomas Wouters1b7f8912007-09-19 03:06:30 +000025arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl116aa622007-08-15 14:28:22 +000026
Christian Heimes3feef612008-02-11 06:19:17 +000027* Decimal "is based on a floating-point model which was designed with people
28 in mind, and necessarily has a paramount guiding principle -- computers must
29 provide an arithmetic that works in the same way as the arithmetic that
30 people learn at school." -- excerpt from the decimal arithmetic specification.
31
Georg Brandl116aa622007-08-15 14:28:22 +000032* Decimal numbers can be represented exactly. In contrast, numbers like
33 :const:`1.1` do not have an exact representation in binary floating point. End
34 users typically would not expect :const:`1.1` to display as
35 :const:`1.1000000000000001` as it does with binary floating point.
36
37* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Thomas Wouters1b7f8912007-09-19 03:06:30 +000038 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl116aa622007-08-15 14:28:22 +000039 is :const:`5.5511151231257827e-017`. While near to zero, the differences
40 prevent reliable equality testing and differences can accumulate. For this
Christian Heimes3feef612008-02-11 06:19:17 +000041 reason, decimal is preferred in accounting applications which have strict
Georg Brandl116aa622007-08-15 14:28:22 +000042 equality invariants.
43
44* The decimal module incorporates a notion of significant places so that ``1.30
45 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
46 This is the customary presentation for monetary applications. For
47 multiplication, the "schoolbook" approach uses all the figures in the
48 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
49 1.20`` gives :const:`1.5600`.
50
51* Unlike hardware based binary floating point, the decimal module has a user
Thomas Wouters1b7f8912007-09-19 03:06:30 +000052 alterable precision (defaulting to 28 places) which can be as large as needed for
Christian Heimesfe337bf2008-03-23 21:54:12 +000053 a given problem:
Georg Brandl116aa622007-08-15 14:28:22 +000054
55 >>> getcontext().prec = 6
56 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000057 Decimal('0.142857')
Georg Brandl116aa622007-08-15 14:28:22 +000058 >>> getcontext().prec = 28
59 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +000060 Decimal('0.1428571428571428571428571429')
Georg Brandl116aa622007-08-15 14:28:22 +000061
62* Both binary and decimal floating point are implemented in terms of published
63 standards. While the built-in float type exposes only a modest portion of its
64 capabilities, the decimal module exposes all required parts of the standard.
65 When needed, the programmer has full control over rounding and signal handling.
Christian Heimes3feef612008-02-11 06:19:17 +000066 This includes an option to enforce exact arithmetic by using exceptions
67 to block any inexact operations.
68
69* The decimal module was designed to support "without prejudice, both exact
70 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
71 and rounded floating-point arithmetic." -- excerpt from the decimal
72 arithmetic specification.
Georg Brandl116aa622007-08-15 14:28:22 +000073
74The module design is centered around three concepts: the decimal number, the
75context for arithmetic, and signals.
76
77A decimal number is immutable. It has a sign, coefficient digits, and an
78exponent. To preserve significance, the coefficient digits do not truncate
Thomas Wouters1b7f8912007-09-19 03:06:30 +000079trailing zeros. Decimals also include special values such as
Georg Brandl116aa622007-08-15 14:28:22 +000080:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
81differentiates :const:`-0` from :const:`+0`.
82
83The context for arithmetic is an environment specifying precision, rounding
84rules, limits on exponents, flags indicating the results of operations, and trap
85enablers which determine whether signals are treated as exceptions. Rounding
86options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
87:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +000088:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl116aa622007-08-15 14:28:22 +000089
90Signals are groups of exceptional conditions arising during the course of
91computation. Depending on the needs of the application, signals may be ignored,
92considered as informational, or treated as exceptions. The signals in the
93decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
94:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
95:const:`Overflow`, and :const:`Underflow`.
96
97For each signal there is a flag and a trap enabler. When a signal is
Raymond Hettinger86173da2008-02-01 20:38:12 +000098encountered, its flag is set to one, then, if the trap enabler is
Georg Brandl116aa622007-08-15 14:28:22 +000099set to one, an exception is raised. Flags are sticky, so the user needs to
100reset them before monitoring a calculation.
101
102
103.. seealso::
104
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000105 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
106 Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000108 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Christian Heimes77c02eb2008-02-09 02:18:51 +0000109 <http://754r.ucbtest.org/standards/854.pdf>`_.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000111.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113
114.. _decimal-tutorial:
115
116Quick-start Tutorial
117--------------------
118
119The usual start to using decimals is importing the module, viewing the current
120context with :func:`getcontext` and, if necessary, setting new values for
121precision, rounding, or enabled traps::
122
123 >>> from decimal import *
124 >>> getcontext()
125 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000126 capitals=1, flags=[], traps=[Overflow, DivisionByZero,
127 InvalidOperation])
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129 >>> getcontext().prec = 7 # Set a new precision
130
131Decimal instances can be constructed from integers, strings, or tuples. To
132create a Decimal from a :class:`float`, first convert it to a string. This
133serves as an explicit reminder of the details of the conversion (including
134representation error). Decimal numbers include special values such as
135:const:`NaN` which stands for "Not a number", positive and negative
Christian Heimesfe337bf2008-03-23 21:54:12 +0000136:const:`Infinity`, and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138 >>> 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
176 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
177 >>> 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)
190 1.3400000000000001
191 >>> round(a, 1) # round() first converts to binary floating point
192 1.3
193 >>> 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
204 >>> Decimal(2).sqrt()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000205 Decimal('1.414213562373095048801688724')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000206 >>> Decimal(1).exp()
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000207 Decimal('2.718281828459045235360287471')
208 >>> Decimal('10').ln()
209 Decimal('2.302585092994045684017991455')
210 >>> Decimal('10').log10()
211 Decimal('1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000212
Georg Brandl116aa622007-08-15 14:28:22 +0000213The :meth:`quantize` method rounds a number to a fixed exponent. This method is
214useful for monetary applications that often round results to a fixed number of
Christian Heimesfe337bf2008-03-23 21:54:12 +0000215places:
Georg Brandl116aa622007-08-15 14:28:22 +0000216
217 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000218 Decimal('7.32')
Georg Brandl116aa622007-08-15 14:28:22 +0000219 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000220 Decimal('8')
Georg Brandl116aa622007-08-15 14:28:22 +0000221
222As shown above, the :func:`getcontext` function accesses the current context and
223allows the settings to be changed. This approach meets the needs of most
224applications.
225
226For more advanced work, it may be useful to create alternate contexts using the
227Context() constructor. To make an alternate active, use the :func:`setcontext`
228function.
229
230In accordance with the standard, the :mod:`Decimal` module provides two ready to
231use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
232former is especially useful for debugging because many of the traps are
Christian Heimesfe337bf2008-03-23 21:54:12 +0000233enabled:
234
235.. doctest:: newcontext
236 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000237
238 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
239 >>> setcontext(myothercontext)
240 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000241 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243 >>> ExtendedContext
244 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
245 capitals=1, flags=[], traps=[])
246 >>> setcontext(ExtendedContext)
247 >>> Decimal(1) / Decimal(7)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000248 Decimal('0.142857143')
Georg Brandl116aa622007-08-15 14:28:22 +0000249 >>> Decimal(42) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000250 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000251
252 >>> setcontext(BasicContext)
253 >>> Decimal(42) / Decimal(0)
254 Traceback (most recent call last):
255 File "<pyshell#143>", line 1, in -toplevel-
256 Decimal(42) / Decimal(0)
257 DivisionByZero: x / 0
258
259Contexts also have signal flags for monitoring exceptional conditions
260encountered during computations. The flags remain set until explicitly cleared,
261so it is best to clear the flags before each set of monitored computations by
262using the :meth:`clear_flags` method. ::
263
264 >>> setcontext(ExtendedContext)
265 >>> getcontext().clear_flags()
266 >>> Decimal(355) / Decimal(113)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000267 Decimal('3.14159292')
Georg Brandl116aa622007-08-15 14:28:22 +0000268 >>> getcontext()
269 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000270 capitals=1, flags=[Rounded, Inexact], traps=[])
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272The *flags* entry shows that the rational approximation to :const:`Pi` was
273rounded (digits beyond the context precision were thrown away) and that the
274result is inexact (some of the discarded digits were non-zero).
275
276Individual traps are set using the dictionary in the :attr:`traps` field of a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000277context:
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Christian Heimesfe337bf2008-03-23 21:54:12 +0000279.. doctest:: newcontext
280
281 >>> setcontext(ExtendedContext)
Georg Brandl116aa622007-08-15 14:28:22 +0000282 >>> Decimal(1) / Decimal(0)
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000283 Decimal('Infinity')
Georg Brandl116aa622007-08-15 14:28:22 +0000284 >>> getcontext().traps[DivisionByZero] = 1
285 >>> Decimal(1) / Decimal(0)
286 Traceback (most recent call last):
287 File "<pyshell#112>", line 1, in -toplevel-
288 Decimal(1) / Decimal(0)
289 DivisionByZero: x / 0
290
291Most programs adjust the current context only once, at the beginning of the
292program. And, in many applications, data is converted to :class:`Decimal` with
293a single cast inside a loop. With context set and decimals created, the bulk of
294the program manipulates the data no differently than with other Python numeric
295types.
296
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000297.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000298
299
300.. _decimal-decimal:
301
302Decimal objects
303---------------
304
305
306.. class:: Decimal([value [, context]])
307
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000308 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
Christian Heimesa62da1d2008-01-12 19:39:10 +0000310 *value* can be an integer, string, tuple, or another :class:`Decimal`
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000311 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Christian Heimesa62da1d2008-01-12 19:39:10 +0000312 string, it should conform to the decimal numeric string syntax after leading
313 and trailing whitespace characters are removed::
Georg Brandl116aa622007-08-15 14:28:22 +0000314
315 sign ::= '+' | '-'
316 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
317 indicator ::= 'e' | 'E'
318 digits ::= digit [digit]...
319 decimal-part ::= digits '.' [digits] | ['.'] digits
320 exponent-part ::= indicator [sign] digits
321 infinity ::= 'Infinity' | 'Inf'
322 nan ::= 'NaN' [digits] | 'sNaN' [digits]
323 numeric-value ::= decimal-part [exponent-part] | infinity
324 numeric-string ::= [sign] numeric-value | [sign] nan
325
326 If *value* is a :class:`tuple`, it should have three components, a sign
327 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
328 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000329 returns ``Decimal('1.414')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000330
331 The *context* precision does not affect how many digits are stored. That is
332 determined exclusively by the number of digits in *value*. For example,
Christian Heimes68f5fbe2008-02-14 08:27:37 +0000333 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl116aa622007-08-15 14:28:22 +0000334 only three.
335
336 The purpose of the *context* argument is determining what to do if *value* is a
337 malformed string. If the context traps :const:`InvalidOperation`, an exception
338 is raised; otherwise, the constructor returns a new Decimal with the value of
339 :const:`NaN`.
340
341 Once constructed, :class:`Decimal` objects are immutable.
342
Benjamin Petersone41251e2008-04-25 01:59:09 +0000343 Decimal floating point objects share many properties with the other built-in
344 numeric types such as :class:`float` and :class:`int`. All of the usual math
345 operations and special methods apply. Likewise, decimal objects can be
346 copied, pickled, printed, used as dictionary keys, used as set elements,
347 compared, sorted, and coerced to another type (such as :class:`float` or
348 :class:`long`).
Christian Heimesa62da1d2008-01-12 19:39:10 +0000349
Benjamin Petersone41251e2008-04-25 01:59:09 +0000350 In addition to the standard numeric properties, decimal floating point
351 objects also have a number of specialized methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000352
Georg Brandl116aa622007-08-15 14:28:22 +0000353
Benjamin Petersone41251e2008-04-25 01:59:09 +0000354 .. method:: adjusted()
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Benjamin Petersone41251e2008-04-25 01:59:09 +0000356 Return the adjusted exponent after shifting out the coefficient's
357 rightmost digits until only the lead digit remains:
358 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the
359 position of the most significant digit with respect to the decimal point.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Georg Brandl116aa622007-08-15 14:28:22 +0000361
Benjamin Petersone41251e2008-04-25 01:59:09 +0000362 .. method:: as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Benjamin Petersone41251e2008-04-25 01:59:09 +0000364 Return a :term:`named tuple` representation of the number:
365 ``DecimalTuple(sign, digits, exponent)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000366
Christian Heimes25bb7832008-01-11 16:17:00 +0000367
Benjamin Petersone41251e2008-04-25 01:59:09 +0000368 .. method:: canonical()
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Benjamin Petersone41251e2008-04-25 01:59:09 +0000370 Return the canonical encoding of the argument. Currently, the encoding of
371 a :class:`Decimal` instance is always canonical, so this operation returns
372 its argument unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000373
Benjamin Petersone41251e2008-04-25 01:59:09 +0000374 .. method:: compare(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000375
Benjamin Petersone41251e2008-04-25 01:59:09 +0000376 Compare the values of two Decimal instances. This operation behaves in
377 the same way as the usual comparison method :meth:`__cmp__`, except that
378 :meth:`compare` returns a Decimal instance rather than an integer, and if
379 either operand is a NaN then the result is a NaN::
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000380
Benjamin Petersone41251e2008-04-25 01:59:09 +0000381 a or b is a NaN ==> Decimal('NaN')
382 a < b ==> Decimal('-1')
383 a == b ==> Decimal('0')
384 a > b ==> Decimal('1')
Georg Brandl116aa622007-08-15 14:28:22 +0000385
Benjamin Petersone41251e2008-04-25 01:59:09 +0000386 .. method:: compare_signal(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Benjamin Petersone41251e2008-04-25 01:59:09 +0000388 This operation is identical to the :meth:`compare` method, except that all
389 NaNs signal. That is, if neither operand is a signaling NaN then any
390 quiet NaN operand is treated as though it were a signaling NaN.
Georg Brandl116aa622007-08-15 14:28:22 +0000391
Benjamin Petersone41251e2008-04-25 01:59:09 +0000392 .. method:: compare_total(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000393
Benjamin Petersone41251e2008-04-25 01:59:09 +0000394 Compare two operands using their abstract representation rather than their
395 numerical value. Similar to the :meth:`compare` method, but the result
396 gives a total ordering on :class:`Decimal` instances. Two
397 :class:`Decimal` instances with the same numeric value but different
398 representations compare unequal in this ordering:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000399
Benjamin Petersone41251e2008-04-25 01:59:09 +0000400 >>> Decimal('12.0').compare_total(Decimal('12'))
401 Decimal('-1')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000402
Benjamin Petersone41251e2008-04-25 01:59:09 +0000403 Quiet and signaling NaNs are also included in the total ordering. The
404 result of this function is ``Decimal('0')`` if both operands have the same
405 representation, ``Decimal('-1')`` if the first operand is lower in the
406 total order than the second, and ``Decimal('1')`` if the first operand is
407 higher in the total order than the second operand. See the specification
408 for details of the total order.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000409
Benjamin Petersone41251e2008-04-25 01:59:09 +0000410 .. method:: compare_total_mag(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000411
Benjamin Petersone41251e2008-04-25 01:59:09 +0000412 Compare two operands using their abstract representation rather than their
413 value as in :meth:`compare_total`, but ignoring the sign of each operand.
414 ``x.compare_total_mag(y)`` is equivalent to
415 ``x.copy_abs().compare_total(y.copy_abs())``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000416
Benjamin Petersone41251e2008-04-25 01:59:09 +0000417 .. method:: copy_abs()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000418
Benjamin Petersone41251e2008-04-25 01:59:09 +0000419 Return the absolute value of the argument. This operation is unaffected
420 by the context and is quiet: no flags are changed and no rounding is
421 performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000422
Benjamin Petersone41251e2008-04-25 01:59:09 +0000423 .. method:: copy_negate()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000424
Benjamin Petersone41251e2008-04-25 01:59:09 +0000425 Return the negation of the argument. This operation is unaffected by the
426 context and is quiet: no flags are changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000427
Benjamin Petersone41251e2008-04-25 01:59:09 +0000428 .. method:: copy_sign(other)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000429
Benjamin Petersone41251e2008-04-25 01:59:09 +0000430 Return a copy of the first operand with the sign set to be the same as the
431 sign of the second operand. For example:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000432
Benjamin Petersone41251e2008-04-25 01:59:09 +0000433 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
434 Decimal('-2.3')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000435
Benjamin Petersone41251e2008-04-25 01:59:09 +0000436 This operation is unaffected by the context and is quiet: no flags are
437 changed and no rounding is performed.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000438
Benjamin Petersone41251e2008-04-25 01:59:09 +0000439 .. method:: exp([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000440
Benjamin Petersone41251e2008-04-25 01:59:09 +0000441 Return the value of the (natural) exponential function ``e**x`` at the
442 given number. The result is correctly rounded using the
443 :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000444
Benjamin Petersone41251e2008-04-25 01:59:09 +0000445 >>> Decimal(1).exp()
446 Decimal('2.718281828459045235360287471')
447 >>> Decimal(321).exp()
448 Decimal('2.561702493119680037517373933E+139')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000449
Benjamin Petersone41251e2008-04-25 01:59:09 +0000450 .. method:: fma(other, third[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000451
Benjamin Petersone41251e2008-04-25 01:59:09 +0000452 Fused multiply-add. Return self*other+third with no rounding of the
453 intermediate product self*other.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000454
Benjamin Petersone41251e2008-04-25 01:59:09 +0000455 >>> Decimal(2).fma(3, 5)
456 Decimal('11')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000457
Benjamin Petersone41251e2008-04-25 01:59:09 +0000458 .. method:: is_canonical()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000459
Benjamin Petersone41251e2008-04-25 01:59:09 +0000460 Return :const:`True` if the argument is canonical and :const:`False`
461 otherwise. Currently, a :class:`Decimal` instance is always canonical, so
462 this operation always returns :const:`True`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000463
Benjamin Petersone41251e2008-04-25 01:59:09 +0000464 .. method:: is_finite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000465
Benjamin Petersone41251e2008-04-25 01:59:09 +0000466 Return :const:`True` if the argument is a finite number, and
467 :const:`False` if the argument is an infinity or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000468
Benjamin Petersone41251e2008-04-25 01:59:09 +0000469 .. method:: is_infinite()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000470
Benjamin Petersone41251e2008-04-25 01:59:09 +0000471 Return :const:`True` if the argument is either positive or negative
472 infinity and :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000473
Benjamin Petersone41251e2008-04-25 01:59:09 +0000474 .. method:: is_nan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000475
Benjamin Petersone41251e2008-04-25 01:59:09 +0000476 Return :const:`True` if the argument is a (quiet or signaling) NaN and
477 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000478
Benjamin Petersone41251e2008-04-25 01:59:09 +0000479 .. method:: is_normal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000480
Benjamin Petersone41251e2008-04-25 01:59:09 +0000481 Return :const:`True` if the argument is a *normal* finite number. Return
482 :const:`False` if the argument is zero, subnormal, infinite or a NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000483
Benjamin Petersone41251e2008-04-25 01:59:09 +0000484 .. method:: is_qnan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000485
Benjamin Petersone41251e2008-04-25 01:59:09 +0000486 Return :const:`True` if the argument is a quiet NaN, and
487 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000488
Benjamin Petersone41251e2008-04-25 01:59:09 +0000489 .. method:: is_signed()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000490
Benjamin Petersone41251e2008-04-25 01:59:09 +0000491 Return :const:`True` if the argument has a negative sign and
492 :const:`False` otherwise. Note that zeros and NaNs can both carry signs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000493
Benjamin Petersone41251e2008-04-25 01:59:09 +0000494 .. method:: is_snan()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000495
Benjamin Petersone41251e2008-04-25 01:59:09 +0000496 Return :const:`True` if the argument is a signaling NaN and :const:`False`
497 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000498
Benjamin Petersone41251e2008-04-25 01:59:09 +0000499 .. method:: is_subnormal()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000500
Benjamin Petersone41251e2008-04-25 01:59:09 +0000501 Return :const:`True` if the argument is subnormal, and :const:`False`
502 otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000503
Benjamin Petersone41251e2008-04-25 01:59:09 +0000504 .. method:: is_zero()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000505
Benjamin Petersone41251e2008-04-25 01:59:09 +0000506 Return :const:`True` if the argument is a (positive or negative) zero and
507 :const:`False` otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000508
Benjamin Petersone41251e2008-04-25 01:59:09 +0000509 .. method:: ln([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000510
Benjamin Petersone41251e2008-04-25 01:59:09 +0000511 Return the natural (base e) logarithm of the operand. The result is
512 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000513
Benjamin Petersone41251e2008-04-25 01:59:09 +0000514 .. method:: log10([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000515
Benjamin Petersone41251e2008-04-25 01:59:09 +0000516 Return the base ten logarithm of the operand. The result is correctly
517 rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000518
Benjamin Petersone41251e2008-04-25 01:59:09 +0000519 .. method:: logb([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000520
Benjamin Petersone41251e2008-04-25 01:59:09 +0000521 For a nonzero number, return the adjusted exponent of its operand as a
522 :class:`Decimal` instance. If the operand is a zero then
523 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
524 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is
525 returned.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000526
Benjamin Petersone41251e2008-04-25 01:59:09 +0000527 .. method:: logical_and(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000528
Benjamin Petersone41251e2008-04-25 01:59:09 +0000529 :meth:`logical_and` is a logical operation which takes two *logical
530 operands* (see :ref:`logical_operands_label`). The result is the
531 digit-wise ``and`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000532
Benjamin Petersone41251e2008-04-25 01:59:09 +0000533 .. method:: logical_invert(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000534
Benjamin Petersone41251e2008-04-25 01:59:09 +0000535 :meth:`logical_invert` is a logical operation. The argument must
536 be a *logical operand* (see :ref:`logical_operands_label`). The
537 result is the digit-wise inversion of the operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000538
Benjamin Petersone41251e2008-04-25 01:59:09 +0000539 .. method:: logical_or(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000540
Benjamin Petersone41251e2008-04-25 01:59:09 +0000541 :meth:`logical_or` is a logical operation which takes two *logical
542 operands* (see :ref:`logical_operands_label`). The result is the
543 digit-wise ``or`` of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000544
Benjamin Petersone41251e2008-04-25 01:59:09 +0000545 .. method:: logical_xor(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546
Benjamin Petersone41251e2008-04-25 01:59:09 +0000547 :meth:`logical_xor` is a logical operation which takes two *logical
548 operands* (see :ref:`logical_operands_label`). The result is the
549 digit-wise exclusive or of the two operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000550
Benjamin Petersone41251e2008-04-25 01:59:09 +0000551 .. method:: max(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000552
Benjamin Petersone41251e2008-04-25 01:59:09 +0000553 Like ``max(self, other)`` except that the context rounding rule is applied
554 before returning and that :const:`NaN` values are either signaled or
555 ignored (depending on the context and whether they are signaling or
556 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000557
Benjamin Petersone41251e2008-04-25 01:59:09 +0000558 .. method:: max_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000559
Benjamin Petersone41251e2008-04-25 01:59:09 +0000560 Similar to the :meth:`max` method, but the comparison is done using the
561 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000562
Benjamin Petersone41251e2008-04-25 01:59:09 +0000563 .. method:: min(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000564
Benjamin Petersone41251e2008-04-25 01:59:09 +0000565 Like ``min(self, other)`` except that the context rounding rule is applied
566 before returning and that :const:`NaN` values are either signaled or
567 ignored (depending on the context and whether they are signaling or
568 quiet).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000569
Benjamin Petersone41251e2008-04-25 01:59:09 +0000570 .. method:: min_mag(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000571
Benjamin Petersone41251e2008-04-25 01:59:09 +0000572 Similar to the :meth:`min` method, but the comparison is done using the
573 absolute values of the operands.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000574
Benjamin Petersone41251e2008-04-25 01:59:09 +0000575 .. method:: next_minus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000576
Benjamin Petersone41251e2008-04-25 01:59:09 +0000577 Return the largest number representable in the given context (or in the
578 current thread's context if no context is given) that is smaller than the
579 given operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000580
Benjamin Petersone41251e2008-04-25 01:59:09 +0000581 .. method:: next_plus([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000582
Benjamin Petersone41251e2008-04-25 01:59:09 +0000583 Return the smallest number representable in the given context (or in the
584 current thread's context if no context is given) that is larger than the
585 given operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000586
Benjamin Petersone41251e2008-04-25 01:59:09 +0000587 .. method:: next_toward(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000588
Benjamin Petersone41251e2008-04-25 01:59:09 +0000589 If the two operands are unequal, return the number closest to the first
590 operand in the direction of the second operand. If both operands are
591 numerically equal, return a copy of the first operand with the sign set to
592 be the same as the sign of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000593
Benjamin Petersone41251e2008-04-25 01:59:09 +0000594 .. method:: normalize([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000595
Benjamin Petersone41251e2008-04-25 01:59:09 +0000596 Normalize the number by stripping the rightmost trailing zeros and
597 converting any result equal to :const:`Decimal('0')` to
598 :const:`Decimal('0e0')`. Used for producing canonical values for members
599 of an equivalence class. For example, ``Decimal('32.100')`` and
600 ``Decimal('0.321000e+2')`` both normalize to the equivalent value
601 ``Decimal('32.1')``.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602
Benjamin Petersone41251e2008-04-25 01:59:09 +0000603 .. method:: number_class([context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
Benjamin Petersone41251e2008-04-25 01:59:09 +0000605 Return a string describing the *class* of the operand. The returned value
606 is one of the following ten strings.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000607
Benjamin Petersone41251e2008-04-25 01:59:09 +0000608 * ``"-Infinity"``, indicating that the operand is negative infinity.
609 * ``"-Normal"``, indicating that the operand is a negative normal number.
610 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
611 * ``"-Zero"``, indicating that the operand is a negative zero.
612 * ``"+Zero"``, indicating that the operand is a positive zero.
613 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
614 * ``"+Normal"``, indicating that the operand is a positive normal number.
615 * ``"+Infinity"``, indicating that the operand is positive infinity.
616 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
617 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000618
Benjamin Petersone41251e2008-04-25 01:59:09 +0000619 .. method:: quantize(exp[, rounding[, context[, watchexp]]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000620
Benjamin Petersone41251e2008-04-25 01:59:09 +0000621 Return a value equal to the first operand after rounding and having the
622 exponent of the second operand.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000623
Benjamin Petersone41251e2008-04-25 01:59:09 +0000624 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
625 Decimal('1.414')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000626
Benjamin Petersone41251e2008-04-25 01:59:09 +0000627 Unlike other operations, if the length of the coefficient after the
628 quantize operation would be greater than precision, then an
629 :const:`InvalidOperation` is signaled. This guarantees that, unless there
630 is an error condition, the quantized exponent is always equal to that of
631 the right-hand operand.
Georg Brandl116aa622007-08-15 14:28:22 +0000632
Benjamin Petersone41251e2008-04-25 01:59:09 +0000633 Also unlike other operations, quantize never signals Underflow, even if
634 the result is subnormal and inexact.
Georg Brandl116aa622007-08-15 14:28:22 +0000635
Benjamin Petersone41251e2008-04-25 01:59:09 +0000636 If the exponent of the second operand is larger than that of the first
637 then rounding may be necessary. In this case, the rounding mode is
638 determined by the ``rounding`` argument if given, else by the given
639 ``context`` argument; if neither argument is given the rounding mode of
640 the current thread's context is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000641
Benjamin Petersone41251e2008-04-25 01:59:09 +0000642 If *watchexp* is set (default), then an error is returned whenever the
643 resulting exponent is greater than :attr:`Emax` or less than
644 :attr:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +0000645
Benjamin Petersone41251e2008-04-25 01:59:09 +0000646 .. method:: radix()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000647
Benjamin Petersone41251e2008-04-25 01:59:09 +0000648 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
649 class does all its arithmetic. Included for compatibility with the
650 specification.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000651
Benjamin Petersone41251e2008-04-25 01:59:09 +0000652 .. method:: remainder_near(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000653
Benjamin Petersone41251e2008-04-25 01:59:09 +0000654 Compute the modulo as either a positive or negative value depending on
655 which is closest to zero. For instance, ``Decimal(10).remainder_near(6)``
656 returns ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl116aa622007-08-15 14:28:22 +0000657
Benjamin Petersone41251e2008-04-25 01:59:09 +0000658 If both are equally close, the one chosen will have the same sign as
659 *self*.
Georg Brandl116aa622007-08-15 14:28:22 +0000660
Benjamin Petersone41251e2008-04-25 01:59:09 +0000661 .. method:: rotate(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662
Benjamin Petersone41251e2008-04-25 01:59:09 +0000663 Return the result of rotating the digits of the first operand by an amount
664 specified by the second operand. The second operand must be an integer in
665 the range -precision through precision. The absolute value of the second
666 operand gives the number of places to rotate. If the second operand is
667 positive then rotation is to the left; otherwise rotation is to the right.
668 The coefficient of the first operand is padded on the left with zeros to
669 length precision if necessary. The sign and exponent of the first operand
670 are unchanged.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000671
Benjamin Petersone41251e2008-04-25 01:59:09 +0000672 .. method:: same_quantum(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000673
Benjamin Petersone41251e2008-04-25 01:59:09 +0000674 Test whether self and other have the same exponent or whether both are
675 :const:`NaN`.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000676
Benjamin Petersone41251e2008-04-25 01:59:09 +0000677 .. method:: scaleb(other[, context])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000678
Benjamin Petersone41251e2008-04-25 01:59:09 +0000679 Return the first operand with exponent adjusted by the second.
680 Equivalently, return the first operand multiplied by ``10**other``. The
681 second operand must be an integer.
Georg Brandl116aa622007-08-15 14:28:22 +0000682
Benjamin Petersone41251e2008-04-25 01:59:09 +0000683 .. method:: shift(other[, context])
Georg Brandl116aa622007-08-15 14:28:22 +0000684
Benjamin Petersone41251e2008-04-25 01:59:09 +0000685 Return the result of shifting the digits of the first operand by an amount
686 specified by the second operand. The second operand must be an integer in
687 the range -precision through precision. The absolute value of the second
688 operand gives the number of places to shift. If the second operand is
689 positive then the shift is to the left; otherwise the shift is to the
690 right. Digits shifted into the coefficient are zeros. The sign and
691 exponent of the first operand are unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +0000692
Benjamin Petersone41251e2008-04-25 01:59:09 +0000693 .. method:: sqrt([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000694
Benjamin Petersone41251e2008-04-25 01:59:09 +0000695 Return the square root of the argument to full precision.
Georg Brandl116aa622007-08-15 14:28:22 +0000696
Georg Brandl116aa622007-08-15 14:28:22 +0000697
Benjamin Petersone41251e2008-04-25 01:59:09 +0000698 .. method:: to_eng_string([context])
Georg Brandl116aa622007-08-15 14:28:22 +0000699
Benjamin Petersone41251e2008-04-25 01:59:09 +0000700 Convert to an engineering-type string.
Georg Brandl116aa622007-08-15 14:28:22 +0000701
Benjamin Petersone41251e2008-04-25 01:59:09 +0000702 Engineering notation has an exponent which is a multiple of 3, so there
703 are up to 3 digits left of the decimal place. For example, converts
704 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705
Benjamin Petersone41251e2008-04-25 01:59:09 +0000706 .. method:: to_integral([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000707
Benjamin Petersone41251e2008-04-25 01:59:09 +0000708 Identical to the :meth:`to_integral_value` method. The ``to_integral``
709 name has been kept for compatibility with older versions.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000710
Benjamin Petersone41251e2008-04-25 01:59:09 +0000711 .. method:: to_integral_exact([rounding[, context]])
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000712
Benjamin Petersone41251e2008-04-25 01:59:09 +0000713 Round to the nearest integer, signaling :const:`Inexact` or
714 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is
715 determined by the ``rounding`` parameter if given, else by the given
716 ``context``. If neither parameter is given then the rounding mode of the
717 current context is used.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000718
Benjamin Petersone41251e2008-04-25 01:59:09 +0000719 .. method:: to_integral_value([rounding[, context]])
Georg Brandl116aa622007-08-15 14:28:22 +0000720
Benjamin Petersone41251e2008-04-25 01:59:09 +0000721 Round to the nearest integer without signaling :const:`Inexact` or
722 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the
723 rounding method in either the supplied *context* or the current context.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000724
Benjamin Petersone41251e2008-04-25 01:59:09 +0000725 .. method:: trim()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000726
Benjamin Petersone41251e2008-04-25 01:59:09 +0000727 Return the decimal with *insignificant* trailing zeros removed. Here, a
728 trailing zero is considered insignificant either if it follows the decimal
729 point, or if the exponent of the argument (that is, the last element of
730 the :meth:`as_tuple` representation) is positive.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000731
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000732
733.. _logical_operands_label:
734
735Logical operands
736^^^^^^^^^^^^^^^^
737
738The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
739and :meth:`logical_xor` methods expect their arguments to be *logical
740operands*. A *logical operand* is a :class:`Decimal` instance whose
741exponent and sign are both zero, and whose digits are all either
742:const:`0` or :const:`1`.
743
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000744.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +0000745
746
747.. _decimal-context:
748
749Context objects
750---------------
751
752Contexts are environments for arithmetic operations. They govern precision, set
753rules for rounding, determine which signals are treated as exceptions, and limit
754the range for exponents.
755
756Each thread has its own current context which is accessed or changed using the
757:func:`getcontext` and :func:`setcontext` functions:
758
759
760.. function:: getcontext()
761
762 Return the current context for the active thread.
763
764
765.. function:: setcontext(c)
766
767 Set the current context for the active thread to *c*.
768
769Beginning with Python 2.5, you can also use the :keyword:`with` statement and
770the :func:`localcontext` function to temporarily change the active context.
771
772
773.. function:: localcontext([c])
774
775 Return a context manager that will set the current context for the active thread
776 to a copy of *c* on entry to the with-statement and restore the previous context
777 when exiting the with-statement. If no context is specified, a copy of the
778 current context is used.
779
Georg Brandl116aa622007-08-15 14:28:22 +0000780 For example, the following code sets the current decimal precision to 42 places,
781 performs a calculation, and then automatically restores the previous context::
782
Georg Brandl116aa622007-08-15 14:28:22 +0000783 from decimal import localcontext
784
785 with localcontext() as ctx:
786 ctx.prec = 42 # Perform a high precision calculation
787 s = calculate_something()
788 s = +s # Round the final result back to the default precision
789
790New contexts can also be created using the :class:`Context` constructor
791described below. In addition, the module provides three pre-made contexts:
792
793
794.. class:: BasicContext
795
796 This is a standard context defined by the General Decimal Arithmetic
797 Specification. Precision is set to nine. Rounding is set to
798 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
799 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
800 :const:`Subnormal`.
801
802 Because many of the traps are enabled, this context is useful for debugging.
803
804
805.. class:: ExtendedContext
806
807 This is a standard context defined by the General Decimal Arithmetic
808 Specification. Precision is set to nine. Rounding is set to
809 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
810 exceptions are not raised during computations).
811
Christian Heimes3feef612008-02-11 06:19:17 +0000812 Because the traps are disabled, this context is useful for applications that
Georg Brandl116aa622007-08-15 14:28:22 +0000813 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
814 raising exceptions. This allows an application to complete a run in the
815 presence of conditions that would otherwise halt the program.
816
817
818.. class:: DefaultContext
819
820 This context is used by the :class:`Context` constructor as a prototype for new
821 contexts. Changing a field (such a precision) has the effect of changing the
822 default for new contexts creating by the :class:`Context` constructor.
823
824 This context is most useful in multi-threaded environments. Changing one of the
825 fields before threads are started has the effect of setting system-wide
826 defaults. Changing the fields after threads have started is not recommended as
827 it would require thread synchronization to prevent race conditions.
828
829 In single threaded environments, it is preferable to not use this context at
830 all. Instead, simply create contexts explicitly as described below.
831
832 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
833 for Overflow, InvalidOperation, and DivisionByZero.
834
835In addition to the three supplied contexts, new contexts can be created with the
836:class:`Context` constructor.
837
838
839.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
840
841 Creates a new context. If a field is not specified or is :const:`None`, the
842 default values are copied from the :const:`DefaultContext`. If the *flags*
843 field is not specified or is :const:`None`, all flags are cleared.
844
845 The *prec* field is a positive integer that sets the precision for arithmetic
846 operations in the context.
847
848 The *rounding* option is one of:
849
850 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
851 * :const:`ROUND_DOWN` (towards zero),
852 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
853 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
854 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
855 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
856 * :const:`ROUND_UP` (away from zero).
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000857 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
858 would have been 0 or 5; otherwise towards zero)
Georg Brandl116aa622007-08-15 14:28:22 +0000859
860 The *traps* and *flags* fields list any signals to be set. Generally, new
861 contexts should only set traps and leave the flags clear.
862
863 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
864 for exponents.
865
866 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
867 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
868 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
869
Georg Brandl116aa622007-08-15 14:28:22 +0000870
Benjamin Petersone41251e2008-04-25 01:59:09 +0000871 The :class:`Context` class defines several general purpose methods as well as
872 a large number of methods for doing arithmetic directly in a given context.
873 In addition, for each of the :class:`Decimal` methods described above (with
874 the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
875 a corresponding :class:`Context` method. For example, ``C.exp(x)`` is
876 equivalent to ``x.exp(context=C)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000877
878
Benjamin Petersone41251e2008-04-25 01:59:09 +0000879 .. method:: clear_flags()
Georg Brandl116aa622007-08-15 14:28:22 +0000880
Benjamin Petersone41251e2008-04-25 01:59:09 +0000881 Resets all of the flags to :const:`0`.
Georg Brandl116aa622007-08-15 14:28:22 +0000882
Benjamin Petersone41251e2008-04-25 01:59:09 +0000883 .. method:: copy()
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884
Benjamin Petersone41251e2008-04-25 01:59:09 +0000885 Return a duplicate of the context.
Georg Brandl116aa622007-08-15 14:28:22 +0000886
Benjamin Petersone41251e2008-04-25 01:59:09 +0000887 .. method:: copy_decimal(num)
Georg Brandl116aa622007-08-15 14:28:22 +0000888
Benjamin Petersone41251e2008-04-25 01:59:09 +0000889 Return a copy of the Decimal instance num.
Georg Brandl116aa622007-08-15 14:28:22 +0000890
Benjamin Petersone41251e2008-04-25 01:59:09 +0000891 .. method:: create_decimal(num)
Christian Heimesfe337bf2008-03-23 21:54:12 +0000892
Benjamin Petersone41251e2008-04-25 01:59:09 +0000893 Creates a new Decimal instance from *num* but using *self* as
894 context. Unlike the :class:`Decimal` constructor, the context precision,
895 rounding method, flags, and traps are applied to the conversion.
Georg Brandl116aa622007-08-15 14:28:22 +0000896
Benjamin Petersone41251e2008-04-25 01:59:09 +0000897 This is useful because constants are often given to a greater precision
898 than is needed by the application. Another benefit is that rounding
899 immediately eliminates unintended effects from digits beyond the current
900 precision. In the following example, using unrounded inputs means that
901 adding zero to a sum can change the result:
Georg Brandl116aa622007-08-15 14:28:22 +0000902
Benjamin Petersone41251e2008-04-25 01:59:09 +0000903 .. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +0000904
Benjamin Petersone41251e2008-04-25 01:59:09 +0000905 >>> getcontext().prec = 3
906 >>> Decimal('3.4445') + Decimal('1.0023')
907 Decimal('4.45')
908 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
909 Decimal('4.44')
Georg Brandl116aa622007-08-15 14:28:22 +0000910
Benjamin Petersone41251e2008-04-25 01:59:09 +0000911 This method implements the to-number operation of the IBM specification.
912 If the argument is a string, no leading or trailing whitespace is
913 permitted.
914
915 .. method:: Etiny()
916
917 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
918 value for subnormal results. When underflow occurs, the exponent is set
919 to :const:`Etiny`.
Georg Brandl116aa622007-08-15 14:28:22 +0000920
921
Benjamin Petersone41251e2008-04-25 01:59:09 +0000922 .. method:: Etop()
Georg Brandl116aa622007-08-15 14:28:22 +0000923
Benjamin Petersone41251e2008-04-25 01:59:09 +0000924 Returns a value equal to ``Emax - prec + 1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000925
Benjamin Petersone41251e2008-04-25 01:59:09 +0000926 The usual approach to working with decimals is to create :class:`Decimal`
927 instances and then apply arithmetic operations which take place within the
928 current context for the active thread. An alternative approach is to use
929 context methods for calculating within a specific context. The methods are
930 similar to those for the :class:`Decimal` class and are only briefly
931 recounted here.
Georg Brandl116aa622007-08-15 14:28:22 +0000932
933
Benjamin Petersone41251e2008-04-25 01:59:09 +0000934 .. method:: abs(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000935
Benjamin Petersone41251e2008-04-25 01:59:09 +0000936 Returns the absolute value of *x*.
Georg Brandl116aa622007-08-15 14:28:22 +0000937
938
Benjamin Petersone41251e2008-04-25 01:59:09 +0000939 .. method:: add(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +0000940
Benjamin Petersone41251e2008-04-25 01:59:09 +0000941 Return the sum of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +0000942
943
Benjamin Petersone41251e2008-04-25 01:59:09 +0000944 .. method:: divide(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +0000945
Benjamin Petersone41251e2008-04-25 01:59:09 +0000946 Return *x* divided by *y*.
Georg Brandl116aa622007-08-15 14:28:22 +0000947
948
Benjamin Petersone41251e2008-04-25 01:59:09 +0000949 .. method:: divide_int(x, y)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000950
Benjamin Petersone41251e2008-04-25 01:59:09 +0000951 Return *x* divided by *y*, truncated to an integer.
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000952
953
Benjamin Petersone41251e2008-04-25 01:59:09 +0000954 .. method:: divmod(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +0000955
Benjamin Petersone41251e2008-04-25 01:59:09 +0000956 Divides two numbers and returns the integer part of the result.
Georg Brandl116aa622007-08-15 14:28:22 +0000957
958
Benjamin Petersone41251e2008-04-25 01:59:09 +0000959 .. method:: minus(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000960
Benjamin Petersone41251e2008-04-25 01:59:09 +0000961 Minus corresponds to the unary prefix minus operator in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000962
963
Benjamin Petersone41251e2008-04-25 01:59:09 +0000964 .. method:: multiply(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +0000965
Benjamin Petersone41251e2008-04-25 01:59:09 +0000966 Return the product of *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +0000967
968
Benjamin Petersone41251e2008-04-25 01:59:09 +0000969 .. method:: plus(x)
Georg Brandl116aa622007-08-15 14:28:22 +0000970
Benjamin Petersone41251e2008-04-25 01:59:09 +0000971 Plus corresponds to the unary prefix plus operator in Python. This
972 operation applies the context precision and rounding, so it is *not* an
973 identity operation.
Georg Brandl116aa622007-08-15 14:28:22 +0000974
975
Benjamin Petersone41251e2008-04-25 01:59:09 +0000976 .. method:: power(x, y[, modulo])
Georg Brandl116aa622007-08-15 14:28:22 +0000977
Benjamin Petersone41251e2008-04-25 01:59:09 +0000978 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.
Georg Brandl116aa622007-08-15 14:28:22 +0000979
Benjamin Petersone41251e2008-04-25 01:59:09 +0000980 With two arguments, compute ``x**y``. If ``x`` is negative then ``y``
981 must be integral. The result will be inexact unless ``y`` is integral and
982 the result is finite and can be expressed exactly in 'precision' digits.
983 The result should always be correctly rounded, using the rounding mode of
984 the current thread's context.
Georg Brandl116aa622007-08-15 14:28:22 +0000985
Benjamin Petersone41251e2008-04-25 01:59:09 +0000986 With three arguments, compute ``(x**y) % modulo``. For the three argument
987 form, the following restrictions on the arguments hold:
Georg Brandl116aa622007-08-15 14:28:22 +0000988
Benjamin Petersone41251e2008-04-25 01:59:09 +0000989 - all three arguments must be integral
990 - ``y`` must be nonnegative
991 - at least one of ``x`` or ``y`` must be nonzero
992 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl116aa622007-08-15 14:28:22 +0000993
Benjamin Petersone41251e2008-04-25 01:59:09 +0000994 The result of ``Context.power(x, y, modulo)`` is identical to the result
995 that would be obtained by computing ``(x**y) % modulo`` with unbounded
996 precision, but is computed more efficiently. It is always exact.
Georg Brandl116aa622007-08-15 14:28:22 +0000997
Benjamin Petersone41251e2008-04-25 01:59:09 +0000998 .. method:: remainder(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +0000999
Benjamin Petersone41251e2008-04-25 01:59:09 +00001000 Returns the remainder from integer division.
Georg Brandl116aa622007-08-15 14:28:22 +00001001
Benjamin Petersone41251e2008-04-25 01:59:09 +00001002 The sign of the result, if non-zero, is the same as that of the original
1003 dividend.
Georg Brandl116aa622007-08-15 14:28:22 +00001004
Benjamin Petersone41251e2008-04-25 01:59:09 +00001005 .. method:: subtract(x, y)
Georg Brandl116aa622007-08-15 14:28:22 +00001006
Benjamin Petersone41251e2008-04-25 01:59:09 +00001007 Return the difference between *x* and *y*.
Georg Brandl116aa622007-08-15 14:28:22 +00001008
Benjamin Petersone41251e2008-04-25 01:59:09 +00001009 .. method:: to_sci_string(x)
Georg Brandl116aa622007-08-15 14:28:22 +00001010
Benjamin Petersone41251e2008-04-25 01:59:09 +00001011 Converts a number to a string using scientific notation.
Georg Brandl116aa622007-08-15 14:28:22 +00001012
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001013.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001014
1015
1016.. _decimal-signals:
1017
1018Signals
1019-------
1020
1021Signals represent conditions that arise during computation. Each corresponds to
1022one context flag and one context trap enabler.
1023
Raymond Hettinger86173da2008-02-01 20:38:12 +00001024The context flag is set whenever the condition is encountered. After the
Georg Brandl116aa622007-08-15 14:28:22 +00001025computation, flags may be checked for informational purposes (for instance, to
1026determine whether a computation was exact). After checking the flags, be sure to
1027clear all flags before starting the next computation.
1028
1029If the context's trap enabler is set for the signal, then the condition causes a
1030Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1031is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1032condition.
1033
1034
1035.. class:: Clamped
1036
1037 Altered an exponent to fit representation constraints.
1038
1039 Typically, clamping occurs when an exponent falls outside the context's
1040 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001041 fit by adding zeros to the coefficient.
Georg Brandl116aa622007-08-15 14:28:22 +00001042
1043
1044.. class:: DecimalException
1045
1046 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1047
1048
1049.. class:: DivisionByZero
1050
1051 Signals the division of a non-infinite number by zero.
1052
1053 Can occur with division, modulo division, or when raising a number to a negative
1054 power. If this signal is not trapped, returns :const:`Infinity` or
1055 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1056
1057
1058.. class:: Inexact
1059
1060 Indicates that rounding occurred and the result is not exact.
1061
1062 Signals when non-zero digits were discarded during rounding. The rounded result
1063 is returned. The signal flag or trap is used to detect when results are
1064 inexact.
1065
1066
1067.. class:: InvalidOperation
1068
1069 An invalid operation was performed.
1070
1071 Indicates that an operation was requested that does not make sense. If not
1072 trapped, returns :const:`NaN`. Possible causes include::
1073
1074 Infinity - Infinity
1075 0 * Infinity
1076 Infinity / Infinity
1077 x % 0
1078 Infinity % x
1079 x._rescale( non-integer )
1080 sqrt(-x) and x > 0
1081 0 ** 0
1082 x ** (non-integer)
1083 x ** Infinity
1084
1085
1086.. class:: Overflow
1087
1088 Numerical overflow.
1089
Benjamin Petersone41251e2008-04-25 01:59:09 +00001090 Indicates the exponent is larger than :attr:`Emax` after rounding has
1091 occurred. If not trapped, the result depends on the rounding mode, either
1092 pulling inward to the largest representable finite number or rounding outward
1093 to :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded`
1094 are also signaled.
Georg Brandl116aa622007-08-15 14:28:22 +00001095
1096
1097.. class:: Rounded
1098
1099 Rounding occurred though possibly no information was lost.
1100
Benjamin Petersone41251e2008-04-25 01:59:09 +00001101 Signaled whenever rounding discards digits; even if those digits are zero
1102 (such as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns
1103 the result unchanged. This signal is used to detect loss of significant
1104 digits.
Georg Brandl116aa622007-08-15 14:28:22 +00001105
1106
1107.. class:: Subnormal
1108
1109 Exponent was lower than :attr:`Emin` prior to rounding.
1110
Benjamin Petersone41251e2008-04-25 01:59:09 +00001111 Occurs when an operation result is subnormal (the exponent is too small). If
1112 not trapped, returns the result unchanged.
Georg Brandl116aa622007-08-15 14:28:22 +00001113
1114
1115.. class:: Underflow
1116
1117 Numerical underflow with result rounded to zero.
1118
1119 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1120 and :class:`Subnormal` are also signaled.
1121
1122The following table summarizes the hierarchy of signals::
1123
1124 exceptions.ArithmeticError(exceptions.Exception)
1125 DecimalException
1126 Clamped
1127 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1128 Inexact
1129 Overflow(Inexact, Rounded)
1130 Underflow(Inexact, Rounded, Subnormal)
1131 InvalidOperation
1132 Rounded
1133 Subnormal
1134
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001135.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001136
1137
1138.. _decimal-notes:
1139
1140Floating Point Notes
1141--------------------
1142
1143
1144Mitigating round-off error with increased precision
1145^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1146
1147The use of decimal floating point eliminates decimal representation error
1148(making it possible to represent :const:`0.1` exactly); however, some operations
1149can still incur round-off error when non-zero digits exceed the fixed precision.
1150
1151The effects of round-off error can be amplified by the addition or subtraction
1152of nearly offsetting quantities resulting in loss of significance. Knuth
1153provides two instructive examples where rounded floating point arithmetic with
1154insufficient precision causes the breakdown of the associative and distributive
Christian Heimesfe337bf2008-03-23 21:54:12 +00001155properties of addition:
1156
1157.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001158
1159 # Examples from Seminumerical Algorithms, Section 4.2.2.
1160 >>> from decimal import Decimal, getcontext
1161 >>> getcontext().prec = 8
1162
1163 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1164 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001165 Decimal('9.5111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001166 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001167 Decimal('10')
Georg Brandl116aa622007-08-15 14:28:22 +00001168
1169 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1170 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001171 Decimal('0.01')
Georg Brandl116aa622007-08-15 14:28:22 +00001172 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001173 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001174
1175The :mod:`decimal` module makes it possible to restore the identities by
Christian Heimesfe337bf2008-03-23 21:54:12 +00001176expanding the precision sufficiently to avoid loss of significance:
1177
1178.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001179
1180 >>> getcontext().prec = 20
1181 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1182 >>> (u + v) + w
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001183 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001184 >>> u + (v + w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001185 Decimal('9.51111111')
Georg Brandl116aa622007-08-15 14:28:22 +00001186 >>>
1187 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1188 >>> (u*v) + (u*w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001189 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001190 >>> u * (v+w)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001191 Decimal('0.0060000')
Georg Brandl116aa622007-08-15 14:28:22 +00001192
1193
1194Special values
1195^^^^^^^^^^^^^^
1196
1197The number system for the :mod:`decimal` module provides special values
1198including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001199and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl116aa622007-08-15 14:28:22 +00001200
1201Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1202they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1203not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1204can result from rounding beyond the limits of the largest representable number.
1205
1206The infinities are signed (affine) and can be used in arithmetic operations
1207where they get treated as very large, indeterminate numbers. For instance,
1208adding a constant to infinity gives another infinite result.
1209
1210Some operations are indeterminate and return :const:`NaN`, or if the
1211:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1212``0/0`` returns :const:`NaN` which means "not a number". This variety of
1213:const:`NaN` is quiet and, once created, will flow through other computations
1214always resulting in another :const:`NaN`. This behavior can be useful for a
1215series of computations that occasionally have missing inputs --- it allows the
1216calculation to proceed while flagging specific results as invalid.
1217
1218A variant is :const:`sNaN` which signals rather than remaining quiet after every
1219operation. This is a useful return value when an invalid result needs to
1220interrupt a calculation for special handling.
1221
Christian Heimes77c02eb2008-02-09 02:18:51 +00001222The behavior of Python's comparison operators can be a little surprising where a
1223:const:`NaN` is involved. A test for equality where one of the operands is a
1224quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1225``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1226:const:`True`. An attempt to compare two Decimals using any of the ``<``,
1227``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1228if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Christian Heimes3feef612008-02-11 06:19:17 +00001229not trapped. Note that the General Decimal Arithmetic specification does not
Christian Heimes77c02eb2008-02-09 02:18:51 +00001230specify the behavior of direct comparisons; these rules for comparisons
1231involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1232section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
1233and :meth:`compare-signal` methods instead.
1234
Georg Brandl116aa622007-08-15 14:28:22 +00001235The signed zeros can result from calculations that underflow. They keep the sign
1236that would have resulted if the calculation had been carried out to greater
1237precision. Since their magnitude is zero, both positive and negative zeros are
1238treated as equal and their sign is informational.
1239
1240In addition to the two signed zeros which are distinct yet equal, there are
1241various representations of zero with differing precisions yet equivalent in
1242value. This takes a bit of getting used to. For an eye accustomed to
1243normalized floating point representations, it is not immediately obvious that
Christian Heimesfe337bf2008-03-23 21:54:12 +00001244the following calculation returns a value equal to zero:
Georg Brandl116aa622007-08-15 14:28:22 +00001245
1246 >>> 1 / Decimal('Infinity')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001247 Decimal('0E-1000000026')
Georg Brandl116aa622007-08-15 14:28:22 +00001248
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001249.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001250
1251
1252.. _decimal-threads:
1253
1254Working with threads
1255--------------------
1256
1257The :func:`getcontext` function accesses a different :class:`Context` object for
1258each thread. Having separate thread contexts means that threads may make
1259changes (such as ``getcontext.prec=10``) without interfering with other threads.
1260
1261Likewise, the :func:`setcontext` function automatically assigns its target to
1262the current thread.
1263
1264If :func:`setcontext` has not been called before :func:`getcontext`, then
1265:func:`getcontext` will automatically create a new context for use in the
1266current thread.
1267
1268The new context is copied from a prototype context called *DefaultContext*. To
1269control the defaults so that each thread will use the same values throughout the
1270application, directly modify the *DefaultContext* object. This should be done
1271*before* any threads are started so that there won't be a race condition between
1272threads calling :func:`getcontext`. For example::
1273
1274 # Set applicationwide defaults for all threads about to be launched
1275 DefaultContext.prec = 12
1276 DefaultContext.rounding = ROUND_DOWN
1277 DefaultContext.traps = ExtendedContext.traps.copy()
1278 DefaultContext.traps[InvalidOperation] = 1
1279 setcontext(DefaultContext)
1280
1281 # Afterwards, the threads can be started
1282 t1.start()
1283 t2.start()
1284 t3.start()
1285 . . .
1286
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001287.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001288
1289
1290.. _decimal-recipes:
1291
1292Recipes
1293-------
1294
1295Here are a few recipes that serve as utility functions and that demonstrate ways
1296to work with the :class:`Decimal` class::
1297
1298 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1299 pos='', neg='-', trailneg=''):
1300 """Convert Decimal to a money formatted string.
1301
1302 places: required number of places after the decimal point
1303 curr: optional currency symbol before the sign (may be blank)
1304 sep: optional grouping separator (comma, period, space, or blank)
1305 dp: decimal point indicator (comma or period)
1306 only specify as blank when places is zero
1307 pos: optional sign for positive numbers: '+', space or blank
1308 neg: optional sign for negative numbers: '-', '(', space or blank
1309 trailneg:optional trailing minus indicator: '-', ')', space or blank
1310
1311 >>> d = Decimal('-1234567.8901')
1312 >>> moneyfmt(d, curr='$')
1313 '-$1,234,567.89'
1314 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1315 '1.234.568-'
1316 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1317 '($1,234,567.89)'
1318 >>> moneyfmt(Decimal(123456789), sep=' ')
1319 '123 456 789.00'
1320 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
Christian Heimesdae2a892008-04-19 00:55:37 +00001321 '<0.02>'
Georg Brandl116aa622007-08-15 14:28:22 +00001322
1323 """
Christian Heimesa156e092008-02-16 07:38:31 +00001324 q = Decimal(10) ** -places # 2 places --> '0.01'
1325 sign, digits, exp = value.quantize(q).as_tuple()
Georg Brandl116aa622007-08-15 14:28:22 +00001326 result = []
1327 digits = map(str, digits)
1328 build, next = result.append, digits.pop
1329 if sign:
1330 build(trailneg)
1331 for i in range(places):
Christian Heimesa156e092008-02-16 07:38:31 +00001332 build(next() if digits else '0')
Georg Brandl116aa622007-08-15 14:28:22 +00001333 build(dp)
Christian Heimesdae2a892008-04-19 00:55:37 +00001334 if not digits:
1335 build('0')
Georg Brandl116aa622007-08-15 14:28:22 +00001336 i = 0
1337 while digits:
1338 build(next())
1339 i += 1
1340 if i == 3 and digits:
1341 i = 0
1342 build(sep)
1343 build(curr)
Christian Heimesa156e092008-02-16 07:38:31 +00001344 build(neg if sign else pos)
1345 return ''.join(reversed(result))
Georg Brandl116aa622007-08-15 14:28:22 +00001346
1347 def pi():
1348 """Compute Pi to the current precision.
1349
Georg Brandl6911e3c2007-09-04 07:15:32 +00001350 >>> print(pi())
Georg Brandl116aa622007-08-15 14:28:22 +00001351 3.141592653589793238462643383
1352
1353 """
1354 getcontext().prec += 2 # extra digits for intermediate steps
1355 three = Decimal(3) # substitute "three=3.0" for regular floats
1356 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1357 while s != lasts:
1358 lasts = s
1359 n, na = n+na, na+8
1360 d, da = d+da, da+32
1361 t = (t * n) / d
1362 s += t
1363 getcontext().prec -= 2
1364 return +s # unary plus applies the new precision
1365
1366 def exp(x):
1367 """Return e raised to the power of x. Result type matches input type.
1368
Georg Brandl6911e3c2007-09-04 07:15:32 +00001369 >>> print(exp(Decimal(1)))
Georg Brandl116aa622007-08-15 14:28:22 +00001370 2.718281828459045235360287471
Georg Brandl6911e3c2007-09-04 07:15:32 +00001371 >>> print(exp(Decimal(2)))
Georg Brandl116aa622007-08-15 14:28:22 +00001372 7.389056098930650227230427461
Georg Brandl6911e3c2007-09-04 07:15:32 +00001373 >>> print(exp(2.0))
Georg Brandl116aa622007-08-15 14:28:22 +00001374 7.38905609893
Georg Brandl6911e3c2007-09-04 07:15:32 +00001375 >>> print(exp(2+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001376 (7.38905609893+0j)
1377
1378 """
1379 getcontext().prec += 2
1380 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1381 while s != lasts:
1382 lasts = s
1383 i += 1
1384 fact *= i
1385 num *= x
1386 s += num / fact
1387 getcontext().prec -= 2
1388 return +s
1389
1390 def cos(x):
1391 """Return the cosine of x as measured in radians.
1392
Georg Brandl6911e3c2007-09-04 07:15:32 +00001393 >>> print(cos(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001394 0.8775825618903727161162815826
Georg Brandl6911e3c2007-09-04 07:15:32 +00001395 >>> print(cos(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001396 0.87758256189
Georg Brandl6911e3c2007-09-04 07:15:32 +00001397 >>> print(cos(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001398 (0.87758256189+0j)
1399
1400 """
1401 getcontext().prec += 2
1402 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1403 while s != lasts:
1404 lasts = s
1405 i += 2
1406 fact *= i * (i-1)
1407 num *= x * x
1408 sign *= -1
1409 s += num / fact * sign
1410 getcontext().prec -= 2
1411 return +s
1412
1413 def sin(x):
1414 """Return the sine of x as measured in radians.
1415
Georg Brandl6911e3c2007-09-04 07:15:32 +00001416 >>> print(sin(Decimal('0.5')))
Georg Brandl116aa622007-08-15 14:28:22 +00001417 0.4794255386042030002732879352
Georg Brandl6911e3c2007-09-04 07:15:32 +00001418 >>> print(sin(0.5))
Georg Brandl116aa622007-08-15 14:28:22 +00001419 0.479425538604
Georg Brandl6911e3c2007-09-04 07:15:32 +00001420 >>> print(sin(0.5+0j))
Georg Brandl116aa622007-08-15 14:28:22 +00001421 (0.479425538604+0j)
1422
1423 """
1424 getcontext().prec += 2
1425 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1426 while s != lasts:
1427 lasts = s
1428 i += 2
1429 fact *= i * (i-1)
1430 num *= x * x
1431 sign *= -1
1432 s += num / fact * sign
1433 getcontext().prec -= 2
1434 return +s
1435
1436
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001437.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl116aa622007-08-15 14:28:22 +00001438
1439
1440.. _decimal-faq:
1441
1442Decimal FAQ
1443-----------
1444
1445Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1446minimize typing when using the interactive interpreter?
1447
Christian Heimesfe337bf2008-03-23 21:54:12 +00001448A. Some users abbreviate the constructor to just a single letter:
Georg Brandl116aa622007-08-15 14:28:22 +00001449
1450 >>> D = decimal.Decimal
1451 >>> D('1.23') + D('3.45')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001452 Decimal('4.68')
Georg Brandl116aa622007-08-15 14:28:22 +00001453
1454Q. In a fixed-point application with two decimal places, some inputs have many
1455places and need to be rounded. Others are not supposed to have excess digits
1456and need to be validated. What methods should be used?
1457
1458A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
Christian Heimesfe337bf2008-03-23 21:54:12 +00001459the :const:`Inexact` trap is set, it is also useful for validation:
Georg Brandl116aa622007-08-15 14:28:22 +00001460
1461 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1462
1463 >>> # Round to two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001464 >>> Decimal('3.214').quantize(TWOPLACES)
1465 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001466
1467 >>> # Validate that a number does not exceed two places
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001468 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1469 Decimal('3.21')
Georg Brandl116aa622007-08-15 14:28:22 +00001470
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001471 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl116aa622007-08-15 14:28:22 +00001472 Traceback (most recent call last):
1473 ...
Christian Heimesfe337bf2008-03-23 21:54:12 +00001474 Inexact
Georg Brandl116aa622007-08-15 14:28:22 +00001475
1476Q. Once I have valid two place inputs, how do I maintain that invariant
1477throughout an application?
1478
Christian Heimesa156e092008-02-16 07:38:31 +00001479A. Some operations like addition, subtraction, and multiplication by an integer
1480will automatically preserve fixed point. Others operations, like division and
1481non-integer multiplication, will change the number of decimal places and need to
Christian Heimesfe337bf2008-03-23 21:54:12 +00001482be followed-up with a :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001483
1484 >>> a = Decimal('102.72') # Initial fixed-point values
1485 >>> b = Decimal('3.17')
1486 >>> a + b # Addition preserves fixed-point
1487 Decimal('105.89')
1488 >>> a - b
1489 Decimal('99.55')
1490 >>> a * 42 # So does integer multiplication
1491 Decimal('4314.24')
1492 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication
1493 Decimal('325.62')
1494 >>> (b / a).quantize(TWOPLACES) # And quantize division
1495 Decimal('0.03')
1496
1497In developing fixed-point applications, it is convenient to define functions
Christian Heimesfe337bf2008-03-23 21:54:12 +00001498to handle the :meth:`quantize` step:
Christian Heimesa156e092008-02-16 07:38:31 +00001499
1500 >>> def mul(x, y, fp=TWOPLACES):
1501 ... return (x * y).quantize(fp)
1502 >>> def div(x, y, fp=TWOPLACES):
1503 ... return (x / y).quantize(fp)
1504
1505 >>> mul(a, b) # Automatically preserve fixed-point
1506 Decimal('325.62')
1507 >>> div(b, a)
1508 Decimal('0.03')
Georg Brandl116aa622007-08-15 14:28:22 +00001509
1510Q. There are many ways to express the same value. The numbers :const:`200`,
1511:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1512various precisions. Is there a way to transform them to a single recognizable
1513canonical value?
1514
1515A. The :meth:`normalize` method maps all equivalent values to a single
Christian Heimesfe337bf2008-03-23 21:54:12 +00001516representative:
Georg Brandl116aa622007-08-15 14:28:22 +00001517
1518 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1519 >>> [v.normalize() for v in values]
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001520 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl116aa622007-08-15 14:28:22 +00001521
1522Q. Some decimal values always print with exponential notation. Is there a way
1523to get a non-exponential representation?
1524
1525A. For some values, exponential notation is the only way to express the number
1526of significant places in the coefficient. For example, expressing
1527:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1528original's two-place significance.
1529
Christian Heimesa156e092008-02-16 07:38:31 +00001530If an application does not care about tracking significance, it is easy to
Christian Heimesc3f30c42008-02-22 16:37:40 +00001531remove the exponent and trailing zeroes, losing significance, but keeping the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001532value unchanged:
Christian Heimesa156e092008-02-16 07:38:31 +00001533
1534 >>> def remove_exponent(d):
1535 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1536
1537 >>> remove_exponent(Decimal('5E+3'))
1538 Decimal('5000')
1539
Georg Brandl116aa622007-08-15 14:28:22 +00001540Q. Is there a way to convert a regular float to a :class:`Decimal`?
1541
1542A. Yes, all binary floating point numbers can be exactly expressed as a
1543Decimal. An exact conversion may take more precision than intuition would
Christian Heimesfe337bf2008-03-23 21:54:12 +00001544suggest, so we trap :const:`Inexact` to signal a need for more precision:
1545
1546.. testcode::
Georg Brandl116aa622007-08-15 14:28:22 +00001547
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001548 def float_to_decimal(f):
1549 "Convert a floating point number to a Decimal with no loss of information"
1550 n, d = f.as_integer_ratio()
1551 with localcontext() as ctx:
1552 ctx.traps[Inexact] = True
1553 while True:
1554 try:
1555 return Decimal(n) / Decimal(d)
1556 except Inexact:
1557 ctx.prec += 1
Georg Brandl116aa622007-08-15 14:28:22 +00001558
Christian Heimesfe337bf2008-03-23 21:54:12 +00001559.. doctest::
1560
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001561 >>> float_to_decimal(math.pi)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001562 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl116aa622007-08-15 14:28:22 +00001563
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001564Q. Why isn't the :func:`float_to_decimal` routine included in the module?
Georg Brandl116aa622007-08-15 14:28:22 +00001565
1566A. There is some question about whether it is advisable to mix binary and
1567decimal floating point. Also, its use requires some care to avoid the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001568representation issues associated with binary floating point:
Georg Brandl116aa622007-08-15 14:28:22 +00001569
Raymond Hettinger66cb7d42008-02-07 20:09:43 +00001570 >>> float_to_decimal(1.1)
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001571 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl116aa622007-08-15 14:28:22 +00001572
1573Q. Within a complex calculation, how can I make sure that I haven't gotten a
1574spurious result because of insufficient precision or rounding anomalies.
1575
1576A. The decimal module makes it easy to test results. A best practice is to
1577re-run calculations using greater precision and with various rounding modes.
1578Widely differing results indicate insufficient precision, rounding mode issues,
1579ill-conditioned inputs, or a numerically unstable algorithm.
1580
1581Q. I noticed that context precision is applied to the results of operations but
1582not to the inputs. Is there anything to watch out for when mixing values of
1583different precisions?
1584
1585A. Yes. The principle is that all values are considered to be exact and so is
1586the arithmetic on those values. Only the results are rounded. The advantage
1587for inputs is that "what you type is what you get". A disadvantage is that the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001588results can look odd if you forget that the inputs haven't been rounded:
1589
1590.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001591
1592 >>> getcontext().prec = 3
Christian Heimesfe337bf2008-03-23 21:54:12 +00001593 >>> Decimal('3.104') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001594 Decimal('5.21')
Christian Heimesfe337bf2008-03-23 21:54:12 +00001595 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001596 Decimal('5.20')
Georg Brandl116aa622007-08-15 14:28:22 +00001597
1598The solution is either to increase precision or to force rounding of inputs
Christian Heimesfe337bf2008-03-23 21:54:12 +00001599using the unary plus operation:
1600
1601.. doctest:: newcontext
Georg Brandl116aa622007-08-15 14:28:22 +00001602
1603 >>> getcontext().prec = 3
1604 >>> +Decimal('1.23456789') # unary plus triggers rounding
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001605 Decimal('1.23')
Georg Brandl116aa622007-08-15 14:28:22 +00001606
1607Alternatively, inputs can be rounded upon creation using the
Christian Heimesfe337bf2008-03-23 21:54:12 +00001608:meth:`Context.create_decimal` method:
Georg Brandl116aa622007-08-15 14:28:22 +00001609
1610 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001611 Decimal('1.2345')
Georg Brandl116aa622007-08-15 14:28:22 +00001612