blob: 3b41d6a7ed63d1b3572a01f7a0335805f1437098 [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
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
Raymond Hettinger97c92082004-07-09 06:13:12 +000092is set to one, an exception is raised. Flags are sticky, so the user
93needs to reset them before monitoring a calculation.
Raymond Hettinger8de63a22004-07-05 05:52:03 +000094
95
96\begin{seealso}
97 \seetext{IBM's General Decimal Arithmetic Specification,
98 \citetitle[http://www2.hursley.ibm.com/decimal/decarith.html]
99 {The General Decimal Arithmetic Specification}.}
100
101 \seetext{IEEE standard 854-1987,
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000102 \citetitle[http://www.cs.berkeley.edu/\textasciitilde ejr/projects/754/private/drafts/854-1987/dir.html]
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000103 {Unofficial IEEE 854 Text}.}
104\end{seealso}
105
106
107
108%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
109\subsection{Quick-start Tutorial \label{decimal-tutorial}}
110
111The normal start to using decimals is to import the module, and then use
112\function{getcontext()} to view the context and, if necessary, set the context
113precision, rounding, or trap enablers:
114
115\begin{verbatim}
116>>> from decimal import *
117>>> getcontext()
118Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
119 setflags=[], settraps=[])
120
121>>> getcontext().prec = 7
122\end{verbatim}
123
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000124Decimal instances can be constructed from integers, strings or tuples. To
125create a Decimal from a \class{float}, first convert it to a string. This
126serves as an explicit reminder of the details of the conversion (including
127representation error). Malformed strings signal \constant{ConversionSyntax}
128and return a special kind of Decimal called a \constant{NaN} which stands for
129``Not a number''. Positive and negative \constant{Infinity} is yet another
130special kind of Decimal.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000131
132\begin{verbatim}
133>>> Decimal(10)
134Decimal("10")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000135>>> Decimal("3.14")
136Decimal("3.14")
137>>> Decimal((0, (3, 1, 4), -2))
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000138Decimal("3.14")
139>>> Decimal(str(2.0 ** 0.5))
140Decimal("1.41421356237")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000141>>> Decimal("NaN")
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000142Decimal("NaN")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000143>>> Decimal("-Infinity")
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000144Decimal("-Infinity")
145\end{verbatim}
146
147Creating decimals is unaffected by context precision. Their level of
148significance is completely determined by the number of digits input. It is
149the arithmetic operations that are governed by context.
150
151\begin{verbatim}
152>>> getcontext().prec = 6
153>>> Decimal('3.0000')
154Decimal("3.0000")
155>>> Decimal('3.0')
156Decimal("3.0")
157>>> Decimal('3.1415926535')
158Decimal("3.1415926535")
159>>> Decimal('3.1415926535') + Decimal('2.7182818285')
160Decimal("5.85987")
161>>> getcontext().rounding = ROUND_UP
162>>> Decimal('3.1415926535') + Decimal('2.7182818285')
163Decimal("5.85988")
164\end{verbatim}
165
166Decimals interact well with much of the rest of python. Here is a small
167decimal floating point flying circus:
168
169\begin{verbatim}
170>>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
171>>> max(data)
172Decimal("9.25")
173>>> min(data)
174Decimal("0.03")
175>>> sorted(data)
176[Decimal("0.03"), Decimal("1.00"), Decimal("1.34"), Decimal("1.87"),
177 Decimal("2.35"), Decimal("3.45"), Decimal("9.25")]
178>>> sum(data)
179Decimal("19.29")
180>>> a,b,c = data[:3]
181>>> str(a)
182'1.34'
183>>> float(a)
1841.3400000000000001
185>>> round(a, 1)
1861.3
187>>> int(a)
1881
189>>> a * 5
190Decimal("6.70")
191>>> a * b
192Decimal("2.5058")
193>>> c % a
194Decimal("0.77")
195\end{verbatim}
196
197The \function{getcontext()} function accesses the current context. This one
198context is sufficient for many applications; however, for more advanced work,
199multiple contexts can be created using the Context() constructor. To make a
200new context active, use the \function{setcontext()} function.
201
202In accordance with the standard, the \module{Decimal} module provides two
203ready to use standard contexts, \constant{BasicContext} and
204\constant{ExtendedContext}. The former is especially useful for debugging
205because many of the traps are enabled:
206
207\begin{verbatim}
208>>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
209>>> myothercontext
210Context(prec=60, rounding=ROUND_HALF_DOWN, Emin=-999999999, Emax=999999999,
211 setflags=[], settraps=[])
212>>> ExtendedContext
213Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
214 setflags=[], settraps=[])
215>>> setcontext(myothercontext)
216>>> Decimal(1) / Decimal(7)
217Decimal("0.142857142857142857142857142857142857142857142857142857142857")
218>>> setcontext(ExtendedContext)
219>>> Decimal(1) / Decimal(7)
220Decimal("0.142857143")
221>>> Decimal(42) / Decimal(0)
222Decimal("Infinity")
223>>> setcontext(BasicContext)
224>>> Decimal(42) / Decimal(0)
225Traceback (most recent call last):
226 File "<pyshell#143>", line 1, in -toplevel-
227 Decimal(42) / Decimal(0)
228DivisionByZero: x / 0
229\end{verbatim}
230
231Besides using contexts to control precision, rounding, and trapping signals,
232they can be used to monitor flags which give information collected during
233computation. The flags remain set until explicitly cleared, so it is best to
234clear the flags before each set of monitored computations by using the
235\method{clear_flags()} method.
236
237\begin{verbatim}
238>>> setcontext(ExtendedContext)
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000239>>> Decimal(355) / Decimal(113)
240Decimal("3.14159292")
241>>> getcontext()
242Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
243 setflags=['Inexact', 'Rounded'], settraps=[])
244\end{verbatim}
245
246The \var{setflags} entry shows that the rational approximation to
247\constant{Pi} was rounded (digits beyond the context precision were thrown
248away) and that the result is inexact (some of the discarded digits were
249non-zero).
250
251Individual traps are set using the dictionary in the \member{trap_enablers}
252field of a context:
253
254\begin{verbatim}
255>>> Decimal(1) / Decimal(0)
256Decimal("Infinity")
257>>> getcontext().trap_enablers[DivisionByZero] = 1
258>>> Decimal(1) / Decimal(0)
259
260Traceback (most recent call last):
261 File "<pyshell#112>", line 1, in -toplevel-
262 Decimal(1) / Decimal(0)
263DivisionByZero: x / 0
264\end{verbatim}
265
266To turn all the traps on or off all at once, use a loop. Also, the
267\method{dict.update()} method is useful for changing a handfull of values.
268
269\begin{verbatim}
270>>> getcontext.clear_flags()
271>>> for sig in getcontext().trap_enablers:
272... getcontext().trap_enablers[sig] = 1
273
274>>> getcontext().trap_enablers.update({Rounded:0, Inexact:0, Subnormal:0})
275>>> getcontext()
276Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
277 setflags=[], settraps=['Underflow', 'DecimalException', 'Clamped',
278 'InvalidContext', 'InvalidOperation', 'ConversionSyntax',
279 'DivisionByZero', 'DivisionImpossible', 'DivisionUndefined',
280 'Overflow'])
281\end{verbatim}
282
283Applications typically set the context once at the beginning of a program
284and no further changes are needed. For many applications, the data resides
285in a resource external to the program and is converted to \class{Decimal} with
286a single cast inside a loop. Afterwards, decimals are as easily manipulated
287as other Python numeric types.
288
289
290
291%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
292\subsection{Decimal objects \label{decimal-decimal}}
293
294\begin{classdesc}{Decimal}{\optional{value \optional{, context}}}
295 Constructs a new \class{Decimal} object based from \var{value}.
296
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000297 \var{value} can be an integer, string, tuple, or another \class{Decimal}
298 object. If no \var{value} is given, returns \code{Decimal("0")}. If
299 \var{value} is a string, it should conform to the decimal numeric string
300 syntax:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000301
302 \begin{verbatim}
303 sign ::= '+' | '-'
304 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
305 indicator ::= 'e' | 'E'
306 digits ::= digit [digit]...
307 decimal-part ::= digits '.' [digits] | ['.'] digits
308 exponent-part ::= indicator [sign] digits
309 infinity ::= 'Infinity' | 'Inf'
310 nan ::= 'NaN' [digits] | 'sNaN' [digits]
311 numeric-value ::= decimal-part [exponent-part] | infinity
312 numeric-string ::= [sign] numeric-value | [sign] nan
313 \end{verbatim}
314
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000315 If \var{value} is a \class{tuple}, it should have three components,
316 a sign (\constant{0} for positive or \constant{1} for negative),
317 a \class{tuple} of digits, and an exponent represented as an integer.
318 For example, \samp{Decimal((0, (1, 4, 1, 4), -3))} returns
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000319 \code{Decimal("1.414")}.
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000320
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000321 The supplied \var{context} or, if not specified, the current context
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000322 governs only the handling of malformed strings not conforming to the
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000323 numeric string syntax. If the context traps \constant{ConversionSyntax},
324 an exception is raised; otherwise, the constructor returns a new Decimal
325 with the value of \constant{NaN}.
326
327 The context serves no other purpose. The number of significant digits
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000328 recorded is determined solely by the \var{value} and the \var{context}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000329 precision is not a factor. For example, \samp{Decimal("3.0000")} records
330 all four zeroes even if the context precision is only three.
331
332 Once constructed, \class{Decimal} objects are immutable.
333\end{classdesc}
334
335Decimal floating point objects share many properties with the other builtin
336numeric types such as \class{float} and \class{int}. All of the usual
337math operations and special methods apply. Likewise, decimal objects can
338be copied, pickled, printed, used as dictionary keys, used as set elements,
339compared, sorted, and coerced to another type (such as \class{float}
340or \class{long}).
341
342In addition to the standard numeric properties, decimal floating point objects
343have a number of more specialized methods:
344
345\begin{methoddesc}{adjusted}{}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000346 Return the adjusted exponent after shifting out the coefficient's rightmost
347 digits until only the lead digit remains: \code{Decimal("321e+5").adjusted()}
348 returns seven. Used for determining the place value of the most significant
349 digit.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000350\end{methoddesc}
351
352\begin{methoddesc}{as_tuple}{}
353 Returns a tuple representation of the number:
354 \samp{(sign, digittuple, exponent)}.
355\end{methoddesc}
356
357\begin{methoddesc}{compare}{other\optional{, context}}
358 Compares like \method{__cmp__()} but returns a decimal instance:
359 \begin{verbatim}
360 a or b is a NaN ==> Decimal("NaN")
361 a < b ==> Decimal("-1")
362 a == b ==> Decimal("0")
363 a > b ==> Decimal("1")
364 \end{verbatim}
365\end{methoddesc}
366
367\begin{methoddesc}{max}{other\optional{, context}}
368 Like \samp{max(self, other)} but returns \constant{NaN} if either is a
369 \constant{NaN}. Applies the context rounding rule before returning.
370\end{methoddesc}
371
372\begin{methoddesc}{min}{other\optional{, context}}
373 Like \samp{min(self, other)} but returns \constant{NaN} if either is a
374 \constant{NaN}. Applies the context rounding rule before returning.
375\end{methoddesc}
376
377\begin{methoddesc}{normalize}{\optional{context}}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000378 Normalize the number by stripping the rightmost trailing zeroes and
379 converting any result equal to \constant{Decimal("0")} to
380 \constant{Decimal("0e0")}. Used for producing canonical values for members
381 of an equivalence class. For example, \code{Decimal("32.100")} and
382 \code{Decimal("0.321000e+2")} both normalize to the equivalent value
383 \code{Decimal("32.1")},
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000384\end{methoddesc}
385
386\begin{methoddesc}{quantize}
387 {\optional{exp \optional{, rounding\optional{, context\optional{, watchexp}}}}}
388 Quantize makes the exponent the same as \var{exp}. Searches for a
389 rounding method in \var{rounding}, then in \var{context}, and then
390 in the current context.
391
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000392 If \var{watchexp} is set (default), then an error is returned whenever
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000393 the resulting exponent is greater than \member{Emax} or less than
394 \member{Etiny}.
395\end{methoddesc}
396
397\begin{methoddesc}{remainder_near}{other\optional{, context}}
398 Computed the modulo as either a positive or negative value depending
399 on which is closest to zero. For instance,
400 \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")}
401 which is closer to zero than \code{Decimal("4")}.
402
403 If both are equally close, the one chosen will have the same sign
404 as \var{self}.
405\end{methoddesc}
406
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000407\begin{methoddesc}{same_quantum}{other\optional{, context}}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000408 Test whether self and other have the same exponent or whether both
409 are \constant{NaN}.
410\end{methoddesc}
411
412\begin{methoddesc}{sqrt}{\optional{context}}
413 Return the square root to full precision.
414\end{methoddesc}
415
416\begin{methoddesc}{to_eng_string}{\optional{context}}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000417 Convert to an engineering-type string.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000418
419 Engineering notation has an exponent which is a multiple of 3, so there
420 are up to 3 digits left of the decimal place. For example, converts
421 \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")}
422\end{methoddesc}
423
424\begin{methoddesc}{to_integral}{\optional{rounding\optional{, context}}}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000425 Rounds to the nearest integer without signaling \constant{Inexact}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000426 or \constant{Rounded}. If given, applies \var{rounding}; otherwise,
427 uses the rounding method in either the supplied \var{context} or the
428 current context.
429\end{methoddesc}
430
431
432%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
433\subsection{Context objects \label{decimal-decimal}}
434
435Contexts are environments for arithmetic operations. They govern the precision,
436rules for rounding, determine which signals are treated as exceptions, and set limits
437on the range for exponents.
438
439Each thread has its own current context which is accessed or changed using
440the \function{getcontext()} and \function{setcontext()} functions:
441
442\begin{funcdesc}{getcontext}{}
443 Return the current context for the active thread.
444\end{funcdesc}
445
446\begin{funcdesc}{setcontext}{c}
447 Set the current context for the active thread to \var{c}.
448\end{funcdesc}
449
450New contexts can formed using the \class{Context} constructor described below.
451In addition, the module provides three pre-made contexts:
452
453
454\begin{classdesc*}{BasicContext}
455 This is a standard context defined by the General Decimal Arithmetic
456 Specification. Precision is set to nine. Rounding is set to
457 \constant{ROUND_HALF_UP}. All flags are cleared. All traps are enabled
458 (treated as exceptions) except \constant{Inexact}, \constant{Rounded}, and
459 \constant{Subnormal}.
460
461 Because many of the traps are enabled, this context is useful for debugging.
462\end{classdesc*}
463
464\begin{classdesc*}{ExtendedContext}
465 This is a standard context defined by the General Decimal Arithmetic
466 Specification. Precision is set to nine. Rounding is set to
467 \constant{ROUND_HALF_EVEN}. All flags are cleared. No traps are enabled
468 (so that exceptions are not raised during computations).
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000469
470 Because the trapped are disabled, this context is useful for applications
471 that prefer to have result value of \constant{NaN} or \constant{Infinity}
472 instead of raising exceptions. This allows an application to complete a
473 run in the presense of conditions that would otherwise halt the program.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000474\end{classdesc*}
475
476\begin{classdesc*}{DefaultContext}
477 This class is used by the \class{Context} constructor as a prototype for
478 new contexts. Changing a field (such a precision) has the effect of
479 changing the default for new contexts creating by the \class{Context}
480 constructor.
481
482 This context is most useful in multi-threaded environments. Changing one of
483 the fields before threads are started has the effect of setting system-wide
484 defaults. Changing the fields after threads have started is not recommended
485 as it would require thread synchronization to prevent race conditions.
486
487 In single threaded environments, it is preferable to not use this context
488 at all. Instead, simply create contexts explicitly. This is especially
489 important because the default values context may change between releases
490 (with initial release having precision=28, rounding=ROUND_HALF_EVEN,
491 cleared flags, and no traps enabled).
492\end{classdesc*}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000493
494
495In addition to the three supplied contexts, new contexts can be created
496with the \class{Context} constructor.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000497
498\begin{classdesc}{Context}{prec=None, rounding=None, trap_enablers=None,
499 flags=None, Emin=None, Emax=None, capitals=1}
500 Creates a new context. If a field is not specified or is \constant{None},
501 the default values are copied from the \constant{DefaultContext}. If the
502 \var{flags} field is not specified or is \constant{None}, all flags are
503 cleared.
504
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000505 The \var{prec} field is a positive integer that sets the precision for
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000506 arithmetic operations in the context.
507
Raymond Hettinger97c92082004-07-09 06:13:12 +0000508 The \var{rounding} option is one of:
509 \constant{ROUND_CEILING} (towards \constant{Infinity}),
510 \constant{ROUND_DOWN} (towards zero),
511 \constant{ROUND_FLOOR} (towards \constant{-Infinity}),
512 \constant{ROUND_HALF_DOWN} (towards zero),
513 \constant{ROUND_HALF_EVEN},
514 \constant{ROUND_HALF_UP} (away from zero), or
515 \constant{ROUND_UP} (away from zero).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000516
517 The \var{trap_enablers} and \var{flags} fields are mappings from signals
518 to either \constant{0} or \constant{1}.
519
520 The \var{Emin} and \var{Emax} fields are integers specifying the outer
521 limits allowable for exponents.
522
523 The \var{capitals} field is either \constant{0} or \constant{1} (the
524 default). If set to \constant{1}, exponents are printed with a capital
525 \constant{E}; otherwise, lowercase is used: \constant{Decimal('6.02e+23')}.
526\end{classdesc}
527
528The \class{Context} class defines several general methods as well as a
529large number of methods for doing arithmetic directly from the context.
530
531\begin{methoddesc}{clear_flags}{}
532 Sets all of the flags to \constant{0}.
533\end{methoddesc}
534
535\begin{methoddesc}{copy}{}
536 Returns a duplicate of the context.
537\end{methoddesc}
538
539\begin{methoddesc}{create_decimal}{num}
540 Creates a new Decimal instance but using \var{self} as context.
541 Unlike the \class{Decimal} constructor, context precision,
542 rounding method, flags, and traps are applied to the conversion.
543
544 This is useful because constants are often given to a greater
545 precision than is needed by the application.
546\end{methoddesc}
547
548\begin{methoddesc}{Etiny}{}
549 Returns a value equal to \samp{Emin - prec + 1} which is the minimum
550 exponent value for subnormal results. When underflow occurs, the
551 exponont is set to \constant{Etiny}.
552\end{methoddesc}
553
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000554\begin{methoddesc}{Etop}{}
555 Returns a value equal to \samp{Emax - prec + 1}.
556\end{methoddesc}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000557
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000558
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000559The usual approach to working with decimals is to create \class{Decimal}
560instances and then apply arithmetic operations which take place within the
561current context for the active thread. An alternate approach is to use
562context methods for calculating within s specific context. The methods are
563similar to those for the \class{Decimal} class and are only briefly recounted
564here.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000565
566\begin{methoddesc}{abs}{x}
567 Returns the absolute value of \var{x}.
568\end{methoddesc}
569
570\begin{methoddesc}{add}{x, y}
571 Return the sum of \var{x} and \var{y}.
572\end{methoddesc}
573
574\begin{methoddesc}{compare}{x, y}
575 Compares values numerically.
576
577 Like \method{__cmp__()} but returns a decimal instance:
578 \begin{verbatim}
579 a or b is a NaN ==> Decimal("NaN")
580 a < b ==> Decimal("-1")
581 a == b ==> Decimal("0")
582 a > b ==> Decimal("1")
583 \end{verbatim}
584\end{methoddesc}
585
586\begin{methoddesc}{divide}{x, y}
587 Return \var{x} divided by \var{y}.
588\end{methoddesc}
589
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000590\begin{methoddesc}{divmod}{x, y}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000591 Divides two numbers and returns the integer part of the result.
592\end{methoddesc}
593
594\begin{methoddesc}{max}{x, y}
595 Compare two values numerically and returns the maximum.
596
597 If they are numerically equal then the left-hand operand is chosen as the
598 result.
599\end{methoddesc}
600
601\begin{methoddesc}{min}{x, y}
602 Compare two values numerically and returns the minimum.
603
604 If they are numerically equal then the left-hand operand is chosen as the
605 result.
606\end{methoddesc}
607
608\begin{methoddesc}{minus}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000609 Minus corresponds to the unary prefix minus operator in Python.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000610\end{methoddesc}
611
612\begin{methoddesc}{multiply}{x, y}
613 Return the product of \var{x} and \var{y}.
614\end{methoddesc}
615
616\begin{methoddesc}{normalize}{x}
617 Normalize reduces an operand to its simplest form.
618
619 Essentially a plus operation with all trailing zeros removed from the
620 result.
621\end{methoddesc}
622
623\begin{methoddesc}{plus}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000624 Minus corresponds to the unary prefix plus operator in Python.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000625\end{methoddesc}
626
627\begin{methoddesc}{power}{x, y\optional{, modulo}}
628 Return \samp{x ** y} to the \var{modulo} if given.
629
630 The right-hand operand must be a whole number whose integer part (after any
631 exponent has been applied) has no more than 9 digits and whose fractional
632 part (if any) is all zeros before any rounding. The operand may be positive,
633 negative, or zero; if negative, the absolute value of the power is used, and
634 the left-hand operand is inverted (divided into 1) before use.
635
636 If the increased precision needed for the intermediate calculations exceeds
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000637 the capabilities of the implementation then an \constant{InvalidOperation}
638 condition is signaled.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000639
640 If, when raising to a negative power, an underflow occurs during the
641 division into 1, the operation is not halted at that point but continues.
642\end{methoddesc}
643
644\begin{methoddesc}{quantize}{x, y}
645 Returns a value equal to \var{x} after rounding and having the
646 exponent of v\var{y}.
647
648 Unlike other operations, if the length of the coefficient after the quantize
649 operation would be greater than precision then an
650 \constant{InvalidOperation} is signaled. This guarantees that, unless there
651 is an error condition, the exponent of the result of a quantize is always
652 equal to that of the right-hand operand.
653
654 Also unlike other operations, quantize never signals Underflow, even
655 if the result is subnormal and inexact.
656\end{methoddesc}
657
658\begin{methoddesc}{remainder}{x, y}
659 Returns the remainder from integer division.
660
661 The sign of the result, if non-zero, is the same as that of the original
662 dividend.
663\end{methoddesc}
664
665\begin{methoddesc}{remainder_near}{x, y}
666 Computed the modulo as either a positive or negative value depending
667 on which is closest to zero. For instance,
668 \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")}
669 which is closer to zero than \code{Decimal("4")}.
670
671 If both are equally close, the one chosen will have the same sign
672 as \var{self}.
673\end{methoddesc}
674
675\begin{methoddesc}{same_quantum}{x, y}
676 Test whether \var{x} and \var{y} have the same exponent or whether both are
677 \constant{NaN}.
678\end{methoddesc}
679
680\begin{methoddesc}{sqrt}{}
681 Return the square root to full precision.
682\end{methoddesc}
683
684\begin{methoddesc}{substract}{x, y}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000685 Return the difference between \var{x} and \var{y}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000686\end{methoddesc}
687
688\begin{methoddesc}{to_eng_string}{}
689 Convert to engineering-type string.
690
691 Engineering notation has an exponent which is a multiple of 3, so there
692 are up to 3 digits left of the decimal place. For example, converts
693 \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")}
694\end{methoddesc}
695
696\begin{methoddesc}{to_integral}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000697 Rounds to the nearest integer without signaling \constant{Inexact}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000698 or \constant{Rounded}.
699\end{methoddesc}
700
701\begin{methoddesc}{to_sci_string}{}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000702 Converts a number to a string using scientific notation.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000703\end{methoddesc}
704
705
706
707%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
708\subsection{Signals \label{decimal-signals}}
709
710Signals represent conditions that arise during computation.
711Each corresponds to one context flag and one context trap enabler.
712
713The context flag is incremented whenever the condition is encountered.
714After the computation, flags may be checked for informational
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000715purposes (for instance, to determine whether a computation was exact).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000716After checking the flags, be sure to clear all flags before starting
717the next computation.
718
719If the context's trap enabler is set for the signal, then the condition
720causes a Python exception to be raised. For example, if the
721\class{DivisionByZero} trap is set, the a \exception{DivisionByZero}
722exception is raised upon encountering the condition.
723
724
725\begin{classdesc*}{Clamped}
726 Altered an exponent to fit representation constraints.
727
728 Typically, clamping occurs when an exponent falls outside the context's
729 \member{Emin} and \member{Emax} limits. If possible, the exponent is
730 reduced to fit by adding zeroes to the coefficient.
731\end{classdesc*}
732
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000733\begin{classdesc*}{ConversionSyntax}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000734 Trying to convert a malformed string such as: \code{Decimal('jump')}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000735
736 Decimal converts only strings conforming to the numeric string
737 syntax. If this signal is not trapped, returns \constant{NaN}.
738\end{classdesc*}
739
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000740\begin{classdesc*}{DecimalException}
741 Base class for other signals.
742\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
747 Can occur with division, modulo division, or when raising a number to
748 a negative power. If this signal is not trapped, return
749 \constant{Infinity} or \constant{-Infinity} with sign determined by
750 the inputs to the calculation.
751\end{classdesc*}
752
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000753\begin{classdesc*}{DivisionImpossible}
754 Error performing a division operation. Caused when an intermediate result
755 has more digits that the allowed by the current precision. If not trapped,
756 returns \constant{NaN}.
757\end{classdesc*}
758
759
760\begin{classdesc*}{DivisionUndefined}
761 This is a subclass of \class{DivisionByZero}.
762
763 It occurs only in the context of division operations.
764\end{classdesc*}
765
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000766\begin{classdesc*}{Inexact}
767 Indicates that rounding occurred and the result is not exact.
768
769 Signals whenever non-zero digits were discarded during rounding.
770 The rounded result is returned. The signal flag or trap is used
771 to detect when results are inexact.
772\end{classdesc*}
773
774
775\begin{classdesc*}{InvalidContext}
776 This is a subclass of \class{InvalidOperation}.
777
778 Indicates an error within the Context object such as an unknown
779 rounding operation. If not trapped, returns \constant{NaN}.
780\end{classdesc*}
781
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000782\begin{classdesc*}{InvalidOperation}
783 An invalid operation was performed.
784
785 Indicates that an operation was requested that does not make sense.
786 If not trapped, returns \constant{NaN}. Possible causes include:
787
788 \begin{verbatim}
789 Infinity - Infinity
790 0 * Infinity
791 Infinity / Infinity
792 x % 0
793 Infinity % x
794 x._rescale( non-integer )
795 sqrt(-x) and x > 0
796 0 ** 0
797 x ** (non-integer)
798 x ** Infinity
799 \end{verbatim}
800\end{classdesc*}
801
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000802\begin{classdesc*}{Overflow}
803 Numerical overflow.
804
805 Indicates the exponent is larger than \member{Emax} after rounding has
806 occurred. If not trapped, the result depends on the rounding mode, either
807 pulling inward to the largest representable finite number or rounding
808 outward to \constant{Infinity}. In either case, \class{Inexact} and
809 \class{Rounded} are also signaled.
810\end{classdesc*}
811
812
813\begin{classdesc*}{Rounded}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000814 Rounding occurred though possibly no information was lost.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000815
816 Signaled whenever rounding discards digits; even if those digits are
817 zero (such as rounding \constant{5.00} to \constant{5.0}). If not
818 trapped, returns the result unchanged. This signal is used to detect
819 loss of significant digits.
820\end{classdesc*}
821
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000822\begin{classdesc*}{Subnormal}
823 Exponent was lower than \member{Emin} prior to rounding.
824
825 Occurs when an operation result is subnormal (the exponent is too small).
826 If not trapped, returns the result unchanged.
827\end{classdesc*}
828
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000829\begin{classdesc*}{Underflow}
830 Numerical underflow with result rounded to zero.
831
832 Occurs when a subnormal result is pushed to zero by rounding.
833 \class{Inexact} and \class{Subnormal} are also signaled.
834\end{classdesc*}
835
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000836The following table summarizes the hierarchy of signals:
837
838\begin{verbatim}
839 exceptions.ArithmeticError(exceptions.StandardError)
840 DecimalException
841 Clamped
842 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
843 Inexact
844 Overflow(Inexact, Rounded)
845 Underflow(Inexact, Rounded, Subnormal)
846 InvalidOperation
847 ConversionSyntax
848 DivisionImpossible
849 DivisionUndefined(InvalidOperation, exceptions.ZeroDivisionError)
850 InvalidContext
851 Rounded
852 Subnormal
853\end{verbatim}
854
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000855
856
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000857%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
858\subsection{Working with threads \label{decimal-threads}}
859
860The \function{getcontext()} function accesses a different \class{Context}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000861object for each thread. Having separate thread contexts means that threads
862may make changes (such as \code{getcontext.prec=10}) without interfering with
863other threads and without needing mutexes.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000864
865Likewise, the \function{setcontext()} function automatically assigns its target
866to the current thread.
867
868If \function{setcontext()} has not been called before \function{getcontext()},
869then \function{getcontext()} will automatically create a new context for use
870in the current thread.
871
872The new context is copied from a prototype context called \var{DefaultContext}.
873To control the defaults so that each thread will use the same values
874throughout the application, directly modify the \var{DefaultContext} object.
875This should be done \emph{before} any threads are started so that there won't
876be a race condition with threads calling \function{getcontext()}. For example:
877
878\begin{verbatim}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000879# Set applicationwide defaults for all threads about to be launched
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000880DefaultContext.prec=12
881DefaultContext.rounding=ROUND_DOWN
882DefaultContext.trap_enablers=dict.fromkeys(Signals, 0)
883setcontext(DefaultContext)
884
885# Now start all of the threads
886t1.start()
887t2.start()
888t3.start()
889 . . .
890\end{verbatim}
891
892
893
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000894%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
895\subsection{Recipes \label{decimal-recipes}}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000896
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000897Here are some functions demonstrating ways to work with the
898\class{Decimal} class:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000899
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000900\begin{verbatim}
901from decimal import Decimal, getcontext
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000902getcontext().prec = 28
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000903
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000904def moneyfmt(value, places=2, curr='$', sep=',', dp='.', pos='', neg='-'):
905 """Convert Decimal to a money formatted string.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000906
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000907 places: required number of places after the decimal point
908 curr: optional currency symbol before the sign (may be blank)
909 sep: optional grouping separator (comma, period, or blank)
910 dp: decimal point indicator (comma or period)
911 only set to blank if places is zero
912 pos: optional sign for positive numbers ("+" or blank)
913 neg: optional sign for negative numbers ("-" or blank)
914 leave blank to separately add brackets or a trailing minus
915
916 >>> d = Decimal('-1234567.8901')
917 >>> moneyfmt(d)
918 '-$1,234,567.89'
919 >>> moneyfmt(d, places=0, curr='', sep='.', dp='')
920 '-1.234.568'
921 >>> '($%s)' % moneyfmt(d, curr='', neg='')
922 '($1,234,567.89)'
923 """
924 q = Decimal((0, (1,), -places)) # 2 places --> '0.01'
925 sign, digits, exp = value.quantize(q).as_tuple()
926 result = []
927 digits = map(str, digits)
928 build, next = result.append, digits.pop
929 for i in range(places):
930 build(next())
931 build(dp)
932 try:
933 while 1:
934 for i in range(3):
935 build(next())
936 if digits:
937 build(sep)
938 except IndexError:
939 pass
940 build(curr)
941 if sign:
942 build(neg)
943 else:
944 build(pos)
945 result.reverse()
946 return ''.join(result)
947
948def pi():
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000949 """Compute Pi to the current precision.
950
951 >>> print pi()
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000952 3.141592653589793238462643383
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000953 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000954 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettinger10959b12004-07-05 21:13:28 +0000955 three = Decimal(3) # substitute "three=3.0" for regular floats
Raymond Hettinger77e13b42004-07-05 20:27:53 +0000956 lastc, t, c, n, na, d, da = 0, three, 3, 1, 0, 0, 24
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000957 while c != lastc:
958 lastc = c
959 n, na = n+na, na+8
960 d, da = d+da, da+32
961 t = (t * n) / d
962 c += t
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000963 getcontext().prec -= 2
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000964 return c + 0 # Adding zero causes rounding to the new precision
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000965
966def exp(x):
Raymond Hettinger10959b12004-07-05 21:13:28 +0000967 """Return e raised to the power of x. Result type matches input type.
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000968
969 >>> print exp(Decimal(1))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000970 2.718281828459045235360287471
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000971 >>> print exp(Decimal(2))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000972 7.389056098930650227230427461
Raymond Hettinger10959b12004-07-05 21:13:28 +0000973 >>> print exp(2.0)
974 7.38905609893
975 >>> print exp(2+0j)
976 (7.38905609893+0j)
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000977 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000978 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000979 i, laste, e, fact, num = 0, 0, 1, 1, 1
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000980 while e != laste:
981 laste = e
982 i += 1
983 fact *= i
984 num *= x
985 e += num / fact
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000986 getcontext().prec -= 2
987 return e + 0
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000988
989def cos(x):
990 """Return the cosine of x as measured in radians.
991
992 >>> print cos(Decimal('0.5'))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000993 0.8775825618903727161162815826
Raymond Hettinger10959b12004-07-05 21:13:28 +0000994 >>> print cos(0.5)
995 0.87758256189
996 >>> print cos(0.5+0j)
997 (0.87758256189+0j)
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000998 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000999 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettingerc4f93d442004-07-05 20:17:13 +00001000 i, laste, e, fact, num, sign = 0, 0, 1, 1, 1, 1
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001001 while e != laste:
1002 laste = e
1003 i += 2
1004 fact *= i * (i-1)
1005 num *= x * x
1006 sign *= -1
1007 e += num / fact * sign
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001008 getcontext().prec -= 2
1009 return e + 0
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001010
1011def sin(x):
1012 """Return the cosine of x as measured in radians.
1013
1014 >>> print sin(Decimal('0.5'))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001015 0.4794255386042030002732879352
Raymond Hettinger10959b12004-07-05 21:13:28 +00001016 >>> print sin(0.5)
1017 0.479425538604
1018 >>> print sin(0.5+0j)
1019 (0.479425538604+0j)
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001020 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001021 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettingerc4f93d442004-07-05 20:17:13 +00001022 i, laste, e, fact, num, sign = 1, 0, x, 1, x, 1
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001023 while e != laste:
1024 laste = e
1025 i += 2
1026 fact *= i * (i-1)
1027 num *= x * x
1028 sign *= -1
1029 e += num / fact * sign
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001030 getcontext().prec -= 2
1031 return e + 0
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001032
1033\end{verbatim}