Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 1 | \section{\module{decimal} --- |
| 2 | Decimal floating point arithmetic} |
| 3 | |
| 4 | \declaremodule{standard}{decimal} |
| 5 | \modulesynopsis{Implementation of the General Decimal Arithmetic |
| 6 | Specification.} |
| 7 | |
| 8 | \moduleauthor{Eric Price}{eprice at tjhsst.edu} |
| 9 | \moduleauthor{Facundo Batista}{facundo at taniquetil.com.ar} |
| 10 | \moduleauthor{Raymond Hettinger}{python at rcn.com} |
| 11 | \moduleauthor{Aahz}{aahz at pobox.com} |
| 12 | \moduleauthor{Tim Peters}{tim.one at comcast.net} |
| 13 | |
| 14 | \sectionauthor{Raymond D. Hettinger}{python at rcn.com} |
| 15 | |
| 16 | \versionadded{2.4} |
| 17 | |
Raymond Hettinger | 97c9208 | 2004-07-09 06:13:12 +0000 | [diff] [blame] | 18 | The \module{decimal} module provides support for decimal floating point |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 19 | arithmetic. It offers several advantages over the \class{float()} datatype: |
| 20 | |
| 21 | \begin{itemize} |
| 22 | |
| 23 | \item Decimal numbers can be represented exactly. In contrast, numbers like |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 24 | \constant{1.1} do not have an exact representation in binary floating point. |
Raymond Hettinger | d7c7115 | 2004-07-12 13:22:14 +0000 | [diff] [blame] | 25 | End users typically would not expect \constant{1.1} to display as |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 26 | \constant{1.1000000000000001} as it does with binary floating point. |
| 27 | |
| 28 | \item The exactness carries over into arithmetic. In decimal floating point, |
| 29 | \samp{0.1 + 0.1 + 0.1 - 0.3} is exactly equal to zero. In binary floating |
| 30 | point, result is \constant{5.5511151231257827e-017}. While near to zero, the |
| 31 | differences prevent reliable equality testing and differences can accumulate. |
| 32 | For this reason, decimal would be preferred in accounting applications which |
| 33 | have strict equality invariants. |
| 34 | |
| 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 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 73 | rules, limits on exponents, flags indicating the results of operations, |
| 74 | and trap enablers which determine whether signals are treated as |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 75 | exceptions. Rounding options include \constant{ROUND_CEILING}, |
| 76 | \constant{ROUND_DOWN}, \constant{ROUND_FLOOR}, \constant{ROUND_HALF_DOWN}, |
| 77 | \constant{ROUND_HALF_EVEN}, \constant{ROUND_HALF_UP}, and \constant{ROUND_UP}. |
| 78 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 79 | Signals are groups of exceptional conditions arising during the course of |
| 80 | computation. Depending on the needs of the application, signals may be |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 81 | ignored, considered as informational, or treated as exceptions. The signals in |
| 82 | the decimal module are: \constant{Clamped}, \constant{InvalidOperation}, |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 83 | \constant{DivisionByZero}, \constant{Inexact}, \constant{Rounded}, |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 84 | \constant{Subnormal}, \constant{Overflow}, and \constant{Underflow}. |
| 85 | |
| 86 | For each signal there is a flag and a trap enabler. When a signal is |
| 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 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 107 | The usual start to using decimals is importing the module, viewing the current |
| 108 | context with \function{getcontext()} and, if necessary, setting new values |
| 109 | for precision, rounding, or enabled traps: |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 110 | |
| 111 | \begin{verbatim} |
| 112 | >>> from decimal import * |
| 113 | >>> getcontext() |
| 114 | Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 115 | capitals=1, flags=[], traps=[Overflow, InvalidOperation, |
| 116 | DivisionByZero]) |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 117 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 118 | >>> getcontext().prec = 7 # Set a new precision |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 119 | \end{verbatim} |
| 120 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 121 | |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 122 | Decimal instances can be constructed from integers, strings or tuples. To |
| 123 | create a Decimal from a \class{float}, first convert it to a string. This |
| 124 | serves as an explicit reminder of the details of the conversion (including |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 125 | representation error). Decimal numbers include special values such as |
| 126 | \constant{NaN} which stands for ``Not a number'', positive and negative |
| 127 | \constant{Infinity}, and \constant{-0}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 128 | |
| 129 | \begin{verbatim} |
| 130 | >>> Decimal(10) |
| 131 | Decimal("10") |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 132 | >>> Decimal("3.14") |
| 133 | Decimal("3.14") |
| 134 | >>> Decimal((0, (3, 1, 4), -2)) |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 135 | Decimal("3.14") |
| 136 | >>> Decimal(str(2.0 ** 0.5)) |
| 137 | Decimal("1.41421356237") |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 138 | >>> Decimal("NaN") |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 139 | Decimal("NaN") |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 140 | >>> Decimal("-Infinity") |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 141 | Decimal("-Infinity") |
| 142 | \end{verbatim} |
| 143 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 144 | |
| 145 | The significance of a new Decimal is determined solely by the number |
| 146 | of digits input. Context precision and rounding only come into play during |
| 147 | arithmetic operations. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 148 | |
| 149 | \begin{verbatim} |
| 150 | >>> getcontext().prec = 6 |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 151 | >>> Decimal('3.0') |
| 152 | Decimal("3.0") |
| 153 | >>> Decimal('3.1415926535') |
| 154 | Decimal("3.1415926535") |
| 155 | >>> Decimal('3.1415926535') + Decimal('2.7182818285') |
| 156 | Decimal("5.85987") |
| 157 | >>> getcontext().rounding = ROUND_UP |
| 158 | >>> Decimal('3.1415926535') + Decimal('2.7182818285') |
| 159 | Decimal("5.85988") |
| 160 | \end{verbatim} |
| 161 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 162 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 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 |
Raymond Hettinger | 9296023 | 2004-07-14 21:06:55 +0000 | [diff] [blame] | 182 | >>> round(a, 1) # round() first converts to binary floating point |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 183 | 1.3 |
| 184 | >>> int(a) |
| 185 | 1 |
| 186 | >>> a * 5 |
| 187 | Decimal("6.70") |
| 188 | >>> a * b |
| 189 | Decimal("2.5058") |
| 190 | >>> c % a |
| 191 | Decimal("0.77") |
| 192 | \end{verbatim} |
| 193 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 194 | The \method{quantize()} method rounds a number to a fixed exponent. This |
| 195 | method is useful for monetary applications that often round results to a fixed |
| 196 | number of places: |
| 197 | |
| 198 | \begin{verbatim} |
| 199 | >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN) |
| 200 | Decimal("7.32") |
| 201 | >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP) |
| 202 | Decimal("8") |
| 203 | \end{verbatim} |
| 204 | |
| 205 | As shown above, the \function{getcontext()} function accesses the current |
| 206 | context and allows the settings to be changed. This approach meets the |
| 207 | needs of most applications. |
| 208 | |
| 209 | For more advanced work, it may be useful to create alternate contexts using |
| 210 | the Context() constructor. To make an alternate active, use the |
| 211 | \function{setcontext()} function. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 212 | |
| 213 | In accordance with the standard, the \module{Decimal} module provides two |
| 214 | ready to use standard contexts, \constant{BasicContext} and |
| 215 | \constant{ExtendedContext}. The former is especially useful for debugging |
| 216 | because many of the traps are enabled: |
| 217 | |
| 218 | \begin{verbatim} |
| 219 | >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN) |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 220 | >>> setcontext(myothercontext) |
| 221 | >>> Decimal(1) / Decimal(7) |
| 222 | Decimal("0.142857142857142857142857142857142857142857142857142857142857") |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 223 | |
| 224 | >>> ExtendedContext |
| 225 | Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, |
| 226 | capitals=1, flags=[], traps=[]) |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 227 | >>> setcontext(ExtendedContext) |
| 228 | >>> Decimal(1) / Decimal(7) |
| 229 | Decimal("0.142857143") |
| 230 | >>> Decimal(42) / Decimal(0) |
| 231 | Decimal("Infinity") |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 232 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 233 | >>> setcontext(BasicContext) |
| 234 | >>> Decimal(42) / Decimal(0) |
| 235 | Traceback (most recent call last): |
| 236 | File "<pyshell#143>", line 1, in -toplevel- |
| 237 | Decimal(42) / Decimal(0) |
| 238 | DivisionByZero: x / 0 |
| 239 | \end{verbatim} |
| 240 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 241 | |
| 242 | Contexts also have signal flags for monitoring exceptional conditions |
| 243 | encountered during computations. The flags remain set until explicitly |
| 244 | cleared, so it is best to clear the flags before each set of monitored |
| 245 | computations by using the \method{clear_flags()} method. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 246 | |
| 247 | \begin{verbatim} |
| 248 | >>> setcontext(ExtendedContext) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 249 | >>> getcontext().clear_flags() |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 250 | >>> Decimal(355) / Decimal(113) |
| 251 | Decimal("3.14159292") |
| 252 | >>> getcontext() |
| 253 | Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 254 | capitals=1, flags=[Inexact, Rounded], traps=[]) |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 255 | \end{verbatim} |
| 256 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 257 | The \var{flags} entry shows that the rational approximation to \constant{Pi} |
| 258 | was rounded (digits beyond the context precision were thrown away) and that |
| 259 | the result is inexact (some of the discarded digits were non-zero). |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 260 | |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 261 | Individual traps are set using the dictionary in the \member{traps} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 262 | field of a context: |
| 263 | |
| 264 | \begin{verbatim} |
| 265 | >>> Decimal(1) / Decimal(0) |
| 266 | Decimal("Infinity") |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 267 | >>> getcontext().traps[DivisionByZero] = 1 |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 268 | >>> Decimal(1) / Decimal(0) |
| 269 | |
| 270 | Traceback (most recent call last): |
| 271 | File "<pyshell#112>", line 1, in -toplevel- |
| 272 | Decimal(1) / Decimal(0) |
| 273 | DivisionByZero: x / 0 |
| 274 | \end{verbatim} |
| 275 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 276 | Most programs adjust the current context only once, at the beginning of the |
| 277 | program. And, in many applications, data is converted to \class{Decimal} with |
| 278 | a single cast inside a loop. With context set and decimals created, the bulk |
| 279 | of the program manipulates the data no differently than with other Python |
| 280 | numeric types. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 281 | |
| 282 | |
| 283 | |
| 284 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 285 | \subsection{Decimal objects \label{decimal-decimal}} |
| 286 | |
| 287 | \begin{classdesc}{Decimal}{\optional{value \optional{, context}}} |
| 288 | Constructs a new \class{Decimal} object based from \var{value}. |
| 289 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 290 | \var{value} can be an integer, string, tuple, or another \class{Decimal} |
| 291 | object. If no \var{value} is given, returns \code{Decimal("0")}. If |
| 292 | \var{value} is a string, it should conform to the decimal numeric string |
| 293 | syntax: |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 294 | |
| 295 | \begin{verbatim} |
| 296 | sign ::= '+' | '-' |
| 297 | digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' |
| 298 | indicator ::= 'e' | 'E' |
| 299 | digits ::= digit [digit]... |
| 300 | decimal-part ::= digits '.' [digits] | ['.'] digits |
| 301 | exponent-part ::= indicator [sign] digits |
| 302 | infinity ::= 'Infinity' | 'Inf' |
| 303 | nan ::= 'NaN' [digits] | 'sNaN' [digits] |
| 304 | numeric-value ::= decimal-part [exponent-part] | infinity |
| 305 | numeric-string ::= [sign] numeric-value | [sign] nan |
| 306 | \end{verbatim} |
| 307 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 308 | If \var{value} is a \class{tuple}, it should have three components, |
| 309 | a sign (\constant{0} for positive or \constant{1} for negative), |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 310 | a \class{tuple} of digits, and an integer exponent. For example, |
| 311 | \samp{Decimal((0, (1, 4, 1, 4), -3))} returns \code{Decimal("1.414")}. |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 312 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 313 | The \var{context} precision does not affect how many digits are stored. |
| 314 | That is determined exclusively by the number of digits in \var{value}. For |
| 315 | example, \samp{Decimal("3.00000")} records all five zeroes even if the |
| 316 | context precision is only three. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 317 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 318 | The purpose of the \var{context} argument is determining what to do if |
| 319 | \var{value} is a malformed string. If the context traps |
| 320 | \constant{InvalidOperation}, an exception is raised; otherwise, the |
| 321 | constructor returns a new Decimal with the value of \constant{NaN}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 322 | |
| 323 | Once constructed, \class{Decimal} objects are immutable. |
| 324 | \end{classdesc} |
| 325 | |
| 326 | Decimal floating point objects share many properties with the other builtin |
| 327 | numeric types such as \class{float} and \class{int}. All of the usual |
| 328 | math operations and special methods apply. Likewise, decimal objects can |
| 329 | be copied, pickled, printed, used as dictionary keys, used as set elements, |
| 330 | compared, sorted, and coerced to another type (such as \class{float} |
| 331 | or \class{long}). |
| 332 | |
| 333 | In addition to the standard numeric properties, decimal floating point objects |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 334 | also have a number of specialized methods: |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 335 | |
| 336 | \begin{methoddesc}{adjusted}{} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 337 | Return the adjusted exponent after shifting out the coefficient's rightmost |
| 338 | digits until only the lead digit remains: \code{Decimal("321e+5").adjusted()} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 339 | returns seven. Used for determining the position of the most significant |
| 340 | digit with respect to the decimal point. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 341 | \end{methoddesc} |
| 342 | |
| 343 | \begin{methoddesc}{as_tuple}{} |
| 344 | Returns a tuple representation of the number: |
| 345 | \samp{(sign, digittuple, exponent)}. |
| 346 | \end{methoddesc} |
| 347 | |
| 348 | \begin{methoddesc}{compare}{other\optional{, context}} |
| 349 | Compares like \method{__cmp__()} but returns a decimal instance: |
| 350 | \begin{verbatim} |
| 351 | a or b is a NaN ==> Decimal("NaN") |
| 352 | a < b ==> Decimal("-1") |
| 353 | a == b ==> Decimal("0") |
| 354 | a > b ==> Decimal("1") |
| 355 | \end{verbatim} |
| 356 | \end{methoddesc} |
| 357 | |
| 358 | \begin{methoddesc}{max}{other\optional{, context}} |
| 359 | Like \samp{max(self, other)} but returns \constant{NaN} if either is a |
| 360 | \constant{NaN}. Applies the context rounding rule before returning. |
| 361 | \end{methoddesc} |
| 362 | |
| 363 | \begin{methoddesc}{min}{other\optional{, context}} |
| 364 | Like \samp{min(self, other)} but returns \constant{NaN} if either is a |
| 365 | \constant{NaN}. Applies the context rounding rule before returning. |
| 366 | \end{methoddesc} |
| 367 | |
| 368 | \begin{methoddesc}{normalize}{\optional{context}} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 369 | Normalize the number by stripping the rightmost trailing zeroes and |
| 370 | converting any result equal to \constant{Decimal("0")} to |
| 371 | \constant{Decimal("0e0")}. Used for producing canonical values for members |
| 372 | of an equivalence class. For example, \code{Decimal("32.100")} and |
| 373 | \code{Decimal("0.321000e+2")} both normalize to the equivalent value |
Raymond Hettinger | 8df4e6b | 2004-08-15 23:51:38 +0000 | [diff] [blame] | 374 | \code{Decimal("32.1")}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 375 | \end{methoddesc} |
| 376 | |
| 377 | \begin{methoddesc}{quantize} |
| 378 | {\optional{exp \optional{, rounding\optional{, context\optional{, watchexp}}}}} |
| 379 | Quantize makes the exponent the same as \var{exp}. Searches for a |
| 380 | rounding method in \var{rounding}, then in \var{context}, and then |
| 381 | in the current context. |
| 382 | |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 383 | If \var{watchexp} is set (default), then an error is returned whenever |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 384 | the resulting exponent is greater than \member{Emax} or less than |
| 385 | \member{Etiny}. |
| 386 | \end{methoddesc} |
| 387 | |
| 388 | \begin{methoddesc}{remainder_near}{other\optional{, context}} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 389 | Computes the modulo as either a positive or negative value depending |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 390 | on which is closest to zero. For instance, |
| 391 | \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")} |
| 392 | which is closer to zero than \code{Decimal("4")}. |
| 393 | |
| 394 | If both are equally close, the one chosen will have the same sign |
| 395 | as \var{self}. |
| 396 | \end{methoddesc} |
| 397 | |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 398 | \begin{methoddesc}{same_quantum}{other\optional{, context}} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 399 | Test whether self and other have the same exponent or whether both |
| 400 | are \constant{NaN}. |
| 401 | \end{methoddesc} |
| 402 | |
| 403 | \begin{methoddesc}{sqrt}{\optional{context}} |
| 404 | Return the square root to full precision. |
| 405 | \end{methoddesc} |
| 406 | |
| 407 | \begin{methoddesc}{to_eng_string}{\optional{context}} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 408 | Convert to an engineering-type string. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 409 | |
| 410 | Engineering notation has an exponent which is a multiple of 3, so there |
| 411 | are up to 3 digits left of the decimal place. For example, converts |
| 412 | \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")} |
| 413 | \end{methoddesc} |
| 414 | |
| 415 | \begin{methoddesc}{to_integral}{\optional{rounding\optional{, context}}} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 416 | Rounds to the nearest integer without signaling \constant{Inexact} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 417 | or \constant{Rounded}. If given, applies \var{rounding}; otherwise, |
| 418 | uses the rounding method in either the supplied \var{context} or the |
| 419 | current context. |
| 420 | \end{methoddesc} |
| 421 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 422 | |
| 423 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 424 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 425 | \subsection{Context objects \label{decimal-decimal}} |
| 426 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 427 | Contexts are environments for arithmetic operations. They govern precision, |
| 428 | set rules for rounding, determine which signals are treated as exceptions, and |
| 429 | limit the range for exponents. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 430 | |
| 431 | Each thread has its own current context which is accessed or changed using |
| 432 | the \function{getcontext()} and \function{setcontext()} functions: |
| 433 | |
| 434 | \begin{funcdesc}{getcontext}{} |
| 435 | Return the current context for the active thread. |
| 436 | \end{funcdesc} |
| 437 | |
| 438 | \begin{funcdesc}{setcontext}{c} |
| 439 | Set the current context for the active thread to \var{c}. |
| 440 | \end{funcdesc} |
| 441 | |
| 442 | New contexts can formed using the \class{Context} constructor described below. |
| 443 | In addition, the module provides three pre-made contexts: |
| 444 | |
| 445 | |
| 446 | \begin{classdesc*}{BasicContext} |
| 447 | This is a standard context defined by the General Decimal Arithmetic |
| 448 | Specification. Precision is set to nine. Rounding is set to |
| 449 | \constant{ROUND_HALF_UP}. All flags are cleared. All traps are enabled |
| 450 | (treated as exceptions) except \constant{Inexact}, \constant{Rounded}, and |
| 451 | \constant{Subnormal}. |
| 452 | |
| 453 | Because many of the traps are enabled, this context is useful for debugging. |
| 454 | \end{classdesc*} |
| 455 | |
| 456 | \begin{classdesc*}{ExtendedContext} |
| 457 | This is a standard context defined by the General Decimal Arithmetic |
| 458 | Specification. Precision is set to nine. Rounding is set to |
| 459 | \constant{ROUND_HALF_EVEN}. All flags are cleared. No traps are enabled |
| 460 | (so that exceptions are not raised during computations). |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 461 | |
| 462 | Because the trapped are disabled, this context is useful for applications |
| 463 | that prefer to have result value of \constant{NaN} or \constant{Infinity} |
| 464 | instead of raising exceptions. This allows an application to complete a |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 465 | run in the presence of conditions that would otherwise halt the program. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 466 | \end{classdesc*} |
| 467 | |
| 468 | \begin{classdesc*}{DefaultContext} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 469 | This context is used by the \class{Context} constructor as a prototype for |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 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 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 480 | at all. Instead, simply create contexts explicitly as described below. |
| 481 | |
| 482 | The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled |
| 483 | traps for Overflow, InvalidOperation, and DivisionByZero. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 484 | \end{classdesc*} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 485 | |
| 486 | |
| 487 | In addition to the three supplied contexts, new contexts can be created |
| 488 | with the \class{Context} constructor. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 489 | |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 490 | \begin{classdesc}{Context}{prec=None, rounding=None, traps=None, |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 491 | flags=None, Emin=None, Emax=None, capitals=1} |
| 492 | Creates a new context. If a field is not specified or is \constant{None}, |
| 493 | the default values are copied from the \constant{DefaultContext}. If the |
| 494 | \var{flags} field is not specified or is \constant{None}, all flags are |
| 495 | cleared. |
| 496 | |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 497 | 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] | 498 | arithmetic operations in the context. |
| 499 | |
Raymond Hettinger | 97c9208 | 2004-07-09 06:13:12 +0000 | [diff] [blame] | 500 | The \var{rounding} option is one of: |
| 501 | \constant{ROUND_CEILING} (towards \constant{Infinity}), |
| 502 | \constant{ROUND_DOWN} (towards zero), |
| 503 | \constant{ROUND_FLOOR} (towards \constant{-Infinity}), |
| 504 | \constant{ROUND_HALF_DOWN} (towards zero), |
| 505 | \constant{ROUND_HALF_EVEN}, |
| 506 | \constant{ROUND_HALF_UP} (away from zero), or |
| 507 | \constant{ROUND_UP} (away from zero). |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 508 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 509 | The \var{traps} and \var{flags} fields list any signals to be set. |
| 510 | Generally, new contexts should only set traps and leave the flags clear. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 511 | |
| 512 | The \var{Emin} and \var{Emax} fields are integers specifying the outer |
| 513 | limits allowable for exponents. |
| 514 | |
| 515 | The \var{capitals} field is either \constant{0} or \constant{1} (the |
| 516 | default). If set to \constant{1}, exponents are printed with a capital |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 517 | \constant{E}; otherwise, a lowercase \constant{e} is used: |
| 518 | \constant{Decimal('6.02e+23')}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 519 | \end{classdesc} |
| 520 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 521 | The \class{Context} class defines several general purpose methods as well as a |
| 522 | large number of methods for doing arithmetic directly in a given context. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 523 | |
| 524 | \begin{methoddesc}{clear_flags}{} |
| 525 | Sets all of the flags to \constant{0}. |
| 526 | \end{methoddesc} |
| 527 | |
| 528 | \begin{methoddesc}{copy}{} |
| 529 | Returns a duplicate of the context. |
| 530 | \end{methoddesc} |
| 531 | |
| 532 | \begin{methoddesc}{create_decimal}{num} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 533 | Creates a new Decimal instance from \var{num} but using \var{self} as |
| 534 | context. Unlike the \class{Decimal} constructor, the context precision, |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 535 | rounding method, flags, and traps are applied to the conversion. |
| 536 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 537 | This is useful because constants are often given to a greater precision than |
Raymond Hettinger | d7c7115 | 2004-07-12 13:22:14 +0000 | [diff] [blame] | 538 | is needed by the application. Another benefit is that rounding immediately |
| 539 | eliminates unintended effects from digits beyond the current precision. |
| 540 | In the following example, using unrounded inputs means that adding zero |
| 541 | to a sum can change the result: |
| 542 | |
| 543 | \begin{verbatim} |
| 544 | >>> getcontext().prec = 3 |
| 545 | >>> Decimal("3.4445") + Decimal("1.0023") |
| 546 | Decimal("4.45") |
| 547 | >>> Decimal("3.4445") + Decimal(0) + Decimal("1.0023") |
| 548 | Decimal("4.44") |
| 549 | \end{verbatim} |
| 550 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 551 | \end{methoddesc} |
| 552 | |
| 553 | \begin{methoddesc}{Etiny}{} |
| 554 | Returns a value equal to \samp{Emin - prec + 1} which is the minimum |
| 555 | exponent value for subnormal results. When underflow occurs, the |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 556 | exponent is set to \constant{Etiny}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 557 | \end{methoddesc} |
| 558 | |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 559 | \begin{methoddesc}{Etop}{} |
| 560 | Returns a value equal to \samp{Emax - prec + 1}. |
| 561 | \end{methoddesc} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 562 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 563 | |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 564 | The usual approach to working with decimals is to create \class{Decimal} |
| 565 | instances and then apply arithmetic operations which take place within the |
| 566 | current context for the active thread. An alternate approach is to use |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 567 | context methods for calculating within a specific context. The methods are |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 568 | similar to those for the \class{Decimal} class and are only briefly recounted |
| 569 | here. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 570 | |
| 571 | \begin{methoddesc}{abs}{x} |
| 572 | Returns the absolute value of \var{x}. |
| 573 | \end{methoddesc} |
| 574 | |
| 575 | \begin{methoddesc}{add}{x, y} |
| 576 | Return the sum of \var{x} and \var{y}. |
| 577 | \end{methoddesc} |
| 578 | |
| 579 | \begin{methoddesc}{compare}{x, y} |
| 580 | Compares values numerically. |
| 581 | |
| 582 | Like \method{__cmp__()} but returns a decimal instance: |
| 583 | \begin{verbatim} |
| 584 | a or b is a NaN ==> Decimal("NaN") |
| 585 | a < b ==> Decimal("-1") |
| 586 | a == b ==> Decimal("0") |
| 587 | a > b ==> Decimal("1") |
| 588 | \end{verbatim} |
| 589 | \end{methoddesc} |
| 590 | |
| 591 | \begin{methoddesc}{divide}{x, y} |
| 592 | Return \var{x} divided by \var{y}. |
| 593 | \end{methoddesc} |
| 594 | |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 595 | \begin{methoddesc}{divmod}{x, y} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 596 | Divides two numbers and returns the integer part of the result. |
| 597 | \end{methoddesc} |
| 598 | |
| 599 | \begin{methoddesc}{max}{x, y} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 600 | Compare two values numerically and return the maximum. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 601 | |
| 602 | If they are numerically equal then the left-hand operand is chosen as the |
| 603 | result. |
| 604 | \end{methoddesc} |
| 605 | |
| 606 | \begin{methoddesc}{min}{x, y} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 607 | Compare two values numerically and return the minimum. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 608 | |
| 609 | If they are numerically equal then the left-hand operand is chosen as the |
| 610 | result. |
| 611 | \end{methoddesc} |
| 612 | |
| 613 | \begin{methoddesc}{minus}{x} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 614 | Minus corresponds to the unary prefix minus operator in Python. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 615 | \end{methoddesc} |
| 616 | |
| 617 | \begin{methoddesc}{multiply}{x, y} |
| 618 | Return the product of \var{x} and \var{y}. |
| 619 | \end{methoddesc} |
| 620 | |
| 621 | \begin{methoddesc}{normalize}{x} |
| 622 | Normalize reduces an operand to its simplest form. |
| 623 | |
Raymond Hettinger | d7c7115 | 2004-07-12 13:22:14 +0000 | [diff] [blame] | 624 | Essentially a \method{plus} operation with all trailing zeros removed from |
| 625 | the result. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 626 | \end{methoddesc} |
| 627 | |
| 628 | \begin{methoddesc}{plus}{x} |
Raymond Hettinger | d7c7115 | 2004-07-12 13:22:14 +0000 | [diff] [blame] | 629 | Plus corresponds to the unary prefix plus operator in Python. This |
| 630 | operation applies the context precision and rounding, so it is |
| 631 | \emph{not} an identity operation. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 632 | \end{methoddesc} |
| 633 | |
| 634 | \begin{methoddesc}{power}{x, y\optional{, modulo}} |
| 635 | Return \samp{x ** y} to the \var{modulo} if given. |
| 636 | |
| 637 | The right-hand operand must be a whole number whose integer part (after any |
| 638 | exponent has been applied) has no more than 9 digits and whose fractional |
| 639 | part (if any) is all zeros before any rounding. The operand may be positive, |
| 640 | negative, or zero; if negative, the absolute value of the power is used, and |
| 641 | the left-hand operand is inverted (divided into 1) before use. |
| 642 | |
| 643 | If the increased precision needed for the intermediate calculations exceeds |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 644 | the capabilities of the implementation then an \constant{InvalidOperation} |
| 645 | condition is signaled. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 646 | |
| 647 | If, when raising to a negative power, an underflow occurs during the |
| 648 | division into 1, the operation is not halted at that point but continues. |
| 649 | \end{methoddesc} |
| 650 | |
| 651 | \begin{methoddesc}{quantize}{x, y} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 652 | Returns a value equal to \var{x} after rounding and having the exponent of |
| 653 | \var{y}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 654 | |
| 655 | Unlike other operations, if the length of the coefficient after the quantize |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 656 | operation would be greater than precision, then an |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 657 | \constant{InvalidOperation} is signaled. This guarantees that, unless there |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 658 | is an error condition, the quantized exponent is always equal to that of the |
| 659 | right-hand operand. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 660 | |
| 661 | Also unlike other operations, quantize never signals Underflow, even |
| 662 | if the result is subnormal and inexact. |
| 663 | \end{methoddesc} |
| 664 | |
| 665 | \begin{methoddesc}{remainder}{x, y} |
| 666 | Returns the remainder from integer division. |
| 667 | |
| 668 | The sign of the result, if non-zero, is the same as that of the original |
| 669 | dividend. |
| 670 | \end{methoddesc} |
| 671 | |
| 672 | \begin{methoddesc}{remainder_near}{x, y} |
| 673 | Computed the modulo as either a positive or negative value depending |
| 674 | on which is closest to zero. For instance, |
| 675 | \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")} |
| 676 | which is closer to zero than \code{Decimal("4")}. |
| 677 | |
| 678 | If both are equally close, the one chosen will have the same sign |
| 679 | as \var{self}. |
| 680 | \end{methoddesc} |
| 681 | |
| 682 | \begin{methoddesc}{same_quantum}{x, y} |
| 683 | Test whether \var{x} and \var{y} have the same exponent or whether both are |
| 684 | \constant{NaN}. |
| 685 | \end{methoddesc} |
| 686 | |
| 687 | \begin{methoddesc}{sqrt}{} |
| 688 | Return the square root to full precision. |
| 689 | \end{methoddesc} |
| 690 | |
| 691 | \begin{methoddesc}{substract}{x, y} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 692 | Return the difference between \var{x} and \var{y}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 693 | \end{methoddesc} |
| 694 | |
| 695 | \begin{methoddesc}{to_eng_string}{} |
| 696 | Convert to engineering-type string. |
| 697 | |
| 698 | Engineering notation has an exponent which is a multiple of 3, so there |
| 699 | are up to 3 digits left of the decimal place. For example, converts |
| 700 | \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")} |
| 701 | \end{methoddesc} |
| 702 | |
| 703 | \begin{methoddesc}{to_integral}{x} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 704 | Rounds to the nearest integer without signaling \constant{Inexact} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 705 | or \constant{Rounded}. |
| 706 | \end{methoddesc} |
| 707 | |
| 708 | \begin{methoddesc}{to_sci_string}{} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 709 | Converts a number to a string using scientific notation. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 710 | \end{methoddesc} |
| 711 | |
| 712 | |
| 713 | |
| 714 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 715 | \subsection{Signals \label{decimal-signals}} |
| 716 | |
| 717 | Signals represent conditions that arise during computation. |
| 718 | Each corresponds to one context flag and one context trap enabler. |
| 719 | |
| 720 | The context flag is incremented whenever the condition is encountered. |
| 721 | After the computation, flags may be checked for informational |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 722 | purposes (for instance, to determine whether a computation was exact). |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 723 | After checking the flags, be sure to clear all flags before starting |
| 724 | the next computation. |
| 725 | |
| 726 | If the context's trap enabler is set for the signal, then the condition |
| 727 | causes a Python exception to be raised. For example, if the |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 728 | \class{DivisionByZero} trap is set, then a \exception{DivisionByZero} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 729 | exception is raised upon encountering the condition. |
| 730 | |
| 731 | |
| 732 | \begin{classdesc*}{Clamped} |
| 733 | Altered an exponent to fit representation constraints. |
| 734 | |
| 735 | Typically, clamping occurs when an exponent falls outside the context's |
| 736 | \member{Emin} and \member{Emax} limits. If possible, the exponent is |
| 737 | reduced to fit by adding zeroes to the coefficient. |
| 738 | \end{classdesc*} |
| 739 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 740 | \begin{classdesc*}{DecimalException} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 741 | Base class for other signals and is a subclass of |
| 742 | \exception{ArithmeticError}. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 743 | \end{classdesc*} |
| 744 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 745 | \begin{classdesc*}{DivisionByZero} |
| 746 | Signals the division of a non-infinite number by zero. |
| 747 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 748 | Can occur with division, modulo division, or when raising a number to a |
| 749 | negative power. If this signal is not trapped, returns |
| 750 | \constant{Infinity} or \constant{-Infinity} with the sign determined by |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 751 | the inputs to the calculation. |
| 752 | \end{classdesc*} |
| 753 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 754 | \begin{classdesc*}{Inexact} |
| 755 | Indicates that rounding occurred and the result is not exact. |
| 756 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 757 | Signals when non-zero digits were discarded during rounding. The rounded |
| 758 | result is returned. The signal flag or trap is used to detect when |
| 759 | results are inexact. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 760 | \end{classdesc*} |
| 761 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 762 | \begin{classdesc*}{InvalidOperation} |
| 763 | An invalid operation was performed. |
| 764 | |
| 765 | Indicates that an operation was requested that does not make sense. |
| 766 | If not trapped, returns \constant{NaN}. Possible causes include: |
| 767 | |
| 768 | \begin{verbatim} |
| 769 | Infinity - Infinity |
| 770 | 0 * Infinity |
| 771 | Infinity / Infinity |
| 772 | x % 0 |
| 773 | Infinity % x |
| 774 | x._rescale( non-integer ) |
| 775 | sqrt(-x) and x > 0 |
| 776 | 0 ** 0 |
| 777 | x ** (non-integer) |
| 778 | x ** Infinity |
| 779 | \end{verbatim} |
| 780 | \end{classdesc*} |
| 781 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 782 | \begin{classdesc*}{Overflow} |
| 783 | Numerical overflow. |
| 784 | |
| 785 | Indicates the exponent is larger than \member{Emax} after rounding has |
| 786 | occurred. If not trapped, the result depends on the rounding mode, either |
| 787 | pulling inward to the largest representable finite number or rounding |
| 788 | outward to \constant{Infinity}. In either case, \class{Inexact} and |
| 789 | \class{Rounded} are also signaled. |
| 790 | \end{classdesc*} |
| 791 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 792 | \begin{classdesc*}{Rounded} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 793 | Rounding occurred though possibly no information was lost. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 794 | |
| 795 | Signaled whenever rounding discards digits; even if those digits are |
| 796 | zero (such as rounding \constant{5.00} to \constant{5.0}). If not |
| 797 | trapped, returns the result unchanged. This signal is used to detect |
| 798 | loss of significant digits. |
| 799 | \end{classdesc*} |
| 800 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 801 | \begin{classdesc*}{Subnormal} |
| 802 | Exponent was lower than \member{Emin} prior to rounding. |
| 803 | |
| 804 | Occurs when an operation result is subnormal (the exponent is too small). |
| 805 | If not trapped, returns the result unchanged. |
| 806 | \end{classdesc*} |
| 807 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 808 | \begin{classdesc*}{Underflow} |
| 809 | Numerical underflow with result rounded to zero. |
| 810 | |
| 811 | Occurs when a subnormal result is pushed to zero by rounding. |
| 812 | \class{Inexact} and \class{Subnormal} are also signaled. |
| 813 | \end{classdesc*} |
| 814 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 815 | The following table summarizes the hierarchy of signals: |
| 816 | |
| 817 | \begin{verbatim} |
| 818 | exceptions.ArithmeticError(exceptions.StandardError) |
| 819 | DecimalException |
| 820 | Clamped |
| 821 | DivisionByZero(DecimalException, exceptions.ZeroDivisionError) |
| 822 | Inexact |
| 823 | Overflow(Inexact, Rounded) |
| 824 | Underflow(Inexact, Rounded, Subnormal) |
| 825 | InvalidOperation |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 826 | Rounded |
| 827 | Subnormal |
| 828 | \end{verbatim} |
| 829 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 830 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 831 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
Raymond Hettinger | 2864b80 | 2004-08-15 23:47:48 +0000 | [diff] [blame] | 832 | \subsection{Floating Point Notes \label{decimal-notes}} |
| 833 | |
| 834 | The use of decimal floating point eliminates decimal representation error |
| 835 | (making it possible to represent \constant{0.1} exactly); however, some |
| 836 | operations can still incur round-off error when non-zero digits exceed the |
| 837 | fixed precision. |
| 838 | |
| 839 | The effects of round-off error can be amplified by the addition or subtraction |
| 840 | of nearly offsetting quantities resulting in loss of significance. Knuth |
| 841 | provides two instructive examples where rounded floating point arithmetic with |
| 842 | insufficient precision causes the break down of the associative and |
| 843 | distributive properties of addition: |
| 844 | |
| 845 | \begin{verbatim} |
| 846 | # Examples from Seminumerical Algorithms, Section 4.2.2. |
| 847 | >>> from decimal import * |
| 848 | >>> getcontext().prec = 8 |
| 849 | |
| 850 | >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') |
| 851 | >>> (u + v) + w |
| 852 | Decimal("9.5111111") |
| 853 | >>> u + (v + w) |
| 854 | Decimal("10") |
| 855 | |
| 856 | >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') |
| 857 | >>> (u*v) + (u*w) |
| 858 | Decimal("0.01") |
| 859 | >>> u * (v+w) |
| 860 | Decimal("0.0060000") |
| 861 | \end{verbatim} |
| 862 | |
| 863 | The \module{decimal} module makes it possible to restore the identities |
| 864 | by expanding the precision sufficiently to avoid loss of significance: |
| 865 | |
| 866 | \begin{verbatim} |
| 867 | >>> getcontext().prec = 20 |
| 868 | >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') |
| 869 | >>> (u + v) + w |
| 870 | Decimal("9.51111111") |
| 871 | >>> u + (v + w) |
| 872 | Decimal("9.51111111") |
| 873 | >>> |
| 874 | >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') |
| 875 | >>> (u*v) + (u*w) |
| 876 | Decimal("0.0060000") |
| 877 | >>> u * (v+w) |
| 878 | Decimal("0.0060000") |
| 879 | \end{verbatim} |
| 880 | |
| 881 | |
| 882 | The number system for the \module{decimal} module provides special |
| 883 | values including \constant{NaN}, \constant{sNaN}, \constant{-Infinity}, |
| 884 | \constant{Infinity}, and two zeroes, \constant{+0} and \constant{-0}. |
| 885 | |
Andrew M. Kuchling | 7ec7584 | 2004-08-16 16:12:23 +0000 | [diff] [blame] | 886 | Infinities can be constructed directly with: \code{Decimal('Infinity')}. Also, |
Raymond Hettinger | 2864b80 | 2004-08-15 23:47:48 +0000 | [diff] [blame] | 887 | they can arise from dividing by zero when the \exception{DivisionByZero} |
| 888 | signal is not trapped. Likewise, when the \exception{Overflow} signal is not |
| 889 | trapped, infinity can result from rounding beyond the limits of the largest |
| 890 | representable number. |
| 891 | |
| 892 | The infinities are signed (affine) and can be used in arithmetic operations |
| 893 | where they get treated as very large, indeterminate numbers. For instance, |
| 894 | adding a constant to infinity gives another infinite result. |
| 895 | |
| 896 | Some operations are indeterminate and return \constant{NaN} or when the |
| 897 | \exception{InvalidOperation} signal is trapped, raise an exception. For |
| 898 | example, \code{0/0} returns \constant{NaN} which means ``not a number''. This |
| 899 | variety of \constant{NaN} is quiet and, once created, will flow through other |
| 900 | computations always resulting in another \constant{NaN}. This behavior can be |
| 901 | useful for a series of computations that occasionally have missing inputs --- |
| 902 | it allows the calculation to proceed while flagging specific results as |
| 903 | invalid. |
| 904 | |
| 905 | A variant is \constant{sNaN} which signals rather than remaining quiet |
| 906 | after every operation. This is a useful return value when an invalid |
| 907 | result needs to interrupt a calculation for special handling. |
| 908 | |
| 909 | The signed zeros can result from calculations that underflow. |
| 910 | They keep the sign that would have resulted if the calculation had |
| 911 | been carried out to greater precision. Since their magnitude is |
| 912 | zero, the positive and negative zero are treated as equal and their |
| 913 | sign is informational. |
| 914 | |
| 915 | In addition to the two signed zeros which are distinct, yet equal, |
| 916 | there are various representations of zero with differing precisions, |
| 917 | yet equivalent in value. This takes a bit of getting used to. For |
| 918 | an eye accustomed to normalized floating point representations, it |
| 919 | is not immediately obvious that the following calculation returns |
| 920 | a value equal to zero: |
| 921 | |
| 922 | \begin{verbatim} |
| 923 | >>> 1 / Decimal('Infinity') |
| 924 | Decimal("0E-1000000026") |
| 925 | \end{verbatim} |
| 926 | |
| 927 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 928 | \subsection{Working with threads \label{decimal-threads}} |
| 929 | |
| 930 | The \function{getcontext()} function accesses a different \class{Context} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 931 | object for each thread. Having separate thread contexts means that threads |
| 932 | may make changes (such as \code{getcontext.prec=10}) without interfering with |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 933 | other threads. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 934 | |
| 935 | Likewise, the \function{setcontext()} function automatically assigns its target |
| 936 | to the current thread. |
| 937 | |
| 938 | If \function{setcontext()} has not been called before \function{getcontext()}, |
| 939 | then \function{getcontext()} will automatically create a new context for use |
| 940 | in the current thread. |
| 941 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 942 | The new context is copied from a prototype context called |
| 943 | \var{DefaultContext}. To control the defaults so that each thread will use the |
| 944 | same values throughout the application, directly modify the |
| 945 | \var{DefaultContext} object. This should be done \emph{before} any threads are |
| 946 | started so that there won't be a race condition between threads calling |
| 947 | \function{getcontext()}. For example: |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 948 | |
| 949 | \begin{verbatim} |
Raymond Hettinger | 536f76b | 2004-07-08 09:22:33 +0000 | [diff] [blame] | 950 | # Set applicationwide defaults for all threads about to be launched |
Raymond Hettinger | 9296023 | 2004-07-14 21:06:55 +0000 | [diff] [blame] | 951 | DefaultContext.prec = 12 |
| 952 | DefaultContext.rounding = ROUND_DOWN |
| 953 | DefaultContext.traps = ExtendedContext.traps.copy() |
| 954 | DefaultContext.traps[InvalidOperation] = 1 |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 955 | setcontext(DefaultContext) |
| 956 | |
Raymond Hettinger | 9296023 | 2004-07-14 21:06:55 +0000 | [diff] [blame] | 957 | # Afterwards, the threads can be started |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 958 | t1.start() |
| 959 | t2.start() |
| 960 | t3.start() |
| 961 | . . . |
| 962 | \end{verbatim} |
Raymond Hettinger | 2864b80 | 2004-08-15 23:47:48 +0000 | [diff] [blame] | 963 | |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 964 | |
| 965 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 966 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
| 967 | \subsection{Recipes \label{decimal-recipes}} |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 968 | |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 969 | Here are a few recipes that serve as utility functions and that demonstrate |
| 970 | ways to work with the \class{Decimal} class: |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 971 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 972 | \begin{verbatim} |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 973 | def moneyfmt(value, places=2, curr='', sep=',', dp='.', |
| 974 | pos='', neg='-', trailneg=''): |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 975 | """Convert Decimal to a money formatted string. |
Raymond Hettinger | 8de63a2 | 2004-07-05 05:52:03 +0000 | [diff] [blame] | 976 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 977 | places: required number of places after the decimal point |
| 978 | curr: optional currency symbol before the sign (may be blank) |
| 979 | sep: optional grouping separator (comma, period, or blank) |
| 980 | dp: decimal point indicator (comma or period) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 981 | only specify as blank when places is zero |
| 982 | pos: optional sign for positive numbers: "+", space or blank |
| 983 | neg: optional sign for negative numbers: "-", "(", space or blank |
| 984 | trailneg:optional trailing minus indicator: "-", ")", space or blank |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 985 | |
| 986 | >>> d = Decimal('-1234567.8901') |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 987 | >>> moneyfmt(d, curr='$') |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 988 | '-$1,234,567.89' |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 989 | >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-') |
| 990 | '1.234.568-' |
| 991 | >>> moneyfmt(d, curr='$', neg='(', trailneg=')') |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 992 | '($1,234,567.89)' |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 993 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 994 | """ |
| 995 | q = Decimal((0, (1,), -places)) # 2 places --> '0.01' |
| 996 | sign, digits, exp = value.quantize(q).as_tuple() |
| 997 | result = [] |
| 998 | digits = map(str, digits) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 999 | build, next = result.append, digits.pop |
| 1000 | if sign: |
| 1001 | build(trailneg) |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1002 | for i in range(places): |
| 1003 | build(next()) |
| 1004 | build(dp) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1005 | i = 0 |
| 1006 | while digits: |
| 1007 | build(next()) |
| 1008 | i += 1 |
| 1009 | if i == 3: |
| 1010 | i = 0 |
| 1011 | build(sep) |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1012 | build(curr) |
| 1013 | if sign: |
| 1014 | build(neg) |
| 1015 | else: |
| 1016 | build(pos) |
| 1017 | result.reverse() |
| 1018 | return ''.join(result) |
| 1019 | |
| 1020 | def pi(): |
Raymond Hettinger | c4f93d44 | 2004-07-05 20:17:13 +0000 | [diff] [blame] | 1021 | """Compute Pi to the current precision. |
| 1022 | |
| 1023 | >>> print pi() |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1024 | 3.141592653589793238462643383 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1025 | |
Raymond Hettinger | c4f93d44 | 2004-07-05 20:17:13 +0000 | [diff] [blame] | 1026 | """ |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1027 | getcontext().prec += 2 # extra digits for intermediate steps |
Raymond Hettinger | 10959b1 | 2004-07-05 21:13:28 +0000 | [diff] [blame] | 1028 | three = Decimal(3) # substitute "three=3.0" for regular floats |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1029 | lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 |
| 1030 | while s != lasts: |
| 1031 | lasts = s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1032 | n, na = n+na, na+8 |
| 1033 | d, da = d+da, da+32 |
| 1034 | t = (t * n) / d |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1035 | s += t |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1036 | getcontext().prec -= 2 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1037 | return +s # unary plus applies the new precision |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1038 | |
| 1039 | def exp(x): |
Raymond Hettinger | 10959b1 | 2004-07-05 21:13:28 +0000 | [diff] [blame] | 1040 | """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] | 1041 | |
| 1042 | >>> print exp(Decimal(1)) |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1043 | 2.718281828459045235360287471 |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1044 | >>> print exp(Decimal(2)) |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1045 | 7.389056098930650227230427461 |
Raymond Hettinger | 10959b1 | 2004-07-05 21:13:28 +0000 | [diff] [blame] | 1046 | >>> print exp(2.0) |
| 1047 | 7.38905609893 |
| 1048 | >>> print exp(2+0j) |
| 1049 | (7.38905609893+0j) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1050 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1051 | """ |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1052 | getcontext().prec += 2 |
| 1053 | i, lasts, s, fact, num = 0, 0, 1, 1, 1 |
| 1054 | while s != lasts: |
| 1055 | lasts = s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1056 | i += 1 |
| 1057 | fact *= i |
| 1058 | num *= x |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1059 | s += num / fact |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1060 | getcontext().prec -= 2 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1061 | return +s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1062 | |
| 1063 | def cos(x): |
| 1064 | """Return the cosine of x as measured in radians. |
| 1065 | |
| 1066 | >>> print cos(Decimal('0.5')) |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1067 | 0.8775825618903727161162815826 |
Raymond Hettinger | 10959b1 | 2004-07-05 21:13:28 +0000 | [diff] [blame] | 1068 | >>> print cos(0.5) |
| 1069 | 0.87758256189 |
| 1070 | >>> print cos(0.5+0j) |
| 1071 | (0.87758256189+0j) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1072 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1073 | """ |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1074 | getcontext().prec += 2 |
| 1075 | i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1 |
| 1076 | while s != lasts: |
| 1077 | lasts = s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1078 | i += 2 |
| 1079 | fact *= i * (i-1) |
| 1080 | num *= x * x |
| 1081 | sign *= -1 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1082 | s += num / fact * sign |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1083 | getcontext().prec -= 2 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1084 | return +s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1085 | |
| 1086 | def sin(x): |
| 1087 | """Return the cosine of x as measured in radians. |
| 1088 | |
| 1089 | >>> print sin(Decimal('0.5')) |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1090 | 0.4794255386042030002732879352 |
Raymond Hettinger | 10959b1 | 2004-07-05 21:13:28 +0000 | [diff] [blame] | 1091 | >>> print sin(0.5) |
| 1092 | 0.479425538604 |
| 1093 | >>> print sin(0.5+0j) |
| 1094 | (0.479425538604+0j) |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1095 | |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1096 | """ |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1097 | getcontext().prec += 2 |
| 1098 | i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1 |
| 1099 | while s != lasts: |
| 1100 | lasts = s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1101 | i += 2 |
| 1102 | fact *= i * (i-1) |
| 1103 | num *= x * x |
| 1104 | sign *= -1 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1105 | s += num / fact * sign |
Raymond Hettinger | 2f55eb4 | 2004-07-06 01:55:14 +0000 | [diff] [blame] | 1106 | getcontext().prec -= 2 |
Raymond Hettinger | 65df07b | 2004-07-11 12:40:19 +0000 | [diff] [blame] | 1107 | return +s |
Raymond Hettinger | d84efb3 | 2004-07-05 18:41:42 +0000 | [diff] [blame] | 1108 | |
| 1109 | \end{verbatim} |