blob: 68748f6fe72d97d5ab0fc0a05a832ee9fdd205c7 [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 Hettingerd7c71152004-07-12 13:22:14 +000025End users typically would not expect \constant{1.1} to display as
Raymond Hettinger8de63a22004-07-05 05:52:03 +000026\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
Raymond Hettinger11666382005-09-11 18:21:52 +000035\item The decimal module incorporates a notion of significant places so that
Raymond Hettinger8de63a22004-07-05 05:52:03 +000036\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
Raymond Hettinger467024c2005-02-21 15:46:52 +000087encountered, its flag is 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 Hettinger467024c2005-02-21 15:46:52 +0000122Decimal instances can be constructed from integers, strings, or tuples. To
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000123create 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 Hettinger467024c2005-02-21 15:46:52 +0000163Decimals interact well with much of the rest of Python. Here is a small
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000164decimal 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
Raymond Hettinger92960232004-07-14 21:06:55 +0000182>>> round(a, 1) # round() first converts to binary floating point
Raymond Hettinger8de63a22004-07-05 05:52:03 +00001831.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)
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000220>>> setcontext(myothercontext)
221>>> Decimal(1) / Decimal(7)
222Decimal("0.142857142857142857142857142857142857142857142857142857142857")
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000223
224>>> ExtendedContext
225Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
226 capitals=1, flags=[], traps=[])
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000227>>> setcontext(ExtendedContext)
228>>> Decimal(1) / Decimal(7)
229Decimal("0.142857143")
230>>> Decimal(42) / Decimal(0)
231Decimal("Infinity")
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000232
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000233>>> setcontext(BasicContext)
234>>> Decimal(42) / Decimal(0)
235Traceback (most recent call last):
236 File "<pyshell#143>", line 1, in -toplevel-
237 Decimal(42) / Decimal(0)
238DivisionByZero: x / 0
239\end{verbatim}
240
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000241
242Contexts also have signal flags for monitoring exceptional conditions
243encountered during computations. The flags remain set until explicitly
244cleared, so it is best to clear the flags before each set of monitored
245computations by using the \method{clear_flags()} method.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000246
247\begin{verbatim}
248>>> setcontext(ExtendedContext)
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000249>>> getcontext().clear_flags()
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000250>>> Decimal(355) / Decimal(113)
251Decimal("3.14159292")
252>>> getcontext()
253Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
Raymond Hettingerbf440692004-07-10 14:14:37 +0000254 capitals=1, flags=[Inexact, Rounded], traps=[])
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000255\end{verbatim}
256
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000257The \var{flags} entry shows that the rational approximation to \constant{Pi}
258was rounded (digits beyond the context precision were thrown away) and that
259the result is inexact (some of the discarded digits were non-zero).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000260
Raymond Hettingerbf440692004-07-10 14:14:37 +0000261Individual traps are set using the dictionary in the \member{traps}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000262field of a context:
263
264\begin{verbatim}
265>>> Decimal(1) / Decimal(0)
266Decimal("Infinity")
Raymond Hettingerbf440692004-07-10 14:14:37 +0000267>>> getcontext().traps[DivisionByZero] = 1
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000268>>> Decimal(1) / Decimal(0)
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000269Traceback (most recent call last):
270 File "<pyshell#112>", line 1, in -toplevel-
271 Decimal(1) / Decimal(0)
272DivisionByZero: x / 0
273\end{verbatim}
274
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000275Most programs adjust the current context only once, at the beginning of the
276program. And, in many applications, data is converted to \class{Decimal} with
277a single cast inside a loop. With context set and decimals created, the bulk
278of the program manipulates the data no differently than with other Python
279numeric types.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000280
281
282
283%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
284\subsection{Decimal objects \label{decimal-decimal}}
285
286\begin{classdesc}{Decimal}{\optional{value \optional{, context}}}
287 Constructs a new \class{Decimal} object based from \var{value}.
288
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000289 \var{value} can be an integer, string, tuple, or another \class{Decimal}
290 object. If no \var{value} is given, returns \code{Decimal("0")}. If
291 \var{value} is a string, it should conform to the decimal numeric string
292 syntax:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000293
294 \begin{verbatim}
295 sign ::= '+' | '-'
296 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
297 indicator ::= 'e' | 'E'
298 digits ::= digit [digit]...
299 decimal-part ::= digits '.' [digits] | ['.'] digits
300 exponent-part ::= indicator [sign] digits
301 infinity ::= 'Infinity' | 'Inf'
302 nan ::= 'NaN' [digits] | 'sNaN' [digits]
303 numeric-value ::= decimal-part [exponent-part] | infinity
304 numeric-string ::= [sign] numeric-value | [sign] nan
305 \end{verbatim}
306
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000307 If \var{value} is a \class{tuple}, it should have three components,
308 a sign (\constant{0} for positive or \constant{1} for negative),
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000309 a \class{tuple} of digits, and an integer exponent. For example,
310 \samp{Decimal((0, (1, 4, 1, 4), -3))} returns \code{Decimal("1.414")}.
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000311
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000312 The \var{context} precision does not affect how many digits are stored.
313 That is determined exclusively by the number of digits in \var{value}. For
314 example, \samp{Decimal("3.00000")} records all five zeroes even if the
315 context precision is only three.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000316
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000317 The purpose of the \var{context} argument is determining what to do if
318 \var{value} is a malformed string. If the context traps
319 \constant{InvalidOperation}, an exception is raised; otherwise, the
320 constructor returns a new Decimal with the value of \constant{NaN}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000321
322 Once constructed, \class{Decimal} objects are immutable.
323\end{classdesc}
324
325Decimal floating point objects share many properties with the other builtin
326numeric types such as \class{float} and \class{int}. All of the usual
327math operations and special methods apply. Likewise, decimal objects can
328be copied, pickled, printed, used as dictionary keys, used as set elements,
329compared, sorted, and coerced to another type (such as \class{float}
330or \class{long}).
331
332In addition to the standard numeric properties, decimal floating point objects
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000333also have a number of specialized methods:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000334
335\begin{methoddesc}{adjusted}{}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000336 Return the adjusted exponent after shifting out the coefficient's rightmost
337 digits until only the lead digit remains: \code{Decimal("321e+5").adjusted()}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000338 returns seven. Used for determining the position of the most significant
339 digit with respect to the decimal point.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000340\end{methoddesc}
341
342\begin{methoddesc}{as_tuple}{}
343 Returns a tuple representation of the number:
344 \samp{(sign, digittuple, exponent)}.
345\end{methoddesc}
346
347\begin{methoddesc}{compare}{other\optional{, context}}
348 Compares like \method{__cmp__()} but returns a decimal instance:
349 \begin{verbatim}
350 a or b is a NaN ==> Decimal("NaN")
351 a < b ==> Decimal("-1")
352 a == b ==> Decimal("0")
353 a > b ==> Decimal("1")
354 \end{verbatim}
355\end{methoddesc}
356
357\begin{methoddesc}{max}{other\optional{, context}}
Facundo Batista44160942004-11-12 02:03:36 +0000358 Like \samp{max(self, other)} except that the context rounding rule
359 is applied before returning and that \constant{NaN} values are
360 either signalled or ignored (depending on the context and whether
361 they are signaling or quiet).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000362\end{methoddesc}
363
364\begin{methoddesc}{min}{other\optional{, context}}
Facundo Batista44160942004-11-12 02:03:36 +0000365 Like \samp{min(self, other)} except that the context rounding rule
366 is applied before returning and that \constant{NaN} values are
367 either signalled or ignored (depending on the context and whether
368 they are signaling or quiet).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000369\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
Raymond Hettinger8df4e6b2004-08-15 23:51:38 +0000377 \code{Decimal("32.1")}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000378\end{methoddesc}
379
380\begin{methoddesc}{quantize}
Facundo Batista139af022004-11-20 00:33:51 +0000381 {exp \optional{, rounding\optional{, context\optional{, watchexp}}}}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000382 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}{}
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000438 Return the current context for the active thread.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000439\end{funcdesc}
440
441\begin{funcdesc}{setcontext}{c}
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000442 Set the current context for the active thread to \var{c}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000443\end{funcdesc}
444
Phillip J. Eby168e99f2006-03-28 00:13:10 +0000445Beginning with Python 2.5, you can also use the \keyword{with} statement
Nick Coghlane7877d92006-09-02 04:04:18 +0000446and the \function{localcontext()} function to temporarily change the
447active context.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000448
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000449\begin{funcdesc}{localcontext}{\optional{c}}
450 Return a context manager that will set the current context for
451 the active thread to a copy of \var{c} on entry to the with statement
Nick Coghlane7877d92006-09-02 04:04:18 +0000452 and restore the previous context when exiting the with statement. If
453 no context is specified, a copy of the current context is used.
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000454
455 For example the following code increases the current decimal precision
Nick Coghlane7877d92006-09-02 04:04:18 +0000456 by 42 places, performs a calculation, and then automatically restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000457 the previous context:
Phillip J. Eby168e99f2006-03-28 00:13:10 +0000458\begin{verbatim}
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000459 from __future__ import with_statement
460 import decimal
Phillip J. Eby168e99f2006-03-28 00:13:10 +0000461
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000462 with decimal.localcontext() as ctx:
Nick Coghlane7877d92006-09-02 04:04:18 +0000463 ctx.prec = 42 # Perform a high precision calculation
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000464 s = calculate_something()
465 s = +s # Round the final result back to the default precision
Phillip J. Eby168e99f2006-03-28 00:13:10 +0000466\end{verbatim}
Nick Coghlane7877d92006-09-02 04:04:18 +0000467
468 The context that is held by the context manager and made active in the
469 body of the \keyword{with} statement is a \emph{copy} of the context
470 you provide to this function, so modifying its attributes doesn't
471 affect anything except that temporary copy.
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000472\end{funcdesc}
Phillip J. Eby168e99f2006-03-28 00:13:10 +0000473
Phillip J. Eby168e99f2006-03-28 00:13:10 +0000474New contexts can also be created using the \class{Context} constructor
475described below. In addition, the module provides three pre-made
476contexts:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000477
478\begin{classdesc*}{BasicContext}
479 This is a standard context defined by the General Decimal Arithmetic
480 Specification. Precision is set to nine. Rounding is set to
481 \constant{ROUND_HALF_UP}. All flags are cleared. All traps are enabled
482 (treated as exceptions) except \constant{Inexact}, \constant{Rounded}, and
483 \constant{Subnormal}.
484
485 Because many of the traps are enabled, this context is useful for debugging.
486\end{classdesc*}
487
488\begin{classdesc*}{ExtendedContext}
489 This is a standard context defined by the General Decimal Arithmetic
490 Specification. Precision is set to nine. Rounding is set to
491 \constant{ROUND_HALF_EVEN}. All flags are cleared. No traps are enabled
492 (so that exceptions are not raised during computations).
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000493
494 Because the trapped are disabled, this context is useful for applications
495 that prefer to have result value of \constant{NaN} or \constant{Infinity}
496 instead of raising exceptions. This allows an application to complete a
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000497 run in the presence of conditions that would otherwise halt the program.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000498\end{classdesc*}
499
500\begin{classdesc*}{DefaultContext}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000501 This context is used by the \class{Context} constructor as a prototype for
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000502 new contexts. Changing a field (such a precision) has the effect of
503 changing the default for new contexts creating by the \class{Context}
504 constructor.
505
506 This context is most useful in multi-threaded environments. Changing one of
507 the fields before threads are started has the effect of setting system-wide
508 defaults. Changing the fields after threads have started is not recommended
509 as it would require thread synchronization to prevent race conditions.
510
511 In single threaded environments, it is preferable to not use this context
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000512 at all. Instead, simply create contexts explicitly as described below.
513
514 The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled
515 traps for Overflow, InvalidOperation, and DivisionByZero.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000516\end{classdesc*}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000517
518
519In addition to the three supplied contexts, new contexts can be created
520with the \class{Context} constructor.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000521
Raymond Hettingerbf440692004-07-10 14:14:37 +0000522\begin{classdesc}{Context}{prec=None, rounding=None, traps=None,
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000523 flags=None, Emin=None, Emax=None, capitals=1}
524 Creates a new context. If a field is not specified or is \constant{None},
525 the default values are copied from the \constant{DefaultContext}. If the
526 \var{flags} field is not specified or is \constant{None}, all flags are
527 cleared.
528
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000529 The \var{prec} field is a positive integer that sets the precision for
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000530 arithmetic operations in the context.
531
Raymond Hettinger97c92082004-07-09 06:13:12 +0000532 The \var{rounding} option is one of:
Raymond Hettinger87de8ed2005-07-01 16:54:12 +0000533 \begin{itemize}
534 \item \constant{ROUND_CEILING} (towards \constant{Infinity}),
535 \item \constant{ROUND_DOWN} (towards zero),
536 \item \constant{ROUND_FLOOR} (towards \constant{-Infinity}),
537 \item \constant{ROUND_HALF_DOWN} (to nearest with ties going towards zero),
538 \item \constant{ROUND_HALF_EVEN} (to nearest with ties going to nearest even integer),
539 \item \constant{ROUND_HALF_UP} (to nearest with ties going away from zero), or
540 \item \constant{ROUND_UP} (away from zero).
541 \end{itemize}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000542
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000543 The \var{traps} and \var{flags} fields list any signals to be set.
544 Generally, new contexts should only set traps and leave the flags clear.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000545
546 The \var{Emin} and \var{Emax} fields are integers specifying the outer
547 limits allowable for exponents.
548
549 The \var{capitals} field is either \constant{0} or \constant{1} (the
550 default). If set to \constant{1}, exponents are printed with a capital
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000551 \constant{E}; otherwise, a lowercase \constant{e} is used:
552 \constant{Decimal('6.02e+23')}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000553\end{classdesc}
554
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000555The \class{Context} class defines several general purpose methods as well as a
556large number of methods for doing arithmetic directly in a given context.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000557
558\begin{methoddesc}{clear_flags}{}
Raymond Hettingerd391d102005-06-07 18:50:56 +0000559 Resets all of the flags to \constant{0}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000560\end{methoddesc}
561
562\begin{methoddesc}{copy}{}
Raymond Hettingerd391d102005-06-07 18:50:56 +0000563 Return a duplicate of the context.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000564\end{methoddesc}
565
566\begin{methoddesc}{create_decimal}{num}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000567 Creates a new Decimal instance from \var{num} but using \var{self} as
568 context. Unlike the \class{Decimal} constructor, the context precision,
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000569 rounding method, flags, and traps are applied to the conversion.
570
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000571 This is useful because constants are often given to a greater precision than
Raymond Hettingerd7c71152004-07-12 13:22:14 +0000572 is needed by the application. Another benefit is that rounding immediately
573 eliminates unintended effects from digits beyond the current precision.
574 In the following example, using unrounded inputs means that adding zero
575 to a sum can change the result:
576
577 \begin{verbatim}
578 >>> getcontext().prec = 3
579 >>> Decimal("3.4445") + Decimal("1.0023")
580 Decimal("4.45")
581 >>> Decimal("3.4445") + Decimal(0) + Decimal("1.0023")
582 Decimal("4.44")
583 \end{verbatim}
584
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000585\end{methoddesc}
586
587\begin{methoddesc}{Etiny}{}
588 Returns a value equal to \samp{Emin - prec + 1} which is the minimum
589 exponent value for subnormal results. When underflow occurs, the
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000590 exponent is set to \constant{Etiny}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000591\end{methoddesc}
592
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000593\begin{methoddesc}{Etop}{}
594 Returns a value equal to \samp{Emax - prec + 1}.
595\end{methoddesc}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000596
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000597
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000598The usual approach to working with decimals is to create \class{Decimal}
599instances and then apply arithmetic operations which take place within the
600current context for the active thread. An alternate approach is to use
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000601context methods for calculating within a specific context. The methods are
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000602similar to those for the \class{Decimal} class and are only briefly recounted
603here.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000604
605\begin{methoddesc}{abs}{x}
606 Returns the absolute value of \var{x}.
607\end{methoddesc}
608
609\begin{methoddesc}{add}{x, y}
610 Return the sum of \var{x} and \var{y}.
611\end{methoddesc}
612
613\begin{methoddesc}{compare}{x, y}
614 Compares values numerically.
615
616 Like \method{__cmp__()} but returns a decimal instance:
617 \begin{verbatim}
618 a or b is a NaN ==> Decimal("NaN")
619 a < b ==> Decimal("-1")
620 a == b ==> Decimal("0")
621 a > b ==> Decimal("1")
622 \end{verbatim}
623\end{methoddesc}
624
625\begin{methoddesc}{divide}{x, y}
626 Return \var{x} divided by \var{y}.
627\end{methoddesc}
628
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000629\begin{methoddesc}{divmod}{x, y}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000630 Divides two numbers and returns the integer part of the result.
631\end{methoddesc}
632
633\begin{methoddesc}{max}{x, y}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000634 Compare two values numerically and return the maximum.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000635
636 If they are numerically equal then the left-hand operand is chosen as the
637 result.
638\end{methoddesc}
639
640\begin{methoddesc}{min}{x, y}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000641 Compare two values numerically and return the minimum.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000642
643 If they are numerically equal then the left-hand operand is chosen as the
644 result.
645\end{methoddesc}
646
647\begin{methoddesc}{minus}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000648 Minus corresponds to the unary prefix minus operator in Python.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000649\end{methoddesc}
650
651\begin{methoddesc}{multiply}{x, y}
652 Return the product of \var{x} and \var{y}.
653\end{methoddesc}
654
655\begin{methoddesc}{normalize}{x}
656 Normalize reduces an operand to its simplest form.
657
Raymond Hettingerd7c71152004-07-12 13:22:14 +0000658 Essentially a \method{plus} operation with all trailing zeros removed from
659 the result.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000660\end{methoddesc}
661
662\begin{methoddesc}{plus}{x}
Raymond Hettingerd7c71152004-07-12 13:22:14 +0000663 Plus corresponds to the unary prefix plus operator in Python. This
664 operation applies the context precision and rounding, so it is
665 \emph{not} an identity operation.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000666\end{methoddesc}
667
668\begin{methoddesc}{power}{x, y\optional{, modulo}}
669 Return \samp{x ** y} to the \var{modulo} if given.
670
671 The right-hand operand must be a whole number whose integer part (after any
672 exponent has been applied) has no more than 9 digits and whose fractional
673 part (if any) is all zeros before any rounding. The operand may be positive,
674 negative, or zero; if negative, the absolute value of the power is used, and
675 the left-hand operand is inverted (divided into 1) before use.
676
677 If the increased precision needed for the intermediate calculations exceeds
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000678 the capabilities of the implementation then an \constant{InvalidOperation}
679 condition is signaled.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000680
681 If, when raising to a negative power, an underflow occurs during the
682 division into 1, the operation is not halted at that point but continues.
683\end{methoddesc}
684
685\begin{methoddesc}{quantize}{x, y}
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000686 Returns a value equal to \var{x} after rounding and having the exponent of
687 \var{y}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000688
689 Unlike other operations, if the length of the coefficient after the quantize
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000690 operation would be greater than precision, then an
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000691 \constant{InvalidOperation} is signaled. This guarantees that, unless there
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000692 is an error condition, the quantized exponent is always equal to that of the
693 right-hand operand.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000694
695 Also unlike other operations, quantize never signals Underflow, even
696 if the result is subnormal and inexact.
697\end{methoddesc}
698
699\begin{methoddesc}{remainder}{x, y}
700 Returns the remainder from integer division.
701
702 The sign of the result, if non-zero, is the same as that of the original
703 dividend.
704\end{methoddesc}
705
706\begin{methoddesc}{remainder_near}{x, y}
707 Computed the modulo as either a positive or negative value depending
708 on which is closest to zero. For instance,
709 \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")}
710 which is closer to zero than \code{Decimal("4")}.
711
712 If both are equally close, the one chosen will have the same sign
713 as \var{self}.
714\end{methoddesc}
715
716\begin{methoddesc}{same_quantum}{x, y}
717 Test whether \var{x} and \var{y} have the same exponent or whether both are
718 \constant{NaN}.
719\end{methoddesc}
720
Georg Brandldd0c3122006-05-10 20:09:23 +0000721\begin{methoddesc}{sqrt}{x}
722 Return the square root of \var{x} to full precision.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000723\end{methoddesc}
724
Georg Brandlf33d01d2005-08-22 19:35:18 +0000725\begin{methoddesc}{subtract}{x, y}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000726 Return the difference between \var{x} and \var{y}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000727\end{methoddesc}
728
729\begin{methoddesc}{to_eng_string}{}
730 Convert to engineering-type string.
731
732 Engineering notation has an exponent which is a multiple of 3, so there
733 are up to 3 digits left of the decimal place. For example, converts
734 \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")}
735\end{methoddesc}
736
737\begin{methoddesc}{to_integral}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000738 Rounds to the nearest integer without signaling \constant{Inexact}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000739 or \constant{Rounded}.
740\end{methoddesc}
741
Georg Brandldd0c3122006-05-10 20:09:23 +0000742\begin{methoddesc}{to_sci_string}{x}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000743 Converts a number to a string using scientific notation.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000744\end{methoddesc}
745
746
747
748%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
749\subsection{Signals \label{decimal-signals}}
750
751Signals represent conditions that arise during computation.
752Each corresponds to one context flag and one context trap enabler.
753
754The context flag is incremented whenever the condition is encountered.
755After the computation, flags may be checked for informational
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000756purposes (for instance, to determine whether a computation was exact).
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000757After checking the flags, be sure to clear all flags before starting
758the next computation.
759
760If the context's trap enabler is set for the signal, then the condition
761causes a Python exception to be raised. For example, if the
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000762\class{DivisionByZero} trap is set, then a \exception{DivisionByZero}
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000763exception is raised upon encountering the condition.
764
765
766\begin{classdesc*}{Clamped}
767 Altered an exponent to fit representation constraints.
768
769 Typically, clamping occurs when an exponent falls outside the context's
770 \member{Emin} and \member{Emax} limits. If possible, the exponent is
771 reduced to fit by adding zeroes to the coefficient.
772\end{classdesc*}
773
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000774\begin{classdesc*}{DecimalException}
Raymond Hettinger467024c2005-02-21 15:46:52 +0000775 Base class for other signals and a subclass of
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000776 \exception{ArithmeticError}.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000777\end{classdesc*}
778
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000779\begin{classdesc*}{DivisionByZero}
780 Signals the division of a non-infinite number by zero.
781
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000782 Can occur with division, modulo division, or when raising a number to a
783 negative power. If this signal is not trapped, returns
784 \constant{Infinity} or \constant{-Infinity} with the sign determined by
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000785 the inputs to the calculation.
786\end{classdesc*}
787
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000788\begin{classdesc*}{Inexact}
789 Indicates that rounding occurred and the result is not exact.
790
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000791 Signals when non-zero digits were discarded during rounding. The rounded
792 result is returned. The signal flag or trap is used to detect when
793 results are inexact.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000794\end{classdesc*}
795
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000796\begin{classdesc*}{InvalidOperation}
797 An invalid operation was performed.
798
799 Indicates that an operation was requested that does not make sense.
800 If not trapped, returns \constant{NaN}. Possible causes include:
801
802 \begin{verbatim}
803 Infinity - Infinity
804 0 * Infinity
805 Infinity / Infinity
806 x % 0
807 Infinity % x
808 x._rescale( non-integer )
809 sqrt(-x) and x > 0
810 0 ** 0
811 x ** (non-integer)
812 x ** Infinity
813 \end{verbatim}
814\end{classdesc*}
815
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000816\begin{classdesc*}{Overflow}
817 Numerical overflow.
818
819 Indicates the exponent is larger than \member{Emax} after rounding has
820 occurred. If not trapped, the result depends on the rounding mode, either
821 pulling inward to the largest representable finite number or rounding
822 outward to \constant{Infinity}. In either case, \class{Inexact} and
823 \class{Rounded} are also signaled.
824\end{classdesc*}
825
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000826\begin{classdesc*}{Rounded}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000827 Rounding occurred though possibly no information was lost.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000828
829 Signaled whenever rounding discards digits; even if those digits are
830 zero (such as rounding \constant{5.00} to \constant{5.0}). If not
831 trapped, returns the result unchanged. This signal is used to detect
832 loss of significant digits.
833\end{classdesc*}
834
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000835\begin{classdesc*}{Subnormal}
836 Exponent was lower than \member{Emin} prior to rounding.
837
838 Occurs when an operation result is subnormal (the exponent is too small).
839 If not trapped, returns the result unchanged.
840\end{classdesc*}
841
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000842\begin{classdesc*}{Underflow}
843 Numerical underflow with result rounded to zero.
844
845 Occurs when a subnormal result is pushed to zero by rounding.
846 \class{Inexact} and \class{Subnormal} are also signaled.
847\end{classdesc*}
848
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000849The following table summarizes the hierarchy of signals:
850
851\begin{verbatim}
852 exceptions.ArithmeticError(exceptions.StandardError)
853 DecimalException
854 Clamped
855 DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
856 Inexact
857 Overflow(Inexact, Rounded)
858 Underflow(Inexact, Rounded, Subnormal)
859 InvalidOperation
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000860 Rounded
861 Subnormal
862\end{verbatim}
863
Raymond Hettingerd84efb32004-07-05 18:41:42 +0000864
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000865%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Raymond Hettinger2864b802004-08-15 23:47:48 +0000866\subsection{Floating Point Notes \label{decimal-notes}}
867
Raymond Hettinger87de8ed2005-07-01 16:54:12 +0000868\subsubsection{Mitigating round-off error with increased precision}
869
Raymond Hettinger2864b802004-08-15 23:47:48 +0000870The use of decimal floating point eliminates decimal representation error
871(making it possible to represent \constant{0.1} exactly); however, some
872operations can still incur round-off error when non-zero digits exceed the
873fixed precision.
874
875The effects of round-off error can be amplified by the addition or subtraction
876of nearly offsetting quantities resulting in loss of significance. Knuth
877provides two instructive examples where rounded floating point arithmetic with
Raymond Hettingerf4fd79c2004-08-26 03:11:56 +0000878insufficient precision causes the breakdown of the associative and
Raymond Hettinger2864b802004-08-15 23:47:48 +0000879distributive properties of addition:
880
881\begin{verbatim}
882# Examples from Seminumerical Algorithms, Section 4.2.2.
Raymond Hettinger467024c2005-02-21 15:46:52 +0000883>>> from decimal import Decimal, getcontext
Raymond Hettinger2864b802004-08-15 23:47:48 +0000884>>> getcontext().prec = 8
885
886>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
887>>> (u + v) + w
888Decimal("9.5111111")
889>>> u + (v + w)
890Decimal("10")
891
892>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
893>>> (u*v) + (u*w)
894Decimal("0.01")
895>>> u * (v+w)
896Decimal("0.0060000")
897\end{verbatim}
898
899The \module{decimal} module makes it possible to restore the identities
900by expanding the precision sufficiently to avoid loss of significance:
901
902\begin{verbatim}
903>>> getcontext().prec = 20
904>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
905>>> (u + v) + w
906Decimal("9.51111111")
907>>> u + (v + w)
908Decimal("9.51111111")
909>>>
910>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
911>>> (u*v) + (u*w)
912Decimal("0.0060000")
913>>> u * (v+w)
914Decimal("0.0060000")
915\end{verbatim}
916
Raymond Hettinger87de8ed2005-07-01 16:54:12 +0000917\subsubsection{Special values}
Raymond Hettinger2864b802004-08-15 23:47:48 +0000918
919The number system for the \module{decimal} module provides special
920values including \constant{NaN}, \constant{sNaN}, \constant{-Infinity},
921\constant{Infinity}, and two zeroes, \constant{+0} and \constant{-0}.
922
Andrew M. Kuchling7ec75842004-08-16 16:12:23 +0000923Infinities can be constructed directly with: \code{Decimal('Infinity')}. Also,
Raymond Hettinger2864b802004-08-15 23:47:48 +0000924they can arise from dividing by zero when the \exception{DivisionByZero}
925signal is not trapped. Likewise, when the \exception{Overflow} signal is not
926trapped, infinity can result from rounding beyond the limits of the largest
927representable number.
928
929The infinities are signed (affine) and can be used in arithmetic operations
930where they get treated as very large, indeterminate numbers. For instance,
931adding a constant to infinity gives another infinite result.
932
Raymond Hettingerf4fd79c2004-08-26 03:11:56 +0000933Some operations are indeterminate and return \constant{NaN}, or if the
Raymond Hettinger2864b802004-08-15 23:47:48 +0000934\exception{InvalidOperation} signal is trapped, raise an exception. For
935example, \code{0/0} returns \constant{NaN} which means ``not a number''. This
936variety of \constant{NaN} is quiet and, once created, will flow through other
937computations always resulting in another \constant{NaN}. This behavior can be
938useful for a series of computations that occasionally have missing inputs ---
939it allows the calculation to proceed while flagging specific results as
940invalid.
941
942A variant is \constant{sNaN} which signals rather than remaining quiet
943after every operation. This is a useful return value when an invalid
944result needs to interrupt a calculation for special handling.
945
946The signed zeros can result from calculations that underflow.
947They keep the sign that would have resulted if the calculation had
948been carried out to greater precision. Since their magnitude is
Raymond Hettingerf4fd79c2004-08-26 03:11:56 +0000949zero, both positive and negative zeros are treated as equal and their
Raymond Hettinger2864b802004-08-15 23:47:48 +0000950sign is informational.
951
Raymond Hettingerf4fd79c2004-08-26 03:11:56 +0000952In addition to the two signed zeros which are distinct yet equal,
953there are various representations of zero with differing precisions
Raymond Hettinger2864b802004-08-15 23:47:48 +0000954yet equivalent in value. This takes a bit of getting used to. For
955an eye accustomed to normalized floating point representations, it
956is not immediately obvious that the following calculation returns
957a value equal to zero:
958
959\begin{verbatim}
960>>> 1 / Decimal('Infinity')
961Decimal("0E-1000000026")
962\end{verbatim}
963
964%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000965\subsection{Working with threads \label{decimal-threads}}
966
967The \function{getcontext()} function accesses a different \class{Context}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000968object for each thread. Having separate thread contexts means that threads
969may make changes (such as \code{getcontext.prec=10}) without interfering with
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000970other threads.
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000971
972Likewise, the \function{setcontext()} function automatically assigns its target
973to the current thread.
974
975If \function{setcontext()} has not been called before \function{getcontext()},
976then \function{getcontext()} will automatically create a new context for use
977in the current thread.
978
Raymond Hettinger65df07b2004-07-11 12:40:19 +0000979The new context is copied from a prototype context called
980\var{DefaultContext}. To control the defaults so that each thread will use the
981same values throughout the application, directly modify the
982\var{DefaultContext} object. This should be done \emph{before} any threads are
983started so that there won't be a race condition between threads calling
984\function{getcontext()}. For example:
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000985
986\begin{verbatim}
Raymond Hettinger536f76b2004-07-08 09:22:33 +0000987# Set applicationwide defaults for all threads about to be launched
Raymond Hettinger92960232004-07-14 21:06:55 +0000988DefaultContext.prec = 12
989DefaultContext.rounding = ROUND_DOWN
990DefaultContext.traps = ExtendedContext.traps.copy()
991DefaultContext.traps[InvalidOperation] = 1
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000992setcontext(DefaultContext)
993
Raymond Hettinger92960232004-07-14 21:06:55 +0000994# Afterwards, the threads can be started
Raymond Hettinger8de63a22004-07-05 05:52:03 +0000995t1.start()
996t2.start()
997t3.start()
998 . . .
999\end{verbatim}
Raymond Hettinger2864b802004-08-15 23:47:48 +00001000
Raymond Hettinger8de63a22004-07-05 05:52:03 +00001001
1002
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001003%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1004\subsection{Recipes \label{decimal-recipes}}
Raymond Hettinger8de63a22004-07-05 05:52:03 +00001005
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001006Here are a few recipes that serve as utility functions and that demonstrate
1007ways to work with the \class{Decimal} class:
Raymond Hettinger8de63a22004-07-05 05:52:03 +00001008
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001009\begin{verbatim}
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001010def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1011 pos='', neg='-', trailneg=''):
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001012 """Convert Decimal to a money formatted string.
Raymond Hettinger8de63a22004-07-05 05:52:03 +00001013
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001014 places: required number of places after the decimal point
1015 curr: optional currency symbol before the sign (may be blank)
Raymond Hettinger3de9aa42004-11-25 04:47:09 +00001016 sep: optional grouping separator (comma, period, space, or blank)
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001017 dp: decimal point indicator (comma or period)
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001018 only specify as blank when places is zero
Raymond Hettinger3de9aa42004-11-25 04:47:09 +00001019 pos: optional sign for positive numbers: '+', space or blank
1020 neg: optional sign for negative numbers: '-', '(', space or blank
1021 trailneg:optional trailing minus indicator: '-', ')', space or blank
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001022
1023 >>> d = Decimal('-1234567.8901')
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001024 >>> moneyfmt(d, curr='$')
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001025 '-$1,234,567.89'
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001026 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1027 '1.234.568-'
1028 >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001029 '($1,234,567.89)'
Raymond Hettinger3de9aa42004-11-25 04:47:09 +00001030 >>> moneyfmt(Decimal(123456789), sep=' ')
1031 '123 456 789.00'
1032 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1033 '<.02>'
1034
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001035 """
1036 q = Decimal((0, (1,), -places)) # 2 places --> '0.01'
1037 sign, digits, exp = value.quantize(q).as_tuple()
Raymond Hettinger3de9aa42004-11-25 04:47:09 +00001038 assert exp == -places
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001039 result = []
1040 digits = map(str, digits)
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001041 build, next = result.append, digits.pop
1042 if sign:
1043 build(trailneg)
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001044 for i in range(places):
Raymond Hettinger3de9aa42004-11-25 04:47:09 +00001045 if digits:
1046 build(next())
1047 else:
1048 build('0')
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001049 build(dp)
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001050 i = 0
1051 while digits:
1052 build(next())
1053 i += 1
Raymond Hettinger8f2c4ee2004-11-24 05:53:26 +00001054 if i == 3 and digits:
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001055 i = 0
1056 build(sep)
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001057 build(curr)
1058 if sign:
1059 build(neg)
1060 else:
1061 build(pos)
1062 result.reverse()
1063 return ''.join(result)
1064
1065def pi():
Raymond Hettingerc4f93d442004-07-05 20:17:13 +00001066 """Compute Pi to the current precision.
1067
1068 >>> print pi()
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001069 3.141592653589793238462643383
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001070
Raymond Hettingerc4f93d442004-07-05 20:17:13 +00001071 """
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001072 getcontext().prec += 2 # extra digits for intermediate steps
Raymond Hettinger10959b12004-07-05 21:13:28 +00001073 three = Decimal(3) # substitute "three=3.0" for regular floats
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001074 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1075 while s != lasts:
1076 lasts = s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001077 n, na = n+na, na+8
1078 d, da = d+da, da+32
1079 t = (t * n) / d
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001080 s += t
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001081 getcontext().prec -= 2
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001082 return +s # unary plus applies the new precision
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001083
1084def exp(x):
Raymond Hettinger10959b12004-07-05 21:13:28 +00001085 """Return e raised to the power of x. Result type matches input type.
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001086
1087 >>> print exp(Decimal(1))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001088 2.718281828459045235360287471
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001089 >>> print exp(Decimal(2))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001090 7.389056098930650227230427461
Raymond Hettinger10959b12004-07-05 21:13:28 +00001091 >>> print exp(2.0)
1092 7.38905609893
1093 >>> print exp(2+0j)
1094 (7.38905609893+0j)
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001095
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001096 """
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001097 getcontext().prec += 2
1098 i, lasts, s, fact, num = 0, 0, 1, 1, 1
1099 while s != lasts:
1100 lasts = s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001101 i += 1
1102 fact *= i
1103 num *= x
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001104 s += num / fact
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001105 getcontext().prec -= 2
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001106 return +s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001107
1108def cos(x):
1109 """Return the cosine of x as measured in radians.
1110
1111 >>> print cos(Decimal('0.5'))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001112 0.8775825618903727161162815826
Raymond Hettinger10959b12004-07-05 21:13:28 +00001113 >>> print cos(0.5)
1114 0.87758256189
1115 >>> print cos(0.5+0j)
1116 (0.87758256189+0j)
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001117
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001118 """
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001119 getcontext().prec += 2
1120 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1121 while s != lasts:
1122 lasts = s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001123 i += 2
1124 fact *= i * (i-1)
1125 num *= x * x
1126 sign *= -1
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001127 s += num / fact * sign
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001128 getcontext().prec -= 2
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001129 return +s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001130
1131def sin(x):
Raymond Hettinger4fd38b32004-11-25 05:35:32 +00001132 """Return the sine of x as measured in radians.
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001133
1134 >>> print sin(Decimal('0.5'))
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001135 0.4794255386042030002732879352
Raymond Hettinger10959b12004-07-05 21:13:28 +00001136 >>> print sin(0.5)
1137 0.479425538604
1138 >>> print sin(0.5+0j)
1139 (0.479425538604+0j)
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001140
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001141 """
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001142 getcontext().prec += 2
1143 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1144 while s != lasts:
1145 lasts = s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001146 i += 2
1147 fact *= i * (i-1)
1148 num *= x * x
1149 sign *= -1
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001150 s += num / fact * sign
Raymond Hettinger2f55eb42004-07-06 01:55:14 +00001151 getcontext().prec -= 2
Raymond Hettinger65df07b2004-07-11 12:40:19 +00001152 return +s
Raymond Hettingerd84efb32004-07-05 18:41:42 +00001153
1154\end{verbatim}
Raymond Hettingerd391d102005-06-07 18:50:56 +00001155
1156
1157
Raymond Hettingered65c3a2005-06-15 16:53:31 +00001158%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Raymond Hettingerd391d102005-06-07 18:50:56 +00001159\subsection{Decimal FAQ \label{decimal-faq}}
1160
Raymond Hettingerd391d102005-06-07 18:50:56 +00001161Q. It is cumbersome to type \code{decimal.Decimal('1234.5')}. Is there a way
1162to minimize typing when using the interactive interpreter?
1163
1164A. Some users abbreviate the constructor to just a single letter:
1165
1166\begin{verbatim}
1167>>> D = decimal.Decimal
1168>>> D('1.23') + D('3.45')
1169Decimal("4.68")
1170\end{verbatim}
1171
1172
Raymond Hettinger11666382005-09-11 18:21:52 +00001173Q. In a fixed-point application with two decimal places, some inputs
Raymond Hettingerd391d102005-06-07 18:50:56 +00001174have many places and need to be rounded. Others are not supposed to have
1175excess digits and need to be validated. What methods should be used?
1176
1177A. The \method{quantize()} method rounds to a fixed number of decimal places.
1178If the \constant{Inexact} trap is set, it is also useful for validation:
1179
1180\begin{verbatim}
1181>>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
1182
1183>>> # Round to two places
1184>>> Decimal("3.214").quantize(TWOPLACES)
1185Decimal("3.21")
1186
1187>>> # Validate that a number does not exceed two places
1188>>> Decimal("3.21").quantize(TWOPLACES, context=Context(traps=[Inexact]))
1189Decimal("3.21")
1190
1191>>> Decimal("3.214").quantize(TWOPLACES, context=Context(traps=[Inexact]))
1192Traceback (most recent call last):
1193 ...
1194Inexact: Changed in rounding
1195\end{verbatim}
1196
1197
1198Q. Once I have valid two place inputs, how do I maintain that invariant
1199throughout an application?
1200
1201A. Some operations like addition and subtraction automatically preserve fixed
1202point. Others, like multiplication and division, change the number of decimal
1203places and need to be followed-up with a \method{quantize()} step.
1204
1205
Raymond Hettingered65c3a2005-06-15 16:53:31 +00001206Q. There are many ways to express the same value. The numbers
Raymond Hettingerd391d102005-06-07 18:50:56 +00001207\constant{200}, \constant{200.000}, \constant{2E2}, and \constant{.02E+4} all
1208have the same value at various precisions. Is there a way to transform them to
1209a single recognizable canonical value?
1210
1211A. The \method{normalize()} method maps all equivalent values to a single
Georg Brandlcaa94bd2006-01-23 22:00:17 +00001212representative:
Raymond Hettingerd391d102005-06-07 18:50:56 +00001213
1214\begin{verbatim}
1215>>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1216>>> [v.normalize() for v in values]
1217[Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2")]
1218\end{verbatim}
1219
1220
Raymond Hettinger11666382005-09-11 18:21:52 +00001221Q. Some decimal values always print with exponential notation. Is there
1222a way to get a non-exponential representation?
1223
1224A. For some values, exponential notation is the only way to express
1225the number of significant places in the coefficient. For example,
1226expressing \constant{5.0E+3} as \constant{5000} keeps the value
1227constant but cannot show the original's two-place significance.
1228
1229
Raymond Hettingerd391d102005-06-07 18:50:56 +00001230Q. Is there a way to convert a regular float to a \class{Decimal}?
1231
1232A. Yes, all binary floating point numbers can be exactly expressed as a
1233Decimal. An exact conversion may take more precision than intuition would
1234suggest, so trapping \constant{Inexact} will signal a need for more precision:
1235
1236\begin{verbatim}
1237def floatToDecimal(f):
1238 "Convert a floating point number to a Decimal with no loss of information"
1239 # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an
1240 # exponent. Double the mantissa until it is an integer. Use the integer
1241 # mantissa and exponent to compute an equivalent Decimal. If this cannot
1242 # be done exactly, then retry with more precision.
1243
1244 mantissa, exponent = math.frexp(f)
1245 while mantissa != int(mantissa):
1246 mantissa *= 2.0
1247 exponent -= 1
1248 mantissa = int(mantissa)
Raymond Hettingered65c3a2005-06-15 16:53:31 +00001249
Raymond Hettingerd391d102005-06-07 18:50:56 +00001250 oldcontext = getcontext()
1251 setcontext(Context(traps=[Inexact]))
1252 try:
1253 while True:
1254 try:
1255 return mantissa * Decimal(2) ** exponent
1256 except Inexact:
1257 getcontext().prec += 1
1258 finally:
1259 setcontext(oldcontext)
1260\end{verbatim}
1261
1262
1263Q. Why isn't the \function{floatToDecimal()} routine included in the module?
1264
1265A. There is some question about whether it is advisable to mix binary and
1266decimal floating point. Also, its use requires some care to avoid the
1267representation issues associated with binary floating point:
1268
1269\begin{verbatim}
1270>>> floatToDecimal(1.1)
1271Decimal("1.100000000000000088817841970012523233890533447265625")
1272\end{verbatim}
1273
1274
1275Q. Within a complex calculation, how can I make sure that I haven't gotten a
1276spurious result because of insufficient precision or rounding anomalies.
1277
1278A. The decimal module makes it easy to test results. A best practice is to
1279re-run calculations using greater precision and with various rounding modes.
1280Widely differing results indicate insufficient precision, rounding mode
1281issues, ill-conditioned inputs, or a numerically unstable algorithm.
1282
1283
1284Q. I noticed that context precision is applied to the results of operations
1285but not to the inputs. Is there anything to watch out for when mixing
1286values of different precisions?
1287
1288A. Yes. The principle is that all values are considered to be exact and so
1289is the arithmetic on those values. Only the results are rounded. The
1290advantage for inputs is that ``what you type is what you get''. A
1291disadvantage is that the results can look odd if you forget that the inputs
1292haven't been rounded:
1293
1294\begin{verbatim}
1295>>> getcontext().prec = 3
1296>>> Decimal('3.104') + D('2.104')
1297Decimal("5.21")
1298>>> Decimal('3.104') + D('0.000') + D('2.104')
1299Decimal("5.20")
1300\end{verbatim}
1301
1302The solution is either to increase precision or to force rounding of inputs
1303using the unary plus operation:
1304
1305\begin{verbatim}
1306>>> getcontext().prec = 3
1307>>> +Decimal('1.23456789') # unary plus triggers rounding
1308Decimal("1.23")
1309\end{verbatim}
1310
1311Alternatively, inputs can be rounded upon creation using the
1312\method{Context.create_decimal()} method:
1313
1314\begin{verbatim}
1315>>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
1316Decimal("1.2345")
1317\end{verbatim}