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