blob: d573f442a06e23d8532f20cdd91a2a25b7d2c1b8 [file] [log] [blame]
Raymond Hettinger8de63a22004-07-05 05:52:03 +00001\section{\module{decimal} ---
2 Decimal floating point arithmetic}
3
4\declaremodule{standard}{decimal}
5\modulesynopsis{Implementation of the General Decimal Arithmetic
6Specification.}
7
8\moduleauthor{Eric Price}{eprice at tjhsst.edu}
9\moduleauthor{Facundo Batista}{facundo at taniquetil.com.ar}
10\moduleauthor{Raymond Hettinger}{python at rcn.com}
11\moduleauthor{Aahz}{aahz at pobox.com}
12\moduleauthor{Tim Peters}{tim.one at comcast.net}
13
14\sectionauthor{Raymond D. Hettinger}{python at rcn.com}
15
16\versionadded{2.4}
17
Raymond Hettinger97c92082004-07-09 06:13:12 +000018The \module{decimal} module provides support for decimal floating point
Raymond Hettinger8de63a22004-07-05 05:52:03 +000019arithmetic. It offers several advantages over the \class{float()} datatype:
20
21\begin{itemize}
22
23\item Decimal numbers can be represented exactly. In contrast, numbers like
Raymond Hettinger65df07b2004-07-11 12:40:19 +000024\constant{1.1} do not have an exact representation in binary floating point.
Raymond Hettinger8de63a22004-07-05 05:52:03 +000025End 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
Raymond Hettinger65df07b2004-07-11 12:40:19 +000073rules, limits on exponents, flags indicating the results of operations,
74and trap enablers which determine whether signals are treated as
Raymond Hettinger8de63a22004-07-05 05:52:03 +000075exceptions. Rounding options include \constant{ROUND_CEILING},
76\constant{ROUND_DOWN}, \constant{ROUND_FLOOR}, \constant{ROUND_HALF_DOWN},
77\constant{ROUND_HALF_EVEN}, \constant{ROUND_HALF_UP}, and \constant{ROUND_UP}.
78
Raymond Hettinger65df07b2004-07-11 12:40:19 +000079Signals are groups of exceptional conditions arising during the course of
80computation. Depending on the needs of the application, signals may be
Raymond Hettinger8de63a22004-07-05 05:52:03 +000081ignored, considered as informational, or treated as exceptions. The signals in
82the decimal module are: \constant{Clamped}, \constant{InvalidOperation},
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000083\constant{DivisionByZero}, \constant{Inexact}, \constant{Rounded},
Raymond Hettinger8de63a22004-07-05 05:52:03 +000084\constant{Subnormal}, \constant{Overflow}, and \constant{Underflow}.
85
86For each signal there is a flag and a trap enabler. When a signal is
87encountered, its flag incremented from zero and, then, if the trap enabler
Raymond Hettinger97c92082004-07-09 06:13:12 +000088is set to one, an exception is raised. Flags are sticky, so the user
89needs to reset them before monitoring a calculation.
Raymond Hettinger8de63a22004-07-05 05:52:03 +000090
91
92\begin{seealso}
93 \seetext{IBM's General Decimal Arithmetic Specification,
94 \citetitle[http://www2.hursley.ibm.com/decimal/decarith.html]
95 {The General Decimal Arithmetic Specification}.}
96
97 \seetext{IEEE standard 854-1987,
Raymond Hettinger536f76b2004-07-08 09:22:33 +000098 \citetitle[http://www.cs.berkeley.edu/\textasciitilde ejr/projects/754/private/drafts/854-1987/dir.html]
Raymond Hettinger8de63a22004-07-05 05:52:03 +000099 {Unofficial IEEE 854 Text}.}
100\end{seealso}
101
102
103
104%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
105\subsection{Quick-start Tutorial \label{decimal-tutorial}}
106
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000107The usual start to using decimals is importing the module, viewing the current
108context with \function{getcontext()} and, if necessary, setting new values
109for precision, rounding, or enabled traps:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000110
111\begin{verbatim}
112>>> from decimal import *
113>>> getcontext()
114Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000115 capitals=1, flags=[], traps=[Overflow, InvalidOperation,
116 DivisionByZero])
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000117
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000118>>> getcontext().prec = 7 # Set a new precision
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000119\end{verbatim}
120
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000121
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000122Decimal instances can be constructed from integers, strings or tuples. To
123create a Decimal from a \class{float}, first convert it to a string. This
124serves as an explicit reminder of the details of the conversion (including
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000125representation error). Decimal numbers include special values such as
126\constant{NaN} which stands for ``Not a number'', positive and negative
127\constant{Infinity}, and \constant{-0}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000128
129\begin{verbatim}
130>>> Decimal(10)
131Decimal("10")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000132>>> Decimal("3.14")
133Decimal("3.14")
134>>> Decimal((0, (3, 1, 4), -2))
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000135Decimal("3.14")
136>>> Decimal(str(2.0 ** 0.5))
137Decimal("1.41421356237")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000138>>> Decimal("NaN")
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000139Decimal("NaN")
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000140>>> Decimal("-Infinity")
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000141Decimal("-Infinity")
142\end{verbatim}
143
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000144
145The significance of a new Decimal is determined solely by the number
146of digits input. Context precision and rounding only come into play during
147arithmetic operations.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000148
149\begin{verbatim}
150>>> getcontext().prec = 6
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000151>>> Decimal('3.0')
152Decimal("3.0")
153>>> Decimal('3.1415926535')
154Decimal("3.1415926535")
155>>> Decimal('3.1415926535') + Decimal('2.7182818285')
156Decimal("5.85987")
157>>> getcontext().rounding = ROUND_UP
158>>> Decimal('3.1415926535') + Decimal('2.7182818285')
159Decimal("5.85988")
160\end{verbatim}
161
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000162
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000163Decimals interact well with much of the rest of python. Here is a small
164decimal floating point flying circus:
165
166\begin{verbatim}
167>>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
168>>> max(data)
169Decimal("9.25")
170>>> min(data)
171Decimal("0.03")
172>>> sorted(data)
173[Decimal("0.03"), Decimal("1.00"), Decimal("1.34"), Decimal("1.87"),
174 Decimal("2.35"), Decimal("3.45"), Decimal("9.25")]
175>>> sum(data)
176Decimal("19.29")
177>>> a,b,c = data[:3]
178>>> str(a)
179'1.34'
180>>> float(a)
1811.3400000000000001
182>>> round(a, 1)
1831.3
184>>> int(a)
1851
186>>> a * 5
187Decimal("6.70")
188>>> a * b
189Decimal("2.5058")
190>>> c % a
191Decimal("0.77")
192\end{verbatim}
193
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000194The \method{quantize()} method rounds a number to a fixed exponent. This
195method is useful for monetary applications that often round results to a fixed
196number of places:
197
198\begin{verbatim}
199>>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
200Decimal("7.32")
201>>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
202Decimal("8")
203\end{verbatim}
204
205As shown above, the \function{getcontext()} function accesses the current
206context and allows the settings to be changed. This approach meets the
207needs of most applications.
208
209For more advanced work, it may be useful to create alternate contexts using
210the Context() constructor. To make an alternate active, use the
211\function{setcontext()} function.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000212
213In accordance with the standard, the \module{Decimal} module provides two
214ready to use standard contexts, \constant{BasicContext} and
215\constant{ExtendedContext}. The former is especially useful for debugging
216because many of the traps are enabled:
217
218\begin{verbatim}
219>>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
220>>> myothercontext
221Context(prec=60, rounding=ROUND_HALF_DOWN, Emin=-999999999, Emax=999999999,
Raymond Hettingerbf440692004-07-10 14:14:37 +0000222 capitals=1, flags=[], traps=[])
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000223>>> setcontext(myothercontext)
224>>> Decimal(1) / Decimal(7)
225Decimal("0.142857142857142857142857142857142857142857142857142857142857")
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000226
227>>> ExtendedContext
228Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
229 capitals=1, flags=[], traps=[])
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000230>>> setcontext(ExtendedContext)
231>>> Decimal(1) / Decimal(7)
232Decimal("0.142857143")
233>>> Decimal(42) / Decimal(0)
234Decimal("Infinity")
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000235
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000236>>> setcontext(BasicContext)
237>>> Decimal(42) / Decimal(0)
238Traceback (most recent call last):
239 File "<pyshell#143>", line 1, in -toplevel-
240 Decimal(42) / Decimal(0)
241DivisionByZero: x / 0
242\end{verbatim}
243
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000244
245Contexts also have signal flags for monitoring exceptional conditions
246encountered during computations. The flags remain set until explicitly
247cleared, so it is best to clear the flags before each set of monitored
248computations by using the \method{clear_flags()} method.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000249
250\begin{verbatim}
251>>> setcontext(ExtendedContext)
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000252>>> getcontext().clear_flags()
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000253>>> Decimal(355) / Decimal(113)
254Decimal("3.14159292")
255>>> getcontext()
256Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Raymond Hettingerbf440692004-07-10 14:14:37 +0000257 capitals=1, flags=[Inexact, Rounded], traps=[])
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000258\end{verbatim}
259
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000260The \var{flags} entry shows that the rational approximation to \constant{Pi}
261was rounded (digits beyond the context precision were thrown away) and that
262the result is inexact (some of the discarded digits were non-zero).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000263
Raymond Hettingerbf440692004-07-10 14:14:37 +0000264Individual traps are set using the dictionary in the \member{traps}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000265field of a context:
266
267\begin{verbatim}
268>>> Decimal(1) / Decimal(0)
269Decimal("Infinity")
Raymond Hettingerbf440692004-07-10 14:14:37 +0000270>>> getcontext().traps[DivisionByZero] = 1
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000271>>> Decimal(1) / Decimal(0)
272
273Traceback (most recent call last):
274 File "<pyshell#112>", line 1, in -toplevel-
275 Decimal(1) / Decimal(0)
276DivisionByZero: x / 0
277\end{verbatim}
278
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000279Most programs adjust the current context only once, at the beginning of the
280program. And, in many applications, data is converted to \class{Decimal} with
281a single cast inside a loop. With context set and decimals created, the bulk
282of the program manipulates the data no differently than with other Python
283numeric types.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000284
285
286
287%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
288\subsection{Decimal objects \label{decimal-decimal}}
289
290\begin{classdesc}{Decimal}{\optional{value \optional{, context}}}
291 Constructs a new \class{Decimal} object based from \var{value}.
292
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000293 \var{value} can be an integer, string, tuple, or another \class{Decimal}
294 object. If no \var{value} is given, returns \code{Decimal("0")}. If
295 \var{value} is a string, it should conform to the decimal numeric string
296 syntax:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000297
298 \begin{verbatim}
299 sign ::= '+' | '-'
300 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
301 indicator ::= 'e' | 'E'
302 digits ::= digit [digit]...
303 decimal-part ::= digits '.' [digits] | ['.'] digits
304 exponent-part ::= indicator [sign] digits
305 infinity ::= 'Infinity' | 'Inf'
306 nan ::= 'NaN' [digits] | 'sNaN' [digits]
307 numeric-value ::= decimal-part [exponent-part] | infinity
308 numeric-string ::= [sign] numeric-value | [sign] nan
309 \end{verbatim}
310
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000311 If \var{value} is a \class{tuple}, it should have three components,
312 a sign (\constant{0} for positive or \constant{1} for negative),
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000313 a \class{tuple} of digits, and an integer exponent. For example,
314 \samp{Decimal((0, (1, 4, 1, 4), -3))} returns \code{Decimal("1.414")}.
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000315
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000316 The \var{context} precision does not affect how many digits are stored.
317 That is determined exclusively by the number of digits in \var{value}. For
318 example, \samp{Decimal("3.00000")} records all five zeroes even if the
319 context precision is only three.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000320
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000321 The purpose of the \var{context} argument is determining what to do if
322 \var{value} is a malformed string. If the context traps
323 \constant{InvalidOperation}, an exception is raised; otherwise, the
324 constructor returns a new Decimal with the value of \constant{NaN}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000325
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
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000337also have a number of specialized methods:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000338
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()}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000342 returns seven. Used for determining the position of the most significant
343 digit with respect to the decimal point.
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}}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000392 Computes the modulo as either a positive or negative value depending
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000393 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
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000425
426
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000427%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
428\subsection{Context objects \label{decimal-decimal}}
429
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000430Contexts are environments for arithmetic operations. They govern precision,
431set rules for rounding, determine which signals are treated as exceptions, and
432limit the range for exponents.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000433
434Each thread has its own current context which is accessed or changed using
435the \function{getcontext()} and \function{setcontext()} functions:
436
437\begin{funcdesc}{getcontext}{}
438 Return the current context for the active thread.
439\end{funcdesc}
440
441\begin{funcdesc}{setcontext}{c}
442 Set the current context for the active thread to \var{c}.
443\end{funcdesc}
444
445New contexts can formed using the \class{Context} constructor described below.
446In addition, the module provides three pre-made contexts:
447
448
449\begin{classdesc*}{BasicContext}
450 This is a standard context defined by the General Decimal Arithmetic
451 Specification. Precision is set to nine. Rounding is set to
452 \constant{ROUND_HALF_UP}. All flags are cleared. All traps are enabled
453 (treated as exceptions) except \constant{Inexact}, \constant{Rounded}, and
454 \constant{Subnormal}.
455
456 Because many of the traps are enabled, this context is useful for debugging.
457\end{classdesc*}
458
459\begin{classdesc*}{ExtendedContext}
460 This is a standard context defined by the General Decimal Arithmetic
461 Specification. Precision is set to nine. Rounding is set to
462 \constant{ROUND_HALF_EVEN}. All flags are cleared. No traps are enabled
463 (so that exceptions are not raised during computations).
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000464
465 Because the trapped are disabled, this context is useful for applications
466 that prefer to have result value of \constant{NaN} or \constant{Infinity}
467 instead of raising exceptions. This allows an application to complete a
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000468 run in the presence of conditions that would otherwise halt the program.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000469\end{classdesc*}
470
471\begin{classdesc*}{DefaultContext}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000472 This context is used by the \class{Context} constructor as a prototype for
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000473 new contexts. Changing a field (such a precision) has the effect of
474 changing the default for new contexts creating by the \class{Context}
475 constructor.
476
477 This context is most useful in multi-threaded environments. Changing one of
478 the fields before threads are started has the effect of setting system-wide
479 defaults. Changing the fields after threads have started is not recommended
480 as it would require thread synchronization to prevent race conditions.
481
482 In single threaded environments, it is preferable to not use this context
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000483 at all. Instead, simply create contexts explicitly as described below.
484
485 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled
486 traps for Overflow, InvalidOperation, and DivisionByZero.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000487\end{classdesc*}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000488
489
490In addition to the three supplied contexts, new contexts can be created
491with the \class{Context} constructor.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000492
Raymond Hettingerbf440692004-07-10 14:14:37 +0000493\begin{classdesc}{Context}{prec=None, rounding=None, traps=None,
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000494 flags=None, Emin=None, Emax=None, capitals=1}
495 Creates a new context. If a field is not specified or is \constant{None},
496 the default values are copied from the \constant{DefaultContext}. If the
497 \var{flags} field is not specified or is \constant{None}, all flags are
498 cleared.
499
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000500 The \var{prec} field is a positive integer that sets the precision for
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000501 arithmetic operations in the context.
502
Raymond Hettinger97c92082004-07-09 06:13:12 +0000503 The \var{rounding} option is one of:
504 \constant{ROUND_CEILING} (towards \constant{Infinity}),
505 \constant{ROUND_DOWN} (towards zero),
506 \constant{ROUND_FLOOR} (towards \constant{-Infinity}),
507 \constant{ROUND_HALF_DOWN} (towards zero),
508 \constant{ROUND_HALF_EVEN},
509 \constant{ROUND_HALF_UP} (away from zero), or
510 \constant{ROUND_UP} (away from zero).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000511
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000512 The \var{traps} and \var{flags} fields list any signals to be set.
513 Generally, new contexts should only set traps and leave the flags clear.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000514
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
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000520 \constant{E}; otherwise, a lowercase \constant{e} is used:
521 \constant{Decimal('6.02e+23')}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000522\end{classdesc}
523
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000524The \class{Context} class defines several general purpose methods as well as a
525large number of methods for doing arithmetic directly in a given context.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000526
527\begin{methoddesc}{clear_flags}{}
528 Sets all of the flags to \constant{0}.
529\end{methoddesc}
530
531\begin{methoddesc}{copy}{}
532 Returns a duplicate of the context.
533\end{methoddesc}
534
535\begin{methoddesc}{create_decimal}{num}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000536 Creates a new Decimal instance from \var{num} but using \var{self} as
537 context. Unlike the \class{Decimal} constructor, the context precision,
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000538 rounding method, flags, and traps are applied to the conversion.
539
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000540 This is useful because constants are often given to a greater precision than
541 is needed by the application.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000542\end{methoddesc}
543
544\begin{methoddesc}{Etiny}{}
545 Returns a value equal to \samp{Emin - prec + 1} which is the minimum
546 exponent value for subnormal results. When underflow occurs, the
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000547 exponent is set to \constant{Etiny}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000548\end{methoddesc}
549
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000550\begin{methoddesc}{Etop}{}
551 Returns a value equal to \samp{Emax - prec + 1}.
552\end{methoddesc}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000553
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000554
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000555The usual approach to working with decimals is to create \class{Decimal}
556instances and then apply arithmetic operations which take place within the
557current context for the active thread. An alternate approach is to use
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000558context methods for calculating within a specific context. The methods are
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000559similar to those for the \class{Decimal} class and are only briefly recounted
560here.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000561
562\begin{methoddesc}{abs}{x}
563 Returns the absolute value of \var{x}.
564\end{methoddesc}
565
566\begin{methoddesc}{add}{x, y}
567 Return the sum of \var{x} and \var{y}.
568\end{methoddesc}
569
570\begin{methoddesc}{compare}{x, y}
571 Compares values numerically.
572
573 Like \method{__cmp__()} but returns a decimal instance:
574 \begin{verbatim}
575 a or b is a NaN ==> Decimal("NaN")
576 a < b ==> Decimal("-1")
577 a == b ==> Decimal("0")
578 a > b ==> Decimal("1")
579 \end{verbatim}
580\end{methoddesc}
581
582\begin{methoddesc}{divide}{x, y}
583 Return \var{x} divided by \var{y}.
584\end{methoddesc}
585
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000586\begin{methoddesc}{divmod}{x, y}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000587 Divides two numbers and returns the integer part of the result.
588\end{methoddesc}
589
590\begin{methoddesc}{max}{x, y}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000591 Compare two values numerically and return the maximum.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000592
593 If they are numerically equal then the left-hand operand is chosen as the
594 result.
595\end{methoddesc}
596
597\begin{methoddesc}{min}{x, y}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000598 Compare two values numerically and return the minimum.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000599
600 If they are numerically equal then the left-hand operand is chosen as the
601 result.
602\end{methoddesc}
603
604\begin{methoddesc}{minus}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000605 Minus corresponds to the unary prefix minus operator in Python.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000606\end{methoddesc}
607
608\begin{methoddesc}{multiply}{x, y}
609 Return the product of \var{x} and \var{y}.
610\end{methoddesc}
611
612\begin{methoddesc}{normalize}{x}
613 Normalize reduces an operand to its simplest form.
614
615 Essentially a plus operation with all trailing zeros removed from the
616 result.
617\end{methoddesc}
618
619\begin{methoddesc}{plus}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000620 Minus corresponds to the unary prefix plus operator in Python.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000621\end{methoddesc}
622
623\begin{methoddesc}{power}{x, y\optional{, modulo}}
624 Return \samp{x ** y} to the \var{modulo} if given.
625
626 The right-hand operand must be a whole number whose integer part (after any
627 exponent has been applied) has no more than 9 digits and whose fractional
628 part (if any) is all zeros before any rounding. The operand may be positive,
629 negative, or zero; if negative, the absolute value of the power is used, and
630 the left-hand operand is inverted (divided into 1) before use.
631
632 If the increased precision needed for the intermediate calculations exceeds
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000633 the capabilities of the implementation then an \constant{InvalidOperation}
634 condition is signaled.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000635
636 If, when raising to a negative power, an underflow occurs during the
637 division into 1, the operation is not halted at that point but continues.
638\end{methoddesc}
639
640\begin{methoddesc}{quantize}{x, y}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000641 Returns a value equal to \var{x} after rounding and having the exponent of
642 \var{y}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000643
644 Unlike other operations, if the length of the coefficient after the quantize
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000645 operation would be greater than precision, then an
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000646 \constant{InvalidOperation} is signaled. This guarantees that, unless there
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000647 is an error condition, the quantized exponent is always equal to that of the
648 right-hand operand.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000649
650 Also unlike other operations, quantize never signals Underflow, even
651 if the result is subnormal and inexact.
652\end{methoddesc}
653
654\begin{methoddesc}{remainder}{x, y}
655 Returns the remainder from integer division.
656
657 The sign of the result, if non-zero, is the same as that of the original
658 dividend.
659\end{methoddesc}
660
661\begin{methoddesc}{remainder_near}{x, y}
662 Computed the modulo as either a positive or negative value depending
663 on which is closest to zero. For instance,
664 \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")}
665 which is closer to zero than \code{Decimal("4")}.
666
667 If both are equally close, the one chosen will have the same sign
668 as \var{self}.
669\end{methoddesc}
670
671\begin{methoddesc}{same_quantum}{x, y}
672 Test whether \var{x} and \var{y} have the same exponent or whether both are
673 \constant{NaN}.
674\end{methoddesc}
675
676\begin{methoddesc}{sqrt}{}
677 Return the square root to full precision.
678\end{methoddesc}
679
680\begin{methoddesc}{substract}{x, y}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000681 Return the difference between \var{x} and \var{y}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000682\end{methoddesc}
683
684\begin{methoddesc}{to_eng_string}{}
685 Convert to engineering-type string.
686
687 Engineering notation has an exponent which is a multiple of 3, so there
688 are up to 3 digits left of the decimal place. For example, converts
689 \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")}
690\end{methoddesc}
691
692\begin{methoddesc}{to_integral}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000693 Rounds to the nearest integer without signaling \constant{Inexact}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000694 or \constant{Rounded}.
695\end{methoddesc}
696
697\begin{methoddesc}{to_sci_string}{}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000698 Converts a number to a string using scientific notation.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000699\end{methoddesc}
700
701
702
703%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
704\subsection{Signals \label{decimal-signals}}
705
706Signals represent conditions that arise during computation.
707Each corresponds to one context flag and one context trap enabler.
708
709The context flag is incremented whenever the condition is encountered.
710After the computation, flags may be checked for informational
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000711purposes (for instance, to determine whether a computation was exact).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000712After checking the flags, be sure to clear all flags before starting
713the next computation.
714
715If the context's trap enabler is set for the signal, then the condition
716causes a Python exception to be raised. For example, if the
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000717\class{DivisionByZero} trap is set, then a \exception{DivisionByZero}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000718exception is raised upon encountering the condition.
719
720
721\begin{classdesc*}{Clamped}
722 Altered an exponent to fit representation constraints.
723
724 Typically, clamping occurs when an exponent falls outside the context's
725 \member{Emin} and \member{Emax} limits. If possible, the exponent is
726 reduced to fit by adding zeroes to the coefficient.
727\end{classdesc*}
728
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000729\begin{classdesc*}{DecimalException}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000730 Base class for other signals and is a subclass of
731 \exception{ArithmeticError}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000732\end{classdesc*}
733
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000734\begin{classdesc*}{DivisionByZero}
735 Signals the division of a non-infinite number by zero.
736
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000737 Can occur with division, modulo division, or when raising a number to a
738 negative power. If this signal is not trapped, returns
739 \constant{Infinity} or \constant{-Infinity} with the sign determined by
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000740 the inputs to the calculation.
741\end{classdesc*}
742
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000743\begin{classdesc*}{Inexact}
744 Indicates that rounding occurred and the result is not exact.
745
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000746 Signals when non-zero digits were discarded during rounding. The rounded
747 result is returned. The signal flag or trap is used to detect when
748 results are inexact.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000749\end{classdesc*}
750
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000751\begin{classdesc*}{InvalidOperation}
752 An invalid operation was performed.
753
754 Indicates that an operation was requested that does not make sense.
755 If not trapped, returns \constant{NaN}. Possible causes include:
756
757 \begin{verbatim}
758 Infinity - Infinity
759 0 * Infinity
760 Infinity / Infinity
761 x % 0
762 Infinity % x
763 x._rescale( non-integer )
764 sqrt(-x) and x > 0
765 0 ** 0
766 x ** (non-integer)
767 x ** Infinity
768 \end{verbatim}
769\end{classdesc*}
770
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000771\begin{classdesc*}{Overflow}
772 Numerical overflow.
773
774 Indicates the exponent is larger than \member{Emax} after rounding has
775 occurred. If not trapped, the result depends on the rounding mode, either
776 pulling inward to the largest representable finite number or rounding
777 outward to \constant{Infinity}. In either case, \class{Inexact} and
778 \class{Rounded} are also signaled.
779\end{classdesc*}
780
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000781\begin{classdesc*}{Rounded}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000782 Rounding occurred though possibly no information was lost.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000783
784 Signaled whenever rounding discards digits; even if those digits are
785 zero (such as rounding \constant{5.00} to \constant{5.0}). If not
786 trapped, returns the result unchanged. This signal is used to detect
787 loss of significant digits.
788\end{classdesc*}
789
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000790\begin{classdesc*}{Subnormal}
791 Exponent was lower than \member{Emin} prior to rounding.
792
793 Occurs when an operation result is subnormal (the exponent is too small).
794 If not trapped, returns the result unchanged.
795\end{classdesc*}
796
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000797\begin{classdesc*}{Underflow}
798 Numerical underflow with result rounded to zero.
799
800 Occurs when a subnormal result is pushed to zero by rounding.
801 \class{Inexact} and \class{Subnormal} are also signaled.
802\end{classdesc*}
803
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000804The following table summarizes the hierarchy of signals:
805
806\begin{verbatim}
807 exceptions.ArithmeticError(exceptions.StandardError)
808 DecimalException
809 Clamped
810 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
811 Inexact
812 Overflow(Inexact, Rounded)
813 Underflow(Inexact, Rounded, Subnormal)
814 InvalidOperation
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000815 Rounded
816 Subnormal
817\end{verbatim}
818
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000819
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000820%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
821\subsection{Working with threads \label{decimal-threads}}
822
823The \function{getcontext()} function accesses a different \class{Context}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000824object for each thread. Having separate thread contexts means that threads
825may make changes (such as \code{getcontext.prec=10}) without interfering with
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000826other threads.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000827
828Likewise, the \function{setcontext()} function automatically assigns its target
829to the current thread.
830
831If \function{setcontext()} has not been called before \function{getcontext()},
832then \function{getcontext()} will automatically create a new context for use
833in the current thread.
834
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000835The new context is copied from a prototype context called
836\var{DefaultContext}. To control the defaults so that each thread will use the
837same values throughout the application, directly modify the
838\var{DefaultContext} object. This should be done \emph{before} any threads are
839started so that there won't be a race condition between threads calling
840\function{getcontext()}. For example:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000841
842\begin{verbatim}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000843# Set applicationwide defaults for all threads about to be launched
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000844DefaultContext = Context(prec=12, rounding=ROUND_DOWN, traps=[InvalidOperation])
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000845setcontext(DefaultContext)
846
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000847# Afterward, the threads can be started
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000848t1.start()
849t2.start()
850t3.start()
851 . . .
852\end{verbatim}
853
854
855
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000856%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
857\subsection{Recipes \label{decimal-recipes}}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000858
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000859Here are a few recipes that serve as utility functions and that demonstrate
860ways to work with the \class{Decimal} class:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000861
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000862\begin{verbatim}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000863def moneyfmt(value, places=2, curr='', sep=',', dp='.',
864 pos='', neg='-', trailneg=''):
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000865 """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)
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000871 only specify as blank when places is zero
872 pos: optional sign for positive numbers: "+", space or blank
873 neg: optional sign for negative numbers: "-", "(", space or blank
874 trailneg:optional trailing minus indicator: "-", ")", space or blank
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000875
876 >>> d = Decimal('-1234567.8901')
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000877 >>> moneyfmt(d, curr='$')
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000878 '-$1,234,567.89'
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000879 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
880 '1.234.568-'
881 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000882 '($1,234,567.89)'
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000883
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000884 """
885 q = Decimal((0, (1,), -places)) # 2 places --> '0.01'
886 sign, digits, exp = value.quantize(q).as_tuple()
887 result = []
888 digits = map(str, digits)
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000889 build, next = result.append, digits.pop
890 if sign:
891 build(trailneg)
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000892 for i in range(places):
893 build(next())
894 build(dp)
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000895 i = 0
896 while digits:
897 build(next())
898 i += 1
899 if i == 3:
900 i = 0
901 build(sep)
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000902 build(curr)
903 if sign:
904 build(neg)
905 else:
906 build(pos)
907 result.reverse()
908 return ''.join(result)
909
910def pi():
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000911 """Compute Pi to the current precision.
912
913 >>> print pi()
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000914 3.141592653589793238462643383
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000915
Raymond Hettingerc4f93d442004-07-05 20:17:13 +0000916 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000917 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettinger10959b12004-07-05 21:13:28 +0000918 three = Decimal(3) # substitute "three=3.0" for regular floats
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000919 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
920 while s != lasts:
921 lasts = s
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000922 n, na = n+na, na+8
923 d, da = d+da, da+32
924 t = (t * n) / d
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000925 s += t
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000926 getcontext().prec -= 2
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000927 return +s # unary plus applies the new precision
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000928
929def exp(x):
Raymond Hettinger10959b12004-07-05 21:13:28 +0000930 """Return e raised to the power of x. Result type matches input type.
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000931
932 >>> print exp(Decimal(1))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000933 2.718281828459045235360287471
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000934 >>> print exp(Decimal(2))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000935 7.389056098930650227230427461
Raymond Hettinger10959b12004-07-05 21:13:28 +0000936 >>> print exp(2.0)
937 7.38905609893
938 >>> print exp(2+0j)
939 (7.38905609893+0j)
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000940
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000941 """
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000942 getcontext().prec += 2
943 i, lasts, s, fact, num = 0, 0, 1, 1, 1
944 while s != lasts:
945 lasts = s
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000946 i += 1
947 fact *= i
948 num *= x
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000949 s += num / fact
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000950 getcontext().prec -= 2
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000951 return +s
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000952
953def cos(x):
954 """Return the cosine of x as measured in radians.
955
956 >>> print cos(Decimal('0.5'))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000957 0.8775825618903727161162815826
Raymond Hettinger10959b12004-07-05 21:13:28 +0000958 >>> print cos(0.5)
959 0.87758256189
960 >>> print cos(0.5+0j)
961 (0.87758256189+0j)
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000962
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000963 """
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000964 getcontext().prec += 2
965 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
966 while s != lasts:
967 lasts = s
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000968 i += 2
969 fact *= i * (i-1)
970 num *= x * x
971 sign *= -1
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000972 s += num / fact * sign
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000973 getcontext().prec -= 2
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000974 return +s
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000975
976def sin(x):
977 """Return the cosine of x as measured in radians.
978
979 >>> print sin(Decimal('0.5'))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000980 0.4794255386042030002732879352
Raymond Hettinger10959b12004-07-05 21:13:28 +0000981 >>> print sin(0.5)
982 0.479425538604
983 >>> print sin(0.5+0j)
984 (0.479425538604+0j)
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000985
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000986 """
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000987 getcontext().prec += 2
988 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
989 while s != lasts:
990 lasts = s
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000991 i += 2
992 fact *= i * (i-1)
993 num *= x * x
994 sign *= -1
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000995 s += num / fact * sign
Raymond Hettinger2f55eb42004-07-06 01:55:14 +0000996 getcontext().prec -= 2
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000997 return +s
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000998
999\end{verbatim}