Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 1 | \section{\module{decimal} --- |
| 2 | Decimal floating point arithmetic} |
| 3 | |
| 4 | \declaremodule{standard}{decimal} |
| 5 | \modulesynopsis{Implementation of the General Decimal Arithmetic |
| 6 | Specification.} |
| 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 Hettinger | 97c9208 | 2004-07-09 06:13:12 +0000 | [diff] [blame] | 18 | The \module{decimal} module provides support for decimal floating point |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 19 | arithmetic. 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 Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 24 | \constant{1.1} do not have an exact representation in binary floating point. |
Raymond Hettinger | d7c7115 | 2004-07-12 13:22:14 +0000 | [diff] [blame] | 25 | End users typically would not expect \constant{1.1} to display as |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 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 |
| 30 | point, result is \constant{5.5511151231257827e-017}. While near to zero, the |
| 31 | differences prevent reliable equality testing and differences can accumulate. |
| 32 | For this reason, decimal would be preferred in accounting applications which |
| 33 | have strict equality invariants. |
| 34 | |
Raymond Hettinger | 1166638 | 2005-09-11 18:21:52 +0000 | [diff] [blame] | 35 | \item The decimal module incorporates a notion of significant places so that |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 36 | \samp{1.30 + 1.20} is \constant{2.50}. The trailing zero is kept to indicate |
| 37 | significance. This is the customary presentation for monetary applications. For |
| 38 | multiplication, the ``schoolbook'' approach uses all the figures in the |
| 39 | multiplicands. 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 |
| 43 | settable precision (defaulting to 28 places) which can be as large as needed for |
| 44 | a given problem: |
| 45 | |
| 46 | \begin{verbatim} |
| 47 | >>> getcontext().prec = 6 |
| 48 | >>> Decimal(1) / Decimal(7) |
| 49 | Decimal("0.142857") |
| 50 | >>> getcontext().prec = 28 |
| 51 | >>> Decimal(1) / Decimal(7) |
| 52 | Decimal("0.1428571428571428571428571429") |
| 53 | \end{verbatim} |
| 54 | |
| 55 | \item Both binary and decimal floating point are implemented in terms of published |
| 56 | standards. While the built-in float type exposes only a modest portion of its |
| 57 | capabilities, the decimal module exposes all required parts of the standard. |
| 58 | When needed, the programmer has full control over rounding and signal handling. |
| 59 | |
| 60 | \end{itemize} |
| 61 | |
| 62 | |
| 63 | The module design is centered around three concepts: the decimal number, the |
| 64 | context for arithmetic, and signals. |
| 65 | |
| 66 | A decimal number is immutable. It has a sign, coefficient digits, and an |
| 67 | exponent. To preserve significance, the coefficient digits do not truncate |
| 68 | trailing zeroes. Decimals also include special values such as |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 69 | \constant{Infinity}, \constant{-Infinity}, and \constant{NaN}. The standard |
| 70 | also differentiates \constant{-0} from \constant{+0}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 71 | |
| 72 | The context for arithmetic is an environment specifying precision, rounding |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 73 | rules, limits on exponents, flags indicating the results of operations, |
| 74 | and trap enablers which determine whether signals are treated as |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 75 | exceptions. 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 Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 79 | Signals are groups of exceptional conditions arising during the course of |
| 80 | computation. Depending on the needs of the application, signals may be |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 81 | ignored, considered as informational, or treated as exceptions. The signals in |
| 82 | the decimal module are: \constant{Clamped}, \constant{InvalidOperation}, |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 83 | \constant{DivisionByZero}, \constant{Inexact}, \constant{Rounded}, |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 84 | \constant{Subnormal}, \constant{Overflow}, and \constant{Underflow}. |
| 85 | |
| 86 | For each signal there is a flag and a trap enabler. When a signal is |
Raymond Hettinger | 467024c | 2005-02-21 15:46:52 +0000 | [diff] [blame] | 87 | encountered, its flag is incremented from zero and, then, if the trap enabler |
Raymond Hettinger | 97c9208 | 2004-07-09 06:13:12 +0000 | [diff] [blame] | 88 | is set to one, an exception is raised. Flags are sticky, so the user |
| 89 | needs to reset them before monitoring a calculation. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 90 | |
| 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 Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 98 | \citetitle[http://www.cs.berkeley.edu/\textasciitilde ejr/projects/754/private/drafts/854-1987/dir.html] |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 99 | {Unofficial IEEE 854 Text}.} |
| 100 | \end{seealso} |
| 101 | |
| 102 | |
| 103 | |
| 104 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 105 | \subsection{Quick-start Tutorial \label{decimal-tutorial}} |
| 106 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 107 | The usual start to using decimals is importing the module, viewing the current |
| 108 | context with \function{getcontext()} and, if necessary, setting new values |
| 109 | for precision, rounding, or enabled traps: |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 110 | |
| 111 | \begin{verbatim} |
| 112 | >>> from decimal import * |
| 113 | >>> getcontext() |
| 114 | Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 115 | capitals=1, flags=[], traps=[Overflow, InvalidOperation, |
| 116 | DivisionByZero]) |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 117 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 118 | >>> getcontext().prec = 7 # Set a new precision |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 119 | \end{verbatim} |
| 120 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 121 | |
Raymond Hettinger | 467024c | 2005-02-21 15:46:52 +0000 | [diff] [blame] | 122 | Decimal instances can be constructed from integers, strings, or tuples. To |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 123 | create a Decimal from a \class{float}, first convert it to a string. This |
| 124 | serves as an explicit reminder of the details of the conversion (including |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 125 | representation 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 Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 128 | |
| 129 | \begin{verbatim} |
| 130 | >>> Decimal(10) |
| 131 | Decimal("10") |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 132 | >>> Decimal("3.14") |
| 133 | Decimal("3.14") |
| 134 | >>> Decimal((0, (3, 1, 4), -2)) |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 135 | Decimal("3.14") |
| 136 | >>> Decimal(str(2.0 ** 0.5)) |
| 137 | Decimal("1.41421356237") |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 138 | >>> Decimal("NaN") |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 139 | Decimal("NaN") |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 140 | >>> Decimal("-Infinity") |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 141 | Decimal("-Infinity") |
| 142 | \end{verbatim} |
| 143 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 144 | |
| 145 | The significance of a new Decimal is determined solely by the number |
| 146 | of digits input. Context precision and rounding only come into play during |
| 147 | arithmetic operations. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 148 | |
| 149 | \begin{verbatim} |
| 150 | >>> getcontext().prec = 6 |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 151 | >>> Decimal('3.0') |
| 152 | Decimal("3.0") |
| 153 | >>> Decimal('3.1415926535') |
| 154 | Decimal("3.1415926535") |
| 155 | >>> Decimal('3.1415926535') + Decimal('2.7182818285') |
| 156 | Decimal("5.85987") |
| 157 | >>> getcontext().rounding = ROUND_UP |
| 158 | >>> Decimal('3.1415926535') + Decimal('2.7182818285') |
| 159 | Decimal("5.85988") |
| 160 | \end{verbatim} |
| 161 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 162 | |
Raymond Hettinger | 467024c | 2005-02-21 15:46:52 +0000 | [diff] [blame] | 163 | Decimals interact well with much of the rest of Python. Here is a small |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 164 | decimal 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) |
| 169 | Decimal("9.25") |
| 170 | >>> min(data) |
| 171 | Decimal("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) |
| 176 | Decimal("19.29") |
| 177 | >>> a,b,c = data[:3] |
| 178 | >>> str(a) |
| 179 | '1.34' |
| 180 | >>> float(a) |
| 181 | 1.3400000000000001 |
Raymond Hettinger | 9296023 | 2004-07-14 21:06:55 +0000 | [diff] [blame] | 182 | >>> round(a, 1) # round() first converts to binary floating point |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 183 | 1.3 |
| 184 | >>> int(a) |
| 185 | 1 |
| 186 | >>> a * 5 |
| 187 | Decimal("6.70") |
| 188 | >>> a * b |
| 189 | Decimal("2.5058") |
| 190 | >>> c % a |
| 191 | Decimal("0.77") |
| 192 | \end{verbatim} |
| 193 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 194 | The \method{quantize()} method rounds a number to a fixed exponent. This |
| 195 | method is useful for monetary applications that often round results to a fixed |
| 196 | number of places: |
| 197 | |
| 198 | \begin{verbatim} |
| 199 | >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN) |
| 200 | Decimal("7.32") |
| 201 | >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP) |
| 202 | Decimal("8") |
| 203 | \end{verbatim} |
| 204 | |
| 205 | As shown above, the \function{getcontext()} function accesses the current |
| 206 | context and allows the settings to be changed. This approach meets the |
| 207 | needs of most applications. |
| 208 | |
| 209 | For more advanced work, it may be useful to create alternate contexts using |
| 210 | the Context() constructor. To make an alternate active, use the |
| 211 | \function{setcontext()} function. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 212 | |
| 213 | In accordance with the standard, the \module{Decimal} module provides two |
| 214 | ready to use standard contexts, \constant{BasicContext} and |
| 215 | \constant{ExtendedContext}. The former is especially useful for debugging |
| 216 | because many of the traps are enabled: |
| 217 | |
| 218 | \begin{verbatim} |
| 219 | >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN) |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 220 | >>> setcontext(myothercontext) |
| 221 | >>> Decimal(1) / Decimal(7) |
| 222 | Decimal("0.142857142857142857142857142857142857142857142857142857142857") |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 223 | |
| 224 | >>> ExtendedContext |
| 225 | Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, |
| 226 | capitals=1, flags=[], traps=[]) |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 227 | >>> setcontext(ExtendedContext) |
| 228 | >>> Decimal(1) / Decimal(7) |
| 229 | Decimal("0.142857143") |
| 230 | >>> Decimal(42) / Decimal(0) |
| 231 | Decimal("Infinity") |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 232 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 233 | >>> setcontext(BasicContext) |
| 234 | >>> Decimal(42) / Decimal(0) |
| 235 | Traceback (most recent call last): |
| 236 | File "<pyshell#143>", line 1, in -toplevel- |
| 237 | Decimal(42) / Decimal(0) |
| 238 | DivisionByZero: x / 0 |
| 239 | \end{verbatim} |
| 240 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 241 | |
| 242 | Contexts also have signal flags for monitoring exceptional conditions |
| 243 | encountered during computations. The flags remain set until explicitly |
| 244 | cleared, so it is best to clear the flags before each set of monitored |
| 245 | computations by using the \method{clear_flags()} method. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 246 | |
| 247 | \begin{verbatim} |
| 248 | >>> setcontext(ExtendedContext) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 249 | >>> getcontext().clear_flags() |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 250 | >>> Decimal(355) / Decimal(113) |
| 251 | Decimal("3.14159292") |
| 252 | >>> getcontext() |
| 253 | Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 254 | capitals=1, flags=[Inexact, Rounded], traps=[]) |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 255 | \end{verbatim} |
| 256 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 257 | The \var{flags} entry shows that the rational approximation to \constant{Pi} |
| 258 | was rounded (digits beyond the context precision were thrown away) and that |
| 259 | the result is inexact (some of the discarded digits were non-zero). |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 260 | |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 261 | Individual traps are set using the dictionary in the \member{traps} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 262 | field of a context: |
| 263 | |
| 264 | \begin{verbatim} |
| 265 | >>> Decimal(1) / Decimal(0) |
| 266 | Decimal("Infinity") |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 267 | >>> getcontext().traps[DivisionByZero] = 1 |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 268 | >>> Decimal(1) / Decimal(0) |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 269 | Traceback (most recent call last): |
| 270 | File "<pyshell#112>", line 1, in -toplevel- |
| 271 | Decimal(1) / Decimal(0) |
| 272 | DivisionByZero: x / 0 |
| 273 | \end{verbatim} |
| 274 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 275 | Most programs adjust the current context only once, at the beginning of the |
| 276 | program. And, in many applications, data is converted to \class{Decimal} with |
| 277 | a single cast inside a loop. With context set and decimals created, the bulk |
| 278 | of the program manipulates the data no differently than with other Python |
| 279 | numeric types. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 280 | |
| 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 Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 289 | \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 Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 293 | |
| 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 Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 307 | 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 Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 309 | 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 Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 311 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 312 | 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 Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 316 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 317 | 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 Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 321 | |
| 322 | Once constructed, \class{Decimal} objects are immutable. |
| 323 | \end{classdesc} |
| 324 | |
| 325 | Decimal floating point objects share many properties with the other builtin |
| 326 | numeric types such as \class{float} and \class{int}. All of the usual |
| 327 | math operations and special methods apply. Likewise, decimal objects can |
| 328 | be copied, pickled, printed, used as dictionary keys, used as set elements, |
| 329 | compared, sorted, and coerced to another type (such as \class{float} |
| 330 | or \class{long}). |
| 331 | |
| 332 | In addition to the standard numeric properties, decimal floating point objects |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 333 | also have a number of specialized methods: |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 334 | |
| 335 | \begin{methoddesc}{adjusted}{} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 336 | 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 Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 338 | returns seven. Used for determining the position of the most significant |
| 339 | digit with respect to the decimal point. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 340 | \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 Batista | 4416094 | 2004-11-12 02:03:36 +0000 | [diff] [blame] | 358 | 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 Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 362 | \end{methoddesc} |
| 363 | |
| 364 | \begin{methoddesc}{min}{other\optional{, context}} |
Facundo Batista | 4416094 | 2004-11-12 02:03:36 +0000 | [diff] [blame] | 365 | 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 Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 369 | \end{methoddesc} |
| 370 | |
| 371 | \begin{methoddesc}{normalize}{\optional{context}} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 372 | 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 Hettinger | 8df4e6b | 2004-08-15 23:51:38 +0000 | [diff] [blame] | 377 | \code{Decimal("32.1")}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 378 | \end{methoddesc} |
| 379 | |
| 380 | \begin{methoddesc}{quantize} |
Facundo Batista | 139af02 | 2004-11-20 00:33:51 +0000 | [diff] [blame] | 381 | {exp \optional{, rounding\optional{, context\optional{, watchexp}}}} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 382 | Quantize makes the exponent the same as \var{exp}. Searches for a |
| 383 | rounding method in \var{rounding}, then in \var{context}, and then |
| 384 | in the current context. |
| 385 | |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 386 | If \var{watchexp} is set (default), then an error is returned whenever |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 387 | 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 Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 392 | Computes the modulo as either a positive or negative value depending |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 393 | on which is closest to zero. For instance, |
| 394 | \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")} |
| 395 | which is closer to zero than \code{Decimal("4")}. |
| 396 | |
| 397 | If both are equally close, the one chosen will have the same sign |
| 398 | as \var{self}. |
| 399 | \end{methoddesc} |
| 400 | |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 401 | \begin{methoddesc}{same_quantum}{other\optional{, context}} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 402 | 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 Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 411 | Convert to an engineering-type string. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 412 | |
| 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 Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 419 | Rounds to the nearest integer without signaling \constant{Inexact} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 420 | 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 Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 425 | |
| 426 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 427 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 428 | \subsection{Context objects \label{decimal-decimal}} |
| 429 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 430 | Contexts are environments for arithmetic operations. They govern precision, |
| 431 | set rules for rounding, determine which signals are treated as exceptions, and |
| 432 | limit the range for exponents. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 433 | |
| 434 | Each thread has its own current context which is accessed or changed using |
| 435 | the \function{getcontext()} and \function{setcontext()} functions: |
| 436 | |
| 437 | \begin{funcdesc}{getcontext}{} |
| 438 | Return the current context for the active thread. |
| 439 | \end{funcdesc} |
| 440 | |
| 441 | \begin{funcdesc}{setcontext}{c} |
| 442 | Set the current context for the active thread to \var{c}. |
| 443 | \end{funcdesc} |
| 444 | |
| 445 | New contexts can formed using the \class{Context} constructor described below. |
| 446 | In addition, the module provides three pre-made contexts: |
| 447 | |
| 448 | |
| 449 | \begin{classdesc*}{BasicContext} |
| 450 | This is a standard context defined by the General Decimal Arithmetic |
| 451 | Specification. Precision is set to nine. Rounding is set to |
| 452 | \constant{ROUND_HALF_UP}. All flags are cleared. All traps are enabled |
| 453 | (treated as exceptions) except \constant{Inexact}, \constant{Rounded}, and |
| 454 | \constant{Subnormal}. |
| 455 | |
| 456 | Because many of the traps are enabled, this context is useful for debugging. |
| 457 | \end{classdesc*} |
| 458 | |
| 459 | \begin{classdesc*}{ExtendedContext} |
| 460 | This is a standard context defined by the General Decimal Arithmetic |
| 461 | Specification. Precision is set to nine. Rounding is set to |
| 462 | \constant{ROUND_HALF_EVEN}. All flags are cleared. No traps are enabled |
| 463 | (so that exceptions are not raised during computations). |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 464 | |
| 465 | Because the trapped are disabled, this context is useful for applications |
| 466 | that prefer to have result value of \constant{NaN} or \constant{Infinity} |
| 467 | instead of raising exceptions. This allows an application to complete a |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 468 | run in the presence of conditions that would otherwise halt the program. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 469 | \end{classdesc*} |
| 470 | |
| 471 | \begin{classdesc*}{DefaultContext} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 472 | This context is used by the \class{Context} constructor as a prototype for |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 473 | new contexts. Changing a field (such a precision) has the effect of |
| 474 | changing the default for new contexts creating by the \class{Context} |
| 475 | constructor. |
| 476 | |
| 477 | This context is most useful in multi-threaded environments. Changing one of |
| 478 | the fields before threads are started has the effect of setting system-wide |
| 479 | defaults. Changing the fields after threads have started is not recommended |
| 480 | as it would require thread synchronization to prevent race conditions. |
| 481 | |
| 482 | In single threaded environments, it is preferable to not use this context |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 483 | at all. Instead, simply create contexts explicitly as described below. |
| 484 | |
| 485 | The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled |
| 486 | traps for Overflow, InvalidOperation, and DivisionByZero. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 487 | \end{classdesc*} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 488 | |
| 489 | |
| 490 | In addition to the three supplied contexts, new contexts can be created |
| 491 | with the \class{Context} constructor. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 492 | |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 493 | \begin{classdesc}{Context}{prec=None, rounding=None, traps=None, |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 494 | flags=None, Emin=None, Emax=None, capitals=1} |
| 495 | Creates a new context. If a field is not specified or is \constant{None}, |
| 496 | the default values are copied from the \constant{DefaultContext}. If the |
| 497 | \var{flags} field is not specified or is \constant{None}, all flags are |
| 498 | cleared. |
| 499 | |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 500 | The \var{prec} field is a positive integer that sets the precision for |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 501 | arithmetic operations in the context. |
| 502 | |
Raymond Hettinger | 97c9208 | 2004-07-09 06:13:12 +0000 | [diff] [blame] | 503 | The \var{rounding} option is one of: |
Raymond Hettinger | 87de8ed | 2005-07-01 16:54:12 +0000 | [diff] [blame] | 504 | \begin{itemize} |
| 505 | \item \constant{ROUND_CEILING} (towards \constant{Infinity}), |
| 506 | \item \constant{ROUND_DOWN} (towards zero), |
| 507 | \item \constant{ROUND_FLOOR} (towards \constant{-Infinity}), |
| 508 | \item \constant{ROUND_HALF_DOWN} (to nearest with ties going towards zero), |
| 509 | \item \constant{ROUND_HALF_EVEN} (to nearest with ties going to nearest even integer), |
| 510 | \item \constant{ROUND_HALF_UP} (to nearest with ties going away from zero), or |
| 511 | \item \constant{ROUND_UP} (away from zero). |
| 512 | \end{itemize} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 513 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 514 | The \var{traps} and \var{flags} fields list any signals to be set. |
| 515 | Generally, new contexts should only set traps and leave the flags clear. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 516 | |
| 517 | The \var{Emin} and \var{Emax} fields are integers specifying the outer |
| 518 | limits allowable for exponents. |
| 519 | |
| 520 | The \var{capitals} field is either \constant{0} or \constant{1} (the |
| 521 | default). If set to \constant{1}, exponents are printed with a capital |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 522 | \constant{E}; otherwise, a lowercase \constant{e} is used: |
| 523 | \constant{Decimal('6.02e+23')}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 524 | \end{classdesc} |
| 525 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 526 | The \class{Context} class defines several general purpose methods as well as a |
| 527 | large number of methods for doing arithmetic directly in a given context. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 528 | |
| 529 | \begin{methoddesc}{clear_flags}{} |
Raymond Hettinger | d391d10 | 2005-06-07 18:50:56 +0000 | [diff] [blame] | 530 | Resets all of the flags to \constant{0}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 531 | \end{methoddesc} |
| 532 | |
| 533 | \begin{methoddesc}{copy}{} |
Raymond Hettinger | d391d10 | 2005-06-07 18:50:56 +0000 | [diff] [blame] | 534 | Return a duplicate of the context. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 535 | \end{methoddesc} |
| 536 | |
| 537 | \begin{methoddesc}{create_decimal}{num} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 538 | Creates a new Decimal instance from \var{num} but using \var{self} as |
| 539 | context. Unlike the \class{Decimal} constructor, the context precision, |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 540 | rounding method, flags, and traps are applied to the conversion. |
| 541 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 542 | This is useful because constants are often given to a greater precision than |
Raymond Hettinger | d7c7115 | 2004-07-12 13:22:14 +0000 | [diff] [blame] | 543 | is needed by the application. Another benefit is that rounding immediately |
| 544 | eliminates unintended effects from digits beyond the current precision. |
| 545 | In the following example, using unrounded inputs means that adding zero |
| 546 | to a sum can change the result: |
| 547 | |
| 548 | \begin{verbatim} |
| 549 | >>> getcontext().prec = 3 |
| 550 | >>> Decimal("3.4445") + Decimal("1.0023") |
| 551 | Decimal("4.45") |
| 552 | >>> Decimal("3.4445") + Decimal(0) + Decimal("1.0023") |
| 553 | Decimal("4.44") |
| 554 | \end{verbatim} |
| 555 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 556 | \end{methoddesc} |
| 557 | |
| 558 | \begin{methoddesc}{Etiny}{} |
| 559 | Returns a value equal to \samp{Emin - prec + 1} which is the minimum |
| 560 | exponent value for subnormal results. When underflow occurs, the |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 561 | exponent is set to \constant{Etiny}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 562 | \end{methoddesc} |
| 563 | |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 564 | \begin{methoddesc}{Etop}{} |
| 565 | Returns a value equal to \samp{Emax - prec + 1}. |
| 566 | \end{methoddesc} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 567 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 568 | |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 569 | The usual approach to working with decimals is to create \class{Decimal} |
| 570 | instances and then apply arithmetic operations which take place within the |
| 571 | current context for the active thread. An alternate approach is to use |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 572 | context methods for calculating within a specific context. The methods are |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 573 | similar to those for the \class{Decimal} class and are only briefly recounted |
| 574 | here. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 575 | |
| 576 | \begin{methoddesc}{abs}{x} |
| 577 | Returns the absolute value of \var{x}. |
| 578 | \end{methoddesc} |
| 579 | |
| 580 | \begin{methoddesc}{add}{x, y} |
| 581 | Return the sum of \var{x} and \var{y}. |
| 582 | \end{methoddesc} |
| 583 | |
| 584 | \begin{methoddesc}{compare}{x, y} |
| 585 | Compares values numerically. |
| 586 | |
| 587 | Like \method{__cmp__()} but returns a decimal instance: |
| 588 | \begin{verbatim} |
| 589 | a or b is a NaN ==> Decimal("NaN") |
| 590 | a < b ==> Decimal("-1") |
| 591 | a == b ==> Decimal("0") |
| 592 | a > b ==> Decimal("1") |
| 593 | \end{verbatim} |
| 594 | \end{methoddesc} |
| 595 | |
| 596 | \begin{methoddesc}{divide}{x, y} |
| 597 | Return \var{x} divided by \var{y}. |
| 598 | \end{methoddesc} |
| 599 | |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 600 | \begin{methoddesc}{divmod}{x, y} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 601 | Divides two numbers and returns the integer part of the result. |
| 602 | \end{methoddesc} |
| 603 | |
| 604 | \begin{methoddesc}{max}{x, y} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 605 | Compare two values numerically and return the maximum. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 606 | |
| 607 | If they are numerically equal then the left-hand operand is chosen as the |
| 608 | result. |
| 609 | \end{methoddesc} |
| 610 | |
| 611 | \begin{methoddesc}{min}{x, y} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 612 | Compare two values numerically and return the minimum. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 613 | |
| 614 | If they are numerically equal then the left-hand operand is chosen as the |
| 615 | result. |
| 616 | \end{methoddesc} |
| 617 | |
| 618 | \begin{methoddesc}{minus}{x} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 619 | Minus corresponds to the unary prefix minus operator in Python. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 620 | \end{methoddesc} |
| 621 | |
| 622 | \begin{methoddesc}{multiply}{x, y} |
| 623 | Return the product of \var{x} and \var{y}. |
| 624 | \end{methoddesc} |
| 625 | |
| 626 | \begin{methoddesc}{normalize}{x} |
| 627 | Normalize reduces an operand to its simplest form. |
| 628 | |
Raymond Hettinger | d7c7115 | 2004-07-12 13:22:14 +0000 | [diff] [blame] | 629 | Essentially a \method{plus} operation with all trailing zeros removed from |
| 630 | the result. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 631 | \end{methoddesc} |
| 632 | |
| 633 | \begin{methoddesc}{plus}{x} |
Raymond Hettinger | d7c7115 | 2004-07-12 13:22:14 +0000 | [diff] [blame] | 634 | Plus corresponds to the unary prefix plus operator in Python. This |
| 635 | operation applies the context precision and rounding, so it is |
| 636 | \emph{not} an identity operation. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 637 | \end{methoddesc} |
| 638 | |
| 639 | \begin{methoddesc}{power}{x, y\optional{, modulo}} |
| 640 | Return \samp{x ** y} to the \var{modulo} if given. |
| 641 | |
| 642 | The right-hand operand must be a whole number whose integer part (after any |
| 643 | exponent has been applied) has no more than 9 digits and whose fractional |
| 644 | part (if any) is all zeros before any rounding. The operand may be positive, |
| 645 | negative, or zero; if negative, the absolute value of the power is used, and |
| 646 | the left-hand operand is inverted (divided into 1) before use. |
| 647 | |
| 648 | If the increased precision needed for the intermediate calculations exceeds |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 649 | the capabilities of the implementation then an \constant{InvalidOperation} |
| 650 | condition is signaled. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 651 | |
| 652 | If, when raising to a negative power, an underflow occurs during the |
| 653 | division into 1, the operation is not halted at that point but continues. |
| 654 | \end{methoddesc} |
| 655 | |
| 656 | \begin{methoddesc}{quantize}{x, y} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 657 | Returns a value equal to \var{x} after rounding and having the exponent of |
| 658 | \var{y}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 659 | |
| 660 | Unlike other operations, if the length of the coefficient after the quantize |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 661 | operation would be greater than precision, then an |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 662 | \constant{InvalidOperation} is signaled. This guarantees that, unless there |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 663 | is an error condition, the quantized exponent is always equal to that of the |
| 664 | right-hand operand. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 665 | |
| 666 | Also unlike other operations, quantize never signals Underflow, even |
| 667 | if the result is subnormal and inexact. |
| 668 | \end{methoddesc} |
| 669 | |
| 670 | \begin{methoddesc}{remainder}{x, y} |
| 671 | Returns the remainder from integer division. |
| 672 | |
| 673 | The sign of the result, if non-zero, is the same as that of the original |
| 674 | dividend. |
| 675 | \end{methoddesc} |
| 676 | |
| 677 | \begin{methoddesc}{remainder_near}{x, y} |
| 678 | Computed the modulo as either a positive or negative value depending |
| 679 | on which is closest to zero. For instance, |
| 680 | \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")} |
| 681 | which is closer to zero than \code{Decimal("4")}. |
| 682 | |
| 683 | If both are equally close, the one chosen will have the same sign |
| 684 | as \var{self}. |
| 685 | \end{methoddesc} |
| 686 | |
| 687 | \begin{methoddesc}{same_quantum}{x, y} |
| 688 | Test whether \var{x} and \var{y} have the same exponent or whether both are |
| 689 | \constant{NaN}. |
| 690 | \end{methoddesc} |
| 691 | |
| 692 | \begin{methoddesc}{sqrt}{} |
| 693 | Return the square root to full precision. |
| 694 | \end{methoddesc} |
| 695 | |
Georg Brandl | f33d01d | 2005-08-22 19:35:18 +0000 | [diff] [blame] | 696 | \begin{methoddesc}{subtract}{x, y} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 697 | Return the difference between \var{x} and \var{y}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 698 | \end{methoddesc} |
| 699 | |
| 700 | \begin{methoddesc}{to_eng_string}{} |
| 701 | Convert to engineering-type string. |
| 702 | |
| 703 | Engineering notation has an exponent which is a multiple of 3, so there |
| 704 | are up to 3 digits left of the decimal place. For example, converts |
| 705 | \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")} |
| 706 | \end{methoddesc} |
| 707 | |
| 708 | \begin{methoddesc}{to_integral}{x} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 709 | Rounds to the nearest integer without signaling \constant{Inexact} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 710 | or \constant{Rounded}. |
| 711 | \end{methoddesc} |
| 712 | |
| 713 | \begin{methoddesc}{to_sci_string}{} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 714 | Converts a number to a string using scientific notation. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 715 | \end{methoddesc} |
| 716 | |
| 717 | |
| 718 | |
| 719 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 720 | \subsection{Signals \label{decimal-signals}} |
| 721 | |
| 722 | Signals represent conditions that arise during computation. |
| 723 | Each corresponds to one context flag and one context trap enabler. |
| 724 | |
| 725 | The context flag is incremented whenever the condition is encountered. |
| 726 | After the computation, flags may be checked for informational |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 727 | purposes (for instance, to determine whether a computation was exact). |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 728 | After checking the flags, be sure to clear all flags before starting |
| 729 | the next computation. |
| 730 | |
| 731 | If the context's trap enabler is set for the signal, then the condition |
| 732 | causes a Python exception to be raised. For example, if the |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 733 | \class{DivisionByZero} trap is set, then a \exception{DivisionByZero} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 734 | exception is raised upon encountering the condition. |
| 735 | |
| 736 | |
| 737 | \begin{classdesc*}{Clamped} |
| 738 | Altered an exponent to fit representation constraints. |
| 739 | |
| 740 | Typically, clamping occurs when an exponent falls outside the context's |
| 741 | \member{Emin} and \member{Emax} limits. If possible, the exponent is |
| 742 | reduced to fit by adding zeroes to the coefficient. |
| 743 | \end{classdesc*} |
| 744 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 745 | \begin{classdesc*}{DecimalException} |
Raymond Hettinger | 467024c | 2005-02-21 15:46:52 +0000 | [diff] [blame] | 746 | Base class for other signals and a subclass of |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 747 | \exception{ArithmeticError}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 748 | \end{classdesc*} |
| 749 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 750 | \begin{classdesc*}{DivisionByZero} |
| 751 | Signals the division of a non-infinite number by zero. |
| 752 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 753 | Can occur with division, modulo division, or when raising a number to a |
| 754 | negative power. If this signal is not trapped, returns |
| 755 | \constant{Infinity} or \constant{-Infinity} with the sign determined by |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 756 | the inputs to the calculation. |
| 757 | \end{classdesc*} |
| 758 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 759 | \begin{classdesc*}{Inexact} |
| 760 | Indicates that rounding occurred and the result is not exact. |
| 761 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 762 | Signals when non-zero digits were discarded during rounding. The rounded |
| 763 | result is returned. The signal flag or trap is used to detect when |
| 764 | results are inexact. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 765 | \end{classdesc*} |
| 766 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 767 | \begin{classdesc*}{InvalidOperation} |
| 768 | An invalid operation was performed. |
| 769 | |
| 770 | Indicates that an operation was requested that does not make sense. |
| 771 | If not trapped, returns \constant{NaN}. Possible causes include: |
| 772 | |
| 773 | \begin{verbatim} |
| 774 | Infinity - Infinity |
| 775 | 0 * Infinity |
| 776 | Infinity / Infinity |
| 777 | x % 0 |
| 778 | Infinity % x |
| 779 | x._rescale( non-integer ) |
| 780 | sqrt(-x) and x > 0 |
| 781 | 0 ** 0 |
| 782 | x ** (non-integer) |
| 783 | x ** Infinity |
| 784 | \end{verbatim} |
| 785 | \end{classdesc*} |
| 786 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 787 | \begin{classdesc*}{Overflow} |
| 788 | Numerical overflow. |
| 789 | |
| 790 | Indicates the exponent is larger than \member{Emax} after rounding has |
| 791 | occurred. If not trapped, the result depends on the rounding mode, either |
| 792 | pulling inward to the largest representable finite number or rounding |
| 793 | outward to \constant{Infinity}. In either case, \class{Inexact} and |
| 794 | \class{Rounded} are also signaled. |
| 795 | \end{classdesc*} |
| 796 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 797 | \begin{classdesc*}{Rounded} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 798 | Rounding occurred though possibly no information was lost. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 799 | |
| 800 | Signaled whenever rounding discards digits; even if those digits are |
| 801 | zero (such as rounding \constant{5.00} to \constant{5.0}). If not |
| 802 | trapped, returns the result unchanged. This signal is used to detect |
| 803 | loss of significant digits. |
| 804 | \end{classdesc*} |
| 805 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 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 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 813 | \begin{classdesc*}{Underflow} |
| 814 | Numerical underflow with result rounded to zero. |
| 815 | |
| 816 | Occurs when a subnormal result is pushed to zero by rounding. |
| 817 | \class{Inexact} and \class{Subnormal} are also signaled. |
| 818 | \end{classdesc*} |
| 819 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 820 | The following table summarizes the hierarchy of signals: |
| 821 | |
| 822 | \begin{verbatim} |
| 823 | exceptions.ArithmeticError(exceptions.StandardError) |
| 824 | DecimalException |
| 825 | Clamped |
| 826 | DivisionByZero(DecimalException, exceptions.ZeroDivisionError) |
| 827 | Inexact |
| 828 | Overflow(Inexact, Rounded) |
| 829 | Underflow(Inexact, Rounded, Subnormal) |
| 830 | InvalidOperation |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 831 | Rounded |
| 832 | Subnormal |
| 833 | \end{verbatim} |
| 834 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 835 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 836 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
Raymond Hettinger | 2864b80 | 2004-08-15 23:47:48 +0000 | [diff] [blame] | 837 | \subsection{Floating Point Notes \label{decimal-notes}} |
| 838 | |
Raymond Hettinger | 87de8ed | 2005-07-01 16:54:12 +0000 | [diff] [blame] | 839 | \subsubsection{Mitigating round-off error with increased precision} |
| 840 | |
Raymond Hettinger | 2864b80 | 2004-08-15 23:47:48 +0000 | [diff] [blame] | 841 | The use of decimal floating point eliminates decimal representation error |
| 842 | (making it possible to represent \constant{0.1} exactly); however, some |
| 843 | operations can still incur round-off error when non-zero digits exceed the |
| 844 | fixed precision. |
| 845 | |
| 846 | The effects of round-off error can be amplified by the addition or subtraction |
| 847 | of nearly offsetting quantities resulting in loss of significance. Knuth |
| 848 | provides two instructive examples where rounded floating point arithmetic with |
Raymond Hettinger | f4fd79c | 2004-08-26 03:11:56 +0000 | [diff] [blame] | 849 | insufficient precision causes the breakdown of the associative and |
Raymond Hettinger | 2864b80 | 2004-08-15 23:47:48 +0000 | [diff] [blame] | 850 | distributive properties of addition: |
| 851 | |
| 852 | \begin{verbatim} |
| 853 | # Examples from Seminumerical Algorithms, Section 4.2.2. |
Raymond Hettinger | 467024c | 2005-02-21 15:46:52 +0000 | [diff] [blame] | 854 | >>> from decimal import Decimal, getcontext |
Raymond Hettinger | 2864b80 | 2004-08-15 23:47:48 +0000 | [diff] [blame] | 855 | >>> getcontext().prec = 8 |
| 856 | |
| 857 | >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') |
| 858 | >>> (u + v) + w |
| 859 | Decimal("9.5111111") |
| 860 | >>> u + (v + w) |
| 861 | Decimal("10") |
| 862 | |
| 863 | >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') |
| 864 | >>> (u*v) + (u*w) |
| 865 | Decimal("0.01") |
| 866 | >>> u * (v+w) |
| 867 | Decimal("0.0060000") |
| 868 | \end{verbatim} |
| 869 | |
| 870 | The \module{decimal} module makes it possible to restore the identities |
| 871 | by expanding the precision sufficiently to avoid loss of significance: |
| 872 | |
| 873 | \begin{verbatim} |
| 874 | >>> getcontext().prec = 20 |
| 875 | >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') |
| 876 | >>> (u + v) + w |
| 877 | Decimal("9.51111111") |
| 878 | >>> u + (v + w) |
| 879 | Decimal("9.51111111") |
| 880 | >>> |
| 881 | >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') |
| 882 | >>> (u*v) + (u*w) |
| 883 | Decimal("0.0060000") |
| 884 | >>> u * (v+w) |
| 885 | Decimal("0.0060000") |
| 886 | \end{verbatim} |
| 887 | |
Raymond Hettinger | 87de8ed | 2005-07-01 16:54:12 +0000 | [diff] [blame] | 888 | \subsubsection{Special values} |
Raymond Hettinger | 2864b80 | 2004-08-15 23:47:48 +0000 | [diff] [blame] | 889 | |
| 890 | The number system for the \module{decimal} module provides special |
| 891 | values including \constant{NaN}, \constant{sNaN}, \constant{-Infinity}, |
| 892 | \constant{Infinity}, and two zeroes, \constant{+0} and \constant{-0}. |
| 893 | |
Andrew M. Kuchling | 7ec7584 | 2004-08-16 16:12:23 +0000 | [diff] [blame] | 894 | Infinities can be constructed directly with: \code{Decimal('Infinity')}. Also, |
Raymond Hettinger | 2864b80 | 2004-08-15 23:47:48 +0000 | [diff] [blame] | 895 | they can arise from dividing by zero when the \exception{DivisionByZero} |
| 896 | signal is not trapped. Likewise, when the \exception{Overflow} signal is not |
| 897 | trapped, infinity can result from rounding beyond the limits of the largest |
| 898 | representable number. |
| 899 | |
| 900 | The infinities are signed (affine) and can be used in arithmetic operations |
| 901 | where they get treated as very large, indeterminate numbers. For instance, |
| 902 | adding a constant to infinity gives another infinite result. |
| 903 | |
Raymond Hettinger | f4fd79c | 2004-08-26 03:11:56 +0000 | [diff] [blame] | 904 | Some operations are indeterminate and return \constant{NaN}, or if the |
Raymond Hettinger | 2864b80 | 2004-08-15 23:47:48 +0000 | [diff] [blame] | 905 | \exception{InvalidOperation} signal is trapped, raise an exception. For |
| 906 | example, \code{0/0} returns \constant{NaN} which means ``not a number''. This |
| 907 | variety of \constant{NaN} is quiet and, once created, will flow through other |
| 908 | computations always resulting in another \constant{NaN}. This behavior can be |
| 909 | useful for a series of computations that occasionally have missing inputs --- |
| 910 | it allows the calculation to proceed while flagging specific results as |
| 911 | invalid. |
| 912 | |
| 913 | A variant is \constant{sNaN} which signals rather than remaining quiet |
| 914 | after every operation. This is a useful return value when an invalid |
| 915 | result needs to interrupt a calculation for special handling. |
| 916 | |
| 917 | The signed zeros can result from calculations that underflow. |
| 918 | They keep the sign that would have resulted if the calculation had |
| 919 | been carried out to greater precision. Since their magnitude is |
Raymond Hettinger | f4fd79c | 2004-08-26 03:11:56 +0000 | [diff] [blame] | 920 | zero, both positive and negative zeros are treated as equal and their |
Raymond Hettinger | 2864b80 | 2004-08-15 23:47:48 +0000 | [diff] [blame] | 921 | sign is informational. |
| 922 | |
Raymond Hettinger | f4fd79c | 2004-08-26 03:11:56 +0000 | [diff] [blame] | 923 | In addition to the two signed zeros which are distinct yet equal, |
| 924 | there are various representations of zero with differing precisions |
Raymond Hettinger | 2864b80 | 2004-08-15 23:47:48 +0000 | [diff] [blame] | 925 | yet equivalent in value. This takes a bit of getting used to. For |
| 926 | an eye accustomed to normalized floating point representations, it |
| 927 | is not immediately obvious that the following calculation returns |
| 928 | a value equal to zero: |
| 929 | |
| 930 | \begin{verbatim} |
| 931 | >>> 1 / Decimal('Infinity') |
| 932 | Decimal("0E-1000000026") |
| 933 | \end{verbatim} |
| 934 | |
| 935 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 936 | \subsection{Working with threads \label{decimal-threads}} |
| 937 | |
| 938 | The \function{getcontext()} function accesses a different \class{Context} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 939 | object for each thread. Having separate thread contexts means that threads |
| 940 | may make changes (such as \code{getcontext.prec=10}) without interfering with |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 941 | other threads. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 942 | |
| 943 | Likewise, the \function{setcontext()} function automatically assigns its target |
| 944 | to the current thread. |
| 945 | |
| 946 | If \function{setcontext()} has not been called before \function{getcontext()}, |
| 947 | then \function{getcontext()} will automatically create a new context for use |
| 948 | in the current thread. |
| 949 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 950 | The new context is copied from a prototype context called |
| 951 | \var{DefaultContext}. To control the defaults so that each thread will use the |
| 952 | same values throughout the application, directly modify the |
| 953 | \var{DefaultContext} object. This should be done \emph{before} any threads are |
| 954 | started so that there won't be a race condition between threads calling |
| 955 | \function{getcontext()}. For example: |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 956 | |
| 957 | \begin{verbatim} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 958 | # Set applicationwide defaults for all threads about to be launched |
Raymond Hettinger | 9296023 | 2004-07-14 21:06:55 +0000 | [diff] [blame] | 959 | DefaultContext.prec = 12 |
| 960 | DefaultContext.rounding = ROUND_DOWN |
| 961 | DefaultContext.traps = ExtendedContext.traps.copy() |
| 962 | DefaultContext.traps[InvalidOperation] = 1 |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 963 | setcontext(DefaultContext) |
| 964 | |
Raymond Hettinger | 9296023 | 2004-07-14 21:06:55 +0000 | [diff] [blame] | 965 | # Afterwards, the threads can be started |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 966 | t1.start() |
| 967 | t2.start() |
| 968 | t3.start() |
| 969 | . . . |
| 970 | \end{verbatim} |
Raymond Hettinger | 2864b80 | 2004-08-15 23:47:48 +0000 | [diff] [blame] | 971 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 972 | |
| 973 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 974 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 975 | \subsection{Recipes \label{decimal-recipes}} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 976 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 977 | Here are a few recipes that serve as utility functions and that demonstrate |
| 978 | ways to work with the \class{Decimal} class: |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 979 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 980 | \begin{verbatim} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 981 | def moneyfmt(value, places=2, curr='', sep=',', dp='.', |
| 982 | pos='', neg='-', trailneg=''): |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 983 | """Convert Decimal to a money formatted string. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 984 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 985 | places: required number of places after the decimal point |
| 986 | curr: optional currency symbol before the sign (may be blank) |
Raymond Hettinger | 3de9aa4 | 2004-11-25 04:47:09 +0000 | [diff] [blame] | 987 | sep: optional grouping separator (comma, period, space, or blank) |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 988 | dp: decimal point indicator (comma or period) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 989 | only specify as blank when places is zero |
Raymond Hettinger | 3de9aa4 | 2004-11-25 04:47:09 +0000 | [diff] [blame] | 990 | pos: optional sign for positive numbers: '+', space or blank |
| 991 | neg: optional sign for negative numbers: '-', '(', space or blank |
| 992 | trailneg:optional trailing minus indicator: '-', ')', space or blank |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 993 | |
| 994 | >>> d = Decimal('-1234567.8901') |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 995 | >>> moneyfmt(d, curr='$') |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 996 | '-$1,234,567.89' |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 997 | >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-') |
| 998 | '1.234.568-' |
| 999 | >>> moneyfmt(d, curr='$', neg='(', trailneg=')') |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1000 | '($1,234,567.89)' |
Raymond Hettinger | 3de9aa4 | 2004-11-25 04:47:09 +0000 | [diff] [blame] | 1001 | >>> moneyfmt(Decimal(123456789), sep=' ') |
| 1002 | '123 456 789.00' |
| 1003 | >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>') |
| 1004 | '<.02>' |
| 1005 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1006 | """ |
| 1007 | q = Decimal((0, (1,), -places)) # 2 places --> '0.01' |
| 1008 | sign, digits, exp = value.quantize(q).as_tuple() |
Raymond Hettinger | 3de9aa4 | 2004-11-25 04:47:09 +0000 | [diff] [blame] | 1009 | assert exp == -places |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1010 | result = [] |
| 1011 | digits = map(str, digits) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1012 | build, next = result.append, digits.pop |
| 1013 | if sign: |
| 1014 | build(trailneg) |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1015 | for i in range(places): |
Raymond Hettinger | 3de9aa4 | 2004-11-25 04:47:09 +0000 | [diff] [blame] | 1016 | if digits: |
| 1017 | build(next()) |
| 1018 | else: |
| 1019 | build('0') |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1020 | build(dp) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1021 | i = 0 |
| 1022 | while digits: |
| 1023 | build(next()) |
| 1024 | i += 1 |
Raymond Hettinger | 8f2c4ee | 2004-11-24 05:53:26 +0000 | [diff] [blame] | 1025 | if i == 3 and digits: |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1026 | i = 0 |
| 1027 | build(sep) |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1028 | build(curr) |
| 1029 | if sign: |
| 1030 | build(neg) |
| 1031 | else: |
| 1032 | build(pos) |
| 1033 | result.reverse() |
| 1034 | return ''.join(result) |
| 1035 | |
| 1036 | def pi(): |
Raymond Hettinger | c4f93d44 | 2004-07-05 20:17:13 +0000 | [diff] [blame] | 1037 | """Compute Pi to the current precision. |
| 1038 | |
| 1039 | >>> print pi() |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1040 | 3.141592653589793238462643383 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1041 | |
Raymond Hettinger | c4f93d44 | 2004-07-05 20:17:13 +0000 | [diff] [blame] | 1042 | """ |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1043 | getcontext().prec += 2 # extra digits for intermediate steps |
Raymond Hettinger | 10959b1 | 2004-07-05 21:13:28 +0000 | [diff] [blame] | 1044 | three = Decimal(3) # substitute "three=3.0" for regular floats |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1045 | lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 |
| 1046 | while s != lasts: |
| 1047 | lasts = s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1048 | n, na = n+na, na+8 |
| 1049 | d, da = d+da, da+32 |
| 1050 | t = (t * n) / d |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1051 | s += t |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1052 | getcontext().prec -= 2 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1053 | return +s # unary plus applies the new precision |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1054 | |
| 1055 | def exp(x): |
Raymond Hettinger | 10959b1 | 2004-07-05 21:13:28 +0000 | [diff] [blame] | 1056 | """Return e raised to the power of x. Result type matches input type. |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1057 | |
| 1058 | >>> print exp(Decimal(1)) |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1059 | 2.718281828459045235360287471 |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1060 | >>> print exp(Decimal(2)) |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1061 | 7.389056098930650227230427461 |
Raymond Hettinger | 10959b1 | 2004-07-05 21:13:28 +0000 | [diff] [blame] | 1062 | >>> print exp(2.0) |
| 1063 | 7.38905609893 |
| 1064 | >>> print exp(2+0j) |
| 1065 | (7.38905609893+0j) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1066 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1067 | """ |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1068 | getcontext().prec += 2 |
| 1069 | i, lasts, s, fact, num = 0, 0, 1, 1, 1 |
| 1070 | while s != lasts: |
| 1071 | lasts = s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1072 | i += 1 |
| 1073 | fact *= i |
| 1074 | num *= x |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1075 | s += num / fact |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1076 | getcontext().prec -= 2 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1077 | return +s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1078 | |
| 1079 | def cos(x): |
| 1080 | """Return the cosine of x as measured in radians. |
| 1081 | |
| 1082 | >>> print cos(Decimal('0.5')) |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1083 | 0.8775825618903727161162815826 |
Raymond Hettinger | 10959b1 | 2004-07-05 21:13:28 +0000 | [diff] [blame] | 1084 | >>> print cos(0.5) |
| 1085 | 0.87758256189 |
| 1086 | >>> print cos(0.5+0j) |
| 1087 | (0.87758256189+0j) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1088 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1089 | """ |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1090 | getcontext().prec += 2 |
| 1091 | i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1 |
| 1092 | while s != lasts: |
| 1093 | lasts = s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1094 | i += 2 |
| 1095 | fact *= i * (i-1) |
| 1096 | num *= x * x |
| 1097 | sign *= -1 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1098 | s += num / fact * sign |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1099 | getcontext().prec -= 2 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1100 | return +s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1101 | |
| 1102 | def sin(x): |
Raymond Hettinger | 4fd38b3 | 2004-11-25 05:35:32 +0000 | [diff] [blame] | 1103 | """Return the sine of x as measured in radians. |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1104 | |
| 1105 | >>> print sin(Decimal('0.5')) |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1106 | 0.4794255386042030002732879352 |
Raymond Hettinger | 10959b1 | 2004-07-05 21:13:28 +0000 | [diff] [blame] | 1107 | >>> print sin(0.5) |
| 1108 | 0.479425538604 |
| 1109 | >>> print sin(0.5+0j) |
| 1110 | (0.479425538604+0j) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1111 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1112 | """ |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1113 | getcontext().prec += 2 |
| 1114 | i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1 |
| 1115 | while s != lasts: |
| 1116 | lasts = s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1117 | i += 2 |
| 1118 | fact *= i * (i-1) |
| 1119 | num *= x * x |
| 1120 | sign *= -1 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1121 | s += num / fact * sign |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1122 | getcontext().prec -= 2 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1123 | return +s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1124 | |
| 1125 | \end{verbatim} |
Raymond Hettinger | d391d10 | 2005-06-07 18:50:56 +0000 | [diff] [blame] | 1126 | |
| 1127 | |
| 1128 | |
Raymond Hettinger | ed65c3a | 2005-06-15 16:53:31 +0000 | [diff] [blame] | 1129 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
Raymond Hettinger | d391d10 | 2005-06-07 18:50:56 +0000 | [diff] [blame] | 1130 | \subsection{Decimal FAQ \label{decimal-faq}} |
| 1131 | |
Raymond Hettinger | d391d10 | 2005-06-07 18:50:56 +0000 | [diff] [blame] | 1132 | Q. It is cumbersome to type \code{decimal.Decimal('1234.5')}. Is there a way |
| 1133 | to minimize typing when using the interactive interpreter? |
| 1134 | |
| 1135 | A. Some users abbreviate the constructor to just a single letter: |
| 1136 | |
| 1137 | \begin{verbatim} |
| 1138 | >>> D = decimal.Decimal |
| 1139 | >>> D('1.23') + D('3.45') |
| 1140 | Decimal("4.68") |
| 1141 | \end{verbatim} |
| 1142 | |
| 1143 | |
Raymond Hettinger | 1166638 | 2005-09-11 18:21:52 +0000 | [diff] [blame] | 1144 | Q. In a fixed-point application with two decimal places, some inputs |
Raymond Hettinger | d391d10 | 2005-06-07 18:50:56 +0000 | [diff] [blame] | 1145 | have many places and need to be rounded. Others are not supposed to have |
| 1146 | excess digits and need to be validated. What methods should be used? |
| 1147 | |
| 1148 | A. The \method{quantize()} method rounds to a fixed number of decimal places. |
| 1149 | If the \constant{Inexact} trap is set, it is also useful for validation: |
| 1150 | |
| 1151 | \begin{verbatim} |
| 1152 | >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01') |
| 1153 | |
| 1154 | >>> # Round to two places |
| 1155 | >>> Decimal("3.214").quantize(TWOPLACES) |
| 1156 | Decimal("3.21") |
| 1157 | |
| 1158 | >>> # Validate that a number does not exceed two places |
| 1159 | >>> Decimal("3.21").quantize(TWOPLACES, context=Context(traps=[Inexact])) |
| 1160 | Decimal("3.21") |
| 1161 | |
| 1162 | >>> Decimal("3.214").quantize(TWOPLACES, context=Context(traps=[Inexact])) |
| 1163 | Traceback (most recent call last): |
| 1164 | ... |
| 1165 | Inexact: Changed in rounding |
| 1166 | \end{verbatim} |
| 1167 | |
| 1168 | |
| 1169 | Q. Once I have valid two place inputs, how do I maintain that invariant |
| 1170 | throughout an application? |
| 1171 | |
| 1172 | A. Some operations like addition and subtraction automatically preserve fixed |
| 1173 | point. Others, like multiplication and division, change the number of decimal |
| 1174 | places and need to be followed-up with a \method{quantize()} step. |
| 1175 | |
| 1176 | |
Raymond Hettinger | ed65c3a | 2005-06-15 16:53:31 +0000 | [diff] [blame] | 1177 | Q. There are many ways to express the same value. The numbers |
Raymond Hettinger | d391d10 | 2005-06-07 18:50:56 +0000 | [diff] [blame] | 1178 | \constant{200}, \constant{200.000}, \constant{2E2}, and \constant{.02E+4} all |
| 1179 | have the same value at various precisions. Is there a way to transform them to |
| 1180 | a single recognizable canonical value? |
| 1181 | |
| 1182 | A. The \method{normalize()} method maps all equivalent values to a single |
| 1183 | representive: |
| 1184 | |
| 1185 | \begin{verbatim} |
| 1186 | >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split()) |
| 1187 | >>> [v.normalize() for v in values] |
| 1188 | [Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2")] |
| 1189 | \end{verbatim} |
| 1190 | |
| 1191 | |
Raymond Hettinger | 1166638 | 2005-09-11 18:21:52 +0000 | [diff] [blame] | 1192 | Q. Some decimal values always print with exponential notation. Is there |
| 1193 | a way to get a non-exponential representation? |
| 1194 | |
| 1195 | A. For some values, exponential notation is the only way to express |
| 1196 | the number of significant places in the coefficient. For example, |
| 1197 | expressing \constant{5.0E+3} as \constant{5000} keeps the value |
| 1198 | constant but cannot show the original's two-place significance. |
| 1199 | |
| 1200 | |
Raymond Hettinger | d391d10 | 2005-06-07 18:50:56 +0000 | [diff] [blame] | 1201 | Q. Is there a way to convert a regular float to a \class{Decimal}? |
| 1202 | |
| 1203 | A. Yes, all binary floating point numbers can be exactly expressed as a |
| 1204 | Decimal. An exact conversion may take more precision than intuition would |
| 1205 | suggest, so trapping \constant{Inexact} will signal a need for more precision: |
| 1206 | |
| 1207 | \begin{verbatim} |
| 1208 | def floatToDecimal(f): |
| 1209 | "Convert a floating point number to a Decimal with no loss of information" |
| 1210 | # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an |
| 1211 | # exponent. Double the mantissa until it is an integer. Use the integer |
| 1212 | # mantissa and exponent to compute an equivalent Decimal. If this cannot |
| 1213 | # be done exactly, then retry with more precision. |
| 1214 | |
| 1215 | mantissa, exponent = math.frexp(f) |
| 1216 | while mantissa != int(mantissa): |
| 1217 | mantissa *= 2.0 |
| 1218 | exponent -= 1 |
| 1219 | mantissa = int(mantissa) |
Raymond Hettinger | ed65c3a | 2005-06-15 16:53:31 +0000 | [diff] [blame] | 1220 | |
Raymond Hettinger | d391d10 | 2005-06-07 18:50:56 +0000 | [diff] [blame] | 1221 | oldcontext = getcontext() |
| 1222 | setcontext(Context(traps=[Inexact])) |
| 1223 | try: |
| 1224 | while True: |
| 1225 | try: |
| 1226 | return mantissa * Decimal(2) ** exponent |
| 1227 | except Inexact: |
| 1228 | getcontext().prec += 1 |
| 1229 | finally: |
| 1230 | setcontext(oldcontext) |
| 1231 | \end{verbatim} |
| 1232 | |
| 1233 | |
| 1234 | Q. Why isn't the \function{floatToDecimal()} routine included in the module? |
| 1235 | |
| 1236 | A. There is some question about whether it is advisable to mix binary and |
| 1237 | decimal floating point. Also, its use requires some care to avoid the |
| 1238 | representation issues associated with binary floating point: |
| 1239 | |
| 1240 | \begin{verbatim} |
| 1241 | >>> floatToDecimal(1.1) |
| 1242 | Decimal("1.100000000000000088817841970012523233890533447265625") |
| 1243 | \end{verbatim} |
| 1244 | |
| 1245 | |
| 1246 | Q. Within a complex calculation, how can I make sure that I haven't gotten a |
| 1247 | spurious result because of insufficient precision or rounding anomalies. |
| 1248 | |
| 1249 | A. The decimal module makes it easy to test results. A best practice is to |
| 1250 | re-run calculations using greater precision and with various rounding modes. |
| 1251 | Widely differing results indicate insufficient precision, rounding mode |
| 1252 | issues, ill-conditioned inputs, or a numerically unstable algorithm. |
| 1253 | |
| 1254 | |
| 1255 | Q. I noticed that context precision is applied to the results of operations |
| 1256 | but not to the inputs. Is there anything to watch out for when mixing |
| 1257 | values of different precisions? |
| 1258 | |
| 1259 | A. Yes. The principle is that all values are considered to be exact and so |
| 1260 | is the arithmetic on those values. Only the results are rounded. The |
| 1261 | advantage for inputs is that ``what you type is what you get''. A |
| 1262 | disadvantage is that the results can look odd if you forget that the inputs |
| 1263 | haven't been rounded: |
| 1264 | |
| 1265 | \begin{verbatim} |
| 1266 | >>> getcontext().prec = 3 |
| 1267 | >>> Decimal('3.104') + D('2.104') |
| 1268 | Decimal("5.21") |
| 1269 | >>> Decimal('3.104') + D('0.000') + D('2.104') |
| 1270 | Decimal("5.20") |
| 1271 | \end{verbatim} |
| 1272 | |
| 1273 | The solution is either to increase precision or to force rounding of inputs |
| 1274 | using the unary plus operation: |
| 1275 | |
| 1276 | \begin{verbatim} |
| 1277 | >>> getcontext().prec = 3 |
| 1278 | >>> +Decimal('1.23456789') # unary plus triggers rounding |
| 1279 | Decimal("1.23") |
| 1280 | \end{verbatim} |
| 1281 | |
| 1282 | Alternatively, inputs can be rounded upon creation using the |
| 1283 | \method{Context.create_decimal()} method: |
| 1284 | |
| 1285 | \begin{verbatim} |
| 1286 | >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678') |
| 1287 | Decimal("1.2345") |
| 1288 | \end{verbatim} |