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