blob: d4126ac676ffaa155f3ea17778c259829e895799 [file] [log] [blame]
Raymond Hettinger8de63a22004-07-05 05:52:03 +00001\section{\module{decimal} ---
2 Decimal floating point arithmetic}
3
4\declaremodule{standard}{decimal}
5\modulesynopsis{Implementation of the General Decimal Arithmetic
6Specification.}
7
8\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}
13
14\sectionauthor{Raymond D. Hettinger}{python at rcn.com}
15
16\versionadded{2.4}
17
Raymond Hettinger97c92082004-07-09 06:13:12 +000018The \module{decimal} module provides support for decimal floating point
Raymond Hettinger8de63a22004-07-05 05:52:03 +000019arithmetic. It offers several advantages over the \class{float()} datatype:
20
21\begin{itemize}
22
23\item Decimal numbers can be represented exactly. In contrast, numbers like
Raymond Hettinger65df07b2004-07-11 12:40:19 +000024\constant{1.1} do not have an exact representation in binary floating point.
Raymond Hettingerd7c71152004-07-12 13:22:14 +000025End users typically would not expect \constant{1.1} to display as
Raymond Hettinger8de63a22004-07-05 05:52:03 +000026\constant{1.1000000000000001} as it does with binary floating point.
27
28\item The exactness carries over into arithmetic. In decimal floating point,
29\samp{0.1 + 0.1 + 0.1 - 0.3} is exactly equal to zero. In binary floating
30point, result is \constant{5.5511151231257827e-017}. While near to zero, the
31differences prevent reliable equality testing and differences can accumulate.
32For this reason, decimal would be preferred in accounting applications which
33have strict equality invariants.
34
35\item The decimal module incorporates notion of significant places so that
36\samp{1.30 + 1.20} is \constant{2.50}. The trailing zero is kept to indicate
37significance. This is the customary presentation for monetary applications. For
38multiplication, the ``schoolbook'' approach uses all the figures in the
39multiplicands. For instance, \samp{1.3 * 1.2} gives \constant{1.56} while
40\samp{1.30 * 1.20} gives \constant{1.5600}.
41
42\item Unlike hardware based binary floating point, the decimal module has a user
43settable precision (defaulting to 28 places) which can be as large as needed for
44a given problem:
45
46\begin{verbatim}
47>>> getcontext().prec = 6
48>>> Decimal(1) / Decimal(7)
49Decimal("0.142857")
50>>> getcontext().prec = 28
51>>> Decimal(1) / Decimal(7)
52Decimal("0.1428571428571428571428571429")
53\end{verbatim}
54
55\item Both binary and decimal floating point are implemented in terms of published
56standards. While the built-in float type exposes only a modest portion of its
57capabilities, the decimal module exposes all required parts of the standard.
58When needed, the programmer has full control over rounding and signal handling.
59
60\end{itemize}
61
62
63The module design is centered around three concepts: the decimal number, the
64context for arithmetic, and signals.
65
66A decimal number is immutable. It has a sign, coefficient digits, and an
67exponent. To preserve significance, the coefficient digits do not truncate
68trailing zeroes. Decimals also include special values such as
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000069\constant{Infinity}, \constant{-Infinity}, and \constant{NaN}. The standard
70also differentiates \constant{-0} from \constant{+0}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +000071
72The context for arithmetic is an environment specifying precision, rounding
Raymond Hettinger65df07b2004-07-11 12:40:19 +000073rules, limits on exponents, flags indicating the results of operations,
74and trap enablers which determine whether signals are treated as
Raymond Hettinger8de63a22004-07-05 05:52:03 +000075exceptions. Rounding options include \constant{ROUND_CEILING},
76\constant{ROUND_DOWN}, \constant{ROUND_FLOOR}, \constant{ROUND_HALF_DOWN},
77\constant{ROUND_HALF_EVEN}, \constant{ROUND_HALF_UP}, and \constant{ROUND_UP}.
78
Raymond Hettinger65df07b2004-07-11 12:40:19 +000079Signals are groups of exceptional conditions arising during the course of
80computation. Depending on the needs of the application, signals may be
Raymond Hettinger8de63a22004-07-05 05:52:03 +000081ignored, considered as informational, or treated as exceptions. The signals in
82the decimal module are: \constant{Clamped}, \constant{InvalidOperation},
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000083\constant{DivisionByZero}, \constant{Inexact}, \constant{Rounded},
Raymond Hettinger8de63a22004-07-05 05:52:03 +000084\constant{Subnormal}, \constant{Overflow}, and \constant{Underflow}.
85
86For each signal there is a flag and a trap enabler. When a signal is
87encountered, its flag incremented from zero and, then, if the trap enabler
Raymond Hettinger97c92082004-07-09 06:13:12 +000088is set to one, an exception is raised. Flags are sticky, so the user
89needs to reset them before monitoring a calculation.
Raymond Hettinger8de63a22004-07-05 05:52:03 +000090
91
92\begin{seealso}
93 \seetext{IBM's General Decimal Arithmetic Specification,
94 \citetitle[http://www2.hursley.ibm.com/decimal/decarith.html]
95 {The General Decimal Arithmetic Specification}.}
96
97 \seetext{IEEE standard 854-1987,
Raymond Hettinger536f76b2004-07-08 09:22:33 +000098 \citetitle[http://www.cs.berkeley.edu/\textasciitilde ejr/projects/754/private/drafts/854-1987/dir.html]
Raymond Hettinger8de63a22004-07-05 05:52:03 +000099 {Unofficial IEEE 854 Text}.}
100\end{seealso}
101
102
103
104%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
105\subsection{Quick-start Tutorial \label{decimal-tutorial}}
106
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000107The usual start to using decimals is importing the module, viewing the current
108context with \function{getcontext()} and, if necessary, setting new values
109for precision, rounding, or enabled traps:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000110
111\begin{verbatim}
112>>> from decimal import *
113>>> getcontext()
114Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000115 capitals=1, flags=[], traps=[Overflow, InvalidOperation,
116 DivisionByZero])
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000117
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000118>>> getcontext().prec = 7 # Set a new precision
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000119\end{verbatim}
120
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000121
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000122Decimal instances can be constructed from integers, strings or tuples. To
123create a Decimal from a \class{float}, first convert it to a string. This
124serves as an explicit reminder of the details of the conversion (including
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000125representation error). Decimal numbers include special values such as
126\constant{NaN} which stands for ``Not a number'', positive and negative
127\constant{Infinity}, and \constant{-0}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000128
129\begin{verbatim}
130>>> Decimal(10)
131Decimal("10")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000132>>> Decimal("3.14")
133Decimal("3.14")
134>>> Decimal((0, (3, 1, 4), -2))
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000135Decimal("3.14")
136>>> Decimal(str(2.0 ** 0.5))
137Decimal("1.41421356237")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000138>>> Decimal("NaN")
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000139Decimal("NaN")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000140>>> Decimal("-Infinity")
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000141Decimal("-Infinity")
142\end{verbatim}
143
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000144
145The significance of a new Decimal is determined solely by the number
146of digits input. Context precision and rounding only come into play during
147arithmetic operations.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000148
149\begin{verbatim}
150>>> getcontext().prec = 6
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000151>>> Decimal('3.0')
152Decimal("3.0")
153>>> Decimal('3.1415926535')
154Decimal("3.1415926535")
155>>> Decimal('3.1415926535') + Decimal('2.7182818285')
156Decimal("5.85987")
157>>> getcontext().rounding = ROUND_UP
158>>> Decimal('3.1415926535') + Decimal('2.7182818285')
159Decimal("5.85988")
160\end{verbatim}
161
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000162
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000163Decimals interact well with much of the rest of python. Here is a small
164decimal floating point flying circus:
165
166\begin{verbatim}
167>>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
168>>> max(data)
169Decimal("9.25")
170>>> min(data)
171Decimal("0.03")
172>>> sorted(data)
173[Decimal("0.03"), Decimal("1.00"), Decimal("1.34"), Decimal("1.87"),
174 Decimal("2.35"), Decimal("3.45"), Decimal("9.25")]
175>>> sum(data)
176Decimal("19.29")
177>>> a,b,c = data[:3]
178>>> str(a)
179'1.34'
180>>> float(a)
1811.3400000000000001
Raymond Hettinger92960232004-07-14 21:06:55 +0000182>>> round(a, 1) # round() first converts to binary floating point
Raymond Hettinger8de63a22004-07-05 05:52:03 +00001831.3
184>>> int(a)
1851
186>>> a * 5
187Decimal("6.70")
188>>> a * b
189Decimal("2.5058")
190>>> c % a
191Decimal("0.77")
192\end{verbatim}
193
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000194The \method{quantize()} method rounds a number to a fixed exponent. This
195method is useful for monetary applications that often round results to a fixed
196number of places:
197
198\begin{verbatim}
199>>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
200Decimal("7.32")
201>>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
202Decimal("8")
203\end{verbatim}
204
205As shown above, the \function{getcontext()} function accesses the current
206context and allows the settings to be changed. This approach meets the
207needs of most applications.
208
209For more advanced work, it may be useful to create alternate contexts using
210the Context() constructor. To make an alternate active, use the
211\function{setcontext()} function.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000212
213In accordance with the standard, the \module{Decimal} module provides two
214ready to use standard contexts, \constant{BasicContext} and
215\constant{ExtendedContext}. The former is especially useful for debugging
216because many of the traps are enabled:
217
218\begin{verbatim}
219>>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000220>>> setcontext(myothercontext)
221>>> Decimal(1) / Decimal(7)
222Decimal("0.142857142857142857142857142857142857142857142857142857142857")
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000223
224>>> ExtendedContext
225Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
226 capitals=1, flags=[], traps=[])
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000227>>> setcontext(ExtendedContext)
228>>> Decimal(1) / Decimal(7)
229Decimal("0.142857143")
230>>> Decimal(42) / Decimal(0)
231Decimal("Infinity")
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000232
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000233>>> setcontext(BasicContext)
234>>> Decimal(42) / Decimal(0)
235Traceback (most recent call last):
236 File "<pyshell#143>", line 1, in -toplevel-
237 Decimal(42) / Decimal(0)
238DivisionByZero: x / 0
239\end{verbatim}
240
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000241
242Contexts also have signal flags for monitoring exceptional conditions
243encountered during computations. The flags remain set until explicitly
244cleared, so it is best to clear the flags before each set of monitored
245computations by using the \method{clear_flags()} method.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000246
247\begin{verbatim}
248>>> setcontext(ExtendedContext)
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000249>>> getcontext().clear_flags()
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000250>>> Decimal(355) / Decimal(113)
251Decimal("3.14159292")
252>>> getcontext()
253Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Raymond Hettingerbf440692004-07-10 14:14:37 +0000254 capitals=1, flags=[Inexact, Rounded], traps=[])
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000255\end{verbatim}
256
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000257The \var{flags} entry shows that the rational approximation to \constant{Pi}
258was rounded (digits beyond the context precision were thrown away) and that
259the result is inexact (some of the discarded digits were non-zero).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000260
Raymond Hettingerbf440692004-07-10 14:14:37 +0000261Individual traps are set using the dictionary in the \member{traps}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000262field of a context:
263
264\begin{verbatim}
265>>> Decimal(1) / Decimal(0)
266Decimal("Infinity")
Raymond Hettingerbf440692004-07-10 14:14:37 +0000267>>> getcontext().traps[DivisionByZero] = 1
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000268>>> Decimal(1) / Decimal(0)
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000269Traceback (most recent call last):
270 File "<pyshell#112>", line 1, in -toplevel-
271 Decimal(1) / Decimal(0)
272DivisionByZero: x / 0
273\end{verbatim}
274
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000275Most programs adjust the current context only once, at the beginning of the
276program. And, in many applications, data is converted to \class{Decimal} with
277a single cast inside a loop. With context set and decimals created, the bulk
278of the program manipulates the data no differently than with other Python
279numeric types.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000280
281
282
283%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
284\subsection{Decimal objects \label{decimal-decimal}}
285
286\begin{classdesc}{Decimal}{\optional{value \optional{, context}}}
287 Constructs a new \class{Decimal} object based from \var{value}.
288
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000289 \var{value} can be an integer, string, tuple, or another \class{Decimal}
290 object. If no \var{value} is given, returns \code{Decimal("0")}. If
291 \var{value} is a string, it should conform to the decimal numeric string
292 syntax:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000293
294 \begin{verbatim}
295 sign ::= '+' | '-'
296 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
297 indicator ::= 'e' | 'E'
298 digits ::= digit [digit]...
299 decimal-part ::= digits '.' [digits] | ['.'] digits
300 exponent-part ::= indicator [sign] digits
301 infinity ::= 'Infinity' | 'Inf'
302 nan ::= 'NaN' [digits] | 'sNaN' [digits]
303 numeric-value ::= decimal-part [exponent-part] | infinity
304 numeric-string ::= [sign] numeric-value | [sign] nan
305 \end{verbatim}
306
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000307 If \var{value} is a \class{tuple}, it should have three components,
308 a sign (\constant{0} for positive or \constant{1} for negative),
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000309 a \class{tuple} of digits, and an integer exponent. For example,
310 \samp{Decimal((0, (1, 4, 1, 4), -3))} returns \code{Decimal("1.414")}.
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000311
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000312 The \var{context} precision does not affect how many digits are stored.
313 That is determined exclusively by the number of digits in \var{value}. For
314 example, \samp{Decimal("3.00000")} records all five zeroes even if the
315 context precision is only three.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000316
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000317 The purpose of the \var{context} argument is determining what to do if
318 \var{value} is a malformed string. If the context traps
319 \constant{InvalidOperation}, an exception is raised; otherwise, the
320 constructor returns a new Decimal with the value of \constant{NaN}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000321
322 Once constructed, \class{Decimal} objects are immutable.
323\end{classdesc}
324
325Decimal floating point objects share many properties with the other builtin
326numeric types such as \class{float} and \class{int}. All of the usual
327math operations and special methods apply. Likewise, decimal objects can
328be copied, pickled, printed, used as dictionary keys, used as set elements,
329compared, sorted, and coerced to another type (such as \class{float}
330or \class{long}).
331
332In addition to the standard numeric properties, decimal floating point objects
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000333also have a number of specialized methods:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000334
335\begin{methoddesc}{adjusted}{}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000336 Return the adjusted exponent after shifting out the coefficient's rightmost
337 digits until only the lead digit remains: \code{Decimal("321e+5").adjusted()}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000338 returns seven. Used for determining the position of the most significant
339 digit with respect to the decimal point.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000340\end{methoddesc}
341
342\begin{methoddesc}{as_tuple}{}
343 Returns a tuple representation of the number:
344 \samp{(sign, digittuple, exponent)}.
345\end{methoddesc}
346
347\begin{methoddesc}{compare}{other\optional{, context}}
348 Compares like \method{__cmp__()} but returns a decimal instance:
349 \begin{verbatim}
350 a or b is a NaN ==> Decimal("NaN")
351 a < b ==> Decimal("-1")
352 a == b ==> Decimal("0")
353 a > b ==> Decimal("1")
354 \end{verbatim}
355\end{methoddesc}
356
357\begin{methoddesc}{max}{other\optional{, context}}
358 Like \samp{max(self, other)} but returns \constant{NaN} if either is a
359 \constant{NaN}. Applies the context rounding rule before returning.
360\end{methoddesc}
361
362\begin{methoddesc}{min}{other\optional{, context}}
363 Like \samp{min(self, other)} but returns \constant{NaN} if either is a
364 \constant{NaN}. Applies the context rounding rule before returning.
365\end{methoddesc}
366
367\begin{methoddesc}{normalize}{\optional{context}}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000368 Normalize the number by stripping the rightmost trailing zeroes and
369 converting any result equal to \constant{Decimal("0")} to
370 \constant{Decimal("0e0")}. Used for producing canonical values for members
371 of an equivalence class. For example, \code{Decimal("32.100")} and
372 \code{Decimal("0.321000e+2")} both normalize to the equivalent value
Raymond Hettinger8df4e6b2004-08-15 23:51:38 +0000373 \code{Decimal("32.1")}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000374\end{methoddesc}
375
376\begin{methoddesc}{quantize}
377 {\optional{exp \optional{, rounding\optional{, context\optional{, watchexp}}}}}
378 Quantize makes the exponent the same as \var{exp}. Searches for a
379 rounding method in \var{rounding}, then in \var{context}, and then
380 in the current context.
381
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000382 If \var{watchexp} is set (default), then an error is returned whenever
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000383 the resulting exponent is greater than \member{Emax} or less than
384 \member{Etiny}.
385\end{methoddesc}
386
387\begin{methoddesc}{remainder_near}{other\optional{, context}}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000388 Computes the modulo as either a positive or negative value depending
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000389 on which is closest to zero. For instance,
390 \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")}
391 which is closer to zero than \code{Decimal("4")}.
392
393 If both are equally close, the one chosen will have the same sign
394 as \var{self}.
395\end{methoddesc}
396
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000397\begin{methoddesc}{same_quantum}{other\optional{, context}}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000398 Test whether self and other have the same exponent or whether both
399 are \constant{NaN}.
400\end{methoddesc}
401
402\begin{methoddesc}{sqrt}{\optional{context}}
403 Return the square root to full precision.
404\end{methoddesc}
405
406\begin{methoddesc}{to_eng_string}{\optional{context}}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000407 Convert to an engineering-type string.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000408
409 Engineering notation has an exponent which is a multiple of 3, so there
410 are up to 3 digits left of the decimal place. For example, converts
411 \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")}
412\end{methoddesc}
413
414\begin{methoddesc}{to_integral}{\optional{rounding\optional{, context}}}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000415 Rounds to the nearest integer without signaling \constant{Inexact}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000416 or \constant{Rounded}. If given, applies \var{rounding}; otherwise,
417 uses the rounding method in either the supplied \var{context} or the
418 current context.
419\end{methoddesc}
420
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000421
422
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000423%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
424\subsection{Context objects \label{decimal-decimal}}
425
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000426Contexts are environments for arithmetic operations. They govern precision,
427set rules for rounding, determine which signals are treated as exceptions, and
428limit the range for exponents.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000429
430Each thread has its own current context which is accessed or changed using
431the \function{getcontext()} and \function{setcontext()} functions:
432
433\begin{funcdesc}{getcontext}{}
434 Return the current context for the active thread.
435\end{funcdesc}
436
437\begin{funcdesc}{setcontext}{c}
438 Set the current context for the active thread to \var{c}.
439\end{funcdesc}
440
441New contexts can formed using the \class{Context} constructor described below.
442In addition, the module provides three pre-made contexts:
443
444
445\begin{classdesc*}{BasicContext}
446 This is a standard context defined by the General Decimal Arithmetic
447 Specification. Precision is set to nine. Rounding is set to
448 \constant{ROUND_HALF_UP}. All flags are cleared. All traps are enabled
449 (treated as exceptions) except \constant{Inexact}, \constant{Rounded}, and
450 \constant{Subnormal}.
451
452 Because many of the traps are enabled, this context is useful for debugging.
453\end{classdesc*}
454
455\begin{classdesc*}{ExtendedContext}
456 This is a standard context defined by the General Decimal Arithmetic
457 Specification. Precision is set to nine. Rounding is set to
458 \constant{ROUND_HALF_EVEN}. All flags are cleared. No traps are enabled
459 (so that exceptions are not raised during computations).
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000460
461 Because the trapped are disabled, this context is useful for applications
462 that prefer to have result value of \constant{NaN} or \constant{Infinity}
463 instead of raising exceptions. This allows an application to complete a
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000464 run in the presence of conditions that would otherwise halt the program.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000465\end{classdesc*}
466
467\begin{classdesc*}{DefaultContext}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000468 This context is used by the \class{Context} constructor as a prototype for
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000469 new contexts. Changing a field (such a precision) has the effect of
470 changing the default for new contexts creating by the \class{Context}
471 constructor.
472
473 This context is most useful in multi-threaded environments. Changing one of
474 the fields before threads are started has the effect of setting system-wide
475 defaults. Changing the fields after threads have started is not recommended
476 as it would require thread synchronization to prevent race conditions.
477
478 In single threaded environments, it is preferable to not use this context
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000479 at all. Instead, simply create contexts explicitly as described below.
480
481 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled
482 traps for Overflow, InvalidOperation, and DivisionByZero.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000483\end{classdesc*}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000484
485
486In addition to the three supplied contexts, new contexts can be created
487with the \class{Context} constructor.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000488
Raymond Hettingerbf440692004-07-10 14:14:37 +0000489\begin{classdesc}{Context}{prec=None, rounding=None, traps=None,
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000490 flags=None, Emin=None, Emax=None, capitals=1}
491 Creates a new context. If a field is not specified or is \constant{None},
492 the default values are copied from the \constant{DefaultContext}. If the
493 \var{flags} field is not specified or is \constant{None}, all flags are
494 cleared.
495
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000496 The \var{prec} field is a positive integer that sets the precision for
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000497 arithmetic operations in the context.
498
Raymond Hettinger97c92082004-07-09 06:13:12 +0000499 The \var{rounding} option is one of:
500 \constant{ROUND_CEILING} (towards \constant{Infinity}),
501 \constant{ROUND_DOWN} (towards zero),
502 \constant{ROUND_FLOOR} (towards \constant{-Infinity}),
503 \constant{ROUND_HALF_DOWN} (towards zero),
504 \constant{ROUND_HALF_EVEN},
505 \constant{ROUND_HALF_UP} (away from zero), or
506 \constant{ROUND_UP} (away from zero).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000507
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000508 The \var{traps} and \var{flags} fields list any signals to be set.
509 Generally, new contexts should only set traps and leave the flags clear.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000510
511 The \var{Emin} and \var{Emax} fields are integers specifying the outer
512 limits allowable for exponents.
513
514 The \var{capitals} field is either \constant{0} or \constant{1} (the
515 default). If set to \constant{1}, exponents are printed with a capital
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000516 \constant{E}; otherwise, a lowercase \constant{e} is used:
517 \constant{Decimal('6.02e+23')}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000518\end{classdesc}
519
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000520The \class{Context} class defines several general purpose methods as well as a
521large number of methods for doing arithmetic directly in a given context.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000522
523\begin{methoddesc}{clear_flags}{}
524 Sets all of the flags to \constant{0}.
525\end{methoddesc}
526
527\begin{methoddesc}{copy}{}
528 Returns a duplicate of the context.
529\end{methoddesc}
530
531\begin{methoddesc}{create_decimal}{num}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000532 Creates a new Decimal instance from \var{num} but using \var{self} as
533 context. Unlike the \class{Decimal} constructor, the context precision,
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000534 rounding method, flags, and traps are applied to the conversion.
535
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000536 This is useful because constants are often given to a greater precision than
Raymond Hettingerd7c71152004-07-12 13:22:14 +0000537 is needed by the application. Another benefit is that rounding immediately
538 eliminates unintended effects from digits beyond the current precision.
539 In the following example, using unrounded inputs means that adding zero
540 to a sum can change the result:
541
542 \begin{verbatim}
543 >>> getcontext().prec = 3
544 >>> Decimal("3.4445") + Decimal("1.0023")
545 Decimal("4.45")
546 >>> Decimal("3.4445") + Decimal(0) + Decimal("1.0023")
547 Decimal("4.44")
548 \end{verbatim}
549
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000550\end{methoddesc}
551
552\begin{methoddesc}{Etiny}{}
553 Returns a value equal to \samp{Emin - prec + 1} which is the minimum
554 exponent value for subnormal results. When underflow occurs, the
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000555 exponent is set to \constant{Etiny}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000556\end{methoddesc}
557
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000558\begin{methoddesc}{Etop}{}
559 Returns a value equal to \samp{Emax - prec + 1}.
560\end{methoddesc}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000561
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000562
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000563The usual approach to working with decimals is to create \class{Decimal}
564instances and then apply arithmetic operations which take place within the
565current context for the active thread. An alternate approach is to use
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000566context methods for calculating within a specific context. The methods are
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000567similar to those for the \class{Decimal} class and are only briefly recounted
568here.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000569
570\begin{methoddesc}{abs}{x}
571 Returns the absolute value of \var{x}.
572\end{methoddesc}
573
574\begin{methoddesc}{add}{x, y}
575 Return the sum of \var{x} and \var{y}.
576\end{methoddesc}
577
578\begin{methoddesc}{compare}{x, y}
579 Compares values numerically.
580
581 Like \method{__cmp__()} but returns a decimal instance:
582 \begin{verbatim}
583 a or b is a NaN ==> Decimal("NaN")
584 a < b ==> Decimal("-1")
585 a == b ==> Decimal("0")
586 a > b ==> Decimal("1")
587 \end{verbatim}
588\end{methoddesc}
589
590\begin{methoddesc}{divide}{x, y}
591 Return \var{x} divided by \var{y}.
592\end{methoddesc}
593
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000594\begin{methoddesc}{divmod}{x, y}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000595 Divides two numbers and returns the integer part of the result.
596\end{methoddesc}
597
598\begin{methoddesc}{max}{x, y}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000599 Compare two values numerically and return the maximum.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000600
601 If they are numerically equal then the left-hand operand is chosen as the
602 result.
603\end{methoddesc}
604
605\begin{methoddesc}{min}{x, y}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000606 Compare two values numerically and return the minimum.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000607
608 If they are numerically equal then the left-hand operand is chosen as the
609 result.
610\end{methoddesc}
611
612\begin{methoddesc}{minus}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000613 Minus corresponds to the unary prefix minus operator in Python.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000614\end{methoddesc}
615
616\begin{methoddesc}{multiply}{x, y}
617 Return the product of \var{x} and \var{y}.
618\end{methoddesc}
619
620\begin{methoddesc}{normalize}{x}
621 Normalize reduces an operand to its simplest form.
622
Raymond Hettingerd7c71152004-07-12 13:22:14 +0000623 Essentially a \method{plus} operation with all trailing zeros removed from
624 the result.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000625\end{methoddesc}
626
627\begin{methoddesc}{plus}{x}
Raymond Hettingerd7c71152004-07-12 13:22:14 +0000628 Plus corresponds to the unary prefix plus operator in Python. This
629 operation applies the context precision and rounding, so it is
630 \emph{not} an identity operation.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000631\end{methoddesc}
632
633\begin{methoddesc}{power}{x, y\optional{, modulo}}
634 Return \samp{x ** y} to the \var{modulo} if given.
635
636 The right-hand operand must be a whole number whose integer part (after any
637 exponent has been applied) has no more than 9 digits and whose fractional
638 part (if any) is all zeros before any rounding. The operand may be positive,
639 negative, or zero; if negative, the absolute value of the power is used, and
640 the left-hand operand is inverted (divided into 1) before use.
641
642 If the increased precision needed for the intermediate calculations exceeds
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000643 the capabilities of the implementation then an \constant{InvalidOperation}
644 condition is signaled.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000645
646 If, when raising to a negative power, an underflow occurs during the
647 division into 1, the operation is not halted at that point but continues.
648\end{methoddesc}
649
650\begin{methoddesc}{quantize}{x, y}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000651 Returns a value equal to \var{x} after rounding and having the exponent of
652 \var{y}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000653
654 Unlike other operations, if the length of the coefficient after the quantize
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000655 operation would be greater than precision, then an
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000656 \constant{InvalidOperation} is signaled. This guarantees that, unless there
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000657 is an error condition, the quantized exponent is always equal to that of the
658 right-hand operand.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000659
660 Also unlike other operations, quantize never signals Underflow, even
661 if the result is subnormal and inexact.
662\end{methoddesc}
663
664\begin{methoddesc}{remainder}{x, y}
665 Returns the remainder from integer division.
666
667 The sign of the result, if non-zero, is the same as that of the original
668 dividend.
669\end{methoddesc}
670
671\begin{methoddesc}{remainder_near}{x, y}
672 Computed the modulo as either a positive or negative value depending
673 on which is closest to zero. For instance,
674 \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")}
675 which is closer to zero than \code{Decimal("4")}.
676
677 If both are equally close, the one chosen will have the same sign
678 as \var{self}.
679\end{methoddesc}
680
681\begin{methoddesc}{same_quantum}{x, y}
682 Test whether \var{x} and \var{y} have the same exponent or whether both are
683 \constant{NaN}.
684\end{methoddesc}
685
686\begin{methoddesc}{sqrt}{}
687 Return the square root to full precision.
688\end{methoddesc}
689
690\begin{methoddesc}{substract}{x, y}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000691 Return the difference between \var{x} and \var{y}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000692\end{methoddesc}
693
694\begin{methoddesc}{to_eng_string}{}
695 Convert to engineering-type string.
696
697 Engineering notation has an exponent which is a multiple of 3, so there
698 are up to 3 digits left of the decimal place. For example, converts
699 \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")}
700\end{methoddesc}
701
702\begin{methoddesc}{to_integral}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000703 Rounds to the nearest integer without signaling \constant{Inexact}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000704 or \constant{Rounded}.
705\end{methoddesc}
706
707\begin{methoddesc}{to_sci_string}{}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000708 Converts a number to a string using scientific notation.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000709\end{methoddesc}
710
711
712
713%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
714\subsection{Signals \label{decimal-signals}}
715
716Signals represent conditions that arise during computation.
717Each corresponds to one context flag and one context trap enabler.
718
719The context flag is incremented whenever the condition is encountered.
720After the computation, flags may be checked for informational
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000721purposes (for instance, to determine whether a computation was exact).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000722After checking the flags, be sure to clear all flags before starting
723the next computation.
724
725If the context's trap enabler is set for the signal, then the condition
726causes a Python exception to be raised. For example, if the
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000727\class{DivisionByZero} trap is set, then a \exception{DivisionByZero}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000728exception is raised upon encountering the condition.
729
730
731\begin{classdesc*}{Clamped}
732 Altered an exponent to fit representation constraints.
733
734 Typically, clamping occurs when an exponent falls outside the context's
735 \member{Emin} and \member{Emax} limits. If possible, the exponent is
736 reduced to fit by adding zeroes to the coefficient.
737\end{classdesc*}
738
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000739\begin{classdesc*}{DecimalException}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000740 Base class for other signals and is a subclass of
741 \exception{ArithmeticError}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000742\end{classdesc*}
743
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000744\begin{classdesc*}{DivisionByZero}
745 Signals the division of a non-infinite number by zero.
746
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000747 Can occur with division, modulo division, or when raising a number to a
748 negative power. If this signal is not trapped, returns
749 \constant{Infinity} or \constant{-Infinity} with the sign determined by
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000750 the inputs to the calculation.
751\end{classdesc*}
752
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000753\begin{classdesc*}{Inexact}
754 Indicates that rounding occurred and the result is not exact.
755
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000756 Signals when non-zero digits were discarded during rounding. The rounded
757 result is returned. The signal flag or trap is used to detect when
758 results are inexact.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000759\end{classdesc*}
760
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000761\begin{classdesc*}{InvalidOperation}
762 An invalid operation was performed.
763
764 Indicates that an operation was requested that does not make sense.
765 If not trapped, returns \constant{NaN}. Possible causes include:
766
767 \begin{verbatim}
768 Infinity - Infinity
769 0 * Infinity
770 Infinity / Infinity
771 x % 0
772 Infinity % x
773 x._rescale( non-integer )
774 sqrt(-x) and x > 0
775 0 ** 0
776 x ** (non-integer)
777 x ** Infinity
778 \end{verbatim}
779\end{classdesc*}
780
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000781\begin{classdesc*}{Overflow}
782 Numerical overflow.
783
784 Indicates the exponent is larger than \member{Emax} after rounding has
785 occurred. If not trapped, the result depends on the rounding mode, either
786 pulling inward to the largest representable finite number or rounding
787 outward to \constant{Infinity}. In either case, \class{Inexact} and
788 \class{Rounded} are also signaled.
789\end{classdesc*}
790
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000791\begin{classdesc*}{Rounded}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000792 Rounding occurred though possibly no information was lost.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000793
794 Signaled whenever rounding discards digits; even if those digits are
795 zero (such as rounding \constant{5.00} to \constant{5.0}). If not
796 trapped, returns the result unchanged. This signal is used to detect
797 loss of significant digits.
798\end{classdesc*}
799
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000800\begin{classdesc*}{Subnormal}
801 Exponent was lower than \member{Emin} prior to rounding.
802
803 Occurs when an operation result is subnormal (the exponent is too small).
804 If not trapped, returns the result unchanged.
805\end{classdesc*}
806
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000807\begin{classdesc*}{Underflow}
808 Numerical underflow with result rounded to zero.
809
810 Occurs when a subnormal result is pushed to zero by rounding.
811 \class{Inexact} and \class{Subnormal} are also signaled.
812\end{classdesc*}
813
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000814The following table summarizes the hierarchy of signals:
815
816\begin{verbatim}
817 exceptions.ArithmeticError(exceptions.StandardError)
818 DecimalException
819 Clamped
820 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
821 Inexact
822 Overflow(Inexact, Rounded)
823 Underflow(Inexact, Rounded, Subnormal)
824 InvalidOperation
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000825 Rounded
826 Subnormal
827\end{verbatim}
828
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000829
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000830%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Raymond Hettinger2864b802004-08-15 23:47:48 +0000831\subsection{Floating Point Notes \label{decimal-notes}}
832
833The use of decimal floating point eliminates decimal representation error
834(making it possible to represent \constant{0.1} exactly); however, some
835operations can still incur round-off error when non-zero digits exceed the
836fixed precision.
837
838The effects of round-off error can be amplified by the addition or subtraction
839of nearly offsetting quantities resulting in loss of significance. Knuth
840provides two instructive examples where rounded floating point arithmetic with
Raymond Hettingerf4fd79c2004-08-26 03:11:56 +0000841insufficient precision causes the breakdown of the associative and
Raymond Hettinger2864b802004-08-15 23:47:48 +0000842distributive properties of addition:
843
844\begin{verbatim}
845# Examples from Seminumerical Algorithms, Section 4.2.2.
846>>> from decimal import *
847>>> getcontext().prec = 8
848
849>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
850>>> (u + v) + w
851Decimal("9.5111111")
852>>> u + (v + w)
853Decimal("10")
854
855>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
856>>> (u*v) + (u*w)
857Decimal("0.01")
858>>> u * (v+w)
859Decimal("0.0060000")
860\end{verbatim}
861
862The \module{decimal} module makes it possible to restore the identities
863by expanding the precision sufficiently to avoid loss of significance:
864
865\begin{verbatim}
866>>> getcontext().prec = 20
867>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
868>>> (u + v) + w
869Decimal("9.51111111")
870>>> u + (v + w)
871Decimal("9.51111111")
872>>>
873>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
874>>> (u*v) + (u*w)
875Decimal("0.0060000")
876>>> u * (v+w)
877Decimal("0.0060000")
878\end{verbatim}
879
880
881The number system for the \module{decimal} module provides special
882values including \constant{NaN}, \constant{sNaN}, \constant{-Infinity},
883\constant{Infinity}, and two zeroes, \constant{+0} and \constant{-0}.
884
Andrew M. Kuchling7ec75842004-08-16 16:12:23 +0000885Infinities can be constructed directly with: \code{Decimal('Infinity')}. Also,
Raymond Hettinger2864b802004-08-15 23:47:48 +0000886they can arise from dividing by zero when the \exception{DivisionByZero}
887signal is not trapped. Likewise, when the \exception{Overflow} signal is not
888trapped, infinity can result from rounding beyond the limits of the largest
889representable number.
890
891The infinities are signed (affine) and can be used in arithmetic operations
892where they get treated as very large, indeterminate numbers. For instance,
893adding a constant to infinity gives another infinite result.
894
Raymond Hettingerf4fd79c2004-08-26 03:11:56 +0000895Some operations are indeterminate and return \constant{NaN}, or if the
Raymond Hettinger2864b802004-08-15 23:47:48 +0000896\exception{InvalidOperation} signal is trapped, raise an exception. For
897example, \code{0/0} returns \constant{NaN} which means ``not a number''. This
898variety of \constant{NaN} is quiet and, once created, will flow through other
899computations always resulting in another \constant{NaN}. This behavior can be
900useful for a series of computations that occasionally have missing inputs ---
901it allows the calculation to proceed while flagging specific results as
902invalid.
903
904A variant is \constant{sNaN} which signals rather than remaining quiet
905after every operation. This is a useful return value when an invalid
906result needs to interrupt a calculation for special handling.
907
908The signed zeros can result from calculations that underflow.
909They keep the sign that would have resulted if the calculation had
910been carried out to greater precision. Since their magnitude is
Raymond Hettingerf4fd79c2004-08-26 03:11:56 +0000911zero, both positive and negative zeros are treated as equal and their
Raymond Hettinger2864b802004-08-15 23:47:48 +0000912sign is informational.
913
Raymond Hettingerf4fd79c2004-08-26 03:11:56 +0000914In addition to the two signed zeros which are distinct yet equal,
915there are various representations of zero with differing precisions
Raymond Hettinger2864b802004-08-15 23:47:48 +0000916yet equivalent in value. This takes a bit of getting used to. For
917an eye accustomed to normalized floating point representations, it
918is not immediately obvious that the following calculation returns
919a value equal to zero:
920
921\begin{verbatim}
922>>> 1 / Decimal('Infinity')
923Decimal("0E-1000000026")
924\end{verbatim}
925
926%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000927\subsection{Working with threads \label{decimal-threads}}
928
929The \function{getcontext()} function accesses a different \class{Context}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000930object for each thread. Having separate thread contexts means that threads
931may make changes (such as \code{getcontext.prec=10}) without interfering with
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000932other threads.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000933
934Likewise, the \function{setcontext()} function automatically assigns its target
935to the current thread.
936
937If \function{setcontext()} has not been called before \function{getcontext()},
938then \function{getcontext()} will automatically create a new context for use
939in the current thread.
940
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000941The new context is copied from a prototype context called
942\var{DefaultContext}. To control the defaults so that each thread will use the
943same values throughout the application, directly modify the
944\var{DefaultContext} object. This should be done \emph{before} any threads are
945started so that there won't be a race condition between threads calling
946\function{getcontext()}. For example:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000947
948\begin{verbatim}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000949# Set applicationwide defaults for all threads about to be launched
Raymond Hettinger92960232004-07-14 21:06:55 +0000950DefaultContext.prec = 12
951DefaultContext.rounding = ROUND_DOWN
952DefaultContext.traps = ExtendedContext.traps.copy()
953DefaultContext.traps[InvalidOperation] = 1
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000954setcontext(DefaultContext)
955
Raymond Hettinger92960232004-07-14 21:06:55 +0000956# Afterwards, the threads can be started
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000957t1.start()
958t2.start()
959t3.start()
960 . . .
961\end{verbatim}
Raymond Hettinger2864b802004-08-15 23:47:48 +0000962
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000963
964
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000965%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
966\subsection{Recipes \label{decimal-recipes}}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000967
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000968Here are a few recipes that serve as utility functions and that demonstrate
969ways to work with the \class{Decimal} class:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000970
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000971\begin{verbatim}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000972def moneyfmt(value, places=2, curr='', sep=',', dp='.',
973 pos='', neg='-', trailneg=''):
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000974 """Convert Decimal to a money formatted string.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000975
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000976 places: required number of places after the decimal point
977 curr: optional currency symbol before the sign (may be blank)
978 sep: optional grouping separator (comma, period, or blank)
979 dp: decimal point indicator (comma or period)
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000980 only specify as blank when places is zero
981 pos: optional sign for positive numbers: "+", space or blank
982 neg: optional sign for negative numbers: "-", "(", space or blank
983 trailneg:optional trailing minus indicator: "-", ")", space or blank
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000984
985 >>> d = Decimal('-1234567.8901')
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000986 >>> moneyfmt(d, curr='$')
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000987 '-$1,234,567.89'
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000988 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
989 '1.234.568-'
990 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000991 '($1,234,567.89)'
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000992
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000993 """
994 q = Decimal((0, (1,), -places)) # 2 places --> '0.01'
995 sign, digits, exp = value.quantize(q).as_tuple()
996 result = []
997 digits = map(str, digits)
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000998 build, next = result.append, digits.pop
999 if sign:
1000 build(trailneg)
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001001 for i in range(places):
1002 build(next())
1003 build(dp)
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001004 i = 0
1005 while digits:
1006 build(next())
1007 i += 1
1008 if i == 3:
1009 i = 0
1010 build(sep)
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001011 build(curr)
1012 if sign:
1013 build(neg)
1014 else:
1015 build(pos)
1016 result.reverse()
1017 return ''.join(result)
1018
1019def pi():
Raymond Hettingerc4f93d442004-07-05 20:17:13 +00001020 """Compute Pi to the current precision.
1021
1022 >>> print pi()
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001023 3.141592653589793238462643383
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001024
Raymond Hettingerc4f93d442004-07-05 20:17:13 +00001025 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001026 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettinger10959b12004-07-05 21:13:28 +00001027 three = Decimal(3) # substitute "three=3.0" for regular floats
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001028 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1029 while s != lasts:
1030 lasts = s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001031 n, na = n+na, na+8
1032 d, da = d+da, da+32
1033 t = (t * n) / d
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001034 s += t
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001035 getcontext().prec -= 2
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001036 return +s # unary plus applies the new precision
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001037
1038def exp(x):
Raymond Hettinger10959b12004-07-05 21:13:28 +00001039 """Return e raised to the power of x. Result type matches input type.
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001040
1041 >>> print exp(Decimal(1))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001042 2.718281828459045235360287471
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001043 >>> print exp(Decimal(2))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001044 7.389056098930650227230427461
Raymond Hettinger10959b12004-07-05 21:13:28 +00001045 >>> print exp(2.0)
1046 7.38905609893
1047 >>> print exp(2+0j)
1048 (7.38905609893+0j)
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001049
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001050 """
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001051 getcontext().prec += 2
1052 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1053 while s != lasts:
1054 lasts = s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001055 i += 1
1056 fact *= i
1057 num *= x
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001058 s += num / fact
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001059 getcontext().prec -= 2
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001060 return +s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001061
1062def cos(x):
1063 """Return the cosine of x as measured in radians.
1064
1065 >>> print cos(Decimal('0.5'))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001066 0.8775825618903727161162815826
Raymond Hettinger10959b12004-07-05 21:13:28 +00001067 >>> print cos(0.5)
1068 0.87758256189
1069 >>> print cos(0.5+0j)
1070 (0.87758256189+0j)
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001071
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001072 """
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001073 getcontext().prec += 2
1074 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1075 while s != lasts:
1076 lasts = s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001077 i += 2
1078 fact *= i * (i-1)
1079 num *= x * x
1080 sign *= -1
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001081 s += num / fact * sign
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001082 getcontext().prec -= 2
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001083 return +s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001084
1085def sin(x):
1086 """Return the cosine of x as measured in radians.
1087
1088 >>> print sin(Decimal('0.5'))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001089 0.4794255386042030002732879352
Raymond Hettinger10959b12004-07-05 21:13:28 +00001090 >>> print sin(0.5)
1091 0.479425538604
1092 >>> print sin(0.5+0j)
1093 (0.479425538604+0j)
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001094
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001095 """
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001096 getcontext().prec += 2
1097 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1098 while s != lasts:
1099 lasts = s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001100 i += 2
1101 fact *= i * (i-1)
1102 num *= x * x
1103 sign *= -1
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001104 s += num / fact * sign
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001105 getcontext().prec -= 2
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001106 return +s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001107
1108\end{verbatim}