Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | |
| 2 | :mod:`decimal` --- Decimal floating point arithmetic |
| 3 | ==================================================== |
| 4 | |
| 5 | .. module:: decimal |
| 6 | :synopsis: Implementation of the General Decimal Arithmetic Specification. |
| 7 | |
| 8 | |
| 9 | .. moduleauthor:: Eric Price <eprice at tjhsst.edu> |
| 10 | .. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar> |
| 11 | .. moduleauthor:: Raymond Hettinger <python at rcn.com> |
| 12 | .. moduleauthor:: Aahz <aahz at pobox.com> |
| 13 | .. moduleauthor:: Tim Peters <tim.one at comcast.net> |
| 14 | |
| 15 | |
| 16 | .. sectionauthor:: Raymond D. Hettinger <python at rcn.com> |
| 17 | |
| 18 | |
| 19 | .. versionadded:: 2.4 |
| 20 | |
| 21 | The :mod:`decimal` module provides support for decimal floating point |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 22 | arithmetic. It offers several advantages over the :class:`float` datatype: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 23 | |
| 24 | * Decimal numbers can be represented exactly. In contrast, numbers like |
| 25 | :const:`1.1` do not have an exact representation in binary floating point. End |
| 26 | users typically would not expect :const:`1.1` to display as |
| 27 | :const:`1.1000000000000001` as it does with binary floating point. |
| 28 | |
| 29 | * The exactness carries over into arithmetic. In decimal floating point, ``0.1 |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 30 | + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 31 | is :const:`5.5511151231257827e-017`. While near to zero, the differences |
| 32 | prevent reliable equality testing and differences can accumulate. For this |
| 33 | reason, decimal would be preferred in accounting applications which have strict |
| 34 | equality invariants. |
| 35 | |
| 36 | * The decimal module incorporates a notion of significant places so that ``1.30 |
| 37 | + 1.20`` is :const:`2.50`. The trailing zero is kept to indicate significance. |
| 38 | This is the customary presentation for monetary applications. For |
| 39 | multiplication, the "schoolbook" approach uses all the figures in the |
| 40 | multiplicands. For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 * |
| 41 | 1.20`` gives :const:`1.5600`. |
| 42 | |
| 43 | * Unlike hardware based binary floating point, the decimal module has a user |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 44 | alterable precision (defaulting to 28 places) which can be as large as needed for |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 45 | a given problem:: |
| 46 | |
| 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 | |
| 54 | * Both binary and decimal floating point are implemented in terms of published |
| 55 | standards. While the built-in float type exposes only a modest portion of its |
| 56 | capabilities, the decimal module exposes all required parts of the standard. |
| 57 | When needed, the programmer has full control over rounding and signal handling. |
| 58 | |
| 59 | The module design is centered around three concepts: the decimal number, the |
| 60 | context for arithmetic, and signals. |
| 61 | |
| 62 | A decimal number is immutable. It has a sign, coefficient digits, and an |
| 63 | exponent. To preserve significance, the coefficient digits do not truncate |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 64 | trailing zeros. Decimals also include special values such as |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 65 | :const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also |
| 66 | differentiates :const:`-0` from :const:`+0`. |
| 67 | |
| 68 | The context for arithmetic is an environment specifying precision, rounding |
| 69 | rules, limits on exponents, flags indicating the results of operations, and trap |
| 70 | enablers which determine whether signals are treated as exceptions. Rounding |
| 71 | options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`, |
| 72 | :const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`, |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 73 | :const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 74 | |
| 75 | Signals are groups of exceptional conditions arising during the course of |
| 76 | computation. Depending on the needs of the application, signals may be ignored, |
| 77 | considered as informational, or treated as exceptions. The signals in the |
| 78 | decimal module are: :const:`Clamped`, :const:`InvalidOperation`, |
| 79 | :const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`, |
| 80 | :const:`Overflow`, and :const:`Underflow`. |
| 81 | |
| 82 | For each signal there is a flag and a trap enabler. When a signal is |
| 83 | encountered, its flag is incremented from zero and, then, if the trap enabler is |
| 84 | set to one, an exception is raised. Flags are sticky, so the user needs to |
| 85 | reset them before monitoring a calculation. |
| 86 | |
| 87 | |
| 88 | .. seealso:: |
| 89 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 90 | * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic |
| 91 | Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 92 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 93 | * IEEE standard 854-1987, `Unofficial IEEE 854 Text |
| 94 | <http://www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html>`_. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 95 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 96 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 97 | |
| 98 | |
| 99 | .. _decimal-tutorial: |
| 100 | |
| 101 | Quick-start Tutorial |
| 102 | -------------------- |
| 103 | |
| 104 | The usual start to using decimals is importing the module, viewing the current |
| 105 | context with :func:`getcontext` and, if necessary, setting new values for |
| 106 | precision, rounding, or enabled traps:: |
| 107 | |
| 108 | >>> from decimal import * |
| 109 | >>> getcontext() |
| 110 | Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, |
| 111 | capitals=1, flags=[], traps=[Overflow, InvalidOperation, |
| 112 | DivisionByZero]) |
| 113 | |
| 114 | >>> getcontext().prec = 7 # Set a new precision |
| 115 | |
| 116 | Decimal instances can be constructed from integers, strings, or tuples. To |
| 117 | create a Decimal from a :class:`float`, first convert it to a string. This |
| 118 | serves as an explicit reminder of the details of the conversion (including |
| 119 | representation error). Decimal numbers include special values such as |
| 120 | :const:`NaN` which stands for "Not a number", positive and negative |
| 121 | :const:`Infinity`, and :const:`-0`. :: |
| 122 | |
| 123 | >>> Decimal(10) |
| 124 | Decimal("10") |
| 125 | >>> Decimal("3.14") |
| 126 | Decimal("3.14") |
| 127 | >>> Decimal((0, (3, 1, 4), -2)) |
| 128 | Decimal("3.14") |
| 129 | >>> Decimal(str(2.0 ** 0.5)) |
| 130 | Decimal("1.41421356237") |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 131 | >>> Decimal(2) ** Decimal("0.5") |
| 132 | Decimal("1.414213562373095048801688724") |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 133 | >>> Decimal("NaN") |
| 134 | Decimal("NaN") |
| 135 | >>> Decimal("-Infinity") |
| 136 | Decimal("-Infinity") |
| 137 | |
| 138 | The significance of a new Decimal is determined solely by the number of digits |
| 139 | input. Context precision and rounding only come into play during arithmetic |
| 140 | operations. :: |
| 141 | |
| 142 | >>> getcontext().prec = 6 |
| 143 | >>> Decimal('3.0') |
| 144 | Decimal("3.0") |
| 145 | >>> Decimal('3.1415926535') |
| 146 | Decimal("3.1415926535") |
| 147 | >>> Decimal('3.1415926535') + Decimal('2.7182818285') |
| 148 | Decimal("5.85987") |
| 149 | >>> getcontext().rounding = ROUND_UP |
| 150 | >>> Decimal('3.1415926535') + Decimal('2.7182818285') |
| 151 | Decimal("5.85988") |
| 152 | |
| 153 | Decimals interact well with much of the rest of Python. Here is a small decimal |
| 154 | floating point flying circus:: |
| 155 | |
| 156 | >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()) |
| 157 | >>> max(data) |
| 158 | Decimal("9.25") |
| 159 | >>> min(data) |
| 160 | Decimal("0.03") |
| 161 | >>> sorted(data) |
| 162 | [Decimal("0.03"), Decimal("1.00"), Decimal("1.34"), Decimal("1.87"), |
| 163 | Decimal("2.35"), Decimal("3.45"), Decimal("9.25")] |
| 164 | >>> sum(data) |
| 165 | Decimal("19.29") |
| 166 | >>> a,b,c = data[:3] |
| 167 | >>> str(a) |
| 168 | '1.34' |
| 169 | >>> float(a) |
| 170 | 1.3400000000000001 |
| 171 | >>> round(a, 1) # round() first converts to binary floating point |
| 172 | 1.3 |
| 173 | >>> int(a) |
| 174 | 1 |
| 175 | >>> a * 5 |
| 176 | Decimal("6.70") |
| 177 | >>> a * b |
| 178 | Decimal("2.5058") |
| 179 | >>> c % a |
| 180 | Decimal("0.77") |
| 181 | |
Andrew M. Kuchling | 6d407e4 | 2007-09-24 23:46:28 +0000 | [diff] [blame] | 182 | And some mathematical functions are also available to Decimal:: |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 183 | |
| 184 | >>> Decimal(2).sqrt() |
| 185 | Decimal("1.414213562373095048801688724") |
| 186 | >>> Decimal(1).exp() |
| 187 | Decimal("2.718281828459045235360287471") |
| 188 | >>> Decimal("10").ln() |
| 189 | Decimal("2.302585092994045684017991455") |
| 190 | >>> Decimal("10").log10() |
| 191 | Decimal("1") |
| 192 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 193 | The :meth:`quantize` method rounds a number to a fixed exponent. This method is |
| 194 | useful for monetary applications that often round results to a fixed number of |
| 195 | places:: |
| 196 | |
| 197 | >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN) |
| 198 | Decimal("7.32") |
| 199 | >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP) |
| 200 | Decimal("8") |
| 201 | |
| 202 | As shown above, the :func:`getcontext` function accesses the current context and |
| 203 | allows the settings to be changed. This approach meets the needs of most |
| 204 | applications. |
| 205 | |
| 206 | For more advanced work, it may be useful to create alternate contexts using the |
| 207 | Context() constructor. To make an alternate active, use the :func:`setcontext` |
| 208 | function. |
| 209 | |
| 210 | In accordance with the standard, the :mod:`Decimal` module provides two ready to |
| 211 | use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The |
| 212 | former is especially useful for debugging because many of the traps are |
| 213 | enabled:: |
| 214 | |
| 215 | >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN) |
| 216 | >>> setcontext(myothercontext) |
| 217 | >>> Decimal(1) / Decimal(7) |
| 218 | Decimal("0.142857142857142857142857142857142857142857142857142857142857") |
| 219 | |
| 220 | >>> ExtendedContext |
| 221 | Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, |
| 222 | capitals=1, flags=[], traps=[]) |
| 223 | >>> setcontext(ExtendedContext) |
| 224 | >>> Decimal(1) / Decimal(7) |
| 225 | Decimal("0.142857143") |
| 226 | >>> Decimal(42) / Decimal(0) |
| 227 | Decimal("Infinity") |
| 228 | |
| 229 | >>> setcontext(BasicContext) |
| 230 | >>> Decimal(42) / Decimal(0) |
| 231 | Traceback (most recent call last): |
| 232 | File "<pyshell#143>", line 1, in -toplevel- |
| 233 | Decimal(42) / Decimal(0) |
| 234 | DivisionByZero: x / 0 |
| 235 | |
| 236 | Contexts also have signal flags for monitoring exceptional conditions |
| 237 | encountered during computations. The flags remain set until explicitly cleared, |
| 238 | so it is best to clear the flags before each set of monitored computations by |
| 239 | using the :meth:`clear_flags` method. :: |
| 240 | |
| 241 | >>> setcontext(ExtendedContext) |
| 242 | >>> getcontext().clear_flags() |
| 243 | >>> Decimal(355) / Decimal(113) |
| 244 | Decimal("3.14159292") |
| 245 | >>> getcontext() |
| 246 | Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, |
| 247 | capitals=1, flags=[Inexact, Rounded], traps=[]) |
| 248 | |
| 249 | The *flags* entry shows that the rational approximation to :const:`Pi` was |
| 250 | rounded (digits beyond the context precision were thrown away) and that the |
| 251 | result is inexact (some of the discarded digits were non-zero). |
| 252 | |
| 253 | Individual traps are set using the dictionary in the :attr:`traps` field of a |
| 254 | context:: |
| 255 | |
| 256 | >>> Decimal(1) / Decimal(0) |
| 257 | Decimal("Infinity") |
| 258 | >>> getcontext().traps[DivisionByZero] = 1 |
| 259 | >>> Decimal(1) / Decimal(0) |
| 260 | Traceback (most recent call last): |
| 261 | File "<pyshell#112>", line 1, in -toplevel- |
| 262 | Decimal(1) / Decimal(0) |
| 263 | DivisionByZero: x / 0 |
| 264 | |
| 265 | Most programs adjust the current context only once, at the beginning of the |
| 266 | program. And, in many applications, data is converted to :class:`Decimal` with |
| 267 | a single cast inside a loop. With context set and decimals created, the bulk of |
| 268 | the program manipulates the data no differently than with other Python numeric |
| 269 | types. |
| 270 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 271 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 272 | |
| 273 | |
| 274 | .. _decimal-decimal: |
| 275 | |
| 276 | Decimal objects |
| 277 | --------------- |
| 278 | |
| 279 | |
| 280 | .. class:: Decimal([value [, context]]) |
| 281 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 282 | Construct a new :class:`Decimal` object based from *value*. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 283 | |
Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 284 | *value* can be an integer, string, tuple, or another :class:`Decimal` |
| 285 | object. If no *value* is given, returns ``Decimal("0")``. If *value* is a |
| 286 | string, it should conform to the decimal numeric string syntax after leading |
| 287 | and trailing whitespace characters are removed:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 288 | |
| 289 | sign ::= '+' | '-' |
| 290 | digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' |
| 291 | indicator ::= 'e' | 'E' |
| 292 | digits ::= digit [digit]... |
| 293 | decimal-part ::= digits '.' [digits] | ['.'] digits |
| 294 | exponent-part ::= indicator [sign] digits |
| 295 | infinity ::= 'Infinity' | 'Inf' |
| 296 | nan ::= 'NaN' [digits] | 'sNaN' [digits] |
| 297 | numeric-value ::= decimal-part [exponent-part] | infinity |
| 298 | numeric-string ::= [sign] numeric-value | [sign] nan |
| 299 | |
| 300 | If *value* is a :class:`tuple`, it should have three components, a sign |
| 301 | (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of |
| 302 | digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))`` |
| 303 | returns ``Decimal("1.414")``. |
| 304 | |
| 305 | The *context* precision does not affect how many digits are stored. That is |
| 306 | determined exclusively by the number of digits in *value*. For example, |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 307 | ``Decimal("3.00000")`` records all five zeros even if the context precision is |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 308 | only three. |
| 309 | |
| 310 | The purpose of the *context* argument is determining what to do if *value* is a |
| 311 | malformed string. If the context traps :const:`InvalidOperation`, an exception |
| 312 | is raised; otherwise, the constructor returns a new Decimal with the value of |
| 313 | :const:`NaN`. |
| 314 | |
| 315 | Once constructed, :class:`Decimal` objects are immutable. |
| 316 | |
Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 317 | .. versionchanged:: 2.6 |
| 318 | leading and trailing whitespace characters are permitted when |
| 319 | creating a Decimal instance from a string. |
| 320 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 321 | Decimal floating point objects share many properties with the other built-in |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 322 | numeric types such as :class:`float` and :class:`int`. All of the usual math |
| 323 | operations and special methods apply. Likewise, decimal objects can be copied, |
| 324 | pickled, printed, used as dictionary keys, used as set elements, compared, |
| 325 | sorted, and coerced to another type (such as :class:`float` or :class:`long`). |
| 326 | |
| 327 | In addition to the standard numeric properties, decimal floating point objects |
| 328 | also have a number of specialized methods: |
| 329 | |
| 330 | |
| 331 | .. method:: Decimal.adjusted() |
| 332 | |
| 333 | Return the adjusted exponent after shifting out the coefficient's rightmost |
| 334 | digits until only the lead digit remains: ``Decimal("321e+5").adjusted()`` |
| 335 | returns seven. Used for determining the position of the most significant digit |
| 336 | with respect to the decimal point. |
| 337 | |
| 338 | |
| 339 | .. method:: Decimal.as_tuple() |
| 340 | |
Georg Brandl | e3c3db5 | 2008-01-11 09:55:53 +0000 | [diff] [blame] | 341 | Return a :term:`named tuple` representation of the number: |
| 342 | ``DecimalTuple(sign, digits, exponent)``. |
| 343 | |
| 344 | .. versionchanged:: 2.6 |
| 345 | Use a named tuple. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 346 | |
| 347 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 348 | .. method:: Decimal.canonical() |
| 349 | |
| 350 | Return the canonical encoding of the argument. Currently, the |
| 351 | encoding of a :class:`Decimal` instance is always canonical, so |
| 352 | this operation returns its argument unchanged. |
| 353 | |
| 354 | .. versionadded:: 2.6 |
| 355 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 356 | .. method:: Decimal.compare(other[, context]) |
| 357 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 358 | Compare the values of two Decimal instances. This operation |
| 359 | behaves in the same way as the usual comparison method |
| 360 | :meth:`__cmp__`, except that :meth:`compare` returns a Decimal |
| 361 | instance rather than an integer, and if either operand is a NaN |
| 362 | then the result is a NaN:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 363 | |
| 364 | a or b is a NaN ==> Decimal("NaN") |
| 365 | a < b ==> Decimal("-1") |
| 366 | a == b ==> Decimal("0") |
| 367 | a > b ==> Decimal("1") |
| 368 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 369 | .. method:: Decimal.compare_signal(other[, context]) |
| 370 | |
| 371 | This operation is identical to the :meth:`compare` method, except |
| 372 | that all NaNs signal. That is, if neither operand is a signaling |
| 373 | NaN then any quiet NaN operand is treated as though it were a |
| 374 | signaling NaN. |
| 375 | |
| 376 | .. versionadded:: 2.6 |
| 377 | |
| 378 | .. method:: Decimal.compare_total(other) |
| 379 | |
| 380 | Compare two operands using their abstract representation rather |
| 381 | than their numerical value. Similar to the :meth:`compare` method, |
| 382 | but the result gives a total ordering on :class:`Decimal` |
| 383 | instances. Two :class:`Decimal` instances with the same numeric |
| 384 | value but different representations compare unequal in this |
| 385 | ordering:: |
| 386 | |
| 387 | >>> Decimal("12.0").compare_total(Decimal("12")) |
| 388 | Decimal("-1") |
| 389 | |
| 390 | Quiet and signaling NaNs are also included in the total ordering. |
| 391 | The result of this function is ``Decimal("0")`` if both operands |
| 392 | have the same representation, ``Decimal("-1")`` if the first |
| 393 | operand is lower in the total order than the second, and |
| 394 | ``Decimal("1")`` if the first operand is higher in the total order |
| 395 | than the second operand. See the specification for details of the |
| 396 | total order. |
| 397 | |
| 398 | .. versionadded:: 2.6 |
| 399 | |
| 400 | .. method:: Decimal.compare_total_mag(other) |
| 401 | |
| 402 | Compare two operands using their abstract representation rather |
| 403 | than their value as in :meth:`compare_total`, but ignoring the sign |
| 404 | of each operand. ``x.compare_total_mag(y)`` is equivalent to |
| 405 | ``x.copy_abs().compare_total(y.copy_abs())``. |
| 406 | |
| 407 | .. versionadded:: 2.6 |
| 408 | |
| 409 | .. method:: Decimal.copy_abs() |
| 410 | |
| 411 | Return the absolute value of the argument. This operation is |
| 412 | unaffected by the context and is quiet: no flags are changed and no |
| 413 | rounding is performed. |
| 414 | |
| 415 | .. versionadded:: 2.6 |
| 416 | |
| 417 | .. method:: Decimal.copy_negate() |
| 418 | |
| 419 | Return the negation of the argument. This operation is unaffected |
| 420 | by the context and is quiet: no flags are changed and no rounding |
| 421 | is performed. |
| 422 | |
| 423 | .. versionadded:: 2.6 |
| 424 | |
| 425 | .. method:: Decimal.copy_sign(other) |
| 426 | |
| 427 | Return a copy of the first operand with the sign set to be the |
| 428 | same as the sign of the second operand. For example:: |
| 429 | |
| 430 | >>> Decimal("2.3").copy_sign(Decimal("-1.5")) |
| 431 | Decimal("-2.3") |
| 432 | |
| 433 | This operation is unaffected by the context and is quiet: no flags |
| 434 | are changed and no rounding is performed. |
| 435 | |
| 436 | .. versionadded:: 2.6 |
| 437 | |
| 438 | .. method:: Decimal.exp([context]) |
| 439 | |
| 440 | Return the value of the (natural) exponential function ``e**x`` at the |
| 441 | given number. The result is correctly rounded using the |
| 442 | :const:`ROUND_HALF_EVEN` rounding mode. |
| 443 | |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 444 | >>> Decimal(1).exp() |
| 445 | Decimal("2.718281828459045235360287471") |
| 446 | >>> Decimal(321).exp() |
| 447 | Decimal("2.561702493119680037517373933E+139") |
| 448 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 449 | .. versionadded:: 2.6 |
| 450 | |
| 451 | .. method:: Decimal.fma(other, third[, context]) |
| 452 | |
| 453 | Fused multiply-add. Return self*other+third with no rounding of |
| 454 | the intermediate product self*other. |
| 455 | |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 456 | >>> Decimal(2).fma(3, 5) |
| 457 | Decimal("11") |
| 458 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 459 | .. versionadded:: 2.6 |
| 460 | |
| 461 | .. method:: Decimal.is_canonical() |
| 462 | |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 463 | Return :const:`True` if the argument is canonical and |
| 464 | :const:`False` otherwise. Currently, a :class:`Decimal` instance |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 465 | is always canonical, so this operation always returns |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 466 | :const:`True`. |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 467 | |
| 468 | .. versionadded:: 2.6 |
| 469 | |
| 470 | .. method:: is_finite() |
| 471 | |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 472 | Return :const:`True` if the argument is a finite number, and |
| 473 | :const:`False` if the argument is an infinity or a NaN. |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 474 | |
| 475 | .. versionadded:: 2.6 |
| 476 | |
| 477 | .. method:: is_infinite() |
| 478 | |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 479 | Return :const:`True` if the argument is either positive or |
| 480 | negative infinity and :const:`False` otherwise. |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 481 | |
| 482 | .. versionadded:: 2.6 |
| 483 | |
| 484 | .. method:: is_nan() |
| 485 | |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 486 | Return :const:`True` if the argument is a (quiet or signaling) |
| 487 | NaN and :const:`False` otherwise. |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 488 | |
| 489 | .. versionadded:: 2.6 |
| 490 | |
| 491 | .. method:: is_normal() |
| 492 | |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 493 | Return :const:`True` if the argument is a *normal* finite number. |
| 494 | Return :const:`False` if the argument is zero, subnormal, infinite |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 495 | or a NaN. |
| 496 | |
| 497 | .. versionadded:: 2.6 |
| 498 | |
| 499 | .. method:: is_qnan() |
| 500 | |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 501 | Return :const:`True` if the argument is a quiet NaN, and |
| 502 | :const:`False` otherwise. |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 503 | |
| 504 | .. versionadded:: 2.6 |
| 505 | |
| 506 | .. method:: is_signed() |
| 507 | |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 508 | Return :const:`True` if the argument has a negative sign and |
| 509 | :const:`False` otherwise. Note that zeros and NaNs can both carry |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 510 | signs. |
| 511 | |
| 512 | .. versionadded:: 2.6 |
| 513 | |
| 514 | .. method:: is_snan() |
| 515 | |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 516 | Return :const:`True` if the argument is a signaling NaN and |
| 517 | :const:`False` otherwise. |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 518 | |
| 519 | .. versionadded:: 2.6 |
| 520 | |
| 521 | .. method:: is_subnormal() |
| 522 | |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 523 | Return :const:`True` if the argument is subnormal, and |
| 524 | :const:`False` otherwise. |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 525 | |
| 526 | .. versionadded:: 2.6 |
| 527 | |
| 528 | .. method:: is_zero() |
| 529 | |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 530 | Return :const:`True` if the argument is a (positive or negative) |
| 531 | zero and :const:`False` otherwise. |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 532 | |
| 533 | .. versionadded:: 2.6 |
| 534 | |
| 535 | .. method:: Decimal.ln([context]) |
| 536 | |
| 537 | Return the natural (base e) logarithm of the operand. The result |
| 538 | is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding |
| 539 | mode. |
| 540 | |
| 541 | .. versionadded:: 2.6 |
| 542 | |
| 543 | .. method:: Decimal.log10([context]) |
| 544 | |
| 545 | Return the base ten logarithm of the operand. The result is |
| 546 | correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode. |
| 547 | |
| 548 | .. versionadded:: 2.6 |
| 549 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 550 | .. method:: Decimal.logb([context]) |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 551 | |
| 552 | For a nonzero number, return the adjusted exponent of its operand |
| 553 | as a :class:`Decimal` instance. If the operand is a zero then |
| 554 | ``Decimal("-Infinity")`` is returned and the |
| 555 | :const:`DivisionByZero` flag is raised. If the operand is an |
| 556 | infinity then ``Decimal("Infinity")`` is returned. |
| 557 | |
| 558 | .. versionadded:: 2.6 |
| 559 | |
| 560 | .. method:: Decimal.logical_and(other[, context]) |
| 561 | |
| 562 | :meth:`logical_and` is a logical operation which takes two |
| 563 | *logical operands* (see :ref:`logical_operands_label`). The result |
| 564 | is the digit-wise ``and`` of the two operands. |
| 565 | |
| 566 | .. versionadded:: 2.6 |
| 567 | |
| 568 | .. method:: Decimal.logical_invert(other[, context]) |
| 569 | |
| 570 | :meth:`logical_invert` is a logical operation. The argument must |
| 571 | be a *logical operand* (see :ref:`logical_operands_label`). The |
| 572 | result is the digit-wise inversion of the operand. |
| 573 | |
| 574 | .. versionadded:: 2.6 |
| 575 | |
| 576 | .. method:: Decimal.logical_or(other[, context]) |
| 577 | |
| 578 | :meth:`logical_or` is a logical operation which takes two *logical |
| 579 | operands* (see :ref:`logical_operands_label`). The result is the |
| 580 | digit-wise ``or`` of the two operands. |
| 581 | |
| 582 | .. versionadded:: 2.6 |
| 583 | |
| 584 | .. method:: Decimal.logical_xor(other[, context]) |
| 585 | |
| 586 | :meth:`logical_xor` is a logical operation which takes two |
| 587 | *logical operands* (see :ref:`logical_operands_label`). The result |
| 588 | is the digit-wise exclusive or of the two operands. |
| 589 | |
| 590 | .. versionadded:: 2.6 |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 591 | |
| 592 | .. method:: Decimal.max(other[, context]) |
| 593 | |
| 594 | Like ``max(self, other)`` except that the context rounding rule is applied |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 595 | before returning and that :const:`NaN` values are either signaled or ignored |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 596 | (depending on the context and whether they are signaling or quiet). |
| 597 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 598 | .. method:: Decimal.max_mag(other[, context]) |
| 599 | |
| 600 | Similar to the :meth:`max` method, but the comparison is done using |
| 601 | the absolute values of the operands. |
| 602 | |
| 603 | .. versionadded:: 2.6 |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 604 | |
| 605 | .. method:: Decimal.min(other[, context]) |
| 606 | |
| 607 | Like ``min(self, other)`` except that the context rounding rule is applied |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 608 | before returning and that :const:`NaN` values are either signaled or ignored |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 609 | (depending on the context and whether they are signaling or quiet). |
| 610 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 611 | .. method:: Decimal.min_mag(other[, context]) |
| 612 | |
| 613 | Similar to the :meth:`min` method, but the comparison is done using |
| 614 | the absolute values of the operands. |
| 615 | |
| 616 | .. versionadded:: 2.6 |
| 617 | |
| 618 | .. method:: Decimal.next_minus([context]) |
| 619 | |
| 620 | Return the largest number representable in the given context (or |
| 621 | in the current thread's context if no context is given) that is smaller |
| 622 | than the given operand. |
| 623 | |
| 624 | .. versionadded:: 2.6 |
| 625 | |
| 626 | .. method:: Decimal.next_plus([context]) |
| 627 | |
| 628 | Return the smallest number representable in the given context (or |
| 629 | in the current thread's context if no context is given) that is |
| 630 | larger than the given operand. |
| 631 | |
| 632 | .. versionadded:: 2.6 |
| 633 | |
| 634 | .. method:: Decimal.next_toward(other[, context]) |
| 635 | |
| 636 | If the two operands are unequal, return the number closest to the |
| 637 | first operand in the direction of the second operand. If both |
| 638 | operands are numerically equal, return a copy of the first operand |
| 639 | with the sign set to be the same as the sign of the second operand. |
| 640 | |
| 641 | .. versionadded:: 2.6 |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 642 | |
| 643 | .. method:: Decimal.normalize([context]) |
| 644 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 645 | Normalize the number by stripping the rightmost trailing zeros and converting |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 646 | any result equal to :const:`Decimal("0")` to :const:`Decimal("0e0")`. Used for |
| 647 | producing canonical values for members of an equivalence class. For example, |
| 648 | ``Decimal("32.100")`` and ``Decimal("0.321000e+2")`` both normalize to the |
| 649 | equivalent value ``Decimal("32.1")``. |
| 650 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 651 | .. method:: Decimal.number_class([context]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 652 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 653 | Return a string describing the *class* of the operand. The |
| 654 | returned value is one of the following ten strings. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 655 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 656 | * ``"-Infinity"``, indicating that the operand is negative infinity. |
| 657 | * ``"-Normal"``, indicating that the operand is a negative normal number. |
| 658 | * ``"-Subnormal"``, indicating that the operand is negative and subnormal. |
| 659 | * ``"-Zero"``, indicating that the operand is a negative zero. |
| 660 | * ``"+Zero"``, indicating that the operand is a positive zero. |
| 661 | * ``"+Subnormal"``, indicating that the operand is positive and subnormal. |
| 662 | * ``"+Normal"``, indicating that the operand is a positive normal number. |
| 663 | * ``"+Infinity"``, indicating that the operand is positive infinity. |
| 664 | * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). |
| 665 | * ``"sNaN"``, indicating that the operand is a signaling NaN. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 666 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 667 | .. versionadded:: 2.6 |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 668 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 669 | .. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]]) |
| 670 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 671 | Return a value equal to the first operand after rounding and |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 672 | having the exponent of the second operand. |
| 673 | |
Facundo Batista | e90bc3c | 2007-09-14 21:29:52 +0000 | [diff] [blame] | 674 | >>> Decimal("1.41421356").quantize(Decimal("1.000")) |
| 675 | Decimal("1.414") |
| 676 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 677 | Unlike other operations, if the length of the coefficient after the |
| 678 | quantize operation would be greater than precision, then an |
| 679 | :const:`InvalidOperation` is signaled. This guarantees that, unless |
| 680 | there is an error condition, the quantized exponent is always equal |
| 681 | to that of the right-hand operand. |
| 682 | |
| 683 | Also unlike other operations, quantize never signals Underflow, |
| 684 | even if the result is subnormal and inexact. |
| 685 | |
| 686 | If the exponent of the second operand is larger than that of the |
| 687 | first then rounding may be necessary. In this case, the rounding |
| 688 | mode is determined by the ``rounding`` argument if given, else by |
| 689 | the given ``context`` argument; if neither argument is given the |
| 690 | rounding mode of the current thread's context is used. |
| 691 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 692 | If *watchexp* is set (default), then an error is returned whenever the |
| 693 | resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`. |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 694 | |
| 695 | .. method:: Decimal.radix() |
| 696 | |
| 697 | Return ``Decimal(10)``, the radix (base) in which the |
| 698 | :class:`Decimal` class does all its arithmetic. Included for |
| 699 | compatibility with the specification. |
| 700 | |
| 701 | .. versionadded:: 2.6 |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 702 | |
| 703 | .. method:: Decimal.remainder_near(other[, context]) |
| 704 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 705 | Compute the modulo as either a positive or negative value depending on which is |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 706 | closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns |
| 707 | ``Decimal("-2")`` which is closer to zero than ``Decimal("4")``. |
| 708 | |
| 709 | If both are equally close, the one chosen will have the same sign as *self*. |
| 710 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 711 | .. method:: Decimal.rotate(other[, context]) |
| 712 | |
| 713 | Return the result of rotating the digits of the first operand by |
| 714 | an amount specified by the second operand. The second operand |
| 715 | must be an integer in the range -precision through precision. The |
| 716 | absolute value of the second operand gives the number of places to |
| 717 | rotate. If the second operand is positive then rotation is to the |
| 718 | left; otherwise rotation is to the right. The coefficient of the |
| 719 | first operand is padded on the left with zeros to length precision |
| 720 | if necessary. The sign and exponent of the first operand are |
| 721 | unchanged. |
| 722 | |
| 723 | .. versionadded:: 2.6 |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 724 | |
| 725 | .. method:: Decimal.same_quantum(other[, context]) |
| 726 | |
| 727 | Test whether self and other have the same exponent or whether both are |
| 728 | :const:`NaN`. |
| 729 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 730 | .. method:: Decimal.scaleb(other[, context]) |
| 731 | |
| 732 | Return the first operand with exponent adjusted by the second. |
| 733 | Equivalently, return the first operand multiplied by ``10**other``. |
| 734 | The second operand must be an integer. |
| 735 | |
| 736 | .. versionadded:: 2.6 |
| 737 | |
| 738 | .. method:: Decimal.shift(other[, context]) |
| 739 | |
| 740 | Return the result of shifting the digits of the first operand by |
| 741 | an amount specified by the second operand. The second operand must |
| 742 | be an integer in the range -precision through precision. The |
| 743 | absolute value of the second operand gives the number of places to |
| 744 | shift. If the second operand is positive then the shift is to the |
| 745 | left; otherwise the shift is to the right. Digits shifted into the |
| 746 | coefficient are zeros. The sign and exponent of the first operand |
| 747 | are unchanged. |
| 748 | |
| 749 | .. versionadded:: 2.6 |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 750 | |
| 751 | .. method:: Decimal.sqrt([context]) |
| 752 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 753 | Return the square root of the argument to full precision. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 754 | |
| 755 | |
| 756 | .. method:: Decimal.to_eng_string([context]) |
| 757 | |
| 758 | Convert to an engineering-type string. |
| 759 | |
| 760 | Engineering notation has an exponent which is a multiple of 3, so there are up |
| 761 | to 3 digits left of the decimal place. For example, converts |
| 762 | ``Decimal('123E+1')`` to ``Decimal("1.23E+3")`` |
| 763 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 764 | .. method:: Decimal.to_integral([rounding[, context]]) |
| 765 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 766 | Identical to the :meth:`to_integral_value` method. The ``to_integral`` |
| 767 | name has been kept for compatibility with older versions. |
| 768 | |
| 769 | .. method:: Decimal.to_integral_exact([rounding[, context]]) |
| 770 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 771 | Round to the nearest integer, signaling |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 772 | :const:`Inexact` or :const:`Rounded` as appropriate if rounding |
| 773 | occurs. The rounding mode is determined by the ``rounding`` |
| 774 | parameter if given, else by the given ``context``. If neither |
| 775 | parameter is given then the rounding mode of the current context is |
| 776 | used. |
| 777 | |
| 778 | .. versionadded:: 2.6 |
| 779 | |
| 780 | .. method:: Decimal.to_integral_value([rounding[, context]]) |
| 781 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 782 | Round to the nearest integer without signaling :const:`Inexact` or |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 783 | :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding |
| 784 | method in either the supplied *context* or the current context. |
| 785 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 786 | .. versionchanged:: 2.6 |
| 787 | renamed from ``to_integral`` to ``to_integral_value``. The old name |
| 788 | remains valid for compatibility. |
| 789 | |
| 790 | .. method:: Decimal.trim() |
| 791 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 792 | Return the decimal with *insignificant* trailing zeros removed. |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 793 | Here, a trailing zero is considered insignificant either if it |
| 794 | follows the decimal point, or if the exponent of the argument (that |
| 795 | is, the last element of the :meth:`as_tuple` representation) is |
| 796 | positive. |
| 797 | |
| 798 | .. versionadded:: 2.6 |
| 799 | |
| 800 | .. _logical_operands_label: |
| 801 | |
| 802 | Logical operands |
| 803 | ^^^^^^^^^^^^^^^^ |
| 804 | |
| 805 | The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`, |
| 806 | and :meth:`logical_xor` methods expect their arguments to be *logical |
| 807 | operands*. A *logical operand* is a :class:`Decimal` instance whose |
| 808 | exponent and sign are both zero, and whose digits are all either |
| 809 | :const:`0` or :const:`1`. |
| 810 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 811 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 812 | |
| 813 | |
| 814 | .. _decimal-context: |
| 815 | |
| 816 | Context objects |
| 817 | --------------- |
| 818 | |
| 819 | Contexts are environments for arithmetic operations. They govern precision, set |
| 820 | rules for rounding, determine which signals are treated as exceptions, and limit |
| 821 | the range for exponents. |
| 822 | |
| 823 | Each thread has its own current context which is accessed or changed using the |
| 824 | :func:`getcontext` and :func:`setcontext` functions: |
| 825 | |
| 826 | |
| 827 | .. function:: getcontext() |
| 828 | |
| 829 | Return the current context for the active thread. |
| 830 | |
| 831 | |
| 832 | .. function:: setcontext(c) |
| 833 | |
| 834 | Set the current context for the active thread to *c*. |
| 835 | |
| 836 | Beginning with Python 2.5, you can also use the :keyword:`with` statement and |
| 837 | the :func:`localcontext` function to temporarily change the active context. |
| 838 | |
| 839 | |
| 840 | .. function:: localcontext([c]) |
| 841 | |
| 842 | Return a context manager that will set the current context for the active thread |
| 843 | to a copy of *c* on entry to the with-statement and restore the previous context |
| 844 | when exiting the with-statement. If no context is specified, a copy of the |
| 845 | current context is used. |
| 846 | |
| 847 | .. versionadded:: 2.5 |
| 848 | |
| 849 | For example, the following code sets the current decimal precision to 42 places, |
| 850 | performs a calculation, and then automatically restores the previous context:: |
| 851 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 852 | from decimal import localcontext |
| 853 | |
| 854 | with localcontext() as ctx: |
| 855 | ctx.prec = 42 # Perform a high precision calculation |
| 856 | s = calculate_something() |
| 857 | s = +s # Round the final result back to the default precision |
| 858 | |
| 859 | New contexts can also be created using the :class:`Context` constructor |
| 860 | described below. In addition, the module provides three pre-made contexts: |
| 861 | |
| 862 | |
| 863 | .. class:: BasicContext |
| 864 | |
| 865 | This is a standard context defined by the General Decimal Arithmetic |
| 866 | Specification. Precision is set to nine. Rounding is set to |
| 867 | :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated |
| 868 | as exceptions) except :const:`Inexact`, :const:`Rounded`, and |
| 869 | :const:`Subnormal`. |
| 870 | |
| 871 | Because many of the traps are enabled, this context is useful for debugging. |
| 872 | |
| 873 | |
| 874 | .. class:: ExtendedContext |
| 875 | |
| 876 | This is a standard context defined by the General Decimal Arithmetic |
| 877 | Specification. Precision is set to nine. Rounding is set to |
| 878 | :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that |
| 879 | exceptions are not raised during computations). |
| 880 | |
| 881 | Because the trapped are disabled, this context is useful for applications that |
| 882 | prefer to have result value of :const:`NaN` or :const:`Infinity` instead of |
| 883 | raising exceptions. This allows an application to complete a run in the |
| 884 | presence of conditions that would otherwise halt the program. |
| 885 | |
| 886 | |
| 887 | .. class:: DefaultContext |
| 888 | |
| 889 | This context is used by the :class:`Context` constructor as a prototype for new |
| 890 | contexts. Changing a field (such a precision) has the effect of changing the |
| 891 | default for new contexts creating by the :class:`Context` constructor. |
| 892 | |
| 893 | This context is most useful in multi-threaded environments. Changing one of the |
| 894 | fields before threads are started has the effect of setting system-wide |
| 895 | defaults. Changing the fields after threads have started is not recommended as |
| 896 | it would require thread synchronization to prevent race conditions. |
| 897 | |
| 898 | In single threaded environments, it is preferable to not use this context at |
| 899 | all. Instead, simply create contexts explicitly as described below. |
| 900 | |
| 901 | The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps |
| 902 | for Overflow, InvalidOperation, and DivisionByZero. |
| 903 | |
| 904 | In addition to the three supplied contexts, new contexts can be created with the |
| 905 | :class:`Context` constructor. |
| 906 | |
| 907 | |
| 908 | .. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1) |
| 909 | |
| 910 | Creates a new context. If a field is not specified or is :const:`None`, the |
| 911 | default values are copied from the :const:`DefaultContext`. If the *flags* |
| 912 | field is not specified or is :const:`None`, all flags are cleared. |
| 913 | |
| 914 | The *prec* field is a positive integer that sets the precision for arithmetic |
| 915 | operations in the context. |
| 916 | |
| 917 | The *rounding* option is one of: |
| 918 | |
| 919 | * :const:`ROUND_CEILING` (towards :const:`Infinity`), |
| 920 | * :const:`ROUND_DOWN` (towards zero), |
| 921 | * :const:`ROUND_FLOOR` (towards :const:`-Infinity`), |
| 922 | * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero), |
| 923 | * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer), |
| 924 | * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or |
| 925 | * :const:`ROUND_UP` (away from zero). |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 926 | * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero |
| 927 | would have been 0 or 5; otherwise towards zero) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 928 | |
| 929 | The *traps* and *flags* fields list any signals to be set. Generally, new |
| 930 | contexts should only set traps and leave the flags clear. |
| 931 | |
| 932 | The *Emin* and *Emax* fields are integers specifying the outer limits allowable |
| 933 | for exponents. |
| 934 | |
| 935 | The *capitals* field is either :const:`0` or :const:`1` (the default). If set to |
| 936 | :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a |
| 937 | lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`. |
| 938 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 939 | .. versionchanged:: 2.6 |
| 940 | The :const:`ROUND_05UP` rounding mode was added. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 941 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 942 | The :class:`Context` class defines several general purpose methods as |
| 943 | well as a large number of methods for doing arithmetic directly in a |
| 944 | given context. In addition, for each of the :class:`Decimal` methods |
| 945 | described above (with the exception of the :meth:`adjusted` and |
| 946 | :meth:`as_tuple` methods) there is a corresponding :class:`Context` |
| 947 | method. For example, ``C.exp(x)`` is equivalent to |
| 948 | ``x.exp(context=C)``. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 949 | |
| 950 | .. method:: Context.clear_flags() |
| 951 | |
| 952 | Resets all of the flags to :const:`0`. |
| 953 | |
| 954 | |
| 955 | .. method:: Context.copy() |
| 956 | |
| 957 | Return a duplicate of the context. |
| 958 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 959 | .. method:: Context.copy_decimal(num) |
| 960 | |
| 961 | Return a copy of the Decimal instance num. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 962 | |
| 963 | .. method:: Context.create_decimal(num) |
| 964 | |
| 965 | Creates a new Decimal instance from *num* but using *self* as context. Unlike |
| 966 | the :class:`Decimal` constructor, the context precision, rounding method, flags, |
| 967 | and traps are applied to the conversion. |
| 968 | |
| 969 | This is useful because constants are often given to a greater precision than is |
| 970 | needed by the application. Another benefit is that rounding immediately |
| 971 | eliminates unintended effects from digits beyond the current precision. In the |
| 972 | following example, using unrounded inputs means that adding zero to a sum can |
| 973 | change the result:: |
| 974 | |
| 975 | >>> getcontext().prec = 3 |
| 976 | >>> Decimal("3.4445") + Decimal("1.0023") |
| 977 | Decimal("4.45") |
| 978 | >>> Decimal("3.4445") + Decimal(0) + Decimal("1.0023") |
| 979 | Decimal("4.44") |
| 980 | |
Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 981 | This method implements the to-number operation of the IBM |
| 982 | specification. If the argument is a string, no leading or trailing |
| 983 | whitespace is permitted. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 984 | |
| 985 | .. method:: Context.Etiny() |
| 986 | |
| 987 | Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value |
| 988 | for subnormal results. When underflow occurs, the exponent is set to |
| 989 | :const:`Etiny`. |
| 990 | |
| 991 | |
| 992 | .. method:: Context.Etop() |
| 993 | |
| 994 | Returns a value equal to ``Emax - prec + 1``. |
| 995 | |
| 996 | The usual approach to working with decimals is to create :class:`Decimal` |
| 997 | instances and then apply arithmetic operations which take place within the |
Georg Brandl | 5d242ee | 2007-09-20 08:44:59 +0000 | [diff] [blame] | 998 | current context for the active thread. An alternative approach is to use context |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 999 | methods for calculating within a specific context. The methods are similar to |
| 1000 | those for the :class:`Decimal` class and are only briefly recounted here. |
| 1001 | |
| 1002 | |
| 1003 | .. method:: Context.abs(x) |
| 1004 | |
| 1005 | Returns the absolute value of *x*. |
| 1006 | |
| 1007 | |
| 1008 | .. method:: Context.add(x, y) |
| 1009 | |
| 1010 | Return the sum of *x* and *y*. |
| 1011 | |
| 1012 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1013 | .. method:: Context.divide(x, y) |
| 1014 | |
| 1015 | Return *x* divided by *y*. |
| 1016 | |
| 1017 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1018 | .. method:: Context.divide_int(x, y) |
| 1019 | |
| 1020 | Return *x* divided by *y*, truncated to an integer. |
| 1021 | |
| 1022 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1023 | .. method:: Context.divmod(x, y) |
| 1024 | |
| 1025 | Divides two numbers and returns the integer part of the result. |
| 1026 | |
| 1027 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1028 | .. method:: Context.minus(x) |
| 1029 | |
| 1030 | Minus corresponds to the unary prefix minus operator in Python. |
| 1031 | |
| 1032 | |
| 1033 | .. method:: Context.multiply(x, y) |
| 1034 | |
| 1035 | Return the product of *x* and *y*. |
| 1036 | |
| 1037 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1038 | .. method:: Context.plus(x) |
| 1039 | |
| 1040 | Plus corresponds to the unary prefix plus operator in Python. This operation |
| 1041 | applies the context precision and rounding, so it is *not* an identity |
| 1042 | operation. |
| 1043 | |
| 1044 | |
| 1045 | .. method:: Context.power(x, y[, modulo]) |
| 1046 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1047 | Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if |
| 1048 | given. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1049 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1050 | With two arguments, compute ``x**y``. If ``x`` is negative then |
| 1051 | ``y`` must be integral. The result will be inexact unless ``y`` is |
| 1052 | integral and the result is finite and can be expressed exactly in |
| 1053 | 'precision' digits. The result should always be correctly rounded, |
| 1054 | using the rounding mode of the current thread's context. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1055 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1056 | With three arguments, compute ``(x**y) % modulo``. For the three |
| 1057 | argument form, the following restrictions on the arguments hold: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1058 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1059 | - all three arguments must be integral |
| 1060 | - ``y`` must be nonnegative |
| 1061 | - at least one of ``x`` or ``y`` must be nonzero |
| 1062 | - ``modulo`` must be nonzero and have at most 'precision' digits |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1063 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1064 | The result of ``Context.power(x, y, modulo)`` is identical to |
| 1065 | the result that would be obtained by computing ``(x**y) % |
| 1066 | modulo`` with unbounded precision, but is computed more |
| 1067 | efficiently. It is always exact. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1068 | |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1069 | .. versionchanged:: 2.6 |
| 1070 | ``y`` may now be nonintegral in ``x**y``. |
| 1071 | Stricter requirements for the three-argument version. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1072 | |
| 1073 | |
| 1074 | .. method:: Context.remainder(x, y) |
| 1075 | |
| 1076 | Returns the remainder from integer division. |
| 1077 | |
| 1078 | The sign of the result, if non-zero, is the same as that of the original |
| 1079 | dividend. |
| 1080 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1081 | .. method:: Context.subtract(x, y) |
| 1082 | |
| 1083 | Return the difference between *x* and *y*. |
| 1084 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1085 | .. method:: Context.to_sci_string(x) |
| 1086 | |
| 1087 | Converts a number to a string using scientific notation. |
| 1088 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 1089 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1090 | |
| 1091 | |
| 1092 | .. _decimal-signals: |
| 1093 | |
| 1094 | Signals |
| 1095 | ------- |
| 1096 | |
| 1097 | Signals represent conditions that arise during computation. Each corresponds to |
| 1098 | one context flag and one context trap enabler. |
| 1099 | |
| 1100 | The context flag is incremented whenever the condition is encountered. After the |
| 1101 | computation, flags may be checked for informational purposes (for instance, to |
| 1102 | determine whether a computation was exact). After checking the flags, be sure to |
| 1103 | clear all flags before starting the next computation. |
| 1104 | |
| 1105 | If the context's trap enabler is set for the signal, then the condition causes a |
| 1106 | Python exception to be raised. For example, if the :class:`DivisionByZero` trap |
| 1107 | is set, then a :exc:`DivisionByZero` exception is raised upon encountering the |
| 1108 | condition. |
| 1109 | |
| 1110 | |
| 1111 | .. class:: Clamped |
| 1112 | |
| 1113 | Altered an exponent to fit representation constraints. |
| 1114 | |
| 1115 | Typically, clamping occurs when an exponent falls outside the context's |
| 1116 | :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1117 | fit by adding zeros to the coefficient. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1118 | |
| 1119 | |
| 1120 | .. class:: DecimalException |
| 1121 | |
| 1122 | Base class for other signals and a subclass of :exc:`ArithmeticError`. |
| 1123 | |
| 1124 | |
| 1125 | .. class:: DivisionByZero |
| 1126 | |
| 1127 | Signals the division of a non-infinite number by zero. |
| 1128 | |
| 1129 | Can occur with division, modulo division, or when raising a number to a negative |
| 1130 | power. If this signal is not trapped, returns :const:`Infinity` or |
| 1131 | :const:`-Infinity` with the sign determined by the inputs to the calculation. |
| 1132 | |
| 1133 | |
| 1134 | .. class:: Inexact |
| 1135 | |
| 1136 | Indicates that rounding occurred and the result is not exact. |
| 1137 | |
| 1138 | Signals when non-zero digits were discarded during rounding. The rounded result |
| 1139 | is returned. The signal flag or trap is used to detect when results are |
| 1140 | inexact. |
| 1141 | |
| 1142 | |
| 1143 | .. class:: InvalidOperation |
| 1144 | |
| 1145 | An invalid operation was performed. |
| 1146 | |
| 1147 | Indicates that an operation was requested that does not make sense. If not |
| 1148 | trapped, returns :const:`NaN`. Possible causes include:: |
| 1149 | |
| 1150 | Infinity - Infinity |
| 1151 | 0 * Infinity |
| 1152 | Infinity / Infinity |
| 1153 | x % 0 |
| 1154 | Infinity % x |
| 1155 | x._rescale( non-integer ) |
| 1156 | sqrt(-x) and x > 0 |
| 1157 | 0 ** 0 |
| 1158 | x ** (non-integer) |
| 1159 | x ** Infinity |
| 1160 | |
| 1161 | |
| 1162 | .. class:: Overflow |
| 1163 | |
| 1164 | Numerical overflow. |
| 1165 | |
| 1166 | Indicates the exponent is larger than :attr:`Emax` after rounding has occurred. |
| 1167 | If not trapped, the result depends on the rounding mode, either pulling inward |
| 1168 | to the largest representable finite number or rounding outward to |
| 1169 | :const:`Infinity`. In either case, :class:`Inexact` and :class:`Rounded` are |
| 1170 | also signaled. |
| 1171 | |
| 1172 | |
| 1173 | .. class:: Rounded |
| 1174 | |
| 1175 | Rounding occurred though possibly no information was lost. |
| 1176 | |
| 1177 | Signaled whenever rounding discards digits; even if those digits are zero (such |
| 1178 | as rounding :const:`5.00` to :const:`5.0`). If not trapped, returns the result |
| 1179 | unchanged. This signal is used to detect loss of significant digits. |
| 1180 | |
| 1181 | |
| 1182 | .. class:: Subnormal |
| 1183 | |
| 1184 | Exponent was lower than :attr:`Emin` prior to rounding. |
| 1185 | |
| 1186 | Occurs when an operation result is subnormal (the exponent is too small). If not |
| 1187 | trapped, returns the result unchanged. |
| 1188 | |
| 1189 | |
| 1190 | .. class:: Underflow |
| 1191 | |
| 1192 | Numerical underflow with result rounded to zero. |
| 1193 | |
| 1194 | Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact` |
| 1195 | and :class:`Subnormal` are also signaled. |
| 1196 | |
| 1197 | The following table summarizes the hierarchy of signals:: |
| 1198 | |
| 1199 | exceptions.ArithmeticError(exceptions.StandardError) |
| 1200 | DecimalException |
| 1201 | Clamped |
| 1202 | DivisionByZero(DecimalException, exceptions.ZeroDivisionError) |
| 1203 | Inexact |
| 1204 | Overflow(Inexact, Rounded) |
| 1205 | Underflow(Inexact, Rounded, Subnormal) |
| 1206 | InvalidOperation |
| 1207 | Rounded |
| 1208 | Subnormal |
| 1209 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 1210 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1211 | |
| 1212 | |
| 1213 | .. _decimal-notes: |
| 1214 | |
| 1215 | Floating Point Notes |
| 1216 | -------------------- |
| 1217 | |
| 1218 | |
| 1219 | Mitigating round-off error with increased precision |
| 1220 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1221 | |
| 1222 | The use of decimal floating point eliminates decimal representation error |
| 1223 | (making it possible to represent :const:`0.1` exactly); however, some operations |
| 1224 | can still incur round-off error when non-zero digits exceed the fixed precision. |
| 1225 | |
| 1226 | The effects of round-off error can be amplified by the addition or subtraction |
| 1227 | of nearly offsetting quantities resulting in loss of significance. Knuth |
| 1228 | provides two instructive examples where rounded floating point arithmetic with |
| 1229 | insufficient precision causes the breakdown of the associative and distributive |
| 1230 | properties of addition:: |
| 1231 | |
| 1232 | # Examples from Seminumerical Algorithms, Section 4.2.2. |
| 1233 | >>> from decimal import Decimal, getcontext |
| 1234 | >>> getcontext().prec = 8 |
| 1235 | |
| 1236 | >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') |
| 1237 | >>> (u + v) + w |
| 1238 | Decimal("9.5111111") |
| 1239 | >>> u + (v + w) |
| 1240 | Decimal("10") |
| 1241 | |
| 1242 | >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') |
| 1243 | >>> (u*v) + (u*w) |
| 1244 | Decimal("0.01") |
| 1245 | >>> u * (v+w) |
| 1246 | Decimal("0.0060000") |
| 1247 | |
| 1248 | The :mod:`decimal` module makes it possible to restore the identities by |
| 1249 | expanding the precision sufficiently to avoid loss of significance:: |
| 1250 | |
| 1251 | >>> getcontext().prec = 20 |
| 1252 | >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') |
| 1253 | >>> (u + v) + w |
| 1254 | Decimal("9.51111111") |
| 1255 | >>> u + (v + w) |
| 1256 | Decimal("9.51111111") |
| 1257 | >>> |
| 1258 | >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') |
| 1259 | >>> (u*v) + (u*w) |
| 1260 | Decimal("0.0060000") |
| 1261 | >>> u * (v+w) |
| 1262 | Decimal("0.0060000") |
| 1263 | |
| 1264 | |
| 1265 | Special values |
| 1266 | ^^^^^^^^^^^^^^ |
| 1267 | |
| 1268 | The number system for the :mod:`decimal` module provides special values |
| 1269 | including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`, |
Facundo Batista | 7c82a3e9 | 2007-09-14 18:58:34 +0000 | [diff] [blame] | 1270 | and two zeros, :const:`+0` and :const:`-0`. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1271 | |
| 1272 | Infinities can be constructed directly with: ``Decimal('Infinity')``. Also, |
| 1273 | they can arise from dividing by zero when the :exc:`DivisionByZero` signal is |
| 1274 | not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity |
| 1275 | can result from rounding beyond the limits of the largest representable number. |
| 1276 | |
| 1277 | The infinities are signed (affine) and can be used in arithmetic operations |
| 1278 | where they get treated as very large, indeterminate numbers. For instance, |
| 1279 | adding a constant to infinity gives another infinite result. |
| 1280 | |
| 1281 | Some operations are indeterminate and return :const:`NaN`, or if the |
| 1282 | :exc:`InvalidOperation` signal is trapped, raise an exception. For example, |
| 1283 | ``0/0`` returns :const:`NaN` which means "not a number". This variety of |
| 1284 | :const:`NaN` is quiet and, once created, will flow through other computations |
| 1285 | always resulting in another :const:`NaN`. This behavior can be useful for a |
| 1286 | series of computations that occasionally have missing inputs --- it allows the |
| 1287 | calculation to proceed while flagging specific results as invalid. |
| 1288 | |
| 1289 | A variant is :const:`sNaN` which signals rather than remaining quiet after every |
| 1290 | operation. This is a useful return value when an invalid result needs to |
| 1291 | interrupt a calculation for special handling. |
| 1292 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 1293 | The behavior of Python's comparison operators can be a little surprising where a |
| 1294 | :const:`NaN` is involved. A test for equality where one of the operands is a |
| 1295 | quiet or signaling :const:`NaN` always returns :const:`False` (even when doing |
| 1296 | ``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns |
Mark Dickinson | bafa942 | 2008-02-06 22:25:16 +0000 | [diff] [blame] | 1297 | :const:`True`. An attempt to compare two Decimals using any of the ``<``, |
| 1298 | ``<=``, ``>`` or ``>=`` operators will raise the |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 1299 | :exc:`InvalidOperation` signal if either operand is a :const:`NaN`, and return |
| 1300 | :const:`False` if this signal is trapped. Note that the General Decimal |
| 1301 | Arithmetic specification does not specify the behavior of direct comparisons; |
| 1302 | these rules for comparisons involving a :const:`NaN` were taken from the IEEE |
| 1303 | 754 standard. To ensure strict standards-compliance, use the :meth:`compare` |
| 1304 | and :meth:`compare-signal` methods instead. |
| 1305 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1306 | The signed zeros can result from calculations that underflow. They keep the sign |
| 1307 | that would have resulted if the calculation had been carried out to greater |
| 1308 | precision. Since their magnitude is zero, both positive and negative zeros are |
| 1309 | treated as equal and their sign is informational. |
| 1310 | |
| 1311 | In addition to the two signed zeros which are distinct yet equal, there are |
| 1312 | various representations of zero with differing precisions yet equivalent in |
| 1313 | value. This takes a bit of getting used to. For an eye accustomed to |
| 1314 | normalized floating point representations, it is not immediately obvious that |
| 1315 | the following calculation returns a value equal to zero:: |
| 1316 | |
| 1317 | >>> 1 / Decimal('Infinity') |
| 1318 | Decimal("0E-1000000026") |
| 1319 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 1320 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1321 | |
| 1322 | |
| 1323 | .. _decimal-threads: |
| 1324 | |
| 1325 | Working with threads |
| 1326 | -------------------- |
| 1327 | |
| 1328 | The :func:`getcontext` function accesses a different :class:`Context` object for |
| 1329 | each thread. Having separate thread contexts means that threads may make |
| 1330 | changes (such as ``getcontext.prec=10``) without interfering with other threads. |
| 1331 | |
| 1332 | Likewise, the :func:`setcontext` function automatically assigns its target to |
| 1333 | the current thread. |
| 1334 | |
| 1335 | If :func:`setcontext` has not been called before :func:`getcontext`, then |
| 1336 | :func:`getcontext` will automatically create a new context for use in the |
| 1337 | current thread. |
| 1338 | |
| 1339 | The new context is copied from a prototype context called *DefaultContext*. To |
| 1340 | control the defaults so that each thread will use the same values throughout the |
| 1341 | application, directly modify the *DefaultContext* object. This should be done |
| 1342 | *before* any threads are started so that there won't be a race condition between |
| 1343 | threads calling :func:`getcontext`. For example:: |
| 1344 | |
| 1345 | # Set applicationwide defaults for all threads about to be launched |
| 1346 | DefaultContext.prec = 12 |
| 1347 | DefaultContext.rounding = ROUND_DOWN |
| 1348 | DefaultContext.traps = ExtendedContext.traps.copy() |
| 1349 | DefaultContext.traps[InvalidOperation] = 1 |
| 1350 | setcontext(DefaultContext) |
| 1351 | |
| 1352 | # Afterwards, the threads can be started |
| 1353 | t1.start() |
| 1354 | t2.start() |
| 1355 | t3.start() |
| 1356 | . . . |
| 1357 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 1358 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1359 | |
| 1360 | |
| 1361 | .. _decimal-recipes: |
| 1362 | |
| 1363 | Recipes |
| 1364 | ------- |
| 1365 | |
| 1366 | Here are a few recipes that serve as utility functions and that demonstrate ways |
| 1367 | to work with the :class:`Decimal` class:: |
| 1368 | |
| 1369 | def moneyfmt(value, places=2, curr='', sep=',', dp='.', |
| 1370 | pos='', neg='-', trailneg=''): |
| 1371 | """Convert Decimal to a money formatted string. |
| 1372 | |
| 1373 | places: required number of places after the decimal point |
| 1374 | curr: optional currency symbol before the sign (may be blank) |
| 1375 | sep: optional grouping separator (comma, period, space, or blank) |
| 1376 | dp: decimal point indicator (comma or period) |
| 1377 | only specify as blank when places is zero |
| 1378 | pos: optional sign for positive numbers: '+', space or blank |
| 1379 | neg: optional sign for negative numbers: '-', '(', space or blank |
| 1380 | trailneg:optional trailing minus indicator: '-', ')', space or blank |
| 1381 | |
| 1382 | >>> d = Decimal('-1234567.8901') |
| 1383 | >>> moneyfmt(d, curr='$') |
| 1384 | '-$1,234,567.89' |
| 1385 | >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-') |
| 1386 | '1.234.568-' |
| 1387 | >>> moneyfmt(d, curr='$', neg='(', trailneg=')') |
| 1388 | '($1,234,567.89)' |
| 1389 | >>> moneyfmt(Decimal(123456789), sep=' ') |
| 1390 | '123 456 789.00' |
| 1391 | >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>') |
| 1392 | '<.02>' |
| 1393 | |
| 1394 | """ |
| 1395 | q = Decimal((0, (1,), -places)) # 2 places --> '0.01' |
| 1396 | sign, digits, exp = value.quantize(q).as_tuple() |
| 1397 | assert exp == -places |
| 1398 | result = [] |
| 1399 | digits = map(str, digits) |
| 1400 | build, next = result.append, digits.pop |
| 1401 | if sign: |
| 1402 | build(trailneg) |
| 1403 | for i in range(places): |
| 1404 | if digits: |
| 1405 | build(next()) |
| 1406 | else: |
| 1407 | build('0') |
| 1408 | build(dp) |
| 1409 | i = 0 |
| 1410 | while digits: |
| 1411 | build(next()) |
| 1412 | i += 1 |
| 1413 | if i == 3 and digits: |
| 1414 | i = 0 |
| 1415 | build(sep) |
| 1416 | build(curr) |
| 1417 | if sign: |
| 1418 | build(neg) |
| 1419 | else: |
| 1420 | build(pos) |
| 1421 | result.reverse() |
| 1422 | return ''.join(result) |
| 1423 | |
| 1424 | def pi(): |
| 1425 | """Compute Pi to the current precision. |
| 1426 | |
| 1427 | >>> print pi() |
| 1428 | 3.141592653589793238462643383 |
| 1429 | |
| 1430 | """ |
| 1431 | getcontext().prec += 2 # extra digits for intermediate steps |
| 1432 | three = Decimal(3) # substitute "three=3.0" for regular floats |
| 1433 | lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 |
| 1434 | while s != lasts: |
| 1435 | lasts = s |
| 1436 | n, na = n+na, na+8 |
| 1437 | d, da = d+da, da+32 |
| 1438 | t = (t * n) / d |
| 1439 | s += t |
| 1440 | getcontext().prec -= 2 |
| 1441 | return +s # unary plus applies the new precision |
| 1442 | |
| 1443 | def exp(x): |
| 1444 | """Return e raised to the power of x. Result type matches input type. |
| 1445 | |
| 1446 | >>> print exp(Decimal(1)) |
| 1447 | 2.718281828459045235360287471 |
| 1448 | >>> print exp(Decimal(2)) |
| 1449 | 7.389056098930650227230427461 |
| 1450 | >>> print exp(2.0) |
| 1451 | 7.38905609893 |
| 1452 | >>> print exp(2+0j) |
| 1453 | (7.38905609893+0j) |
| 1454 | |
| 1455 | """ |
| 1456 | getcontext().prec += 2 |
| 1457 | i, lasts, s, fact, num = 0, 0, 1, 1, 1 |
| 1458 | while s != lasts: |
| 1459 | lasts = s |
| 1460 | i += 1 |
| 1461 | fact *= i |
| 1462 | num *= x |
| 1463 | s += num / fact |
| 1464 | getcontext().prec -= 2 |
| 1465 | return +s |
| 1466 | |
| 1467 | def cos(x): |
| 1468 | """Return the cosine of x as measured in radians. |
| 1469 | |
| 1470 | >>> print cos(Decimal('0.5')) |
| 1471 | 0.8775825618903727161162815826 |
| 1472 | >>> print cos(0.5) |
| 1473 | 0.87758256189 |
| 1474 | >>> print cos(0.5+0j) |
| 1475 | (0.87758256189+0j) |
| 1476 | |
| 1477 | """ |
| 1478 | getcontext().prec += 2 |
| 1479 | i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1 |
| 1480 | while s != lasts: |
| 1481 | lasts = s |
| 1482 | i += 2 |
| 1483 | fact *= i * (i-1) |
| 1484 | num *= x * x |
| 1485 | sign *= -1 |
| 1486 | s += num / fact * sign |
| 1487 | getcontext().prec -= 2 |
| 1488 | return +s |
| 1489 | |
| 1490 | def sin(x): |
| 1491 | """Return the sine of x as measured in radians. |
| 1492 | |
| 1493 | >>> print sin(Decimal('0.5')) |
| 1494 | 0.4794255386042030002732879352 |
| 1495 | >>> print sin(0.5) |
| 1496 | 0.479425538604 |
| 1497 | >>> print sin(0.5+0j) |
| 1498 | (0.479425538604+0j) |
| 1499 | |
| 1500 | """ |
| 1501 | getcontext().prec += 2 |
| 1502 | i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1 |
| 1503 | while s != lasts: |
| 1504 | lasts = s |
| 1505 | i += 2 |
| 1506 | fact *= i * (i-1) |
| 1507 | num *= x * x |
| 1508 | sign *= -1 |
| 1509 | s += num / fact * sign |
| 1510 | getcontext().prec -= 2 |
| 1511 | return +s |
| 1512 | |
| 1513 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 1514 | .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1515 | |
| 1516 | |
| 1517 | .. _decimal-faq: |
| 1518 | |
| 1519 | Decimal FAQ |
| 1520 | ----------- |
| 1521 | |
| 1522 | Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to |
| 1523 | minimize typing when using the interactive interpreter? |
| 1524 | |
| 1525 | \A. Some users abbreviate the constructor to just a single letter:: |
| 1526 | |
| 1527 | >>> D = decimal.Decimal |
| 1528 | >>> D('1.23') + D('3.45') |
| 1529 | Decimal("4.68") |
| 1530 | |
| 1531 | Q. In a fixed-point application with two decimal places, some inputs have many |
| 1532 | places and need to be rounded. Others are not supposed to have excess digits |
| 1533 | and need to be validated. What methods should be used? |
| 1534 | |
| 1535 | A. The :meth:`quantize` method rounds to a fixed number of decimal places. If |
| 1536 | the :const:`Inexact` trap is set, it is also useful for validation:: |
| 1537 | |
| 1538 | >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01') |
| 1539 | |
| 1540 | >>> # Round to two places |
| 1541 | >>> Decimal("3.214").quantize(TWOPLACES) |
| 1542 | Decimal("3.21") |
| 1543 | |
| 1544 | >>> # Validate that a number does not exceed two places |
| 1545 | >>> Decimal("3.21").quantize(TWOPLACES, context=Context(traps=[Inexact])) |
| 1546 | Decimal("3.21") |
| 1547 | |
| 1548 | >>> Decimal("3.214").quantize(TWOPLACES, context=Context(traps=[Inexact])) |
| 1549 | Traceback (most recent call last): |
| 1550 | ... |
| 1551 | Inexact: Changed in rounding |
| 1552 | |
| 1553 | Q. Once I have valid two place inputs, how do I maintain that invariant |
| 1554 | throughout an application? |
| 1555 | |
| 1556 | A. Some operations like addition and subtraction automatically preserve fixed |
| 1557 | point. Others, like multiplication and division, change the number of decimal |
| 1558 | places and need to be followed-up with a :meth:`quantize` step. |
| 1559 | |
| 1560 | Q. There are many ways to express the same value. The numbers :const:`200`, |
| 1561 | :const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at |
| 1562 | various precisions. Is there a way to transform them to a single recognizable |
| 1563 | canonical value? |
| 1564 | |
| 1565 | A. The :meth:`normalize` method maps all equivalent values to a single |
| 1566 | representative:: |
| 1567 | |
| 1568 | >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split()) |
| 1569 | >>> [v.normalize() for v in values] |
| 1570 | [Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2"), Decimal("2E+2")] |
| 1571 | |
| 1572 | Q. Some decimal values always print with exponential notation. Is there a way |
| 1573 | to get a non-exponential representation? |
| 1574 | |
| 1575 | A. For some values, exponential notation is the only way to express the number |
| 1576 | of significant places in the coefficient. For example, expressing |
| 1577 | :const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the |
| 1578 | original's two-place significance. |
| 1579 | |
| 1580 | Q. Is there a way to convert a regular float to a :class:`Decimal`? |
| 1581 | |
| 1582 | A. Yes, all binary floating point numbers can be exactly expressed as a |
| 1583 | Decimal. An exact conversion may take more precision than intuition would |
| 1584 | suggest, so trapping :const:`Inexact` will signal a need for more precision:: |
| 1585 | |
| 1586 | def floatToDecimal(f): |
| 1587 | "Convert a floating point number to a Decimal with no loss of information" |
| 1588 | # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an |
| 1589 | # exponent. Double the mantissa until it is an integer. Use the integer |
| 1590 | # mantissa and exponent to compute an equivalent Decimal. If this cannot |
| 1591 | # be done exactly, then retry with more precision. |
| 1592 | |
| 1593 | mantissa, exponent = math.frexp(f) |
| 1594 | while mantissa != int(mantissa): |
| 1595 | mantissa *= 2.0 |
| 1596 | exponent -= 1 |
| 1597 | mantissa = int(mantissa) |
| 1598 | |
| 1599 | oldcontext = getcontext() |
| 1600 | setcontext(Context(traps=[Inexact])) |
| 1601 | try: |
| 1602 | while True: |
| 1603 | try: |
| 1604 | return mantissa * Decimal(2) ** exponent |
| 1605 | except Inexact: |
| 1606 | getcontext().prec += 1 |
| 1607 | finally: |
| 1608 | setcontext(oldcontext) |
| 1609 | |
| 1610 | Q. Why isn't the :func:`floatToDecimal` routine included in the module? |
| 1611 | |
| 1612 | A. There is some question about whether it is advisable to mix binary and |
| 1613 | decimal floating point. Also, its use requires some care to avoid the |
| 1614 | representation issues associated with binary floating point:: |
| 1615 | |
| 1616 | >>> floatToDecimal(1.1) |
| 1617 | Decimal("1.100000000000000088817841970012523233890533447265625") |
| 1618 | |
| 1619 | Q. Within a complex calculation, how can I make sure that I haven't gotten a |
| 1620 | spurious result because of insufficient precision or rounding anomalies. |
| 1621 | |
| 1622 | A. The decimal module makes it easy to test results. A best practice is to |
| 1623 | re-run calculations using greater precision and with various rounding modes. |
| 1624 | Widely differing results indicate insufficient precision, rounding mode issues, |
| 1625 | ill-conditioned inputs, or a numerically unstable algorithm. |
| 1626 | |
| 1627 | Q. I noticed that context precision is applied to the results of operations but |
| 1628 | not to the inputs. Is there anything to watch out for when mixing values of |
| 1629 | different precisions? |
| 1630 | |
| 1631 | A. Yes. The principle is that all values are considered to be exact and so is |
| 1632 | the arithmetic on those values. Only the results are rounded. The advantage |
| 1633 | for inputs is that "what you type is what you get". A disadvantage is that the |
| 1634 | results can look odd if you forget that the inputs haven't been rounded:: |
| 1635 | |
| 1636 | >>> getcontext().prec = 3 |
| 1637 | >>> Decimal('3.104') + D('2.104') |
| 1638 | Decimal("5.21") |
| 1639 | >>> Decimal('3.104') + D('0.000') + D('2.104') |
| 1640 | Decimal("5.20") |
| 1641 | |
| 1642 | The solution is either to increase precision or to force rounding of inputs |
| 1643 | using the unary plus operation:: |
| 1644 | |
| 1645 | >>> getcontext().prec = 3 |
| 1646 | >>> +Decimal('1.23456789') # unary plus triggers rounding |
| 1647 | Decimal("1.23") |
| 1648 | |
| 1649 | Alternatively, inputs can be rounded upon creation using the |
| 1650 | :meth:`Context.create_decimal` method:: |
| 1651 | |
| 1652 | >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678') |
| 1653 | Decimal("1.2345") |
| 1654 | |