blob: 977e95dcdd2f6cc190a07826ad5d0f730350a42c [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
Raymond Hettinger13a70752008-02-10 07:21:09 +00002:mod:`decimal` --- Decimal fixed point and floating point arithmetic
3====================================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00004
5.. module:: decimal
6 :synopsis: Implementation of the General Decimal Arithmetic Specification.
7
8
9.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
10.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
11.. moduleauthor:: Raymond Hettinger <python at rcn.com>
12.. moduleauthor:: Aahz <aahz at pobox.com>
13.. moduleauthor:: Tim Peters <tim.one at comcast.net>
14
15
16.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
17
18
19.. versionadded:: 2.4
20
21The :mod:`decimal` module provides support for decimal floating point
Facundo Batista7c82a3e92007-09-14 18:58:34 +000022arithmetic. It offers several advantages over the :class:`float` datatype:
Georg Brandl8ec7f652007-08-15 14:28:01 +000023
Raymond Hettinger13a70752008-02-10 07:21:09 +000024* Decimal "is based on a floating-point model which was designed with people
25 in mind, and necessarily has a paramount guiding principle -- computers must
26 provide an arithmetic that works in the same way as the arithmetic that
27 people learn at school." -- excerpt from the decimal arithmetic specification.
28
Georg Brandl8ec7f652007-08-15 14:28:01 +000029* Decimal numbers can be represented exactly. In contrast, numbers like
30 :const:`1.1` do not have an exact representation in binary floating point. End
31 users typically would not expect :const:`1.1` to display as
32 :const:`1.1000000000000001` as it does with binary floating point.
33
34* The exactness carries over into arithmetic. In decimal floating point, ``0.1
Facundo Batista7c82a3e92007-09-14 18:58:34 +000035 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result
Georg Brandl8ec7f652007-08-15 14:28:01 +000036 is :const:`5.5511151231257827e-017`. While near to zero, the differences
37 prevent reliable equality testing and differences can accumulate. For this
Raymond Hettinger13a70752008-02-10 07:21:09 +000038 reason, decimal is preferred in accounting applications which have strict
Georg Brandl8ec7f652007-08-15 14:28:01 +000039 equality invariants.
40
41* The decimal module incorporates a notion of significant places so that ``1.30
42 + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance.
43 This is the customary presentation for monetary applications. For
44 multiplication, the "schoolbook" approach uses all the figures in the
45 multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
46 1.20`` gives :const:`1.5600`.
47
48* Unlike hardware based binary floating point, the decimal module has a user
Facundo Batista7c82a3e92007-09-14 18:58:34 +000049 alterable precision (defaulting to 28 places) which can be as large as needed for
Georg Brandl8ec7f652007-08-15 14:28:01 +000050 a given problem::
51
52 >>> getcontext().prec = 6
53 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +000054 Decimal('0.142857')
Georg Brandl8ec7f652007-08-15 14:28:01 +000055 >>> getcontext().prec = 28
56 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +000057 Decimal('0.1428571428571428571428571429')
Georg Brandl8ec7f652007-08-15 14:28:01 +000058
59* Both binary and decimal floating point are implemented in terms of published
60 standards. While the built-in float type exposes only a modest portion of its
61 capabilities, the decimal module exposes all required parts of the standard.
62 When needed, the programmer has full control over rounding and signal handling.
Raymond Hettinger13a70752008-02-10 07:21:09 +000063 This includes an option to enforce exact arithmetic by using exceptions
64 to block any inexact operations.
65
66* The decimal module was designed to support "without prejudice, both exact
67 unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
68 and rounded floating-point arithmetic." -- excerpt from the decimal
69 arithmetic specification.
Georg Brandl8ec7f652007-08-15 14:28:01 +000070
71The module design is centered around three concepts: the decimal number, the
72context for arithmetic, and signals.
73
74A decimal number is immutable. It has a sign, coefficient digits, and an
75exponent. To preserve significance, the coefficient digits do not truncate
Facundo Batista7c82a3e92007-09-14 18:58:34 +000076trailing zeros. Decimals also include special values such as
Georg Brandl8ec7f652007-08-15 14:28:01 +000077:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also
78differentiates :const:`-0` from :const:`+0`.
79
80The context for arithmetic is an environment specifying precision, rounding
81rules, limits on exponents, flags indicating the results of operations, and trap
82enablers which determine whether signals are treated as exceptions. Rounding
83options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
84:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +000085:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000086
87Signals are groups of exceptional conditions arising during the course of
88computation. Depending on the needs of the application, signals may be ignored,
89considered as informational, or treated as exceptions. The signals in the
90decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
91:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
92:const:`Overflow`, and :const:`Underflow`.
93
94For each signal there is a flag and a trap enabler. When a signal is
95encountered, its flag is incremented from zero and, then, if the trap enabler is
96set to one, an exception is raised. Flags are sticky, so the user needs to
97reset them before monitoring a calculation.
98
99
100.. seealso::
101
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000102 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
103 Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000104
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000105 * IEEE standard 854-1987, `Unofficial IEEE 854 Text
Mark Dickinsonff6672f2008-02-07 01:14:23 +0000106 <http://754r.ucbtest.org/standards/854.pdf>`_.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000107
Georg Brandlb19be572007-12-29 10:57:00 +0000108.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000109
110
111.. _decimal-tutorial:
112
113Quick-start Tutorial
114--------------------
115
116The usual start to using decimals is importing the module, viewing the current
117context with :func:`getcontext` and, if necessary, setting new values for
118precision, rounding, or enabled traps::
119
120 >>> from decimal import *
121 >>> getcontext()
122 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
123 capitals=1, flags=[], traps=[Overflow, InvalidOperation,
124 DivisionByZero])
125
126 >>> getcontext().prec = 7 # Set a new precision
127
128Decimal instances can be constructed from integers, strings, or tuples. To
129create a Decimal from a :class:`float`, first convert it to a string. This
130serves as an explicit reminder of the details of the conversion (including
131representation error). Decimal numbers include special values such as
132:const:`NaN` which stands for "Not a number", positive and negative
133:const:`Infinity`, and :const:`-0`. ::
134
135 >>> Decimal(10)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000136 Decimal('10')
137 >>> Decimal('3.14')
138 Decimal('3.14')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000139 >>> Decimal((0, (3, 1, 4), -2))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000140 Decimal('3.14')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000141 >>> Decimal(str(2.0 ** 0.5))
Raymond Hettingerabe32372008-02-14 02:41:22 +0000142 Decimal('1.41421356237')
143 >>> Decimal(2) ** Decimal('0.5')
144 Decimal('1.414213562373095048801688724')
145 >>> Decimal('NaN')
146 Decimal('NaN')
147 >>> Decimal('-Infinity')
148 Decimal('-Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000149
150The significance of a new Decimal is determined solely by the number of digits
151input. Context precision and rounding only come into play during arithmetic
152operations. ::
153
154 >>> getcontext().prec = 6
155 >>> Decimal('3.0')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000156 Decimal('3.0')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000157 >>> Decimal('3.1415926535')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000158 Decimal('3.1415926535')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000159 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000160 Decimal('5.85987')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000161 >>> getcontext().rounding = ROUND_UP
162 >>> Decimal('3.1415926535') + Decimal('2.7182818285')
Raymond Hettingerabe32372008-02-14 02:41:22 +0000163 Decimal('5.85988')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000164
165Decimals interact well with much of the rest of Python. Here is a small decimal
166floating point flying circus::
167
168 >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
169 >>> max(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000170 Decimal('9.25')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000171 >>> min(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000172 Decimal('0.03')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000173 >>> sorted(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000174 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
175 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000176 >>> sum(data)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000177 Decimal('19.29')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000178 >>> a,b,c = data[:3]
179 >>> str(a)
180 '1.34'
181 >>> float(a)
182 1.3400000000000001
183 >>> round(a, 1) # round() first converts to binary floating point
184 1.3
185 >>> int(a)
186 1
187 >>> a * 5
Raymond Hettingerabe32372008-02-14 02:41:22 +0000188 Decimal('6.70')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000189 >>> a * b
Raymond Hettingerabe32372008-02-14 02:41:22 +0000190 Decimal('2.5058')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000191 >>> c % a
Raymond Hettingerabe32372008-02-14 02:41:22 +0000192 Decimal('0.77')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000193
Andrew M. Kuchling6d407e42007-09-24 23:46:28 +0000194And some mathematical functions are also available to Decimal::
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000195
196 >>> Decimal(2).sqrt()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000197 Decimal('1.414213562373095048801688724')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000198 >>> Decimal(1).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000199 Decimal('2.718281828459045235360287471')
200 >>> Decimal('10').ln()
201 Decimal('2.302585092994045684017991455')
202 >>> Decimal('10').log10()
203 Decimal('1')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000204
Georg Brandl8ec7f652007-08-15 14:28:01 +0000205The :meth:`quantize` method rounds a number to a fixed exponent. This method is
206useful for monetary applications that often round results to a fixed number of
207places::
208
209 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000210 Decimal('7.32')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000211 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000212 Decimal('8')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000213
214As shown above, the :func:`getcontext` function accesses the current context and
215allows the settings to be changed. This approach meets the needs of most
216applications.
217
218For more advanced work, it may be useful to create alternate contexts using the
219Context() constructor. To make an alternate active, use the :func:`setcontext`
220function.
221
222In accordance with the standard, the :mod:`Decimal` module provides two ready to
223use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
224former is especially useful for debugging because many of the traps are
225enabled::
226
227 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
228 >>> setcontext(myothercontext)
229 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000230 Decimal('0.142857142857142857142857142857142857142857142857142857142857')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000231
232 >>> ExtendedContext
233 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
234 capitals=1, flags=[], traps=[])
235 >>> setcontext(ExtendedContext)
236 >>> Decimal(1) / Decimal(7)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000237 Decimal('0.142857143')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000238 >>> Decimal(42) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000239 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000240
241 >>> setcontext(BasicContext)
242 >>> Decimal(42) / Decimal(0)
243 Traceback (most recent call last):
244 File "<pyshell#143>", line 1, in -toplevel-
245 Decimal(42) / Decimal(0)
246 DivisionByZero: x / 0
247
248Contexts also have signal flags for monitoring exceptional conditions
249encountered during computations. The flags remain set until explicitly cleared,
250so it is best to clear the flags before each set of monitored computations by
251using the :meth:`clear_flags` method. ::
252
253 >>> setcontext(ExtendedContext)
254 >>> getcontext().clear_flags()
255 >>> Decimal(355) / Decimal(113)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000256 Decimal('3.14159292')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000257 >>> getcontext()
258 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
259 capitals=1, flags=[Inexact, Rounded], traps=[])
260
261The *flags* entry shows that the rational approximation to :const:`Pi` was
262rounded (digits beyond the context precision were thrown away) and that the
263result is inexact (some of the discarded digits were non-zero).
264
265Individual traps are set using the dictionary in the :attr:`traps` field of a
266context::
267
268 >>> Decimal(1) / Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000269 Decimal('Infinity')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000270 >>> getcontext().traps[DivisionByZero] = 1
271 >>> Decimal(1) / Decimal(0)
272 Traceback (most recent call last):
273 File "<pyshell#112>", line 1, in -toplevel-
274 Decimal(1) / Decimal(0)
275 DivisionByZero: x / 0
276
277Most programs adjust the current context only once, at the beginning of the
278program. And, in many applications, data is converted to :class:`Decimal` with
279a single cast inside a loop. With context set and decimals created, the bulk of
280the program manipulates the data no differently than with other Python numeric
281types.
282
Georg Brandlb19be572007-12-29 10:57:00 +0000283.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000284
285
286.. _decimal-decimal:
287
288Decimal objects
289---------------
290
291
292.. class:: Decimal([value [, context]])
293
Georg Brandlb19be572007-12-29 10:57:00 +0000294 Construct a new :class:`Decimal` object based from *value*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000295
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000296 *value* can be an integer, string, tuple, or another :class:`Decimal`
Raymond Hettingerabe32372008-02-14 02:41:22 +0000297 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000298 string, it should conform to the decimal numeric string syntax after leading
299 and trailing whitespace characters are removed::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000300
301 sign ::= '+' | '-'
302 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
303 indicator ::= 'e' | 'E'
304 digits ::= digit [digit]...
305 decimal-part ::= digits '.' [digits] | ['.'] digits
306 exponent-part ::= indicator [sign] digits
307 infinity ::= 'Infinity' | 'Inf'
308 nan ::= 'NaN' [digits] | 'sNaN' [digits]
309 numeric-value ::= decimal-part [exponent-part] | infinity
310 numeric-string ::= [sign] numeric-value | [sign] nan
311
312 If *value* is a :class:`tuple`, it should have three components, a sign
313 (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
314 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
Raymond Hettingerabe32372008-02-14 02:41:22 +0000315 returns ``Decimal('1.414')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000316
317 The *context* precision does not affect how many digits are stored. That is
318 determined exclusively by the number of digits in *value*. For example,
Raymond Hettingerabe32372008-02-14 02:41:22 +0000319 ``Decimal('3.00000')`` records all five zeros even if the context precision is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000320 only three.
321
322 The purpose of the *context* argument is determining what to do if *value* is a
323 malformed string. If the context traps :const:`InvalidOperation`, an exception
324 is raised; otherwise, the constructor returns a new Decimal with the value of
325 :const:`NaN`.
326
327 Once constructed, :class:`Decimal` objects are immutable.
328
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000329 .. versionchanged:: 2.6
330 leading and trailing whitespace characters are permitted when
331 creating a Decimal instance from a string.
332
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000333Decimal floating point objects share many properties with the other built-in
Georg Brandl8ec7f652007-08-15 14:28:01 +0000334numeric types such as :class:`float` and :class:`int`. All of the usual math
335operations and special methods apply. Likewise, decimal objects can be copied,
336pickled, printed, used as dictionary keys, used as set elements, compared,
337sorted, and coerced to another type (such as :class:`float` or :class:`long`).
338
339In addition to the standard numeric properties, decimal floating point objects
340also have a number of specialized methods:
341
342
343.. method:: Decimal.adjusted()
344
345 Return the adjusted exponent after shifting out the coefficient's rightmost
Raymond Hettingerabe32372008-02-14 02:41:22 +0000346 digits until only the lead digit remains: ``Decimal('321e+5').adjusted()``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000347 returns seven. Used for determining the position of the most significant digit
348 with respect to the decimal point.
349
350
351.. method:: Decimal.as_tuple()
352
Georg Brandle3c3db52008-01-11 09:55:53 +0000353 Return a :term:`named tuple` representation of the number:
354 ``DecimalTuple(sign, digits, exponent)``.
355
356 .. versionchanged:: 2.6
357 Use a named tuple.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000358
359
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000360.. method:: Decimal.canonical()
361
362 Return the canonical encoding of the argument. Currently, the
363 encoding of a :class:`Decimal` instance is always canonical, so
364 this operation returns its argument unchanged.
365
366 .. versionadded:: 2.6
367
Georg Brandl8ec7f652007-08-15 14:28:01 +0000368.. method:: Decimal.compare(other[, context])
369
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000370 Compare the values of two Decimal instances. This operation
371 behaves in the same way as the usual comparison method
372 :meth:`__cmp__`, except that :meth:`compare` returns a Decimal
373 instance rather than an integer, and if either operand is a NaN
374 then the result is a NaN::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000375
Raymond Hettingerabe32372008-02-14 02:41:22 +0000376 a or b is a NaN ==> Decimal('NaN')
377 a < b ==> Decimal('-1')
378 a == b ==> Decimal('0')
379 a > b ==> Decimal('1')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000380
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000381.. method:: Decimal.compare_signal(other[, context])
382
383 This operation is identical to the :meth:`compare` method, except
384 that all NaNs signal. That is, if neither operand is a signaling
385 NaN then any quiet NaN operand is treated as though it were a
386 signaling NaN.
387
388 .. versionadded:: 2.6
389
390.. method:: Decimal.compare_total(other)
391
392 Compare two operands using their abstract representation rather
393 than their numerical value. Similar to the :meth:`compare` method,
394 but the result gives a total ordering on :class:`Decimal`
395 instances. Two :class:`Decimal` instances with the same numeric
396 value but different representations compare unequal in this
397 ordering::
398
Raymond Hettingerabe32372008-02-14 02:41:22 +0000399 >>> Decimal('12.0').compare_total(Decimal('12'))
400 Decimal('-1')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000401
402 Quiet and signaling NaNs are also included in the total ordering.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000403 The result of this function is ``Decimal('0')`` if both operands
404 have the same representation, ``Decimal('-1')`` if the first
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000405 operand is lower in the total order than the second, and
Raymond Hettingerabe32372008-02-14 02:41:22 +0000406 ``Decimal('1')`` if the first operand is higher in the total order
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000407 than the second operand. See the specification for details of the
408 total order.
409
410 .. versionadded:: 2.6
411
412.. method:: Decimal.compare_total_mag(other)
413
414 Compare two operands using their abstract representation rather
415 than their value as in :meth:`compare_total`, but ignoring the sign
416 of each operand. ``x.compare_total_mag(y)`` is equivalent to
417 ``x.copy_abs().compare_total(y.copy_abs())``.
418
419 .. versionadded:: 2.6
420
421.. method:: Decimal.copy_abs()
422
423 Return the absolute value of the argument. This operation is
424 unaffected by the context and is quiet: no flags are changed and no
425 rounding is performed.
426
427 .. versionadded:: 2.6
428
429.. method:: Decimal.copy_negate()
430
431 Return the negation of the argument. This operation is unaffected
432 by the context and is quiet: no flags are changed and no rounding
433 is performed.
434
435 .. versionadded:: 2.6
436
437.. method:: Decimal.copy_sign(other)
438
439 Return a copy of the first operand with the sign set to be the
440 same as the sign of the second operand. For example::
441
Raymond Hettingerabe32372008-02-14 02:41:22 +0000442 >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
443 Decimal('-2.3')
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000444
445 This operation is unaffected by the context and is quiet: no flags
446 are changed and no rounding is performed.
447
448 .. versionadded:: 2.6
449
450.. method:: Decimal.exp([context])
451
452 Return the value of the (natural) exponential function ``e**x`` at the
453 given number. The result is correctly rounded using the
454 :const:`ROUND_HALF_EVEN` rounding mode.
455
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000456 >>> Decimal(1).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000457 Decimal('2.718281828459045235360287471')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000458 >>> Decimal(321).exp()
Raymond Hettingerabe32372008-02-14 02:41:22 +0000459 Decimal('2.561702493119680037517373933E+139')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000460
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000461 .. versionadded:: 2.6
462
463.. method:: Decimal.fma(other, third[, context])
464
465 Fused multiply-add. Return self*other+third with no rounding of
466 the intermediate product self*other.
467
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000468 >>> Decimal(2).fma(3, 5)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000469 Decimal('11')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000470
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000471 .. versionadded:: 2.6
472
473.. method:: Decimal.is_canonical()
474
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000475 Return :const:`True` if the argument is canonical and
476 :const:`False` otherwise. Currently, a :class:`Decimal` instance
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000477 is always canonical, so this operation always returns
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000478 :const:`True`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000479
480 .. versionadded:: 2.6
481
482.. method:: is_finite()
483
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000484 Return :const:`True` if the argument is a finite number, and
485 :const:`False` if the argument is an infinity or a NaN.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000486
487 .. versionadded:: 2.6
488
489.. method:: is_infinite()
490
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000491 Return :const:`True` if the argument is either positive or
492 negative infinity and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000493
494 .. versionadded:: 2.6
495
496.. method:: is_nan()
497
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000498 Return :const:`True` if the argument is a (quiet or signaling)
499 NaN and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000500
501 .. versionadded:: 2.6
502
503.. method:: is_normal()
504
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000505 Return :const:`True` if the argument is a *normal* finite number.
506 Return :const:`False` if the argument is zero, subnormal, infinite
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000507 or a NaN.
508
509 .. versionadded:: 2.6
510
511.. method:: is_qnan()
512
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000513 Return :const:`True` if the argument is a quiet NaN, and
514 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000515
516 .. versionadded:: 2.6
517
518.. method:: is_signed()
519
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000520 Return :const:`True` if the argument has a negative sign and
521 :const:`False` otherwise. Note that zeros and NaNs can both carry
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000522 signs.
523
524 .. versionadded:: 2.6
525
526.. method:: is_snan()
527
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000528 Return :const:`True` if the argument is a signaling NaN and
529 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000530
531 .. versionadded:: 2.6
532
533.. method:: is_subnormal()
534
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000535 Return :const:`True` if the argument is subnormal, and
536 :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000537
538 .. versionadded:: 2.6
539
540.. method:: is_zero()
541
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000542 Return :const:`True` if the argument is a (positive or negative)
543 zero and :const:`False` otherwise.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000544
545 .. versionadded:: 2.6
546
547.. method:: Decimal.ln([context])
548
549 Return the natural (base e) logarithm of the operand. The result
550 is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
551 mode.
552
553 .. versionadded:: 2.6
554
555.. method:: Decimal.log10([context])
556
557 Return the base ten logarithm of the operand. The result is
558 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
559
560 .. versionadded:: 2.6
561
Georg Brandlb19be572007-12-29 10:57:00 +0000562.. method:: Decimal.logb([context])
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000563
564 For a nonzero number, return the adjusted exponent of its operand
565 as a :class:`Decimal` instance. If the operand is a zero then
Raymond Hettingerabe32372008-02-14 02:41:22 +0000566 ``Decimal('-Infinity')`` is returned and the
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000567 :const:`DivisionByZero` flag is raised. If the operand is an
Raymond Hettingerabe32372008-02-14 02:41:22 +0000568 infinity then ``Decimal('Infinity')`` is returned.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000569
570 .. versionadded:: 2.6
571
572.. method:: Decimal.logical_and(other[, context])
573
574 :meth:`logical_and` is a logical operation which takes two
575 *logical operands* (see :ref:`logical_operands_label`). The result
576 is the digit-wise ``and`` of the two operands.
577
578 .. versionadded:: 2.6
579
580.. method:: Decimal.logical_invert(other[, context])
581
582 :meth:`logical_invert` is a logical operation. The argument must
583 be a *logical operand* (see :ref:`logical_operands_label`). The
584 result is the digit-wise inversion of the operand.
585
586 .. versionadded:: 2.6
587
588.. method:: Decimal.logical_or(other[, context])
589
590 :meth:`logical_or` is a logical operation which takes two *logical
591 operands* (see :ref:`logical_operands_label`). The result is the
592 digit-wise ``or`` of the two operands.
593
594 .. versionadded:: 2.6
595
596.. method:: Decimal.logical_xor(other[, context])
597
598 :meth:`logical_xor` is a logical operation which takes two
599 *logical operands* (see :ref:`logical_operands_label`). The result
600 is the digit-wise exclusive or of the two operands.
601
602 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000603
604.. method:: Decimal.max(other[, context])
605
606 Like ``max(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000607 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000608 (depending on the context and whether they are signaling or quiet).
609
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000610.. method:: Decimal.max_mag(other[, context])
611
612 Similar to the :meth:`max` method, but the comparison is done using
613 the absolute values of the operands.
614
615 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000616
617.. method:: Decimal.min(other[, context])
618
619 Like ``min(self, other)`` except that the context rounding rule is applied
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000620 before returning and that :const:`NaN` values are either signaled or ignored
Georg Brandl8ec7f652007-08-15 14:28:01 +0000621 (depending on the context and whether they are signaling or quiet).
622
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000623.. method:: Decimal.min_mag(other[, context])
624
625 Similar to the :meth:`min` method, but the comparison is done using
626 the absolute values of the operands.
627
628 .. versionadded:: 2.6
629
630.. method:: Decimal.next_minus([context])
631
632 Return the largest number representable in the given context (or
633 in the current thread's context if no context is given) that is smaller
634 than the given operand.
635
636 .. versionadded:: 2.6
637
638.. method:: Decimal.next_plus([context])
639
640 Return the smallest number representable in the given context (or
641 in the current thread's context if no context is given) that is
642 larger than the given operand.
643
644 .. versionadded:: 2.6
645
646.. method:: Decimal.next_toward(other[, context])
647
648 If the two operands are unequal, return the number closest to the
649 first operand in the direction of the second operand. If both
650 operands are numerically equal, return a copy of the first operand
651 with the sign set to be the same as the sign of the second operand.
652
653 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000654
655.. method:: Decimal.normalize([context])
656
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000657 Normalize the number by stripping the rightmost trailing zeros and converting
Raymond Hettingerabe32372008-02-14 02:41:22 +0000658 any result equal to :const:`Decimal('0')` to :const:`Decimal('0e0')`. Used for
Georg Brandl8ec7f652007-08-15 14:28:01 +0000659 producing canonical values for members of an equivalence class. For example,
Raymond Hettingerabe32372008-02-14 02:41:22 +0000660 ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both normalize to the
661 equivalent value ``Decimal('32.1')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000662
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000663.. method:: Decimal.number_class([context])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000664
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000665 Return a string describing the *class* of the operand. The
666 returned value is one of the following ten strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000667
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000668 * ``"-Infinity"``, indicating that the operand is negative infinity.
669 * ``"-Normal"``, indicating that the operand is a negative normal number.
670 * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
671 * ``"-Zero"``, indicating that the operand is a negative zero.
672 * ``"+Zero"``, indicating that the operand is a positive zero.
673 * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
674 * ``"+Normal"``, indicating that the operand is a positive normal number.
675 * ``"+Infinity"``, indicating that the operand is positive infinity.
676 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
677 * ``"sNaN"``, indicating that the operand is a signaling NaN.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000678
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000679 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000680
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000681.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]])
682
Georg Brandlb19be572007-12-29 10:57:00 +0000683 Return a value equal to the first operand after rounding and
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000684 having the exponent of the second operand.
685
Raymond Hettingerabe32372008-02-14 02:41:22 +0000686 >>> Decimal('1.41421356').quantize(Decimal('1.000'))
687 Decimal('1.414')
Facundo Batistae90bc3c2007-09-14 21:29:52 +0000688
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000689 Unlike other operations, if the length of the coefficient after the
690 quantize operation would be greater than precision, then an
691 :const:`InvalidOperation` is signaled. This guarantees that, unless
692 there is an error condition, the quantized exponent is always equal
693 to that of the right-hand operand.
694
695 Also unlike other operations, quantize never signals Underflow,
696 even if the result is subnormal and inexact.
697
698 If the exponent of the second operand is larger than that of the
699 first then rounding may be necessary. In this case, the rounding
700 mode is determined by the ``rounding`` argument if given, else by
701 the given ``context`` argument; if neither argument is given the
702 rounding mode of the current thread's context is used.
703
Georg Brandlb19be572007-12-29 10:57:00 +0000704 If *watchexp* is set (default), then an error is returned whenever the
705 resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000706
707.. method:: Decimal.radix()
708
709 Return ``Decimal(10)``, the radix (base) in which the
710 :class:`Decimal` class does all its arithmetic. Included for
711 compatibility with the specification.
712
713 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000714
715.. method:: Decimal.remainder_near(other[, context])
716
Georg Brandlb19be572007-12-29 10:57:00 +0000717 Compute the modulo as either a positive or negative value depending on which is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000718 closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns
Raymond Hettingerabe32372008-02-14 02:41:22 +0000719 ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000720
721 If both are equally close, the one chosen will have the same sign as *self*.
722
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000723.. method:: Decimal.rotate(other[, context])
724
725 Return the result of rotating the digits of the first operand by
726 an amount specified by the second operand. The second operand
727 must be an integer in the range -precision through precision. The
728 absolute value of the second operand gives the number of places to
729 rotate. If the second operand is positive then rotation is to the
730 left; otherwise rotation is to the right. The coefficient of the
731 first operand is padded on the left with zeros to length precision
732 if necessary. The sign and exponent of the first operand are
733 unchanged.
734
735 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000736
737.. method:: Decimal.same_quantum(other[, context])
738
739 Test whether self and other have the same exponent or whether both are
740 :const:`NaN`.
741
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000742.. method:: Decimal.scaleb(other[, context])
743
744 Return the first operand with exponent adjusted by the second.
745 Equivalently, return the first operand multiplied by ``10**other``.
746 The second operand must be an integer.
747
748 .. versionadded:: 2.6
749
750.. method:: Decimal.shift(other[, context])
751
752 Return the result of shifting the digits of the first operand by
753 an amount specified by the second operand. The second operand must
754 be an integer in the range -precision through precision. The
755 absolute value of the second operand gives the number of places to
756 shift. If the second operand is positive then the shift is to the
757 left; otherwise the shift is to the right. Digits shifted into the
758 coefficient are zeros. The sign and exponent of the first operand
759 are unchanged.
760
761 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +0000762
763.. method:: Decimal.sqrt([context])
764
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000765 Return the square root of the argument to full precision.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000766
767
768.. method:: Decimal.to_eng_string([context])
769
770 Convert to an engineering-type string.
771
772 Engineering notation has an exponent which is a multiple of 3, so there are up
773 to 3 digits left of the decimal place. For example, converts
Raymond Hettingerabe32372008-02-14 02:41:22 +0000774 ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000775
Georg Brandl8ec7f652007-08-15 14:28:01 +0000776.. method:: Decimal.to_integral([rounding[, context]])
777
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000778 Identical to the :meth:`to_integral_value` method. The ``to_integral``
779 name has been kept for compatibility with older versions.
780
781.. method:: Decimal.to_integral_exact([rounding[, context]])
782
Georg Brandlb19be572007-12-29 10:57:00 +0000783 Round to the nearest integer, signaling
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000784 :const:`Inexact` or :const:`Rounded` as appropriate if rounding
785 occurs. The rounding mode is determined by the ``rounding``
786 parameter if given, else by the given ``context``. If neither
787 parameter is given then the rounding mode of the current context is
788 used.
789
790 .. versionadded:: 2.6
791
792.. method:: Decimal.to_integral_value([rounding[, context]])
793
Georg Brandlb19be572007-12-29 10:57:00 +0000794 Round to the nearest integer without signaling :const:`Inexact` or
Georg Brandl8ec7f652007-08-15 14:28:01 +0000795 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding
796 method in either the supplied *context* or the current context.
797
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000798 .. versionchanged:: 2.6
799 renamed from ``to_integral`` to ``to_integral_value``. The old name
800 remains valid for compatibility.
801
802.. method:: Decimal.trim()
803
Georg Brandlb19be572007-12-29 10:57:00 +0000804 Return the decimal with *insignificant* trailing zeros removed.
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000805 Here, a trailing zero is considered insignificant either if it
806 follows the decimal point, or if the exponent of the argument (that
807 is, the last element of the :meth:`as_tuple` representation) is
808 positive.
809
810 .. versionadded:: 2.6
811
812.. _logical_operands_label:
813
814Logical operands
815^^^^^^^^^^^^^^^^
816
817The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
818and :meth:`logical_xor` methods expect their arguments to be *logical
819operands*. A *logical operand* is a :class:`Decimal` instance whose
820exponent and sign are both zero, and whose digits are all either
821:const:`0` or :const:`1`.
822
Georg Brandlb19be572007-12-29 10:57:00 +0000823.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +0000824
825
826.. _decimal-context:
827
828Context objects
829---------------
830
831Contexts are environments for arithmetic operations. They govern precision, set
832rules for rounding, determine which signals are treated as exceptions, and limit
833the range for exponents.
834
835Each thread has its own current context which is accessed or changed using the
836:func:`getcontext` and :func:`setcontext` functions:
837
838
839.. function:: getcontext()
840
841 Return the current context for the active thread.
842
843
844.. function:: setcontext(c)
845
846 Set the current context for the active thread to *c*.
847
848Beginning with Python 2.5, you can also use the :keyword:`with` statement and
849the :func:`localcontext` function to temporarily change the active context.
850
851
852.. function:: localcontext([c])
853
854 Return a context manager that will set the current context for the active thread
855 to a copy of *c* on entry to the with-statement and restore the previous context
856 when exiting the with-statement. If no context is specified, a copy of the
857 current context is used.
858
859 .. versionadded:: 2.5
860
861 For example, the following code sets the current decimal precision to 42 places,
862 performs a calculation, and then automatically restores the previous context::
863
Georg Brandl8ec7f652007-08-15 14:28:01 +0000864 from decimal import localcontext
865
866 with localcontext() as ctx:
867 ctx.prec = 42 # Perform a high precision calculation
868 s = calculate_something()
869 s = +s # Round the final result back to the default precision
870
871New contexts can also be created using the :class:`Context` constructor
872described below. In addition, the module provides three pre-made contexts:
873
874
875.. class:: BasicContext
876
877 This is a standard context defined by the General Decimal Arithmetic
878 Specification. Precision is set to nine. Rounding is set to
879 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated
880 as exceptions) except :const:`Inexact`, :const:`Rounded`, and
881 :const:`Subnormal`.
882
883 Because many of the traps are enabled, this context is useful for debugging.
884
885
886.. class:: ExtendedContext
887
888 This is a standard context defined by the General Decimal Arithmetic
889 Specification. Precision is set to nine. Rounding is set to
890 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that
891 exceptions are not raised during computations).
892
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000893 Because the traps are disabled, this context is useful for applications that
Georg Brandl8ec7f652007-08-15 14:28:01 +0000894 prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
895 raising exceptions. This allows an application to complete a run in the
896 presence of conditions that would otherwise halt the program.
897
898
899.. class:: DefaultContext
900
901 This context is used by the :class:`Context` constructor as a prototype for new
902 contexts. Changing a field (such a precision) has the effect of changing the
903 default for new contexts creating by the :class:`Context` constructor.
904
905 This context is most useful in multi-threaded environments. Changing one of the
906 fields before threads are started has the effect of setting system-wide
907 defaults. Changing the fields after threads have started is not recommended as
908 it would require thread synchronization to prevent race conditions.
909
910 In single threaded environments, it is preferable to not use this context at
911 all. Instead, simply create contexts explicitly as described below.
912
913 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
914 for Overflow, InvalidOperation, and DivisionByZero.
915
916In addition to the three supplied contexts, new contexts can be created with the
917:class:`Context` constructor.
918
919
920.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
921
922 Creates a new context. If a field is not specified or is :const:`None`, the
923 default values are copied from the :const:`DefaultContext`. If the *flags*
924 field is not specified or is :const:`None`, all flags are cleared.
925
926 The *prec* field is a positive integer that sets the precision for arithmetic
927 operations in the context.
928
929 The *rounding* option is one of:
930
931 * :const:`ROUND_CEILING` (towards :const:`Infinity`),
932 * :const:`ROUND_DOWN` (towards zero),
933 * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
934 * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
935 * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
936 * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
937 * :const:`ROUND_UP` (away from zero).
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000938 * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
939 would have been 0 or 5; otherwise towards zero)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000940
941 The *traps* and *flags* fields list any signals to be set. Generally, new
942 contexts should only set traps and leave the flags clear.
943
944 The *Emin* and *Emax* fields are integers specifying the outer limits allowable
945 for exponents.
946
947 The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
948 :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
949 lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
950
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000951 .. versionchanged:: 2.6
952 The :const:`ROUND_05UP` rounding mode was added.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000953
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000954The :class:`Context` class defines several general purpose methods as
955well as a large number of methods for doing arithmetic directly in a
956given context. In addition, for each of the :class:`Decimal` methods
957described above (with the exception of the :meth:`adjusted` and
958:meth:`as_tuple` methods) there is a corresponding :class:`Context`
959method. For example, ``C.exp(x)`` is equivalent to
960``x.exp(context=C)``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000961
962.. method:: Context.clear_flags()
963
964 Resets all of the flags to :const:`0`.
965
966
967.. method:: Context.copy()
968
969 Return a duplicate of the context.
970
Facundo Batista7c82a3e92007-09-14 18:58:34 +0000971.. method:: Context.copy_decimal(num)
972
973 Return a copy of the Decimal instance num.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000974
975.. method:: Context.create_decimal(num)
976
977 Creates a new Decimal instance from *num* but using *self* as context. Unlike
978 the :class:`Decimal` constructor, the context precision, rounding method, flags,
979 and traps are applied to the conversion.
980
981 This is useful because constants are often given to a greater precision than is
982 needed by the application. Another benefit is that rounding immediately
983 eliminates unintended effects from digits beyond the current precision. In the
984 following example, using unrounded inputs means that adding zero to a sum can
985 change the result::
986
987 >>> getcontext().prec = 3
Raymond Hettingerabe32372008-02-14 02:41:22 +0000988 >>> Decimal('3.4445') + Decimal('1.0023')
989 Decimal('4.45')
990 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
991 Decimal('4.44')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000992
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000993 This method implements the to-number operation of the IBM
994 specification. If the argument is a string, no leading or trailing
995 whitespace is permitted.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000996
997.. method:: Context.Etiny()
998
999 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
1000 for subnormal results. When underflow occurs, the exponent is set to
1001 :const:`Etiny`.
1002
1003
1004.. method:: Context.Etop()
1005
1006 Returns a value equal to ``Emax - prec + 1``.
1007
1008The usual approach to working with decimals is to create :class:`Decimal`
1009instances and then apply arithmetic operations which take place within the
Georg Brandl5d242ee2007-09-20 08:44:59 +00001010current context for the active thread. An alternative approach is to use context
Georg Brandl8ec7f652007-08-15 14:28:01 +00001011methods for calculating within a specific context. The methods are similar to
1012those for the :class:`Decimal` class and are only briefly recounted here.
1013
1014
1015.. method:: Context.abs(x)
1016
1017 Returns the absolute value of *x*.
1018
1019
1020.. method:: Context.add(x, y)
1021
1022 Return the sum of *x* and *y*.
1023
1024
Georg Brandl8ec7f652007-08-15 14:28:01 +00001025.. method:: Context.divide(x, y)
1026
1027 Return *x* divided by *y*.
1028
1029
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001030.. method:: Context.divide_int(x, y)
1031
1032 Return *x* divided by *y*, truncated to an integer.
1033
1034
Georg Brandl8ec7f652007-08-15 14:28:01 +00001035.. method:: Context.divmod(x, y)
1036
1037 Divides two numbers and returns the integer part of the result.
1038
1039
Georg Brandl8ec7f652007-08-15 14:28:01 +00001040.. method:: Context.minus(x)
1041
1042 Minus corresponds to the unary prefix minus operator in Python.
1043
1044
1045.. method:: Context.multiply(x, y)
1046
1047 Return the product of *x* and *y*.
1048
1049
Georg Brandl8ec7f652007-08-15 14:28:01 +00001050.. method:: Context.plus(x)
1051
1052 Plus corresponds to the unary prefix plus operator in Python. This operation
1053 applies the context precision and rounding, so it is *not* an identity
1054 operation.
1055
1056
1057.. method:: Context.power(x, y[, modulo])
1058
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001059 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if
1060 given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001061
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001062 With two arguments, compute ``x**y``. If ``x`` is negative then
1063 ``y`` must be integral. The result will be inexact unless ``y`` is
1064 integral and the result is finite and can be expressed exactly in
1065 'precision' digits. The result should always be correctly rounded,
1066 using the rounding mode of the current thread's context.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001067
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001068 With three arguments, compute ``(x**y) % modulo``. For the three
1069 argument form, the following restrictions on the arguments hold:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001070
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001071 - all three arguments must be integral
1072 - ``y`` must be nonnegative
1073 - at least one of ``x`` or ``y`` must be nonzero
1074 - ``modulo`` must be nonzero and have at most 'precision' digits
Georg Brandl8ec7f652007-08-15 14:28:01 +00001075
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001076 The result of ``Context.power(x, y, modulo)`` is identical to
1077 the result that would be obtained by computing ``(x**y) %
1078 modulo`` with unbounded precision, but is computed more
1079 efficiently. It is always exact.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001080
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001081 .. versionchanged:: 2.6
1082 ``y`` may now be nonintegral in ``x**y``.
1083 Stricter requirements for the three-argument version.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001084
1085
1086.. method:: Context.remainder(x, y)
1087
1088 Returns the remainder from integer division.
1089
1090 The sign of the result, if non-zero, is the same as that of the original
1091 dividend.
1092
Georg Brandl8ec7f652007-08-15 14:28:01 +00001093.. method:: Context.subtract(x, y)
1094
1095 Return the difference between *x* and *y*.
1096
Georg Brandl8ec7f652007-08-15 14:28:01 +00001097.. method:: Context.to_sci_string(x)
1098
1099 Converts a number to a string using scientific notation.
1100
Georg Brandlb19be572007-12-29 10:57:00 +00001101.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001102
1103
1104.. _decimal-signals:
1105
1106Signals
1107-------
1108
1109Signals represent conditions that arise during computation. Each corresponds to
1110one context flag and one context trap enabler.
1111
1112The context flag is incremented whenever the condition is encountered. After the
1113computation, flags may be checked for informational purposes (for instance, to
1114determine whether a computation was exact). After checking the flags, be sure to
1115clear all flags before starting the next computation.
1116
1117If the context's trap enabler is set for the signal, then the condition causes a
1118Python exception to be raised. For example, if the :class:`DivisionByZero` trap
1119is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1120condition.
1121
1122
1123.. class:: Clamped
1124
1125 Altered an exponent to fit representation constraints.
1126
1127 Typically, clamping occurs when an exponent falls outside the context's
1128 :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001129 fit by adding zeros to the coefficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001130
1131
1132.. class:: DecimalException
1133
1134 Base class for other signals and a subclass of :exc:`ArithmeticError`.
1135
1136
1137.. class:: DivisionByZero
1138
1139 Signals the division of a non-infinite number by zero.
1140
1141 Can occur with division, modulo division, or when raising a number to a negative
1142 power. If this signal is not trapped, returns :const:`Infinity` or
1143 :const:`-Infinity` with the sign determined by the inputs to the calculation.
1144
1145
1146.. class:: Inexact
1147
1148 Indicates that rounding occurred and the result is not exact.
1149
1150 Signals when non-zero digits were discarded during rounding. The rounded result
1151 is returned. The signal flag or trap is used to detect when results are
1152 inexact.
1153
1154
1155.. class:: InvalidOperation
1156
1157 An invalid operation was performed.
1158
1159 Indicates that an operation was requested that does not make sense. If not
1160 trapped, returns :const:`NaN`. Possible causes include::
1161
1162 Infinity - Infinity
1163 0 * Infinity
1164 Infinity / Infinity
1165 x % 0
1166 Infinity % x
1167 x._rescale( non-integer )
1168 sqrt(-x) and x > 0
1169 0 ** 0
1170 x ** (non-integer)
1171 x ** Infinity
1172
1173
1174.. class:: Overflow
1175
1176 Numerical overflow.
1177
1178 Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
1179 If not trapped, the result depends on the rounding mode, either pulling inward
1180 to the largest representable finite number or rounding outward to
1181 :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are
1182 also signaled.
1183
1184
1185.. class:: Rounded
1186
1187 Rounding occurred though possibly no information was lost.
1188
1189 Signaled whenever rounding discards digits; even if those digits are zero (such
1190 as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result
1191 unchanged. This signal is used to detect loss of significant digits.
1192
1193
1194.. class:: Subnormal
1195
1196 Exponent was lower than :attr:`Emin` prior to rounding.
1197
1198 Occurs when an operation result is subnormal (the exponent is too small). If not
1199 trapped, returns the result unchanged.
1200
1201
1202.. class:: Underflow
1203
1204 Numerical underflow with result rounded to zero.
1205
1206 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1207 and :class:`Subnormal` are also signaled.
1208
1209The following table summarizes the hierarchy of signals::
1210
1211 exceptions.ArithmeticError(exceptions.StandardError)
1212 DecimalException
1213 Clamped
1214 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1215 Inexact
1216 Overflow(Inexact, Rounded)
1217 Underflow(Inexact, Rounded, Subnormal)
1218 InvalidOperation
1219 Rounded
1220 Subnormal
1221
Georg Brandlb19be572007-12-29 10:57:00 +00001222.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001223
1224
1225.. _decimal-notes:
1226
1227Floating Point Notes
1228--------------------
1229
1230
1231Mitigating round-off error with increased precision
1232^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1233
1234The use of decimal floating point eliminates decimal representation error
1235(making it possible to represent :const:`0.1` exactly); however, some operations
1236can still incur round-off error when non-zero digits exceed the fixed precision.
1237
1238The effects of round-off error can be amplified by the addition or subtraction
1239of nearly offsetting quantities resulting in loss of significance. Knuth
1240provides two instructive examples where rounded floating point arithmetic with
1241insufficient precision causes the breakdown of the associative and distributive
1242properties of addition::
1243
1244 # Examples from Seminumerical Algorithms, Section 4.2.2.
1245 >>> from decimal import Decimal, getcontext
1246 >>> getcontext().prec = 8
1247
1248 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1249 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001250 Decimal('9.5111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001251 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001252 Decimal('10')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001253
1254 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1255 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001256 Decimal('0.01')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001257 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001258 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001259
1260The :mod:`decimal` module makes it possible to restore the identities by
1261expanding the precision sufficiently to avoid loss of significance::
1262
1263 >>> getcontext().prec = 20
1264 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1265 >>> (u + v) + w
Raymond Hettingerabe32372008-02-14 02:41:22 +00001266 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001267 >>> u + (v + w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001268 Decimal('9.51111111')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001269 >>>
1270 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1271 >>> (u*v) + (u*w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001272 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001273 >>> u * (v+w)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001274 Decimal('0.0060000')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001275
1276
1277Special values
1278^^^^^^^^^^^^^^
1279
1280The number system for the :mod:`decimal` module provides special values
1281including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
Facundo Batista7c82a3e92007-09-14 18:58:34 +00001282and two zeros, :const:`+0` and :const:`-0`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001283
1284Infinities can be constructed directly with: ``Decimal('Infinity')``. Also,
1285they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1286not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1287can result from rounding beyond the limits of the largest representable number.
1288
1289The infinities are signed (affine) and can be used in arithmetic operations
1290where they get treated as very large, indeterminate numbers. For instance,
1291adding a constant to infinity gives another infinite result.
1292
1293Some operations are indeterminate and return :const:`NaN`, or if the
1294:exc:`InvalidOperation` signal is trapped, raise an exception. For example,
1295``0/0`` returns :const:`NaN` which means "not a number". This variety of
1296:const:`NaN` is quiet and, once created, will flow through other computations
1297always resulting in another :const:`NaN`. This behavior can be useful for a
1298series of computations that occasionally have missing inputs --- it allows the
1299calculation to proceed while flagging specific results as invalid.
1300
1301A variant is :const:`sNaN` which signals rather than remaining quiet after every
1302operation. This is a useful return value when an invalid result needs to
1303interrupt a calculation for special handling.
1304
Mark Dickinson2fc92632008-02-06 22:10:50 +00001305The behavior of Python's comparison operators can be a little surprising where a
1306:const:`NaN` is involved. A test for equality where one of the operands is a
1307quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1308``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
Mark Dickinsonbafa9422008-02-06 22:25:16 +00001309:const:`True`. An attempt to compare two Decimals using any of the ``<``,
Mark Dickinson00c2e652008-02-07 01:42:06 +00001310``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1311if either operand is a :const:`NaN`, and return :const:`False` if this signal is
Mark Dickinson3a94ee02008-02-10 15:19:58 +00001312not trapped. Note that the General Decimal Arithmetic specification does not
Mark Dickinson00c2e652008-02-07 01:42:06 +00001313specify the behavior of direct comparisons; these rules for comparisons
1314involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1315section 5.7). To ensure strict standards-compliance, use the :meth:`compare`
Mark Dickinson2fc92632008-02-06 22:10:50 +00001316and :meth:`compare-signal` methods instead.
1317
Georg Brandl8ec7f652007-08-15 14:28:01 +00001318The signed zeros can result from calculations that underflow. They keep the sign
1319that would have resulted if the calculation had been carried out to greater
1320precision. Since their magnitude is zero, both positive and negative zeros are
1321treated as equal and their sign is informational.
1322
1323In addition to the two signed zeros which are distinct yet equal, there are
1324various representations of zero with differing precisions yet equivalent in
1325value. This takes a bit of getting used to. For an eye accustomed to
1326normalized floating point representations, it is not immediately obvious that
1327the following calculation returns a value equal to zero::
1328
1329 >>> 1 / Decimal('Infinity')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001330 Decimal('0E-1000000026')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001331
Georg Brandlb19be572007-12-29 10:57:00 +00001332.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001333
1334
1335.. _decimal-threads:
1336
1337Working with threads
1338--------------------
1339
1340The :func:`getcontext` function accesses a different :class:`Context` object for
1341each thread. Having separate thread contexts means that threads may make
1342changes (such as ``getcontext.prec=10``) without interfering with other threads.
1343
1344Likewise, the :func:`setcontext` function automatically assigns its target to
1345the current thread.
1346
1347If :func:`setcontext` has not been called before :func:`getcontext`, then
1348:func:`getcontext` will automatically create a new context for use in the
1349current thread.
1350
1351The new context is copied from a prototype context called *DefaultContext*. To
1352control the defaults so that each thread will use the same values throughout the
1353application, directly modify the *DefaultContext* object. This should be done
1354*before* any threads are started so that there won't be a race condition between
1355threads calling :func:`getcontext`. For example::
1356
1357 # Set applicationwide defaults for all threads about to be launched
1358 DefaultContext.prec = 12
1359 DefaultContext.rounding = ROUND_DOWN
1360 DefaultContext.traps = ExtendedContext.traps.copy()
1361 DefaultContext.traps[InvalidOperation] = 1
1362 setcontext(DefaultContext)
1363
1364 # Afterwards, the threads can be started
1365 t1.start()
1366 t2.start()
1367 t3.start()
1368 . . .
1369
Georg Brandlb19be572007-12-29 10:57:00 +00001370.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001371
1372
1373.. _decimal-recipes:
1374
1375Recipes
1376-------
1377
1378Here are a few recipes that serve as utility functions and that demonstrate ways
1379to work with the :class:`Decimal` class::
1380
1381 def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1382 pos='', neg='-', trailneg=''):
1383 """Convert Decimal to a money formatted string.
1384
1385 places: required number of places after the decimal point
1386 curr: optional currency symbol before the sign (may be blank)
1387 sep: optional grouping separator (comma, period, space, or blank)
1388 dp: decimal point indicator (comma or period)
1389 only specify as blank when places is zero
1390 pos: optional sign for positive numbers: '+', space or blank
1391 neg: optional sign for negative numbers: '-', '(', space or blank
1392 trailneg:optional trailing minus indicator: '-', ')', space or blank
1393
1394 >>> d = Decimal('-1234567.8901')
1395 >>> moneyfmt(d, curr='$')
1396 '-$1,234,567.89'
1397 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1398 '1.234.568-'
1399 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1400 '($1,234,567.89)'
1401 >>> moneyfmt(Decimal(123456789), sep=' ')
1402 '123 456 789.00'
1403 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1404 '<.02>'
1405
1406 """
1407 q = Decimal((0, (1,), -places)) # 2 places --> '0.01'
1408 sign, digits, exp = value.quantize(q).as_tuple()
1409 assert exp == -places
1410 result = []
1411 digits = map(str, digits)
1412 build, next = result.append, digits.pop
1413 if sign:
1414 build(trailneg)
1415 for i in range(places):
1416 if digits:
1417 build(next())
1418 else:
1419 build('0')
1420 build(dp)
1421 i = 0
1422 while digits:
1423 build(next())
1424 i += 1
1425 if i == 3 and digits:
1426 i = 0
1427 build(sep)
1428 build(curr)
1429 if sign:
1430 build(neg)
1431 else:
1432 build(pos)
1433 result.reverse()
1434 return ''.join(result)
1435
1436 def pi():
1437 """Compute Pi to the current precision.
1438
1439 >>> print pi()
1440 3.141592653589793238462643383
1441
1442 """
1443 getcontext().prec += 2 # extra digits for intermediate steps
1444 three = Decimal(3) # substitute "three=3.0" for regular floats
1445 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1446 while s != lasts:
1447 lasts = s
1448 n, na = n+na, na+8
1449 d, da = d+da, da+32
1450 t = (t * n) / d
1451 s += t
1452 getcontext().prec -= 2
1453 return +s # unary plus applies the new precision
1454
1455 def exp(x):
1456 """Return e raised to the power of x. Result type matches input type.
1457
1458 >>> print exp(Decimal(1))
1459 2.718281828459045235360287471
1460 >>> print exp(Decimal(2))
1461 7.389056098930650227230427461
1462 >>> print exp(2.0)
1463 7.38905609893
1464 >>> print exp(2+0j)
1465 (7.38905609893+0j)
1466
1467 """
1468 getcontext().prec += 2
1469 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1470 while s != lasts:
1471 lasts = s
1472 i += 1
1473 fact *= i
1474 num *= x
1475 s += num / fact
1476 getcontext().prec -= 2
1477 return +s
1478
1479 def cos(x):
1480 """Return the cosine of x as measured in radians.
1481
1482 >>> print cos(Decimal('0.5'))
1483 0.8775825618903727161162815826
1484 >>> print cos(0.5)
1485 0.87758256189
1486 >>> print cos(0.5+0j)
1487 (0.87758256189+0j)
1488
1489 """
1490 getcontext().prec += 2
1491 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1492 while s != lasts:
1493 lasts = s
1494 i += 2
1495 fact *= i * (i-1)
1496 num *= x * x
1497 sign *= -1
1498 s += num / fact * sign
1499 getcontext().prec -= 2
1500 return +s
1501
1502 def sin(x):
1503 """Return the sine of x as measured in radians.
1504
1505 >>> print sin(Decimal('0.5'))
1506 0.4794255386042030002732879352
1507 >>> print sin(0.5)
1508 0.479425538604
1509 >>> print sin(0.5+0j)
1510 (0.479425538604+0j)
1511
1512 """
1513 getcontext().prec += 2
1514 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1515 while s != lasts:
1516 lasts = s
1517 i += 2
1518 fact *= i * (i-1)
1519 num *= x * x
1520 sign *= -1
1521 s += num / fact * sign
1522 getcontext().prec -= 2
1523 return +s
1524
1525
Georg Brandlb19be572007-12-29 10:57:00 +00001526.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Georg Brandl8ec7f652007-08-15 14:28:01 +00001527
1528
1529.. _decimal-faq:
1530
1531Decimal FAQ
1532-----------
1533
1534Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to
1535minimize typing when using the interactive interpreter?
1536
1537\A. Some users abbreviate the constructor to just a single letter::
1538
1539 >>> D = decimal.Decimal
1540 >>> D('1.23') + D('3.45')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001541 Decimal('4.68')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001542
1543Q. In a fixed-point application with two decimal places, some inputs have many
1544places and need to be rounded. Others are not supposed to have excess digits
1545and need to be validated. What methods should be used?
1546
1547A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
1548the :const:`Inexact` trap is set, it is also useful for validation::
1549
1550 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1551
1552 >>> # Round to two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001553 >>> Decimal('3.214').quantize(TWOPLACES)
1554 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001555
1556 >>> # Validate that a number does not exceed two places
Raymond Hettingerabe32372008-02-14 02:41:22 +00001557 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1558 Decimal('3.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001559
Raymond Hettingerabe32372008-02-14 02:41:22 +00001560 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Georg Brandl8ec7f652007-08-15 14:28:01 +00001561 Traceback (most recent call last):
1562 ...
1563 Inexact: Changed in rounding
1564
1565Q. Once I have valid two place inputs, how do I maintain that invariant
1566throughout an application?
1567
1568A. Some operations like addition and subtraction automatically preserve fixed
1569point. Others, like multiplication and division, change the number of decimal
1570places and need to be followed-up with a :meth:`quantize` step.
1571
1572Q. There are many ways to express the same value. The numbers :const:`200`,
1573:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1574various precisions. Is there a way to transform them to a single recognizable
1575canonical value?
1576
1577A. The :meth:`normalize` method maps all equivalent values to a single
1578representative::
1579
1580 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1581 >>> [v.normalize() for v in values]
Raymond Hettingerabe32372008-02-14 02:41:22 +00001582 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001583
1584Q. Some decimal values always print with exponential notation. Is there a way
1585to get a non-exponential representation?
1586
1587A. For some values, exponential notation is the only way to express the number
1588of significant places in the coefficient. For example, expressing
1589:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1590original's two-place significance.
1591
1592Q. Is there a way to convert a regular float to a :class:`Decimal`?
1593
1594A. Yes, all binary floating point numbers can be exactly expressed as a
1595Decimal. An exact conversion may take more precision than intuition would
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001596suggest, so we trap :const:`Inexact` to signal a need for more precision::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001597
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001598 def float_to_decimal(f):
1599 "Convert a floating point number to a Decimal with no loss of information"
1600 n, d = f.as_integer_ratio()
1601 with localcontext() as ctx:
1602 ctx.traps[Inexact] = True
1603 while True:
1604 try:
1605 return Decimal(n) / Decimal(d)
1606 except Inexact:
1607 ctx.prec += 1
Georg Brandl8ec7f652007-08-15 14:28:01 +00001608
Raymond Hettingerff1f9732008-02-07 20:04:37 +00001609 >>> float_to_decimal(math.pi)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001610 Decimal('3.141592653589793115997963468544185161590576171875')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001611
Raymond Hettinger23bdcc92008-02-07 20:10:49 +00001612Q. Why isn't the :func:`float_to_decimal` routine included in the module?
Georg Brandl8ec7f652007-08-15 14:28:01 +00001613
1614A. There is some question about whether it is advisable to mix binary and
1615decimal floating point. Also, its use requires some care to avoid the
1616representation issues associated with binary floating point::
1617
Raymond Hettinger23bdcc92008-02-07 20:10:49 +00001618 >>> float_to_decimal(1.1)
Raymond Hettingerabe32372008-02-14 02:41:22 +00001619 Decimal('1.100000000000000088817841970012523233890533447265625')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001620
1621Q. Within a complex calculation, how can I make sure that I haven't gotten a
1622spurious result because of insufficient precision or rounding anomalies.
1623
1624A. The decimal module makes it easy to test results. A best practice is to
1625re-run calculations using greater precision and with various rounding modes.
1626Widely differing results indicate insufficient precision, rounding mode issues,
1627ill-conditioned inputs, or a numerically unstable algorithm.
1628
1629Q. I noticed that context precision is applied to the results of operations but
1630not to the inputs. Is there anything to watch out for when mixing values of
1631different precisions?
1632
1633A. Yes. The principle is that all values are considered to be exact and so is
1634the arithmetic on those values. Only the results are rounded. The advantage
1635for inputs is that "what you type is what you get". A disadvantage is that the
1636results can look odd if you forget that the inputs haven't been rounded::
1637
1638 >>> getcontext().prec = 3
1639 >>> Decimal('3.104') + D('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001640 Decimal('5.21')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001641 >>> Decimal('3.104') + D('0.000') + D('2.104')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001642 Decimal('5.20')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001643
1644The solution is either to increase precision or to force rounding of inputs
1645using the unary plus operation::
1646
1647 >>> getcontext().prec = 3
1648 >>> +Decimal('1.23456789') # unary plus triggers rounding
Raymond Hettingerabe32372008-02-14 02:41:22 +00001649 Decimal('1.23')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001650
1651Alternatively, inputs can be rounded upon creation using the
1652:meth:`Context.create_decimal` method::
1653
1654 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Raymond Hettingerabe32372008-02-14 02:41:22 +00001655 Decimal('1.2345')
Georg Brandl8ec7f652007-08-15 14:28:01 +00001656