blob: b6164fc39f17b881c7f6619ad1d68bb9024f93c6 [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
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
73rules, limits on exponents, flags that indicate the results of operations,
74and trap enablers which determine whether signals are to be treated as
75exceptions. 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
79Signals are types of information that arise during the course of a
80computation. Depending on the needs of the application, some signals may be
81ignored, 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
107The normal start to using decimals is to import the module, and then use
108\function{getcontext()} to view the context and, if necessary, set the context
109precision, rounding, or trap enablers:
110
111\begin{verbatim}
112>>> from decimal import *
113>>> getcontext()
114Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
115 setflags=[], settraps=[])
116
117>>> getcontext().prec = 7
118\end{verbatim}
119
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000120Decimal instances can be constructed from integers, strings or tuples. To
121create a Decimal from a \class{float}, first convert it to a string. This
122serves as an explicit reminder of the details of the conversion (including
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000123representation error). Malformed strings signal \constant{InvalidOperation}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000124and return a special kind of Decimal called a \constant{NaN} which stands for
125``Not a number''. Positive and negative \constant{Infinity} is yet another
126special kind of Decimal.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000127
128\begin{verbatim}
129>>> Decimal(10)
130Decimal("10")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000131>>> Decimal("3.14")
132Decimal("3.14")
133>>> Decimal((0, (3, 1, 4), -2))
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000134Decimal("3.14")
135>>> Decimal(str(2.0 ** 0.5))
136Decimal("1.41421356237")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000137>>> Decimal("NaN")
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000138Decimal("NaN")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000139>>> Decimal("-Infinity")
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000140Decimal("-Infinity")
141\end{verbatim}
142
143Creating decimals is unaffected by context precision. Their level of
144significance is completely determined by the number of digits input. It is
145the arithmetic operations that are governed by context.
146
147\begin{verbatim}
148>>> getcontext().prec = 6
149>>> Decimal('3.0000')
150Decimal("3.0000")
151>>> 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
162Decimals interact well with much of the rest of python. Here is a small
163decimal floating point flying circus:
164
165\begin{verbatim}
166>>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
167>>> max(data)
168Decimal("9.25")
169>>> min(data)
170Decimal("0.03")
171>>> sorted(data)
172[Decimal("0.03"), Decimal("1.00"), Decimal("1.34"), Decimal("1.87"),
173 Decimal("2.35"), Decimal("3.45"), Decimal("9.25")]
174>>> sum(data)
175Decimal("19.29")
176>>> a,b,c = data[:3]
177>>> str(a)
178'1.34'
179>>> float(a)
1801.3400000000000001
181>>> round(a, 1)
1821.3
183>>> int(a)
1841
185>>> a * 5
186Decimal("6.70")
187>>> a * b
188Decimal("2.5058")
189>>> c % a
190Decimal("0.77")
191\end{verbatim}
192
193The \function{getcontext()} function accesses the current context. This one
194context is sufficient for many applications; however, for more advanced work,
195multiple contexts can be created using the Context() constructor. To make a
196new context active, use the \function{setcontext()} function.
197
198In accordance with the standard, the \module{Decimal} module provides two
199ready to use standard contexts, \constant{BasicContext} and
200\constant{ExtendedContext}. The former is especially useful for debugging
201because many of the traps are enabled:
202
203\begin{verbatim}
204>>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
205>>> myothercontext
206Context(prec=60, rounding=ROUND_HALF_DOWN, Emin=-999999999, Emax=999999999,
207 setflags=[], settraps=[])
208>>> ExtendedContext
209Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
210 setflags=[], settraps=[])
211>>> setcontext(myothercontext)
212>>> Decimal(1) / Decimal(7)
213Decimal("0.142857142857142857142857142857142857142857142857142857142857")
214>>> setcontext(ExtendedContext)
215>>> Decimal(1) / Decimal(7)
216Decimal("0.142857143")
217>>> Decimal(42) / Decimal(0)
218Decimal("Infinity")
219>>> setcontext(BasicContext)
220>>> Decimal(42) / Decimal(0)
221Traceback (most recent call last):
222 File "<pyshell#143>", line 1, in -toplevel-
223 Decimal(42) / Decimal(0)
224DivisionByZero: x / 0
225\end{verbatim}
226
227Besides using contexts to control precision, rounding, and trapping signals,
228they can be used to monitor flags which give information collected during
229computation. The flags remain set until explicitly cleared, so it is best to
230clear the flags before each set of monitored computations by using the
231\method{clear_flags()} method.
232
233\begin{verbatim}
234>>> setcontext(ExtendedContext)
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000235>>> Decimal(355) / Decimal(113)
236Decimal("3.14159292")
237>>> getcontext()
238Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
239 setflags=['Inexact', 'Rounded'], settraps=[])
240\end{verbatim}
241
242The \var{setflags} entry shows that the rational approximation to
243\constant{Pi} was rounded (digits beyond the context precision were thrown
244away) and that the result is inexact (some of the discarded digits were
245non-zero).
246
247Individual traps are set using the dictionary in the \member{trap_enablers}
248field of a context:
249
250\begin{verbatim}
251>>> Decimal(1) / Decimal(0)
252Decimal("Infinity")
253>>> getcontext().trap_enablers[DivisionByZero] = 1
254>>> Decimal(1) / Decimal(0)
255
256Traceback (most recent call last):
257 File "<pyshell#112>", line 1, in -toplevel-
258 Decimal(1) / Decimal(0)
259DivisionByZero: x / 0
260\end{verbatim}
261
262To turn all the traps on or off all at once, use a loop. Also, the
263\method{dict.update()} method is useful for changing a handfull of values.
264
265\begin{verbatim}
266>>> getcontext.clear_flags()
267>>> for sig in getcontext().trap_enablers:
268... getcontext().trap_enablers[sig] = 1
269
270>>> getcontext().trap_enablers.update({Rounded:0, Inexact:0, Subnormal:0})
271>>> getcontext()
272Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000273 setflags=[], settraps=['Clamped', 'Underflow', 'InvalidOperation',
274 'DivisionByZero', 'Overflow'])
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000275\end{verbatim}
276
277Applications typically set the context once at the beginning of a program
278and no further changes are needed. For many applications, the data resides
279in a resource external to the program and is converted to \class{Decimal} with
280a single cast inside a loop. Afterwards, decimals are as easily manipulated
281as other Python numeric types.
282
283
284
285%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
286\subsection{Decimal objects \label{decimal-decimal}}
287
288\begin{classdesc}{Decimal}{\optional{value \optional{, context}}}
289 Constructs a new \class{Decimal} object based from \var{value}.
290
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000291 \var{value} can be an integer, string, tuple, or another \class{Decimal}
292 object. If no \var{value} is given, returns \code{Decimal("0")}. If
293 \var{value} is a string, it should conform to the decimal numeric string
294 syntax:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000295
296 \begin{verbatim}
297 sign ::= '+' | '-'
298 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
299 indicator ::= 'e' | 'E'
300 digits ::= digit [digit]...
301 decimal-part ::= digits '.' [digits] | ['.'] digits
302 exponent-part ::= indicator [sign] digits
303 infinity ::= 'Infinity' | 'Inf'
304 nan ::= 'NaN' [digits] | 'sNaN' [digits]
305 numeric-value ::= decimal-part [exponent-part] | infinity
306 numeric-string ::= [sign] numeric-value | [sign] nan
307 \end{verbatim}
308
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000309 If \var{value} is a \class{tuple}, it should have three components,
310 a sign (\constant{0} for positive or \constant{1} for negative),
311 a \class{tuple} of digits, and an exponent represented as an integer.
312 For example, \samp{Decimal((0, (1, 4, 1, 4), -3))} returns
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000313 \code{Decimal("1.414")}.
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000314
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000315 The supplied \var{context} or, if not specified, the current context
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000316 governs only the handling of malformed strings not conforming to the
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000317 numeric string syntax. If the context traps \constant{InvalidOperation},
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000318 an exception is raised; otherwise, the constructor returns a new Decimal
319 with the value of \constant{NaN}.
320
321 The context serves no other purpose. The number of significant digits
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000322 recorded is determined solely by the \var{value} and the \var{context}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000323 precision is not a factor. For example, \samp{Decimal("3.0000")} records
324 all four zeroes even if the context precision is only three.
325
326 Once constructed, \class{Decimal} objects are immutable.
327\end{classdesc}
328
329Decimal floating point objects share many properties with the other builtin
330numeric types such as \class{float} and \class{int}. All of the usual
331math operations and special methods apply. Likewise, decimal objects can
332be copied, pickled, printed, used as dictionary keys, used as set elements,
333compared, sorted, and coerced to another type (such as \class{float}
334or \class{long}).
335
336In addition to the standard numeric properties, decimal floating point objects
337have a number of more specialized methods:
338
339\begin{methoddesc}{adjusted}{}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000340 Return the adjusted exponent after shifting out the coefficient's rightmost
341 digits until only the lead digit remains: \code{Decimal("321e+5").adjusted()}
342 returns seven. Used for determining the place value of the most significant
343 digit.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000344\end{methoddesc}
345
346\begin{methoddesc}{as_tuple}{}
347 Returns a tuple representation of the number:
348 \samp{(sign, digittuple, exponent)}.
349\end{methoddesc}
350
351\begin{methoddesc}{compare}{other\optional{, context}}
352 Compares like \method{__cmp__()} but returns a decimal instance:
353 \begin{verbatim}
354 a or b is a NaN ==> Decimal("NaN")
355 a < b ==> Decimal("-1")
356 a == b ==> Decimal("0")
357 a > b ==> Decimal("1")
358 \end{verbatim}
359\end{methoddesc}
360
361\begin{methoddesc}{max}{other\optional{, context}}
362 Like \samp{max(self, other)} but returns \constant{NaN} if either is a
363 \constant{NaN}. Applies the context rounding rule before returning.
364\end{methoddesc}
365
366\begin{methoddesc}{min}{other\optional{, context}}
367 Like \samp{min(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}{normalize}{\optional{context}}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000372 Normalize the number by stripping the rightmost trailing zeroes and
373 converting any result equal to \constant{Decimal("0")} to
374 \constant{Decimal("0e0")}. Used for producing canonical values for members
375 of an equivalence class. For example, \code{Decimal("32.100")} and
376 \code{Decimal("0.321000e+2")} both normalize to the equivalent value
377 \code{Decimal("32.1")},
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000378\end{methoddesc}
379
380\begin{methoddesc}{quantize}
381 {\optional{exp \optional{, rounding\optional{, context\optional{, watchexp}}}}}
382 Quantize makes the exponent the same as \var{exp}. Searches for a
383 rounding method in \var{rounding}, then in \var{context}, and then
384 in the current context.
385
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000386 If \var{watchexp} is set (default), then an error is returned whenever
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000387 the resulting exponent is greater than \member{Emax} or less than
388 \member{Etiny}.
389\end{methoddesc}
390
391\begin{methoddesc}{remainder_near}{other\optional{, context}}
392 Computed the modulo as either a positive or negative value depending
393 on which is closest to zero. For instance,
394 \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")}
395 which is closer to zero than \code{Decimal("4")}.
396
397 If both are equally close, the one chosen will have the same sign
398 as \var{self}.
399\end{methoddesc}
400
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000401\begin{methoddesc}{same_quantum}{other\optional{, context}}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000402 Test whether self and other have the same exponent or whether both
403 are \constant{NaN}.
404\end{methoddesc}
405
406\begin{methoddesc}{sqrt}{\optional{context}}
407 Return the square root to full precision.
408\end{methoddesc}
409
410\begin{methoddesc}{to_eng_string}{\optional{context}}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000411 Convert to an engineering-type string.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000412
413 Engineering notation has an exponent which is a multiple of 3, so there
414 are up to 3 digits left of the decimal place. For example, converts
415 \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")}
416\end{methoddesc}
417
418\begin{methoddesc}{to_integral}{\optional{rounding\optional{, context}}}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000419 Rounds to the nearest integer without signaling \constant{Inexact}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000420 or \constant{Rounded}. If given, applies \var{rounding}; otherwise,
421 uses the rounding method in either the supplied \var{context} or the
422 current context.
423\end{methoddesc}
424
425
426%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
427\subsection{Context objects \label{decimal-decimal}}
428
429Contexts are environments for arithmetic operations. They govern the precision,
430rules for rounding, determine which signals are treated as exceptions, and set limits
431on the range for exponents.
432
433Each thread has its own current context which is accessed or changed using
434the \function{getcontext()} and \function{setcontext()} functions:
435
436\begin{funcdesc}{getcontext}{}
437 Return the current context for the active thread.
438\end{funcdesc}
439
440\begin{funcdesc}{setcontext}{c}
441 Set the current context for the active thread to \var{c}.
442\end{funcdesc}
443
444New contexts can formed using the \class{Context} constructor described below.
445In addition, the module provides three pre-made contexts:
446
447
448\begin{classdesc*}{BasicContext}
449 This is a standard context defined by the General Decimal Arithmetic
450 Specification. Precision is set to nine. Rounding is set to
451 \constant{ROUND_HALF_UP}. All flags are cleared. All traps are enabled
452 (treated as exceptions) except \constant{Inexact}, \constant{Rounded}, and
453 \constant{Subnormal}.
454
455 Because many of the traps are enabled, this context is useful for debugging.
456\end{classdesc*}
457
458\begin{classdesc*}{ExtendedContext}
459 This is a standard context defined by the General Decimal Arithmetic
460 Specification. Precision is set to nine. Rounding is set to
461 \constant{ROUND_HALF_EVEN}. All flags are cleared. No traps are enabled
462 (so that exceptions are not raised during computations).
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000463
464 Because the trapped are disabled, this context is useful for applications
465 that prefer to have result value of \constant{NaN} or \constant{Infinity}
466 instead of raising exceptions. This allows an application to complete a
467 run in the presense of conditions that would otherwise halt the program.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000468\end{classdesc*}
469
470\begin{classdesc*}{DefaultContext}
471 This class is used by the \class{Context} constructor as a prototype for
472 new contexts. Changing a field (such a precision) has the effect of
473 changing the default for new contexts creating by the \class{Context}
474 constructor.
475
476 This context is most useful in multi-threaded environments. Changing one of
477 the fields before threads are started has the effect of setting system-wide
478 defaults. Changing the fields after threads have started is not recommended
479 as it would require thread synchronization to prevent race conditions.
480
481 In single threaded environments, it is preferable to not use this context
482 at all. Instead, simply create contexts explicitly. This is especially
483 important because the default values context may change between releases
484 (with initial release having precision=28, rounding=ROUND_HALF_EVEN,
485 cleared flags, and no traps enabled).
486\end{classdesc*}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000487
488
489In addition to the three supplied contexts, new contexts can be created
490with the \class{Context} constructor.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000491
492\begin{classdesc}{Context}{prec=None, rounding=None, trap_enablers=None,
493 flags=None, Emin=None, Emax=None, capitals=1}
494 Creates a new context. If a field is not specified or is \constant{None},
495 the default values are copied from the \constant{DefaultContext}. If the
496 \var{flags} field is not specified or is \constant{None}, all flags are
497 cleared.
498
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000499 The \var{prec} field is a positive integer that sets the precision for
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000500 arithmetic operations in the context.
501
Raymond Hettinger97c92082004-07-09 06:13:12 +0000502 The \var{rounding} option is one of:
503 \constant{ROUND_CEILING} (towards \constant{Infinity}),
504 \constant{ROUND_DOWN} (towards zero),
505 \constant{ROUND_FLOOR} (towards \constant{-Infinity}),
506 \constant{ROUND_HALF_DOWN} (towards zero),
507 \constant{ROUND_HALF_EVEN},
508 \constant{ROUND_HALF_UP} (away from zero), or
509 \constant{ROUND_UP} (away from zero).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000510
511 The \var{trap_enablers} and \var{flags} fields are mappings from signals
512 to either \constant{0} or \constant{1}.
513
514 The \var{Emin} and \var{Emax} fields are integers specifying the outer
515 limits allowable for exponents.
516
517 The \var{capitals} field is either \constant{0} or \constant{1} (the
518 default). If set to \constant{1}, exponents are printed with a capital
519 \constant{E}; otherwise, lowercase is used: \constant{Decimal('6.02e+23')}.
520\end{classdesc}
521
522The \class{Context} class defines several general methods as well as a
523large number of methods for doing arithmetic directly from the context.
524
525\begin{methoddesc}{clear_flags}{}
526 Sets all of the flags to \constant{0}.
527\end{methoddesc}
528
529\begin{methoddesc}{copy}{}
530 Returns a duplicate of the context.
531\end{methoddesc}
532
533\begin{methoddesc}{create_decimal}{num}
534 Creates a new Decimal instance but using \var{self} as context.
535 Unlike the \class{Decimal} constructor, context precision,
536 rounding method, flags, and traps are applied to the conversion.
537
538 This is useful because constants are often given to a greater
539 precision than is needed by the application.
540\end{methoddesc}
541
542\begin{methoddesc}{Etiny}{}
543 Returns a value equal to \samp{Emin - prec + 1} which is the minimum
544 exponent value for subnormal results. When underflow occurs, the
545 exponont is set to \constant{Etiny}.
546\end{methoddesc}
547
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000548\begin{methoddesc}{Etop}{}
549 Returns a value equal to \samp{Emax - prec + 1}.
550\end{methoddesc}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000551
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000552
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000553The usual approach to working with decimals is to create \class{Decimal}
554instances and then apply arithmetic operations which take place within the
555current context for the active thread. An alternate approach is to use
556context methods for calculating within s specific context. The methods are
557similar to those for the \class{Decimal} class and are only briefly recounted
558here.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000559
560\begin{methoddesc}{abs}{x}
561 Returns the absolute value of \var{x}.
562\end{methoddesc}
563
564\begin{methoddesc}{add}{x, y}
565 Return the sum of \var{x} and \var{y}.
566\end{methoddesc}
567
568\begin{methoddesc}{compare}{x, y}
569 Compares values numerically.
570
571 Like \method{__cmp__()} but returns a decimal instance:
572 \begin{verbatim}
573 a or b is a NaN ==> Decimal("NaN")
574 a < b ==> Decimal("-1")
575 a == b ==> Decimal("0")
576 a > b ==> Decimal("1")
577 \end{verbatim}
578\end{methoddesc}
579
580\begin{methoddesc}{divide}{x, y}
581 Return \var{x} divided by \var{y}.
582\end{methoddesc}
583
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000584\begin{methoddesc}{divmod}{x, y}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000585 Divides two numbers and returns the integer part of the result.
586\end{methoddesc}
587
588\begin{methoddesc}{max}{x, y}
589 Compare two values numerically and returns the maximum.
590
591 If they are numerically equal then the left-hand operand is chosen as the
592 result.
593\end{methoddesc}
594
595\begin{methoddesc}{min}{x, y}
596 Compare two values numerically and returns the minimum.
597
598 If they are numerically equal then the left-hand operand is chosen as the
599 result.
600\end{methoddesc}
601
602\begin{methoddesc}{minus}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000603 Minus corresponds to the unary prefix minus operator in Python.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000604\end{methoddesc}
605
606\begin{methoddesc}{multiply}{x, y}
607 Return the product of \var{x} and \var{y}.
608\end{methoddesc}
609
610\begin{methoddesc}{normalize}{x}
611 Normalize reduces an operand to its simplest form.
612
613 Essentially a plus operation with all trailing zeros removed from the
614 result.
615\end{methoddesc}
616
617\begin{methoddesc}{plus}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000618 Minus corresponds to the unary prefix plus operator in Python.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000619\end{methoddesc}
620
621\begin{methoddesc}{power}{x, y\optional{, modulo}}
622 Return \samp{x ** y} to the \var{modulo} if given.
623
624 The right-hand operand must be a whole number whose integer part (after any
625 exponent has been applied) has no more than 9 digits and whose fractional
626 part (if any) is all zeros before any rounding. The operand may be positive,
627 negative, or zero; if negative, the absolute value of the power is used, and
628 the left-hand operand is inverted (divided into 1) before use.
629
630 If the increased precision needed for the intermediate calculations exceeds
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000631 the capabilities of the implementation then an \constant{InvalidOperation}
632 condition is signaled.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000633
634 If, when raising to a negative power, an underflow occurs during the
635 division into 1, the operation is not halted at that point but continues.
636\end{methoddesc}
637
638\begin{methoddesc}{quantize}{x, y}
639 Returns a value equal to \var{x} after rounding and having the
640 exponent of v\var{y}.
641
642 Unlike other operations, if the length of the coefficient after the quantize
643 operation would be greater than precision then an
644 \constant{InvalidOperation} is signaled. This guarantees that, unless there
645 is an error condition, the exponent of the result of a quantize is always
646 equal to that of the right-hand operand.
647
648 Also unlike other operations, quantize never signals Underflow, even
649 if the result is subnormal and inexact.
650\end{methoddesc}
651
652\begin{methoddesc}{remainder}{x, y}
653 Returns the remainder from integer division.
654
655 The sign of the result, if non-zero, is the same as that of the original
656 dividend.
657\end{methoddesc}
658
659\begin{methoddesc}{remainder_near}{x, y}
660 Computed the modulo as either a positive or negative value depending
661 on which is closest to zero. For instance,
662 \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")}
663 which is closer to zero than \code{Decimal("4")}.
664
665 If both are equally close, the one chosen will have the same sign
666 as \var{self}.
667\end{methoddesc}
668
669\begin{methoddesc}{same_quantum}{x, y}
670 Test whether \var{x} and \var{y} have the same exponent or whether both are
671 \constant{NaN}.
672\end{methoddesc}
673
674\begin{methoddesc}{sqrt}{}
675 Return the square root to full precision.
676\end{methoddesc}
677
678\begin{methoddesc}{substract}{x, y}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000679 Return the difference between \var{x} and \var{y}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000680\end{methoddesc}
681
682\begin{methoddesc}{to_eng_string}{}
683 Convert to engineering-type string.
684
685 Engineering notation has an exponent which is a multiple of 3, so there
686 are up to 3 digits left of the decimal place. For example, converts
687 \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")}
688\end{methoddesc}
689
690\begin{methoddesc}{to_integral}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000691 Rounds to the nearest integer without signaling \constant{Inexact}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000692 or \constant{Rounded}.
693\end{methoddesc}
694
695\begin{methoddesc}{to_sci_string}{}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000696 Converts a number to a string using scientific notation.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000697\end{methoddesc}
698
699
700
701%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
702\subsection{Signals \label{decimal-signals}}
703
704Signals represent conditions that arise during computation.
705Each corresponds to one context flag and one context trap enabler.
706
707The context flag is incremented whenever the condition is encountered.
708After the computation, flags may be checked for informational
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000709purposes (for instance, to determine whether a computation was exact).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000710After checking the flags, be sure to clear all flags before starting
711the next computation.
712
713If the context's trap enabler is set for the signal, then the condition
714causes a Python exception to be raised. For example, if the
715\class{DivisionByZero} trap is set, the a \exception{DivisionByZero}
716exception is raised upon encountering the condition.
717
718
719\begin{classdesc*}{Clamped}
720 Altered an exponent to fit representation constraints.
721
722 Typically, clamping occurs when an exponent falls outside the context's
723 \member{Emin} and \member{Emax} limits. If possible, the exponent is
724 reduced to fit by adding zeroes to the coefficient.
725\end{classdesc*}
726
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000727\begin{classdesc*}{DecimalException}
728 Base class for other signals.
729\end{classdesc*}
730
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000731\begin{classdesc*}{DivisionByZero}
732 Signals the division of a non-infinite number by zero.
733
734 Can occur with division, modulo division, or when raising a number to
735 a negative power. If this signal is not trapped, return
736 \constant{Infinity} or \constant{-Infinity} with sign determined by
737 the inputs to the calculation.
738\end{classdesc*}
739
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000740\begin{classdesc*}{Inexact}
741 Indicates that rounding occurred and the result is not exact.
742
743 Signals whenever non-zero digits were discarded during rounding.
744 The rounded result is returned. The signal flag or trap is used
745 to detect when results are inexact.
746\end{classdesc*}
747
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000748\begin{classdesc*}{InvalidOperation}
749 An invalid operation was performed.
750
751 Indicates that an operation was requested that does not make sense.
752 If not trapped, returns \constant{NaN}. Possible causes include:
753
754 \begin{verbatim}
755 Infinity - Infinity
756 0 * Infinity
757 Infinity / Infinity
758 x % 0
759 Infinity % x
760 x._rescale( non-integer )
761 sqrt(-x) and x > 0
762 0 ** 0
763 x ** (non-integer)
764 x ** Infinity
765 \end{verbatim}
766\end{classdesc*}
767
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000768\begin{classdesc*}{Overflow}
769 Numerical overflow.
770
771 Indicates the exponent is larger than \member{Emax} after rounding has
772 occurred. If not trapped, the result depends on the rounding mode, either
773 pulling inward to the largest representable finite number or rounding
774 outward to \constant{Infinity}. In either case, \class{Inexact} and
775 \class{Rounded} are also signaled.
776\end{classdesc*}
777
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000778\begin{classdesc*}{Rounded}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000779 Rounding occurred though possibly no information was lost.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000780
781 Signaled whenever rounding discards digits; even if those digits are
782 zero (such as rounding \constant{5.00} to \constant{5.0}). If not
783 trapped, returns the result unchanged. This signal is used to detect
784 loss of significant digits.
785\end{classdesc*}
786
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000787\begin{classdesc*}{Subnormal}
788 Exponent was lower than \member{Emin} prior to rounding.
789
790 Occurs when an operation result is subnormal (the exponent is too small).
791 If not trapped, returns the result unchanged.
792\end{classdesc*}
793
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000794\begin{classdesc*}{Underflow}
795 Numerical underflow with result rounded to zero.
796
797 Occurs when a subnormal result is pushed to zero by rounding.
798 \class{Inexact} and \class{Subnormal} are also signaled.
799\end{classdesc*}
800
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000801The following table summarizes the hierarchy of signals:
802
803\begin{verbatim}
804 exceptions.ArithmeticError(exceptions.StandardError)
805 DecimalException
806 Clamped
807 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
808 Inexact
809 Overflow(Inexact, Rounded)
810 Underflow(Inexact, Rounded, Subnormal)
811 InvalidOperation
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000812 Rounded
813 Subnormal
814\end{verbatim}
815
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000816
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000817%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
818\subsection{Working with threads \label{decimal-threads}}
819
820The \function{getcontext()} function accesses a different \class{Context}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000821object for each thread. Having separate thread contexts means that threads
822may make changes (such as \code{getcontext.prec=10}) without interfering with
823other threads and without needing mutexes.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000824
825Likewise, the \function{setcontext()} function automatically assigns its target
826to the current thread.
827
828If \function{setcontext()} has not been called before \function{getcontext()},
829then \function{getcontext()} will automatically create a new context for use
830in the current thread.
831
832The new context is copied from a prototype context called \var{DefaultContext}.
833To control the defaults so that each thread will use the same values
834throughout the application, directly modify the \var{DefaultContext} object.
835This should be done \emph{before} any threads are started so that there won't
836be a race condition with threads calling \function{getcontext()}. For example:
837
838\begin{verbatim}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000839# Set applicationwide defaults for all threads about to be launched
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000840DefaultContext.prec=12
841DefaultContext.rounding=ROUND_DOWN
842DefaultContext.trap_enablers=dict.fromkeys(Signals, 0)
843setcontext(DefaultContext)
844
845# Now start all of the threads
846t1.start()
847t2.start()
848t3.start()
849 . . .
850\end{verbatim}
851
852
853
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000854%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
855\subsection{Recipes \label{decimal-recipes}}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000856
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000857Here are some functions demonstrating ways to work with the
858\class{Decimal} class:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000859
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000860\begin{verbatim}
861from decimal import Decimal, getcontext
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000862getcontext().prec = 28
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000863
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000864def moneyfmt(value, places=2, curr='$', sep=',', dp='.', pos='', neg='-'):
865 """Convert Decimal to a money formatted string.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000866
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000867 places: required number of places after the decimal point
868 curr: optional currency symbol before the sign (may be blank)
869 sep: optional grouping separator (comma, period, or blank)
870 dp: decimal point indicator (comma or period)
871 only set to blank if places is zero
872 pos: optional sign for positive numbers ("+" or blank)
873 neg: optional sign for negative numbers ("-" or blank)
874 leave blank to separately add brackets or a trailing minus
875
876 >>> d = Decimal('-1234567.8901')
877 >>> moneyfmt(d)
878 '-$1,234,567.89'
879 >>> moneyfmt(d, places=0, curr='', sep='.', dp='')
880 '-1.234.568'
881 >>> '($%s)' % moneyfmt(d, curr='', neg='')
882 '($1,234,567.89)'
883 """
884 q = Decimal((0, (1,), -places)) # 2 places --> '0.01'
885 sign, digits, exp = value.quantize(q).as_tuple()
886 result = []
887 digits = map(str, digits)
888 build, next = result.append, digits.pop
889 for i in range(places):
890 build(next())
891 build(dp)
892 try:
893 while 1:
894 for i in range(3):
895 build(next())
896 if digits:
897 build(sep)
898 except IndexError:
899 pass
900 build(curr)
901 if sign:
902 build(neg)
903 else:
904 build(pos)
905 result.reverse()
906 return ''.join(result)
907
908def pi():
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000909 """Compute Pi to the current precision.
910
911 >>> print pi()
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000912 3.141592653589793238462643383
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000913 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000914 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettinger10959b12004-07-05 21:13:28 +0000915 three = Decimal(3) # substitute "three=3.0" for regular floats
Raymond Hettinger77e13b42004-07-05 20:27:53 +0000916 lastc, t, c, n, na, d, da = 0, three, 3, 1, 0, 0, 24
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000917 while c != lastc:
918 lastc = c
919 n, na = n+na, na+8
920 d, da = d+da, da+32
921 t = (t * n) / d
922 c += t
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000923 getcontext().prec -= 2
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000924 return c + 0 # Adding zero causes rounding to the new precision
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000925
926def exp(x):
Raymond Hettinger10959b12004-07-05 21:13:28 +0000927 """Return e raised to the power of x. Result type matches input type.
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000928
929 >>> print exp(Decimal(1))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000930 2.718281828459045235360287471
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000931 >>> print exp(Decimal(2))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000932 7.389056098930650227230427461
Raymond Hettinger10959b12004-07-05 21:13:28 +0000933 >>> print exp(2.0)
934 7.38905609893
935 >>> print exp(2+0j)
936 (7.38905609893+0j)
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000937 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000938 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000939 i, laste, e, fact, num = 0, 0, 1, 1, 1
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000940 while e != laste:
941 laste = e
942 i += 1
943 fact *= i
944 num *= x
945 e += num / fact
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000946 getcontext().prec -= 2
947 return e + 0
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000948
949def cos(x):
950 """Return the cosine of x as measured in radians.
951
952 >>> print cos(Decimal('0.5'))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000953 0.8775825618903727161162815826
Raymond Hettinger10959b12004-07-05 21:13:28 +0000954 >>> print cos(0.5)
955 0.87758256189
956 >>> print cos(0.5+0j)
957 (0.87758256189+0j)
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000958 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000959 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000960 i, laste, e, fact, num, sign = 0, 0, 1, 1, 1, 1
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000961 while e != laste:
962 laste = e
963 i += 2
964 fact *= i * (i-1)
965 num *= x * x
966 sign *= -1
967 e += num / fact * sign
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000968 getcontext().prec -= 2
969 return e + 0
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000970
971def sin(x):
972 """Return the cosine of x as measured in radians.
973
974 >>> print sin(Decimal('0.5'))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000975 0.4794255386042030002732879352
Raymond Hettinger10959b12004-07-05 21:13:28 +0000976 >>> print sin(0.5)
977 0.479425538604
978 >>> print sin(0.5+0j)
979 (0.479425538604+0j)
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000980 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000981 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000982 i, laste, e, fact, num, sign = 1, 0, x, 1, x, 1
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000983 while e != laste:
984 laste = e
985 i += 2
986 fact *= i * (i-1)
987 num *= x * x
988 sign *= -1
989 e += num / fact * sign
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000990 getcontext().prec -= 2
991 return e + 0
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000992
993\end{verbatim}