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