blob: 205a2c8e7444bf77e59749a96a434eb7b05b2c1a [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
18The decimal \module{module} provides support for decimal floating point
19arithmetic. 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
24\constant{1.1} do not have an exact representations in binary floating point.
25End users typically wound not expect \constant{1.1} to display as
26\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
69\constant{Infinity} (the result of \samp{1 / 0}), \constant{-Infinity},
70(the result of \samp{-1 / 0}), and \constant{NaN} (the result of
71\samp{0 / 0}). The standard also differentiates \constant{-0} from
72\constant{+0}.
73
74The context for arithmetic is an environment specifying precision, rounding
75rules, limits on exponents, flags that indicate the results of operations,
76and trap enablers which determine whether signals are to be treated as
77exceptions. Rounding options include \constant{ROUND_CEILING},
78\constant{ROUND_DOWN}, \constant{ROUND_FLOOR}, \constant{ROUND_HALF_DOWN},
79\constant{ROUND_HALF_EVEN}, \constant{ROUND_HALF_UP}, and \constant{ROUND_UP}.
80
81Signals are types of information that arise during the course of a
82computation. Depending on the needs of the application, some signals may be
83ignored, considered as informational, or treated as exceptions. The signals in
84the decimal module are: \constant{Clamped}, \constant{InvalidOperation},
85\constant{ConversionSyntax}, \constant{DivisionByZero},
86\constant{DivisionImpossible}, \constant{DivisionUndefined},
87\constant{Inexact}, \constant{InvalidContext}, \constant{Rounded},
88\constant{Subnormal}, \constant{Overflow}, and \constant{Underflow}.
89
90For each signal there is a flag and a trap enabler. When a signal is
91encountered, its flag incremented from zero and, then, if the trap enabler
92is set to one, an exception is raised.
93
94
95\begin{seealso}
96 \seetext{IBM's General Decimal Arithmetic Specification,
97 \citetitle[http://www2.hursley.ibm.com/decimal/decarith.html]
98 {The General Decimal Arithmetic Specification}.}
99
100 \seetext{IEEE standard 854-1987,
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000101 \citetitle[http://www.cs.berkeley.edu/\textasciitilde ejr/projects/754/private/drafts/854-1987/dir.html]
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000102 {Unofficial IEEE 854 Text}.}
103\end{seealso}
104
105
106
107%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
108\subsection{Quick-start Tutorial \label{decimal-tutorial}}
109
110The normal start to using decimals is to import the module, and then use
111\function{getcontext()} to view the context and, if necessary, set the context
112precision, rounding, or trap enablers:
113
114\begin{verbatim}
115>>> from decimal import *
116>>> getcontext()
117Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
118 setflags=[], settraps=[])
119
120>>> getcontext().prec = 7
121\end{verbatim}
122
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000123Decimal instances can be constructed from integers, strings or tuples. To
124create a Decimal from a \class{float}, first convert it to a string. This
125serves as an explicit reminder of the details of the conversion (including
126representation error). Malformed strings signal \constant{ConversionSyntax}
127and return a special kind of Decimal called a \constant{NaN} which stands for
128``Not a number''. Positive and negative \constant{Infinity} is yet another
129special kind of Decimal.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000130
131\begin{verbatim}
132>>> Decimal(10)
133Decimal("10")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000134>>> Decimal("3.14")
135Decimal("3.14")
136>>> Decimal((0, (3, 1, 4), -2))
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000137Decimal("3.14")
138>>> Decimal(str(2.0 ** 0.5))
139Decimal("1.41421356237")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000140>>> Decimal("NaN")
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000141Decimal("NaN")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000142>>> Decimal("-Infinity")
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000143Decimal("-Infinity")
144\end{verbatim}
145
146Creating decimals is unaffected by context precision. Their level of
147significance is completely determined by the number of digits input. It is
148the arithmetic operations that are governed by context.
149
150\begin{verbatim}
151>>> getcontext().prec = 6
152>>> Decimal('3.0000')
153Decimal("3.0000")
154>>> Decimal('3.0')
155Decimal("3.0")
156>>> Decimal('3.1415926535')
157Decimal("3.1415926535")
158>>> Decimal('3.1415926535') + Decimal('2.7182818285')
159Decimal("5.85987")
160>>> getcontext().rounding = ROUND_UP
161>>> Decimal('3.1415926535') + Decimal('2.7182818285')
162Decimal("5.85988")
163\end{verbatim}
164
165Decimals interact well with much of the rest of python. Here is a small
166decimal floating point flying circus:
167
168\begin{verbatim}
169>>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
170>>> max(data)
171Decimal("9.25")
172>>> min(data)
173Decimal("0.03")
174>>> sorted(data)
175[Decimal("0.03"), Decimal("1.00"), Decimal("1.34"), Decimal("1.87"),
176 Decimal("2.35"), Decimal("3.45"), Decimal("9.25")]
177>>> sum(data)
178Decimal("19.29")
179>>> a,b,c = data[:3]
180>>> str(a)
181'1.34'
182>>> float(a)
1831.3400000000000001
184>>> round(a, 1)
1851.3
186>>> int(a)
1871
188>>> a * 5
189Decimal("6.70")
190>>> a * b
191Decimal("2.5058")
192>>> c % a
193Decimal("0.77")
194\end{verbatim}
195
196The \function{getcontext()} function accesses the current context. This one
197context is sufficient for many applications; however, for more advanced work,
198multiple contexts can be created using the Context() constructor. To make a
199new context active, use the \function{setcontext()} function.
200
201In accordance with the standard, the \module{Decimal} module provides two
202ready to use standard contexts, \constant{BasicContext} and
203\constant{ExtendedContext}. The former is especially useful for debugging
204because many of the traps are enabled:
205
206\begin{verbatim}
207>>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
208>>> myothercontext
209Context(prec=60, rounding=ROUND_HALF_DOWN, Emin=-999999999, Emax=999999999,
210 setflags=[], settraps=[])
211>>> ExtendedContext
212Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
213 setflags=[], settraps=[])
214>>> setcontext(myothercontext)
215>>> Decimal(1) / Decimal(7)
216Decimal("0.142857142857142857142857142857142857142857142857142857142857")
217>>> setcontext(ExtendedContext)
218>>> Decimal(1) / Decimal(7)
219Decimal("0.142857143")
220>>> Decimal(42) / Decimal(0)
221Decimal("Infinity")
222>>> setcontext(BasicContext)
223>>> Decimal(42) / Decimal(0)
224Traceback (most recent call last):
225 File "<pyshell#143>", line 1, in -toplevel-
226 Decimal(42) / Decimal(0)
227DivisionByZero: x / 0
228\end{verbatim}
229
230Besides using contexts to control precision, rounding, and trapping signals,
231they can be used to monitor flags which give information collected during
232computation. The flags remain set until explicitly cleared, so it is best to
233clear the flags before each set of monitored computations by using the
234\method{clear_flags()} method.
235
236\begin{verbatim}
237>>> setcontext(ExtendedContext)
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000238>>> Decimal(355) / Decimal(113)
239Decimal("3.14159292")
240>>> getcontext()
241Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
242 setflags=['Inexact', 'Rounded'], settraps=[])
243\end{verbatim}
244
245The \var{setflags} entry shows that the rational approximation to
246\constant{Pi} was rounded (digits beyond the context precision were thrown
247away) and that the result is inexact (some of the discarded digits were
248non-zero).
249
250Individual traps are set using the dictionary in the \member{trap_enablers}
251field of a context:
252
253\begin{verbatim}
254>>> Decimal(1) / Decimal(0)
255Decimal("Infinity")
256>>> getcontext().trap_enablers[DivisionByZero] = 1
257>>> Decimal(1) / Decimal(0)
258
259Traceback (most recent call last):
260 File "<pyshell#112>", line 1, in -toplevel-
261 Decimal(1) / Decimal(0)
262DivisionByZero: x / 0
263\end{verbatim}
264
265To turn all the traps on or off all at once, use a loop. Also, the
266\method{dict.update()} method is useful for changing a handfull of values.
267
268\begin{verbatim}
269>>> getcontext.clear_flags()
270>>> for sig in getcontext().trap_enablers:
271... getcontext().trap_enablers[sig] = 1
272
273>>> getcontext().trap_enablers.update({Rounded:0, Inexact:0, Subnormal:0})
274>>> getcontext()
275Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
276 setflags=[], settraps=['Underflow', 'DecimalException', 'Clamped',
277 'InvalidContext', 'InvalidOperation', 'ConversionSyntax',
278 'DivisionByZero', 'DivisionImpossible', 'DivisionUndefined',
279 'Overflow'])
280\end{verbatim}
281
282Applications typically set the context once at the beginning of a program
283and no further changes are needed. For many applications, the data resides
284in a resource external to the program and is converted to \class{Decimal} with
285a single cast inside a loop. Afterwards, decimals are as easily manipulated
286as other Python numeric types.
287
288
289
290%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
291\subsection{Decimal objects \label{decimal-decimal}}
292
293\begin{classdesc}{Decimal}{\optional{value \optional{, context}}}
294 Constructs a new \class{Decimal} object based from \var{value}.
295
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000296 \var{value} can be an integer, string, tuple, or another \class{Decimal}
297 object. If no \var{value} is given, returns \code{Decimal("0")}. If
298 \var{value} is a string, it should conform to the decimal numeric string
299 syntax:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000300
301 \begin{verbatim}
302 sign ::= '+' | '-'
303 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
304 indicator ::= 'e' | 'E'
305 digits ::= digit [digit]...
306 decimal-part ::= digits '.' [digits] | ['.'] digits
307 exponent-part ::= indicator [sign] digits
308 infinity ::= 'Infinity' | 'Inf'
309 nan ::= 'NaN' [digits] | 'sNaN' [digits]
310 numeric-value ::= decimal-part [exponent-part] | infinity
311 numeric-string ::= [sign] numeric-value | [sign] nan
312 \end{verbatim}
313
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000314 If \var{value} is a \class{tuple}, it should have three components,
315 a sign (\constant{0} for positive or \constant{1} for negative),
316 a \class{tuple} of digits, and an exponent represented as an integer.
317 For example, \samp{Decimal((0, (1, 4, 1, 4), -3))} returns
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000318 \code{Decimal("1.414")}.
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000319
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000320 The supplied \var{context} or, if not specified, the current context
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000321 governs only the handling of malformed strings not conforming to the
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000322 numeric string syntax. If the context traps \constant{ConversionSyntax},
323 an exception is raised; otherwise, the constructor returns a new Decimal
324 with the value of \constant{NaN}.
325
326 The context serves no other purpose. The number of significant digits
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000327 recorded is determined solely by the \var{value} and the \var{context}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000328 precision is not a factor. For example, \samp{Decimal("3.0000")} records
329 all four zeroes even if the context precision is only three.
330
331 Once constructed, \class{Decimal} objects are immutable.
332\end{classdesc}
333
334Decimal floating point objects share many properties with the other builtin
335numeric types such as \class{float} and \class{int}. All of the usual
336math operations and special methods apply. Likewise, decimal objects can
337be copied, pickled, printed, used as dictionary keys, used as set elements,
338compared, sorted, and coerced to another type (such as \class{float}
339or \class{long}).
340
341In addition to the standard numeric properties, decimal floating point objects
342have a number of more specialized methods:
343
344\begin{methoddesc}{adjusted}{}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000345 Return the adjusted exponent after shifting out the coefficient's rightmost
346 digits until only the lead digit remains: \code{Decimal("321e+5").adjusted()}
347 returns seven. Used for determining the place value of the most significant
348 digit.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000349\end{methoddesc}
350
351\begin{methoddesc}{as_tuple}{}
352 Returns a tuple representation of the number:
353 \samp{(sign, digittuple, exponent)}.
354\end{methoddesc}
355
356\begin{methoddesc}{compare}{other\optional{, context}}
357 Compares like \method{__cmp__()} but returns a decimal instance:
358 \begin{verbatim}
359 a or b is a NaN ==> Decimal("NaN")
360 a < b ==> Decimal("-1")
361 a == b ==> Decimal("0")
362 a > b ==> Decimal("1")
363 \end{verbatim}
364\end{methoddesc}
365
366\begin{methoddesc}{max}{other\optional{, context}}
367 Like \samp{max(self, other)} but returns \constant{NaN} if either is a
368 \constant{NaN}. Applies the context rounding rule before returning.
369\end{methoddesc}
370
371\begin{methoddesc}{min}{other\optional{, context}}
372 Like \samp{min(self, other)} but returns \constant{NaN} if either is a
373 \constant{NaN}. Applies the context rounding rule before returning.
374\end{methoddesc}
375
376\begin{methoddesc}{normalize}{\optional{context}}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000377 Normalize the number by stripping the rightmost trailing zeroes and
378 converting any result equal to \constant{Decimal("0")} to
379 \constant{Decimal("0e0")}. Used for producing canonical values for members
380 of an equivalence class. For example, \code{Decimal("32.100")} and
381 \code{Decimal("0.321000e+2")} both normalize to the equivalent value
382 \code{Decimal("32.1")},
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000383\end{methoddesc}
384
385\begin{methoddesc}{quantize}
386 {\optional{exp \optional{, rounding\optional{, context\optional{, watchexp}}}}}
387 Quantize makes the exponent the same as \var{exp}. Searches for a
388 rounding method in \var{rounding}, then in \var{context}, and then
389 in the current context.
390
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000391 If \var{watchexp} is set (default), then an error is returned whenever
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000392 the resulting exponent is greater than \member{Emax} or less than
393 \member{Etiny}.
394\end{methoddesc}
395
396\begin{methoddesc}{remainder_near}{other\optional{, context}}
397 Computed the modulo as either a positive or negative value depending
398 on which is closest to zero. For instance,
399 \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")}
400 which is closer to zero than \code{Decimal("4")}.
401
402 If both are equally close, the one chosen will have the same sign
403 as \var{self}.
404\end{methoddesc}
405
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000406\begin{methoddesc}{same_quantum}{other\optional{, context}}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000407 Test whether self and other have the same exponent or whether both
408 are \constant{NaN}.
409\end{methoddesc}
410
411\begin{methoddesc}{sqrt}{\optional{context}}
412 Return the square root to full precision.
413\end{methoddesc}
414
415\begin{methoddesc}{to_eng_string}{\optional{context}}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000416 Convert to an engineering-type string.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000417
418 Engineering notation has an exponent which is a multiple of 3, so there
419 are up to 3 digits left of the decimal place. For example, converts
420 \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")}
421\end{methoddesc}
422
423\begin{methoddesc}{to_integral}{\optional{rounding\optional{, context}}}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000424 Rounds to the nearest integer without signaling \constant{Inexact}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000425 or \constant{Rounded}. If given, applies \var{rounding}; otherwise,
426 uses the rounding method in either the supplied \var{context} or the
427 current context.
428\end{methoddesc}
429
430
431%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
432\subsection{Context objects \label{decimal-decimal}}
433
434Contexts are environments for arithmetic operations. They govern the precision,
435rules for rounding, determine which signals are treated as exceptions, and set limits
436on the range for exponents.
437
438Each thread has its own current context which is accessed or changed using
439the \function{getcontext()} and \function{setcontext()} functions:
440
441\begin{funcdesc}{getcontext}{}
442 Return the current context for the active thread.
443\end{funcdesc}
444
445\begin{funcdesc}{setcontext}{c}
446 Set the current context for the active thread to \var{c}.
447\end{funcdesc}
448
449New contexts can formed using the \class{Context} constructor described below.
450In addition, the module provides three pre-made contexts:
451
452
453\begin{classdesc*}{BasicContext}
454 This is a standard context defined by the General Decimal Arithmetic
455 Specification. Precision is set to nine. Rounding is set to
456 \constant{ROUND_HALF_UP}. All flags are cleared. All traps are enabled
457 (treated as exceptions) except \constant{Inexact}, \constant{Rounded}, and
458 \constant{Subnormal}.
459
460 Because many of the traps are enabled, this context is useful for debugging.
461\end{classdesc*}
462
463\begin{classdesc*}{ExtendedContext}
464 This is a standard context defined by the General Decimal Arithmetic
465 Specification. Precision is set to nine. Rounding is set to
466 \constant{ROUND_HALF_EVEN}. All flags are cleared. No traps are enabled
467 (so that exceptions are not raised during computations).
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000468
469 Because the trapped are disabled, this context is useful for applications
470 that prefer to have result value of \constant{NaN} or \constant{Infinity}
471 instead of raising exceptions. This allows an application to complete a
472 run in the presense of conditions that would otherwise halt the program.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000473\end{classdesc*}
474
475\begin{classdesc*}{DefaultContext}
476 This class is used by the \class{Context} constructor as a prototype for
477 new contexts. Changing a field (such a precision) has the effect of
478 changing the default for new contexts creating by the \class{Context}
479 constructor.
480
481 This context is most useful in multi-threaded environments. Changing one of
482 the fields before threads are started has the effect of setting system-wide
483 defaults. Changing the fields after threads have started is not recommended
484 as it would require thread synchronization to prevent race conditions.
485
486 In single threaded environments, it is preferable to not use this context
487 at all. Instead, simply create contexts explicitly. This is especially
488 important because the default values context may change between releases
489 (with initial release having precision=28, rounding=ROUND_HALF_EVEN,
490 cleared flags, and no traps enabled).
491\end{classdesc*}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000492
493
494In addition to the three supplied contexts, new contexts can be created
495with the \class{Context} constructor.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000496
497\begin{classdesc}{Context}{prec=None, rounding=None, trap_enablers=None,
498 flags=None, Emin=None, Emax=None, capitals=1}
499 Creates a new context. If a field is not specified or is \constant{None},
500 the default values are copied from the \constant{DefaultContext}. If the
501 \var{flags} field is not specified or is \constant{None}, all flags are
502 cleared.
503
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000504 The \var{prec} field is a positive integer that sets the precision for
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000505 arithmetic operations in the context.
506
507 The \var{rounding} option is one of: \constant{ROUND_CEILING},
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000508 \constant{ROUND_DOWN}, \constant{ROUND_FLOOR}, \constant{ROUND_HALF_DOWN}
509 (towards zero), \constant{ROUND_HALF_EVEN}, \constant{ROUND_HALF_UP}, or
510 \constant{ROUND_UP} (away from zero).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000511
512 The \var{trap_enablers} and \var{flags} fields are mappings from signals
513 to either \constant{0} or \constant{1}.
514
515 The \var{Emin} and \var{Emax} fields are integers specifying the outer
516 limits allowable for exponents.
517
518 The \var{capitals} field is either \constant{0} or \constant{1} (the
519 default). If set to \constant{1}, exponents are printed with a capital
520 \constant{E}; otherwise, lowercase is used: \constant{Decimal('6.02e+23')}.
521\end{classdesc}
522
523The \class{Context} class defines several general methods as well as a
524large number of methods for doing arithmetic directly from the context.
525
526\begin{methoddesc}{clear_flags}{}
527 Sets all of the flags to \constant{0}.
528\end{methoddesc}
529
530\begin{methoddesc}{copy}{}
531 Returns a duplicate of the context.
532\end{methoddesc}
533
534\begin{methoddesc}{create_decimal}{num}
535 Creates a new Decimal instance but using \var{self} as context.
536 Unlike the \class{Decimal} constructor, context precision,
537 rounding method, flags, and traps are applied to the conversion.
538
539 This is useful because constants are often given to a greater
540 precision than is needed by the application.
541\end{methoddesc}
542
543\begin{methoddesc}{Etiny}{}
544 Returns a value equal to \samp{Emin - prec + 1} which is the minimum
545 exponent value for subnormal results. When underflow occurs, the
546 exponont is set to \constant{Etiny}.
547\end{methoddesc}
548
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000549\begin{methoddesc}{Etop}{}
550 Returns a value equal to \samp{Emax - prec + 1}.
551\end{methoddesc}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000552
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000553
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000554The usual approach to working with decimals is to create \class{Decimal}
555instances and then apply arithmetic operations which take place within the
556current context for the active thread. An alternate approach is to use
557context methods for calculating within s specific context. The methods are
558similar to those for the \class{Decimal} class and are only briefly recounted
559here.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000560
561\begin{methoddesc}{abs}{x}
562 Returns the absolute value of \var{x}.
563\end{methoddesc}
564
565\begin{methoddesc}{add}{x, y}
566 Return the sum of \var{x} and \var{y}.
567\end{methoddesc}
568
569\begin{methoddesc}{compare}{x, y}
570 Compares values numerically.
571
572 Like \method{__cmp__()} but returns a decimal instance:
573 \begin{verbatim}
574 a or b is a NaN ==> Decimal("NaN")
575 a < b ==> Decimal("-1")
576 a == b ==> Decimal("0")
577 a > b ==> Decimal("1")
578 \end{verbatim}
579\end{methoddesc}
580
581\begin{methoddesc}{divide}{x, y}
582 Return \var{x} divided by \var{y}.
583\end{methoddesc}
584
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000585\begin{methoddesc}{divmod}{x, y}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000586 Divides two numbers and returns the integer part of the result.
587\end{methoddesc}
588
589\begin{methoddesc}{max}{x, y}
590 Compare two values numerically and returns the maximum.
591
592 If they are numerically equal then the left-hand operand is chosen as the
593 result.
594\end{methoddesc}
595
596\begin{methoddesc}{min}{x, y}
597 Compare two values numerically and returns the minimum.
598
599 If they are numerically equal then the left-hand operand is chosen as the
600 result.
601\end{methoddesc}
602
603\begin{methoddesc}{minus}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000604 Minus corresponds to the unary prefix minus operator in Python.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000605\end{methoddesc}
606
607\begin{methoddesc}{multiply}{x, y}
608 Return the product of \var{x} and \var{y}.
609\end{methoddesc}
610
611\begin{methoddesc}{normalize}{x}
612 Normalize reduces an operand to its simplest form.
613
614 Essentially a plus operation with all trailing zeros removed from the
615 result.
616\end{methoddesc}
617
618\begin{methoddesc}{plus}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000619 Minus corresponds to the unary prefix plus operator in Python.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000620\end{methoddesc}
621
622\begin{methoddesc}{power}{x, y\optional{, modulo}}
623 Return \samp{x ** y} to the \var{modulo} if given.
624
625 The right-hand operand must be a whole number whose integer part (after any
626 exponent has been applied) has no more than 9 digits and whose fractional
627 part (if any) is all zeros before any rounding. The operand may be positive,
628 negative, or zero; if negative, the absolute value of the power is used, and
629 the left-hand operand is inverted (divided into 1) before use.
630
631 If the increased precision needed for the intermediate calculations exceeds
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000632 the capabilities of the implementation then an \constant{InvalidOperation}
633 condition is signaled.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000634
635 If, when raising to a negative power, an underflow occurs during the
636 division into 1, the operation is not halted at that point but continues.
637\end{methoddesc}
638
639\begin{methoddesc}{quantize}{x, y}
640 Returns a value equal to \var{x} after rounding and having the
641 exponent of v\var{y}.
642
643 Unlike other operations, if the length of the coefficient after the quantize
644 operation would be greater than precision then an
645 \constant{InvalidOperation} is signaled. This guarantees that, unless there
646 is an error condition, the exponent of the result of a quantize is always
647 equal to that of the right-hand operand.
648
649 Also unlike other operations, quantize never signals Underflow, even
650 if the result is subnormal and inexact.
651\end{methoddesc}
652
653\begin{methoddesc}{remainder}{x, y}
654 Returns the remainder from integer division.
655
656 The sign of the result, if non-zero, is the same as that of the original
657 dividend.
658\end{methoddesc}
659
660\begin{methoddesc}{remainder_near}{x, y}
661 Computed the modulo as either a positive or negative value depending
662 on which is closest to zero. For instance,
663 \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")}
664 which is closer to zero than \code{Decimal("4")}.
665
666 If both are equally close, the one chosen will have the same sign
667 as \var{self}.
668\end{methoddesc}
669
670\begin{methoddesc}{same_quantum}{x, y}
671 Test whether \var{x} and \var{y} have the same exponent or whether both are
672 \constant{NaN}.
673\end{methoddesc}
674
675\begin{methoddesc}{sqrt}{}
676 Return the square root to full precision.
677\end{methoddesc}
678
679\begin{methoddesc}{substract}{x, y}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000680 Return the difference between \var{x} and \var{y}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000681\end{methoddesc}
682
683\begin{methoddesc}{to_eng_string}{}
684 Convert to engineering-type string.
685
686 Engineering notation has an exponent which is a multiple of 3, so there
687 are up to 3 digits left of the decimal place. For example, converts
688 \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")}
689\end{methoddesc}
690
691\begin{methoddesc}{to_integral}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000692 Rounds to the nearest integer without signaling \constant{Inexact}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000693 or \constant{Rounded}.
694\end{methoddesc}
695
696\begin{methoddesc}{to_sci_string}{}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000697 Converts a number to a string using scientific notation.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000698\end{methoddesc}
699
700
701
702%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
703\subsection{Signals \label{decimal-signals}}
704
705Signals represent conditions that arise during computation.
706Each corresponds to one context flag and one context trap enabler.
707
708The context flag is incremented whenever the condition is encountered.
709After the computation, flags may be checked for informational
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000710purposes (for instance, to determine whether a computation was exact).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000711After checking the flags, be sure to clear all flags before starting
712the next computation.
713
714If the context's trap enabler is set for the signal, then the condition
715causes a Python exception to be raised. For example, if the
716\class{DivisionByZero} trap is set, the a \exception{DivisionByZero}
717exception is raised upon encountering the condition.
718
719
720\begin{classdesc*}{Clamped}
721 Altered an exponent to fit representation constraints.
722
723 Typically, clamping occurs when an exponent falls outside the context's
724 \member{Emin} and \member{Emax} limits. If possible, the exponent is
725 reduced to fit by adding zeroes to the coefficient.
726\end{classdesc*}
727
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000728\begin{classdesc*}{ConversionSyntax}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000729 Trying to convert a malformed string such as: \code{Decimal('jump')}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000730
731 Decimal converts only strings conforming to the numeric string
732 syntax. If this signal is not trapped, returns \constant{NaN}.
733\end{classdesc*}
734
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000735\begin{classdesc*}{DecimalException}
736 Base class for other signals.
737\end{classdesc*}
738
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000739\begin{classdesc*}{DivisionByZero}
740 Signals the division of a non-infinite number by zero.
741
742 Can occur with division, modulo division, or when raising a number to
743 a negative power. If this signal is not trapped, return
744 \constant{Infinity} or \constant{-Infinity} with sign determined by
745 the inputs to the calculation.
746\end{classdesc*}
747
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000748\begin{classdesc*}{DivisionImpossible}
749 Error performing a division operation. Caused when an intermediate result
750 has more digits that the allowed by the current precision. If not trapped,
751 returns \constant{NaN}.
752\end{classdesc*}
753
754
755\begin{classdesc*}{DivisionUndefined}
756 This is a subclass of \class{DivisionByZero}.
757
758 It occurs only in the context of division operations.
759\end{classdesc*}
760
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000761\begin{classdesc*}{Inexact}
762 Indicates that rounding occurred and the result is not exact.
763
764 Signals whenever non-zero digits were discarded during rounding.
765 The rounded result is returned. The signal flag or trap is used
766 to detect when results are inexact.
767\end{classdesc*}
768
769
770\begin{classdesc*}{InvalidContext}
771 This is a subclass of \class{InvalidOperation}.
772
773 Indicates an error within the Context object such as an unknown
774 rounding operation. If not trapped, returns \constant{NaN}.
775\end{classdesc*}
776
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000777\begin{classdesc*}{InvalidOperation}
778 An invalid operation was performed.
779
780 Indicates that an operation was requested that does not make sense.
781 If not trapped, returns \constant{NaN}. Possible causes include:
782
783 \begin{verbatim}
784 Infinity - Infinity
785 0 * Infinity
786 Infinity / Infinity
787 x % 0
788 Infinity % x
789 x._rescale( non-integer )
790 sqrt(-x) and x > 0
791 0 ** 0
792 x ** (non-integer)
793 x ** Infinity
794 \end{verbatim}
795\end{classdesc*}
796
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000797\begin{classdesc*}{Overflow}
798 Numerical overflow.
799
800 Indicates the exponent is larger than \member{Emax} after rounding has
801 occurred. If not trapped, the result depends on the rounding mode, either
802 pulling inward to the largest representable finite number or rounding
803 outward to \constant{Infinity}. In either case, \class{Inexact} and
804 \class{Rounded} are also signaled.
805\end{classdesc*}
806
807
808\begin{classdesc*}{Rounded}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000809 Rounding occurred though possibly no information was lost.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000810
811 Signaled whenever rounding discards digits; even if those digits are
812 zero (such as rounding \constant{5.00} to \constant{5.0}). If not
813 trapped, returns the result unchanged. This signal is used to detect
814 loss of significant digits.
815\end{classdesc*}
816
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000817\begin{classdesc*}{Subnormal}
818 Exponent was lower than \member{Emin} prior to rounding.
819
820 Occurs when an operation result is subnormal (the exponent is too small).
821 If not trapped, returns the result unchanged.
822\end{classdesc*}
823
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000824\begin{classdesc*}{Underflow}
825 Numerical underflow with result rounded to zero.
826
827 Occurs when a subnormal result is pushed to zero by rounding.
828 \class{Inexact} and \class{Subnormal} are also signaled.
829\end{classdesc*}
830
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000831The following table summarizes the hierarchy of signals:
832
833\begin{verbatim}
834 exceptions.ArithmeticError(exceptions.StandardError)
835 DecimalException
836 Clamped
837 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
838 Inexact
839 Overflow(Inexact, Rounded)
840 Underflow(Inexact, Rounded, Subnormal)
841 InvalidOperation
842 ConversionSyntax
843 DivisionImpossible
844 DivisionUndefined(InvalidOperation, exceptions.ZeroDivisionError)
845 InvalidContext
846 Rounded
847 Subnormal
848\end{verbatim}
849
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000850
851
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000852%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
853\subsection{Working with threads \label{decimal-threads}}
854
855The \function{getcontext()} function accesses a different \class{Context}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000856object for each thread. Having separate thread contexts means that threads
857may make changes (such as \code{getcontext.prec=10}) without interfering with
858other threads and without needing mutexes.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000859
860Likewise, the \function{setcontext()} function automatically assigns its target
861to the current thread.
862
863If \function{setcontext()} has not been called before \function{getcontext()},
864then \function{getcontext()} will automatically create a new context for use
865in the current thread.
866
867The new context is copied from a prototype context called \var{DefaultContext}.
868To control the defaults so that each thread will use the same values
869throughout the application, directly modify the \var{DefaultContext} object.
870This should be done \emph{before} any threads are started so that there won't
871be a race condition with threads calling \function{getcontext()}. For example:
872
873\begin{verbatim}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000874# Set applicationwide defaults for all threads about to be launched
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000875DefaultContext.prec=12
876DefaultContext.rounding=ROUND_DOWN
877DefaultContext.trap_enablers=dict.fromkeys(Signals, 0)
878setcontext(DefaultContext)
879
880# Now start all of the threads
881t1.start()
882t2.start()
883t3.start()
884 . . .
885\end{verbatim}
886
887
888
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000889%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
890\subsection{Recipes \label{decimal-recipes}}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000891
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000892Here are some functions demonstrating ways to work with the
893\class{Decimal} class:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000894
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000895\begin{verbatim}
896from decimal import Decimal, getcontext
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000897getcontext().prec = 28
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000898
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000899def moneyfmt(value, places=2, curr='$', sep=',', dp='.', pos='', neg='-'):
900 """Convert Decimal to a money formatted string.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000901
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000902 places: required number of places after the decimal point
903 curr: optional currency symbol before the sign (may be blank)
904 sep: optional grouping separator (comma, period, or blank)
905 dp: decimal point indicator (comma or period)
906 only set to blank if places is zero
907 pos: optional sign for positive numbers ("+" or blank)
908 neg: optional sign for negative numbers ("-" or blank)
909 leave blank to separately add brackets or a trailing minus
910
911 >>> d = Decimal('-1234567.8901')
912 >>> moneyfmt(d)
913 '-$1,234,567.89'
914 >>> moneyfmt(d, places=0, curr='', sep='.', dp='')
915 '-1.234.568'
916 >>> '($%s)' % moneyfmt(d, curr='', neg='')
917 '($1,234,567.89)'
918 """
919 q = Decimal((0, (1,), -places)) # 2 places --> '0.01'
920 sign, digits, exp = value.quantize(q).as_tuple()
921 result = []
922 digits = map(str, digits)
923 build, next = result.append, digits.pop
924 for i in range(places):
925 build(next())
926 build(dp)
927 try:
928 while 1:
929 for i in range(3):
930 build(next())
931 if digits:
932 build(sep)
933 except IndexError:
934 pass
935 build(curr)
936 if sign:
937 build(neg)
938 else:
939 build(pos)
940 result.reverse()
941 return ''.join(result)
942
943def pi():
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000944 """Compute Pi to the current precision.
945
946 >>> print pi()
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000947 3.141592653589793238462643383
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000948 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000949 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettinger10959b12004-07-05 21:13:28 +0000950 three = Decimal(3) # substitute "three=3.0" for regular floats
Raymond Hettinger77e13b42004-07-05 20:27:53 +0000951 lastc, t, c, n, na, d, da = 0, three, 3, 1, 0, 0, 24
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000952 while c != lastc:
953 lastc = c
954 n, na = n+na, na+8
955 d, da = d+da, da+32
956 t = (t * n) / d
957 c += t
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000958 getcontext().prec -= 2
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000959 return c + 0 # Adding zero causes rounding to the new precision
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000960
961def exp(x):
Raymond Hettinger10959b12004-07-05 21:13:28 +0000962 """Return e raised to the power of x. Result type matches input type.
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000963
964 >>> print exp(Decimal(1))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000965 2.718281828459045235360287471
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000966 >>> print exp(Decimal(2))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000967 7.389056098930650227230427461
Raymond Hettinger10959b12004-07-05 21:13:28 +0000968 >>> print exp(2.0)
969 7.38905609893
970 >>> print exp(2+0j)
971 (7.38905609893+0j)
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000972 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000973 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000974 i, laste, e, fact, num = 0, 0, 1, 1, 1
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000975 while e != laste:
976 laste = e
977 i += 1
978 fact *= i
979 num *= x
980 e += num / fact
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000981 getcontext().prec -= 2
982 return e + 0
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000983
984def cos(x):
985 """Return the cosine of x as measured in radians.
986
987 >>> print cos(Decimal('0.5'))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000988 0.8775825618903727161162815826
Raymond Hettinger10959b12004-07-05 21:13:28 +0000989 >>> print cos(0.5)
990 0.87758256189
991 >>> print cos(0.5+0j)
992 (0.87758256189+0j)
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000993 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000994 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000995 i, laste, e, fact, num, sign = 0, 0, 1, 1, 1, 1
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000996 while e != laste:
997 laste = e
998 i += 2
999 fact *= i * (i-1)
1000 num *= x * x
1001 sign *= -1
1002 e += num / fact * sign
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001003 getcontext().prec -= 2
1004 return e + 0
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001005
1006def sin(x):
1007 """Return the cosine of x as measured in radians.
1008
1009 >>> print sin(Decimal('0.5'))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001010 0.4794255386042030002732879352
Raymond Hettinger10959b12004-07-05 21:13:28 +00001011 >>> print sin(0.5)
1012 0.479425538604
1013 >>> print sin(0.5+0j)
1014 (0.479425538604+0j)
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001015 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001016 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettingerc4f93d442004-07-05 20:17:13 +00001017 i, laste, e, fact, num, sign = 1, 0, x, 1, x, 1
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001018 while e != laste:
1019 laste = e
1020 i += 2
1021 fact *= i * (i-1)
1022 num *= x * x
1023 sign *= -1
1024 e += num / fact * sign
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001025 getcontext().prec -= 2
1026 return e + 0
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001027
1028\end{verbatim}