blob: e6686717b609f8d09d3957b4768722ff7fd888ea [file] [log] [blame]
Raymond Hettinger8de63a22004-07-05 05:52:03 +00001\section{\module{decimal} ---
2 Decimal floating point arithmetic}
3
4\declaremodule{standard}{decimal}
5\modulesynopsis{Implementation of the General Decimal Arithmetic
6Specification.}
7
8\moduleauthor{Eric Price}{eprice at tjhsst.edu}
9\moduleauthor{Facundo Batista}{facundo at taniquetil.com.ar}
10\moduleauthor{Raymond Hettinger}{python at rcn.com}
11\moduleauthor{Aahz}{aahz at pobox.com}
12\moduleauthor{Tim Peters}{tim.one at comcast.net}
13
14\sectionauthor{Raymond D. Hettinger}{python at rcn.com}
15
16\versionadded{2.4}
17
18The decimal \module{module} provides support for decimal floating point
19arithmetic. It offers several advantages over the \class{float()} datatype:
20
21\begin{itemize}
22
23\item Decimal numbers can be represented exactly. In contrast, numbers like
24\constant{1.1} do not have an exact representations in binary floating point.
25End users typically wound not expect \constant{1.1} to display as
26\constant{1.1000000000000001} as it does with binary floating point.
27
28\item The exactness carries over into arithmetic. In decimal floating point,
29\samp{0.1 + 0.1 + 0.1 - 0.3} is exactly equal to zero. In binary floating
30point, result is \constant{5.5511151231257827e-017}. While near to zero, the
31differences prevent reliable equality testing and differences can accumulate.
32For this reason, decimal would be preferred in accounting applications which
33have strict equality invariants.
34
35\item The decimal module incorporates notion of significant places so that
36\samp{1.30 + 1.20} is \constant{2.50}. The trailing zero is kept to indicate
37significance. This is the customary presentation for monetary applications. For
38multiplication, the ``schoolbook'' approach uses all the figures in the
39multiplicands. For instance, \samp{1.3 * 1.2} gives \constant{1.56} while
40\samp{1.30 * 1.20} gives \constant{1.5600}.
41
42\item Unlike hardware based binary floating point, the decimal module has a user
43settable precision (defaulting to 28 places) which can be as large as needed for
44a given problem:
45
46\begin{verbatim}
47>>> getcontext().prec = 6
48>>> Decimal(1) / Decimal(7)
49Decimal("0.142857")
50>>> getcontext().prec = 28
51>>> Decimal(1) / Decimal(7)
52Decimal("0.1428571428571428571428571429")
53\end{verbatim}
54
55\item Both binary and decimal floating point are implemented in terms of published
56standards. While the built-in float type exposes only a modest portion of its
57capabilities, the decimal module exposes all required parts of the standard.
58When needed, the programmer has full control over rounding and signal handling.
59
60\end{itemize}
61
62
63The module design is centered around three concepts: the decimal number, the
64context for arithmetic, and signals.
65
66A decimal number is immutable. It has a sign, coefficient digits, and an
67exponent. To preserve significance, the coefficient digits do not truncate
68trailing zeroes. Decimals also include special values such as
69\constant{Infinity} (the result of \samp{1 / 0}), \constant{-Infinity},
70(the result of \samp{-1 / 0}), and \constant{NaN} (the result of
71\samp{0 / 0}). The standard also differentiates \constant{-0} from
72\constant{+0}.
73
74The context for arithmetic is an environment specifying precision, rounding
75rules, limits on exponents, flags that indicate the results of operations,
76and trap enablers which determine whether signals are to be treated as
77exceptions. Rounding options include \constant{ROUND_CEILING},
78\constant{ROUND_DOWN}, \constant{ROUND_FLOOR}, \constant{ROUND_HALF_DOWN},
79\constant{ROUND_HALF_EVEN}, \constant{ROUND_HALF_UP}, and \constant{ROUND_UP}.
80
81Signals are types of information that arise during the course of a
82computation. Depending on the needs of the application, some signals may be
83ignored, considered as informational, or treated as exceptions. The signals in
84the decimal module are: \constant{Clamped}, \constant{InvalidOperation},
85\constant{ConversionSyntax}, \constant{DivisionByZero},
86\constant{DivisionImpossible}, \constant{DivisionUndefined},
87\constant{Inexact}, \constant{InvalidContext}, \constant{Rounded},
88\constant{Subnormal}, \constant{Overflow}, and \constant{Underflow}.
89
90For each signal there is a flag and a trap enabler. When a signal is
91encountered, its flag incremented from zero and, then, if the trap enabler
92is set to one, an exception is raised.
93
94
95\begin{seealso}
96 \seetext{IBM's General Decimal Arithmetic Specification,
97 \citetitle[http://www2.hursley.ibm.com/decimal/decarith.html]
98 {The General Decimal Arithmetic Specification}.}
99
100 \seetext{IEEE standard 854-1987,
101 \citetitle[http://www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html]
102 {Unofficial IEEE 854 Text}.}
103\end{seealso}
104
105
106
107%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
108\subsection{Quick-start Tutorial \label{decimal-tutorial}}
109
110The normal start to using decimals is to import the module, and then use
111\function{getcontext()} to view the context and, if necessary, set the context
112precision, rounding, or trap enablers:
113
114\begin{verbatim}
115>>> from decimal import *
116>>> getcontext()
117Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
118 setflags=[], settraps=[])
119
120>>> getcontext().prec = 7
121\end{verbatim}
122
123Decimal instances can be constructed from integers or strings. To create a
124Decimal from a \class{float}, first convert it to a string. This serves as an
125explicit reminder of the details of the conversion (including representation
126error). Malformed strings signal \constant{ConversionSyntax} and return a
127special kind of Decimal called a \constant{NaN} which stands for ``Not a
128number''. Positive and negative \constant{Infinity} is yet another special
129kind of Decimal.
130
131\begin{verbatim}
132>>> Decimal(10)
133Decimal("10")
134>>> Decimal('3.14')
135Decimal("3.14")
136>>> Decimal(str(2.0 ** 0.5))
137Decimal("1.41421356237")
138>>> Decimal('Mickey Mouse')
139Decimal("NaN")
140>>> Decimal('-Infinity')
141Decimal("-Infinity")
142\end{verbatim}
143
144Creating decimals is unaffected by context precision. Their level of
145significance is completely determined by the number of digits input. It is
146the arithmetic operations that are governed by context.
147
148\begin{verbatim}
149>>> getcontext().prec = 6
150>>> Decimal('3.0000')
151Decimal("3.0000")
152>>> Decimal('3.0')
153Decimal("3.0")
154>>> Decimal('3.1415926535')
155Decimal("3.1415926535")
156>>> Decimal('3.1415926535') + Decimal('2.7182818285')
157Decimal("5.85987")
158>>> getcontext().rounding = ROUND_UP
159>>> Decimal('3.1415926535') + Decimal('2.7182818285')
160Decimal("5.85988")
161\end{verbatim}
162
163Decimals 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
194The \function{getcontext()} function accesses the current context. This one
195context is sufficient for many applications; however, for more advanced work,
196multiple contexts can be created using the Context() constructor. To make a
197new context active, use the \function{setcontext()} function.
198
199In accordance with the standard, the \module{Decimal} module provides two
200ready to use standard contexts, \constant{BasicContext} and
201\constant{ExtendedContext}. The former is especially useful for debugging
202because many of the traps are enabled:
203
204\begin{verbatim}
205>>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
206>>> myothercontext
207Context(prec=60, rounding=ROUND_HALF_DOWN, Emin=-999999999, Emax=999999999,
208 setflags=[], settraps=[])
209>>> ExtendedContext
210Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
211 setflags=[], settraps=[])
212>>> setcontext(myothercontext)
213>>> Decimal(1) / Decimal(7)
214Decimal("0.142857142857142857142857142857142857142857142857142857142857")
215>>> setcontext(ExtendedContext)
216>>> Decimal(1) / Decimal(7)
217Decimal("0.142857143")
218>>> Decimal(42) / Decimal(0)
219Decimal("Infinity")
220>>> setcontext(BasicContext)
221>>> Decimal(42) / Decimal(0)
222Traceback (most recent call last):
223 File "<pyshell#143>", line 1, in -toplevel-
224 Decimal(42) / Decimal(0)
225DivisionByZero: x / 0
226\end{verbatim}
227
228Besides using contexts to control precision, rounding, and trapping signals,
229they can be used to monitor flags which give information collected during
230computation. The flags remain set until explicitly cleared, so it is best to
231clear the flags before each set of monitored computations by using the
232\method{clear_flags()} method.
233
234\begin{verbatim}
235>>> setcontext(ExtendedContext)
236>>> getcontext().clear_flags()
237>>> Decimal(355) / Decimal(113)
238Decimal("3.14159292")
239>>> getcontext()
240Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
241 setflags=['Inexact', 'Rounded'], settraps=[])
242\end{verbatim}
243
244The \var{setflags} entry shows that the rational approximation to
245\constant{Pi} was rounded (digits beyond the context precision were thrown
246away) and that the result is inexact (some of the discarded digits were
247non-zero).
248
249Individual traps are set using the dictionary in the \member{trap_enablers}
250field of a context:
251
252\begin{verbatim}
253>>> Decimal(1) / Decimal(0)
254Decimal("Infinity")
255>>> getcontext().trap_enablers[DivisionByZero] = 1
256>>> Decimal(1) / Decimal(0)
257
258Traceback (most recent call last):
259 File "<pyshell#112>", line 1, in -toplevel-
260 Decimal(1) / Decimal(0)
261DivisionByZero: x / 0
262\end{verbatim}
263
264To turn all the traps on or off all at once, use a loop. Also, the
265\method{dict.update()} method is useful for changing a handfull of values.
266
267\begin{verbatim}
268>>> getcontext.clear_flags()
269>>> for sig in getcontext().trap_enablers:
270... getcontext().trap_enablers[sig] = 1
271
272>>> getcontext().trap_enablers.update({Rounded:0, Inexact:0, Subnormal:0})
273>>> getcontext()
274Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
275 setflags=[], settraps=['Underflow', 'DecimalException', 'Clamped',
276 'InvalidContext', 'InvalidOperation', 'ConversionSyntax',
277 'DivisionByZero', 'DivisionImpossible', 'DivisionUndefined',
278 'Overflow'])
279\end{verbatim}
280
281Applications typically set the context once at the beginning of a program
282and no further changes are needed. For many applications, the data resides
283in a resource external to the program and is converted to \class{Decimal} with
284a single cast inside a loop. Afterwards, decimals are as easily manipulated
285as other Python numeric types.
286
287
288
289%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
290\subsection{Decimal objects \label{decimal-decimal}}
291
292\begin{classdesc}{Decimal}{\optional{value \optional{, context}}}
293 Constructs a new \class{Decimal} object based from \var{value}.
294
295 \var{value} can be an integer, string, or another \class{Decimal} object.
296 If no \var{value} is given, returns \code{Decimal("0")}. If \var{value} is
297 a string, it should conform to the decimal numeric string syntax:
298
299 \begin{verbatim}
300 sign ::= '+' | '-'
301 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
302 indicator ::= 'e' | 'E'
303 digits ::= digit [digit]...
304 decimal-part ::= digits '.' [digits] | ['.'] digits
305 exponent-part ::= indicator [sign] digits
306 infinity ::= 'Infinity' | 'Inf'
307 nan ::= 'NaN' [digits] | 'sNaN' [digits]
308 numeric-value ::= decimal-part [exponent-part] | infinity
309 numeric-string ::= [sign] numeric-value | [sign] nan
310 \end{verbatim}
311
312 The supplied \var{context} or, if not specified, the current context
313 governs only the handling of mal-formed strings not conforming to the
314 numeric string syntax. If the context traps \constant{ConversionSyntax},
315 an exception is raised; otherwise, the constructor returns a new Decimal
316 with the value of \constant{NaN}.
317
318 The context serves no other purpose. The number of significant digits
319 recorded is determined solely by the \var{value} and the var{context}
320 precision is not a factor. For example, \samp{Decimal("3.0000")} records
321 all four zeroes even if the context precision is only three.
322
323 Once constructed, \class{Decimal} objects are immutable.
324\end{classdesc}
325
326Decimal floating point objects share many properties with the other builtin
327numeric types such as \class{float} and \class{int}. All of the usual
328math operations and special methods apply. Likewise, decimal objects can
329be copied, pickled, printed, used as dictionary keys, used as set elements,
330compared, sorted, and coerced to another type (such as \class{float}
331or \class{long}).
332
333In addition to the standard numeric properties, decimal floating point objects
334have a number of more specialized methods:
335
336\begin{methoddesc}{adjusted}{}
337 Return the number's adjusted exponent that results from shifting out the
338 coefficients rightmost digits until only the lead digit remains:
339 \code{Decimal("321e+5").adjusted()} returns seven. Used for determining
340 the place value of the most significant digit.
341\end{methoddesc}
342
343\begin{methoddesc}{as_tuple}{}
344 Returns a tuple representation of the number:
345 \samp{(sign, digittuple, exponent)}.
346\end{methoddesc}
347
348\begin{methoddesc}{compare}{other\optional{, context}}
349 Compares like \method{__cmp__()} but returns a decimal instance:
350 \begin{verbatim}
351 a or b is a NaN ==> Decimal("NaN")
352 a < b ==> Decimal("-1")
353 a == b ==> Decimal("0")
354 a > b ==> Decimal("1")
355 \end{verbatim}
356\end{methoddesc}
357
358\begin{methoddesc}{max}{other\optional{, context}}
359 Like \samp{max(self, other)} but returns \constant{NaN} if either is a
360 \constant{NaN}. Applies the context rounding rule before returning.
361\end{methoddesc}
362
363\begin{methoddesc}{min}{other\optional{, context}}
364 Like \samp{min(self, other)} but returns \constant{NaN} if either is a
365 \constant{NaN}. Applies the context rounding rule before returning.
366\end{methoddesc}
367
368\begin{methoddesc}{normalize}{\optional{context}}
369 Normalize the number by striping the rightmost trailing zeroes and
370 converting any result equal to \constant{Decimal("0")} to Decimal("0e0").
371 Used for producing a canonical value for members of an equivalence class.
372 For example, \code{Decimal("32.100")} and \code{Decimal("0.321000e+2")}
373 both normalize to the equivalent value \code{Decimal("32.1")}
374\end{methoddesc}
375
376\begin{methoddesc}{quantize}
377 {\optional{exp \optional{, rounding\optional{, context\optional{, watchexp}}}}}
378 Quantize makes the exponent the same as \var{exp}. Searches for a
379 rounding method in \var{rounding}, then in \var{context}, and then
380 in the current context.
381
382 Of \var{watchexp} is set (default), then an error is returned if
383 the resulting exponent is greater than \member{Emax} or less than
384 \member{Etiny}.
385\end{methoddesc}
386
387\begin{methoddesc}{remainder_near}{other\optional{, context}}
388 Computed the modulo as either a positive or negative value depending
389 on which is closest to zero. For instance,
390 \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")}
391 which is closer to zero than \code{Decimal("4")}.
392
393 If both are equally close, the one chosen will have the same sign
394 as \var{self}.
395\end{methoddesc}
396
397\begin{methoddesc}{same_quantum{other\optional{, context}}}
398 Test whether self and other have the same exponent or whether both
399 are \constant{NaN}.
400\end{methoddesc}
401
402\begin{methoddesc}{sqrt}{\optional{context}}
403 Return the square root to full precision.
404\end{methoddesc}
405
406\begin{methoddesc}{to_eng_string}{\optional{context}}
407 Convert to engineering-type string.
408
409 Engineering notation has an exponent which is a multiple of 3, so there
410 are up to 3 digits left of the decimal place. For example, converts
411 \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")}
412\end{methoddesc}
413
414\begin{methoddesc}{to_integral}{\optional{rounding\optional{, context}}}
415 Rounds to the nearest integer, without signaling \constant{Inexact}
416 or \constant{Rounded}. If given, applies \var{rounding}; otherwise,
417 uses the rounding method in either the supplied \var{context} or the
418 current context.
419\end{methoddesc}
420
421
422%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
423\subsection{Context objects \label{decimal-decimal}}
424
425Contexts are environments for arithmetic operations. They govern the precision,
426rules for rounding, determine which signals are treated as exceptions, and set limits
427on the range for exponents.
428
429Each thread has its own current context which is accessed or changed using
430the \function{getcontext()} and \function{setcontext()} functions:
431
432\begin{funcdesc}{getcontext}{}
433 Return the current context for the active thread.
434\end{funcdesc}
435
436\begin{funcdesc}{setcontext}{c}
437 Set the current context for the active thread to \var{c}.
438\end{funcdesc}
439
440New contexts can formed using the \class{Context} constructor described below.
441In addition, the module provides three pre-made contexts:
442
443
444\begin{classdesc*}{BasicContext}
445 This is a standard context defined by the General Decimal Arithmetic
446 Specification. Precision is set to nine. Rounding is set to
447 \constant{ROUND_HALF_UP}. All flags are cleared. All traps are enabled
448 (treated as exceptions) except \constant{Inexact}, \constant{Rounded}, and
449 \constant{Subnormal}.
450
451 Because many of the traps are enabled, this context is useful for debugging.
452\end{classdesc*}
453
454\begin{classdesc*}{ExtendedContext}
455 This is a standard context defined by the General Decimal Arithmetic
456 Specification. Precision is set to nine. Rounding is set to
457 \constant{ROUND_HALF_EVEN}. All flags are cleared. No traps are enabled
458 (so that exceptions are not raised during computations).
459\end{classdesc*}
460
461\begin{classdesc*}{DefaultContext}
462 This class is used by the \class{Context} constructor as a prototype for
463 new contexts. Changing a field (such a precision) has the effect of
464 changing the default for new contexts creating by the \class{Context}
465 constructor.
466
467 This context is most useful in multi-threaded environments. Changing one of
468 the fields before threads are started has the effect of setting system-wide
469 defaults. Changing the fields after threads have started is not recommended
470 as it would require thread synchronization to prevent race conditions.
471
472 In single threaded environments, it is preferable to not use this context
473 at all. Instead, simply create contexts explicitly. This is especially
474 important because the default values context may change between releases
475 (with initial release having precision=28, rounding=ROUND_HALF_EVEN,
476 cleared flags, and no traps enabled).
477\end{classdesc*}
478
479
480\begin{classdesc}{Context}{prec=None, rounding=None, trap_enablers=None,
481 flags=None, Emin=None, Emax=None, capitals=1}
482 Creates a new context. If a field is not specified or is \constant{None},
483 the default values are copied from the \constant{DefaultContext}. If the
484 \var{flags} field is not specified or is \constant{None}, all flags are
485 cleared.
486
487 The \var{prec} field in an positive integer that sets the precision for
488 arithmetic operations in the context.
489
490 The \var{rounding} option is one of: \constant{ROUND_CEILING},
491 \constant{ROUND_DOWN}, \constant{ROUND_FLOOR}, \constant{ROUND_HALF_DOWN},
492 \constant{ROUND_HALF_EVEN}, \constant{ROUND_HALF_UP}, or
493 \constant{ROUND_UP}.
494
495 The \var{trap_enablers} and \var{flags} fields are mappings from signals
496 to either \constant{0} or \constant{1}.
497
498 The \var{Emin} and \var{Emax} fields are integers specifying the outer
499 limits allowable for exponents.
500
501 The \var{capitals} field is either \constant{0} or \constant{1} (the
502 default). If set to \constant{1}, exponents are printed with a capital
503 \constant{E}; otherwise, lowercase is used: \constant{Decimal('6.02e+23')}.
504\end{classdesc}
505
506The \class{Context} class defines several general methods as well as a
507large number of methods for doing arithmetic directly from the context.
508
509\begin{methoddesc}{clear_flags}{}
510 Sets all of the flags to \constant{0}.
511\end{methoddesc}
512
513\begin{methoddesc}{copy}{}
514 Returns a duplicate of the context.
515\end{methoddesc}
516
517\begin{methoddesc}{create_decimal}{num}
518 Creates a new Decimal instance but using \var{self} as context.
519 Unlike the \class{Decimal} constructor, context precision,
520 rounding method, flags, and traps are applied to the conversion.
521
522 This is useful because constants are often given to a greater
523 precision than is needed by the application.
524\end{methoddesc}
525
526\begin{methoddesc}{Etiny}{}
527 Returns a value equal to \samp{Emin - prec + 1} which is the minimum
528 exponent value for subnormal results. When underflow occurs, the
529 exponont is set to \constant{Etiny}.
530\end{methoddesc}
531
532The usual approach to working with decimals is to create Decimal
533instances and then apply arithmetic operations which take place
534within the current context for the active thread. An alternate
535approach is to use a context method to perform a particular
536computation within the given context rather than the current context.
537
538Those methods parallel those for the \class{Decimal} class and are
539only briefed recounted here.
540
541
542\begin{methoddesc}{abs}{x}
543 Returns the absolute value of \var{x}.
544\end{methoddesc}
545
546\begin{methoddesc}{add}{x, y}
547 Return the sum of \var{x} and \var{y}.
548\end{methoddesc}
549
550\begin{methoddesc}{compare}{x, y}
551 Compares values numerically.
552
553 Like \method{__cmp__()} but returns a decimal instance:
554 \begin{verbatim}
555 a or b is a NaN ==> Decimal("NaN")
556 a < b ==> Decimal("-1")
557 a == b ==> Decimal("0")
558 a > b ==> Decimal("1")
559 \end{verbatim}
560\end{methoddesc}
561
562\begin{methoddesc}{divide}{x, y}
563 Return \var{x} divided by \var{y}.
564\end{methoddesc}
565
566\begin{methoddesc}{divide}{x, y}
567 Divides two numbers and returns the integer part of the result.
568\end{methoddesc}
569
570\begin{methoddesc}{max}{x, y}
571 Compare two values numerically and returns the maximum.
572
573 If they are numerically equal then the left-hand operand is chosen as the
574 result.
575\end{methoddesc}
576
577\begin{methoddesc}{min}{x, y}
578 Compare two values numerically and returns the minimum.
579
580 If they are numerically equal then the left-hand operand is chosen as the
581 result.
582\end{methoddesc}
583
584\begin{methoddesc}{minus}{x}
585 Minus corresponds to unary prefix minus in Python.
586\end{methoddesc}
587
588\begin{methoddesc}{multiply}{x, y}
589 Return the product of \var{x} and \var{y}.
590\end{methoddesc}
591
592\begin{methoddesc}{normalize}{x}
593 Normalize reduces an operand to its simplest form.
594
595 Essentially a plus operation with all trailing zeros removed from the
596 result.
597\end{methoddesc}
598
599\begin{methoddesc}{plus}{x}
600 Minus corresponds to unary prefix plus in Python.
601\end{methoddesc}
602
603\begin{methoddesc}{power}{x, y\optional{, modulo}}
604 Return \samp{x ** y} to the \var{modulo} if given.
605
606 The right-hand operand must be a whole number whose integer part (after any
607 exponent has been applied) has no more than 9 digits and whose fractional
608 part (if any) is all zeros before any rounding. The operand may be positive,
609 negative, or zero; if negative, the absolute value of the power is used, and
610 the left-hand operand is inverted (divided into 1) before use.
611
612 If the increased precision needed for the intermediate calculations exceeds
613 the capabilities of the implementation then an Invalid operation condition
614 is raised.
615
616 If, when raising to a negative power, an underflow occurs during the
617 division into 1, the operation is not halted at that point but continues.
618\end{methoddesc}
619
620\begin{methoddesc}{quantize}{x, y}
621 Returns a value equal to \var{x} after rounding and having the
622 exponent of v\var{y}.
623
624 Unlike other operations, if the length of the coefficient after the quantize
625 operation would be greater than precision then an
626 \constant{InvalidOperation} is signaled. This guarantees that, unless there
627 is an error condition, the exponent of the result of a quantize is always
628 equal to that of the right-hand operand.
629
630 Also unlike other operations, quantize never signals Underflow, even
631 if the result is subnormal and inexact.
632\end{methoddesc}
633
634\begin{methoddesc}{remainder}{x, y}
635 Returns the remainder from integer division.
636
637 The sign of the result, if non-zero, is the same as that of the original
638 dividend.
639\end{methoddesc}
640
641\begin{methoddesc}{remainder_near}{x, y}
642 Computed the modulo as either a positive or negative value depending
643 on which is closest to zero. For instance,
644 \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")}
645 which is closer to zero than \code{Decimal("4")}.
646
647 If both are equally close, the one chosen will have the same sign
648 as \var{self}.
649\end{methoddesc}
650
651\begin{methoddesc}{same_quantum}{x, y}
652 Test whether \var{x} and \var{y} have the same exponent or whether both are
653 \constant{NaN}.
654\end{methoddesc}
655
656\begin{methoddesc}{sqrt}{}
657 Return the square root to full precision.
658\end{methoddesc}
659
660\begin{methoddesc}{substract}{x, y}
661 Return the difference of \var{x} and \var{y}.
662\end{methoddesc}
663
664\begin{methoddesc}{to_eng_string}{}
665 Convert to engineering-type string.
666
667 Engineering notation has an exponent which is a multiple of 3, so there
668 are up to 3 digits left of the decimal place. For example, converts
669 \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")}
670\end{methoddesc}
671
672\begin{methoddesc}{to_integral}{x}
673 Rounds to the nearest integer, without signaling \constant{Inexact}
674 or \constant{Rounded}.
675\end{methoddesc}
676
677\begin{methoddesc}{to_sci_string}{}
678 Converts a number to a string, using scientific notation.
679\end{methoddesc}
680
681
682
683%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
684\subsection{Signals \label{decimal-signals}}
685
686Signals represent conditions that arise during computation.
687Each corresponds to one context flag and one context trap enabler.
688
689The context flag is incremented whenever the condition is encountered.
690After the computation, flags may be checked for informational
691purposed (for instance, to determine whether a computation was exact).
692After checking the flags, be sure to clear all flags before starting
693the next computation.
694
695If the context's trap enabler is set for the signal, then the condition
696causes a Python exception to be raised. For example, if the
697\class{DivisionByZero} trap is set, the a \exception{DivisionByZero}
698exception is raised upon encountering the condition.
699
700
701\begin{classdesc*}{Clamped}
702 Altered an exponent to fit representation constraints.
703
704 Typically, clamping occurs when an exponent falls outside the context's
705 \member{Emin} and \member{Emax} limits. If possible, the exponent is
706 reduced to fit by adding zeroes to the coefficient.
707\end{classdesc*}
708
709
710\begin{classdesc*}{ConversionSyntax}
711 Trying to convert a mal-formed string such as: \code{Decimal('jump')}.
712
713 Decimal converts only strings conforming to the numeric string
714 syntax. If this signal is not trapped, returns \constant{NaN}.
715\end{classdesc*}
716
717
718\begin{classdesc*}{DecimalException}
719 Base class for other signals.
720\end{classdesc*}
721
722
723\begin{classdesc*}{DivisionByZero}
724 Signals the division of a non-infinite number by zero.
725
726 Can occur with division, modulo division, or when raising a number to
727 a negative power. If this signal is not trapped, return
728 \constant{Infinity} or \constant{-Infinity} with sign determined by
729 the inputs to the calculation.
730\end{classdesc*}
731
732
733\begin{classdesc*}{DivisionImpossible}
734 Error performing a division operation. Caused when an intermediate result
735 has more digits that the allowed by the current precision. If not trapped,
736 returns \constant{NaN}.
737\end{classdesc*}
738
739
740\begin{classdesc*}{DivisionUndefined}
741 This is a subclass of \class{DivisionByZero}.
742
743 It occurs only in the context of division operations.
744\end{classdesc*}
745
746
747\begin{classdesc*}{Inexact}
748 Indicates that rounding occurred and the result is not exact.
749
750 Signals whenever non-zero digits were discarded during rounding.
751 The rounded result is returned. The signal flag or trap is used
752 to detect when results are inexact.
753\end{classdesc*}
754
755
756\begin{classdesc*}{InvalidContext}
757 This is a subclass of \class{InvalidOperation}.
758
759 Indicates an error within the Context object such as an unknown
760 rounding operation. If not trapped, returns \constant{NaN}.
761\end{classdesc*}
762
763
764\begin{classdesc*}{InvalidOperation}
765 An invalid operation was performed.
766
767 Indicates that an operation was requested that does not make sense.
768 If not trapped, returns \constant{NaN}. Possible causes include:
769
770 \begin{verbatim}
771 Infinity - Infinity
772 0 * Infinity
773 Infinity / Infinity
774 x % 0
775 Infinity % x
776 x._rescale( non-integer )
777 sqrt(-x) and x > 0
778 0 ** 0
779 x ** (non-integer)
780 x ** Infinity
781 \end{verbatim}
782\end{classdesc*}
783
784
785\begin{classdesc*}{Overflow}
786 Numerical overflow.
787
788 Indicates the exponent is larger than \member{Emax} after rounding has
789 occurred. If not trapped, the result depends on the rounding mode, either
790 pulling inward to the largest representable finite number or rounding
791 outward to \constant{Infinity}. In either case, \class{Inexact} and
792 \class{Rounded} are also signaled.
793\end{classdesc*}
794
795
796\begin{classdesc*}{Rounded}
797 Rounding occurred though possibly not information was lost.
798
799 Signaled whenever rounding discards digits; even if those digits are
800 zero (such as rounding \constant{5.00} to \constant{5.0}). If not
801 trapped, returns the result unchanged. This signal is used to detect
802 loss of significant digits.
803\end{classdesc*}
804
805
806\begin{classdesc*}{Subnormal}
807 Exponent was lower than \member{Emin} prior to rounding.
808
809 Occurs when an operation result is subnormal (the exponent is too small).
810 If not trapped, returns the result unchanged.
811\end{classdesc*}
812
813
814\begin{classdesc*}{Underflow}
815 Numerical underflow with result rounded to zero.
816
817 Occurs when a subnormal result is pushed to zero by rounding.
818 \class{Inexact} and \class{Subnormal} are also signaled.
819\end{classdesc*}
820
821
822The following table summarizes the hierarchy of signals:
823
824\begin{verbatim}
825 exceptions.ArithmeticError(exceptions.StandardError)
826 DecimalException
827 Clamped
828 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
829 Inexact
830 Overflow(Inexact, Rounded)
831 Underflow(Inexact, Rounded, Subnormal)
832 InvalidOperation
833 ConversionSyntax
834 DivisionImpossible
835 DivisionUndefined(InvalidOperation, exceptions.ZeroDivisionError)
836 InvalidContext
837 Rounded
838 Subnormal
839\end{verbatim}
840
841%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
842\subsection{Working with threads \label{decimal-threads}}
843
844The \function{getcontext()} function accesses a different \class{Context}
845object for each thread. Having separate contexts means that threads may make
846changes (such as \code{getcontext.prec=10}) without interfering with other
847threads and without needing mutexes.
848
849Likewise, the \function{setcontext()} function automatically assigns its target
850to the current thread.
851
852If \function{setcontext()} has not been called before \function{getcontext()},
853then \function{getcontext()} will automatically create a new context for use
854in the current thread.
855
856The new context is copied from a prototype context called \var{DefaultContext}.
857To control the defaults so that each thread will use the same values
858throughout the application, directly modify the \var{DefaultContext} object.
859This should be done \emph{before} any threads are started so that there won't
860be a race condition with threads calling \function{getcontext()}. For example:
861
862\begin{verbatim}
863# Set application wide defaults for all threads about to be launched
864DefaultContext.prec=12
865DefaultContext.rounding=ROUND_DOWN
866DefaultContext.trap_enablers=dict.fromkeys(Signals, 0)
867setcontext(DefaultContext)
868
869# Now start all of the threads
870t1.start()
871t2.start()
872t3.start()
873 . . .
874\end{verbatim}
875
876
877
878
879
880
881
882