1:mod:`decimal` --- Decimal fixed point and floating point arithmetic 2==================================================================== 3 4.. module:: decimal 5 :synopsis: Implementation of the General Decimal Arithmetic Specification. 6 7.. moduleauthor:: Eric Price <eprice at tjhsst.edu> 8.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar> 9.. moduleauthor:: Raymond Hettinger <python at rcn.com> 10.. moduleauthor:: Aahz <aahz at pobox.com> 11.. moduleauthor:: Tim Peters <tim.one at comcast.net> 12.. moduleauthor:: Stefan Krah <skrah at bytereef.org> 13.. sectionauthor:: Raymond D. Hettinger <python at rcn.com> 14 15**Source code:** :source:`Lib/decimal.py` 16 17.. import modules for testing inline doctests with the Sphinx doctest builder 18.. testsetup:: * 19 20 import decimal 21 import math 22 from decimal import * 23 # make sure each group gets a fresh context 24 setcontext(Context()) 25 26.. testcleanup:: * 27 28 # make sure other tests (outside this file) get a fresh context 29 setcontext(Context()) 30 31-------------- 32 33The :mod:`decimal` module provides support for fast correctly rounded 34decimal floating point arithmetic. It offers several advantages over the 35:class:`float` datatype: 36 37* Decimal "is based on a floating-point model which was designed with people 38 in mind, and necessarily has a paramount guiding principle -- computers must 39 provide an arithmetic that works in the same way as the arithmetic that 40 people learn at school." -- excerpt from the decimal arithmetic specification. 41 42* Decimal numbers can be represented exactly. In contrast, numbers like 43 ``1.1`` and ``2.2`` do not have exact representations in binary 44 floating point. End users typically would not expect ``1.1 + 2.2`` to display 45 as ``3.3000000000000003`` as it does with binary floating point. 46 47* The exactness carries over into arithmetic. In decimal floating point, ``0.1 48 + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result 49 is ``5.5511151231257827e-017``. While near to zero, the differences 50 prevent reliable equality testing and differences can accumulate. For this 51 reason, decimal is preferred in accounting applications which have strict 52 equality invariants. 53 54* The decimal module incorporates a notion of significant places so that ``1.30 55 + 1.20`` is ``2.50``. The trailing zero is kept to indicate significance. 56 This is the customary presentation for monetary applications. For 57 multiplication, the "schoolbook" approach uses all the figures in the 58 multiplicands. For instance, ``1.3 * 1.2`` gives ``1.56`` while ``1.30 * 59 1.20`` gives ``1.5600``. 60 61* Unlike hardware based binary floating point, the decimal module has a user 62 alterable precision (defaulting to 28 places) which can be as large as needed for 63 a given problem: 64 65 >>> from decimal import * 66 >>> getcontext().prec = 6 67 >>> Decimal(1) / Decimal(7) 68 Decimal('0.142857') 69 >>> getcontext().prec = 28 70 >>> Decimal(1) / Decimal(7) 71 Decimal('0.1428571428571428571428571429') 72 73* Both binary and decimal floating point are implemented in terms of published 74 standards. While the built-in float type exposes only a modest portion of its 75 capabilities, the decimal module exposes all required parts of the standard. 76 When needed, the programmer has full control over rounding and signal handling. 77 This includes an option to enforce exact arithmetic by using exceptions 78 to block any inexact operations. 79 80* The decimal module was designed to support "without prejudice, both exact 81 unrounded decimal arithmetic (sometimes called fixed-point arithmetic) 82 and rounded floating-point arithmetic." -- excerpt from the decimal 83 arithmetic specification. 84 85The module design is centered around three concepts: the decimal number, the 86context for arithmetic, and signals. 87 88A decimal number is immutable. It has a sign, coefficient digits, and an 89exponent. To preserve significance, the coefficient digits do not truncate 90trailing zeros. Decimals also include special values such as 91``Infinity``, ``-Infinity``, and ``NaN``. The standard also 92differentiates ``-0`` from ``+0``. 93 94The context for arithmetic is an environment specifying precision, rounding 95rules, limits on exponents, flags indicating the results of operations, and trap 96enablers which determine whether signals are treated as exceptions. Rounding 97options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`, 98:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`, 99:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`. 100 101Signals are groups of exceptional conditions arising during the course of 102computation. Depending on the needs of the application, signals may be ignored, 103considered as informational, or treated as exceptions. The signals in the 104decimal module are: :const:`Clamped`, :const:`InvalidOperation`, 105:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`, 106:const:`Overflow`, :const:`Underflow` and :const:`FloatOperation`. 107 108For each signal there is a flag and a trap enabler. When a signal is 109encountered, its flag is set to one, then, if the trap enabler is 110set to one, an exception is raised. Flags are sticky, so the user needs to 111reset them before monitoring a calculation. 112 113 114.. seealso:: 115 116 * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic 117 Specification <https://speleotrove.com/decimal/decarith.html>`_. 118 119.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 120 121 122.. _decimal-tutorial: 123 124Quick-start Tutorial 125-------------------- 126 127The usual start to using decimals is importing the module, viewing the current 128context with :func:`getcontext` and, if necessary, setting new values for 129precision, rounding, or enabled traps:: 130 131 >>> from decimal import * 132 >>> getcontext() 133 Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, 134 capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero, 135 InvalidOperation]) 136 137 >>> getcontext().prec = 7 # Set a new precision 138 139Decimal instances can be constructed from integers, strings, floats, or tuples. 140Construction from an integer or a float performs an exact conversion of the 141value of that integer or float. Decimal numbers include special values such as 142``NaN`` which stands for "Not a number", positive and negative 143``Infinity``, and ``-0``:: 144 145 >>> getcontext().prec = 28 146 >>> Decimal(10) 147 Decimal('10') 148 >>> Decimal('3.14') 149 Decimal('3.14') 150 >>> Decimal(3.14) 151 Decimal('3.140000000000000124344978758017532527446746826171875') 152 >>> Decimal((0, (3, 1, 4), -2)) 153 Decimal('3.14') 154 >>> Decimal(str(2.0 ** 0.5)) 155 Decimal('1.4142135623730951') 156 >>> Decimal(2) ** Decimal('0.5') 157 Decimal('1.414213562373095048801688724') 158 >>> Decimal('NaN') 159 Decimal('NaN') 160 >>> Decimal('-Infinity') 161 Decimal('-Infinity') 162 163If the :exc:`FloatOperation` signal is trapped, accidental mixing of 164decimals and floats in constructors or ordering comparisons raises 165an exception:: 166 167 >>> c = getcontext() 168 >>> c.traps[FloatOperation] = True 169 >>> Decimal(3.14) 170 Traceback (most recent call last): 171 File "<stdin>", line 1, in <module> 172 decimal.FloatOperation: [<class 'decimal.FloatOperation'>] 173 >>> Decimal('3.5') < 3.7 174 Traceback (most recent call last): 175 File "<stdin>", line 1, in <module> 176 decimal.FloatOperation: [<class 'decimal.FloatOperation'>] 177 >>> Decimal('3.5') == 3.5 178 True 179 180.. versionadded:: 3.3 181 182The significance of a new Decimal is determined solely by the number of digits 183input. Context precision and rounding only come into play during arithmetic 184operations. 185 186.. doctest:: newcontext 187 188 >>> getcontext().prec = 6 189 >>> Decimal('3.0') 190 Decimal('3.0') 191 >>> Decimal('3.1415926535') 192 Decimal('3.1415926535') 193 >>> Decimal('3.1415926535') + Decimal('2.7182818285') 194 Decimal('5.85987') 195 >>> getcontext().rounding = ROUND_UP 196 >>> Decimal('3.1415926535') + Decimal('2.7182818285') 197 Decimal('5.85988') 198 199If the internal limits of the C version are exceeded, constructing 200a decimal raises :class:`InvalidOperation`:: 201 202 >>> Decimal("1e9999999999999999999") 203 Traceback (most recent call last): 204 File "<stdin>", line 1, in <module> 205 decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>] 206 207.. versionchanged:: 3.3 208 209Decimals interact well with much of the rest of Python. Here is a small decimal 210floating point flying circus: 211 212.. doctest:: 213 :options: +NORMALIZE_WHITESPACE 214 215 >>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())) 216 >>> max(data) 217 Decimal('9.25') 218 >>> min(data) 219 Decimal('0.03') 220 >>> sorted(data) 221 [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'), 222 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')] 223 >>> sum(data) 224 Decimal('19.29') 225 >>> a,b,c = data[:3] 226 >>> str(a) 227 '1.34' 228 >>> float(a) 229 1.34 230 >>> round(a, 1) 231 Decimal('1.3') 232 >>> int(a) 233 1 234 >>> a * 5 235 Decimal('6.70') 236 >>> a * b 237 Decimal('2.5058') 238 >>> c % a 239 Decimal('0.77') 240 241And some mathematical functions are also available to Decimal: 242 243 >>> getcontext().prec = 28 244 >>> Decimal(2).sqrt() 245 Decimal('1.414213562373095048801688724') 246 >>> Decimal(1).exp() 247 Decimal('2.718281828459045235360287471') 248 >>> Decimal('10').ln() 249 Decimal('2.302585092994045684017991455') 250 >>> Decimal('10').log10() 251 Decimal('1') 252 253The :meth:`~Decimal.quantize` method rounds a number to a fixed exponent. This method is 254useful for monetary applications that often round results to a fixed number of 255places: 256 257 >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN) 258 Decimal('7.32') 259 >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP) 260 Decimal('8') 261 262As shown above, the :func:`getcontext` function accesses the current context and 263allows the settings to be changed. This approach meets the needs of most 264applications. 265 266For more advanced work, it may be useful to create alternate contexts using the 267Context() constructor. To make an alternate active, use the :func:`setcontext` 268function. 269 270In accordance with the standard, the :mod:`decimal` module provides two ready to 271use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The 272former is especially useful for debugging because many of the traps are 273enabled: 274 275.. doctest:: newcontext 276 :options: +NORMALIZE_WHITESPACE 277 278 >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN) 279 >>> setcontext(myothercontext) 280 >>> Decimal(1) / Decimal(7) 281 Decimal('0.142857142857142857142857142857142857142857142857142857142857') 282 283 >>> ExtendedContext 284 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, 285 capitals=1, clamp=0, flags=[], traps=[]) 286 >>> setcontext(ExtendedContext) 287 >>> Decimal(1) / Decimal(7) 288 Decimal('0.142857143') 289 >>> Decimal(42) / Decimal(0) 290 Decimal('Infinity') 291 292 >>> setcontext(BasicContext) 293 >>> Decimal(42) / Decimal(0) 294 Traceback (most recent call last): 295 File "<pyshell#143>", line 1, in -toplevel- 296 Decimal(42) / Decimal(0) 297 DivisionByZero: x / 0 298 299Contexts also have signal flags for monitoring exceptional conditions 300encountered during computations. The flags remain set until explicitly cleared, 301so it is best to clear the flags before each set of monitored computations by 302using the :meth:`~Context.clear_flags` method. :: 303 304 >>> setcontext(ExtendedContext) 305 >>> getcontext().clear_flags() 306 >>> Decimal(355) / Decimal(113) 307 Decimal('3.14159292') 308 >>> getcontext() 309 Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, 310 capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[]) 311 312The *flags* entry shows that the rational approximation to pi was 313rounded (digits beyond the context precision were thrown away) and that the 314result is inexact (some of the discarded digits were non-zero). 315 316Individual traps are set using the dictionary in the :attr:`~Context.traps` 317attribute of a context: 318 319.. doctest:: newcontext 320 321 >>> setcontext(ExtendedContext) 322 >>> Decimal(1) / Decimal(0) 323 Decimal('Infinity') 324 >>> getcontext().traps[DivisionByZero] = 1 325 >>> Decimal(1) / Decimal(0) 326 Traceback (most recent call last): 327 File "<pyshell#112>", line 1, in -toplevel- 328 Decimal(1) / Decimal(0) 329 DivisionByZero: x / 0 330 331Most programs adjust the current context only once, at the beginning of the 332program. And, in many applications, data is converted to :class:`Decimal` with 333a single cast inside a loop. With context set and decimals created, the bulk of 334the program manipulates the data no differently than with other Python numeric 335types. 336 337.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 338 339 340.. _decimal-decimal: 341 342Decimal objects 343--------------- 344 345 346.. class:: Decimal(value="0", context=None) 347 348 Construct a new :class:`Decimal` object based from *value*. 349 350 *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal` 351 object. If no *value* is given, returns ``Decimal('0')``. If *value* is a 352 string, it should conform to the decimal numeric string syntax after leading 353 and trailing whitespace characters, as well as underscores throughout, are removed:: 354 355 sign ::= '+' | '-' 356 digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' 357 indicator ::= 'e' | 'E' 358 digits ::= digit [digit]... 359 decimal-part ::= digits '.' [digits] | ['.'] digits 360 exponent-part ::= indicator [sign] digits 361 infinity ::= 'Infinity' | 'Inf' 362 nan ::= 'NaN' [digits] | 'sNaN' [digits] 363 numeric-value ::= decimal-part [exponent-part] | infinity 364 numeric-string ::= [sign] numeric-value | [sign] nan 365 366 Other Unicode decimal digits are also permitted where ``digit`` 367 appears above. These include decimal digits from various other 368 alphabets (for example, Arabic-Indic and Devanāgarī digits) along 369 with the fullwidth digits ``'\uff10'`` through ``'\uff19'``. 370 371 If *value* is a :class:`tuple`, it should have three components, a sign 372 (``0`` for positive or ``1`` for negative), a :class:`tuple` of 373 digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))`` 374 returns ``Decimal('1.414')``. 375 376 If *value* is a :class:`float`, the binary floating point value is losslessly 377 converted to its exact decimal equivalent. This conversion can often require 378 53 or more digits of precision. For example, ``Decimal(float('1.1'))`` 379 converts to 380 ``Decimal('1.100000000000000088817841970012523233890533447265625')``. 381 382 The *context* precision does not affect how many digits are stored. That is 383 determined exclusively by the number of digits in *value*. For example, 384 ``Decimal('3.00000')`` records all five zeros even if the context precision is 385 only three. 386 387 The purpose of the *context* argument is determining what to do if *value* is a 388 malformed string. If the context traps :const:`InvalidOperation`, an exception 389 is raised; otherwise, the constructor returns a new Decimal with the value of 390 ``NaN``. 391 392 Once constructed, :class:`Decimal` objects are immutable. 393 394 .. versionchanged:: 3.2 395 The argument to the constructor is now permitted to be a :class:`float` 396 instance. 397 398 .. versionchanged:: 3.3 399 :class:`float` arguments raise an exception if the :exc:`FloatOperation` 400 trap is set. By default the trap is off. 401 402 .. versionchanged:: 3.6 403 Underscores are allowed for grouping, as with integral and floating-point 404 literals in code. 405 406 Decimal floating point objects share many properties with the other built-in 407 numeric types such as :class:`float` and :class:`int`. All of the usual math 408 operations and special methods apply. Likewise, decimal objects can be 409 copied, pickled, printed, used as dictionary keys, used as set elements, 410 compared, sorted, and coerced to another type (such as :class:`float` or 411 :class:`int`). 412 413 There are some small differences between arithmetic on Decimal objects and 414 arithmetic on integers and floats. When the remainder operator ``%`` is 415 applied to Decimal objects, the sign of the result is the sign of the 416 *dividend* rather than the sign of the divisor:: 417 418 >>> (-7) % 4 419 1 420 >>> Decimal(-7) % Decimal(4) 421 Decimal('-3') 422 423 The integer division operator ``//`` behaves analogously, returning the 424 integer part of the true quotient (truncating towards zero) rather than its 425 floor, so as to preserve the usual identity ``x == (x // y) * y + x % y``:: 426 427 >>> -7 // 4 428 -2 429 >>> Decimal(-7) // Decimal(4) 430 Decimal('-1') 431 432 The ``%`` and ``//`` operators implement the ``remainder`` and 433 ``divide-integer`` operations (respectively) as described in the 434 specification. 435 436 Decimal objects cannot generally be combined with floats or 437 instances of :class:`fractions.Fraction` in arithmetic operations: 438 an attempt to add a :class:`Decimal` to a :class:`float`, for 439 example, will raise a :exc:`TypeError`. However, it is possible to 440 use Python's comparison operators to compare a :class:`Decimal` 441 instance ``x`` with another number ``y``. This avoids confusing results 442 when doing equality comparisons between numbers of different types. 443 444 .. versionchanged:: 3.2 445 Mixed-type comparisons between :class:`Decimal` instances and other 446 numeric types are now fully supported. 447 448 In addition to the standard numeric properties, decimal floating point 449 objects also have a number of specialized methods: 450 451 452 .. method:: adjusted() 453 454 Return the adjusted exponent after shifting out the coefficient's 455 rightmost digits until only the lead digit remains: 456 ``Decimal('321e+5').adjusted()`` returns seven. Used for determining the 457 position of the most significant digit with respect to the decimal point. 458 459 .. method:: as_integer_ratio() 460 461 Return a pair ``(n, d)`` of integers that represent the given 462 :class:`Decimal` instance as a fraction, in lowest terms and 463 with a positive denominator:: 464 465 >>> Decimal('-3.14').as_integer_ratio() 466 (-157, 50) 467 468 The conversion is exact. Raise OverflowError on infinities and ValueError 469 on NaNs. 470 471 .. versionadded:: 3.6 472 473 .. method:: as_tuple() 474 475 Return a :term:`named tuple` representation of the number: 476 ``DecimalTuple(sign, digits, exponent)``. 477 478 479 .. method:: canonical() 480 481 Return the canonical encoding of the argument. Currently, the encoding of 482 a :class:`Decimal` instance is always canonical, so this operation returns 483 its argument unchanged. 484 485 .. method:: compare(other, context=None) 486 487 Compare the values of two Decimal instances. :meth:`compare` returns a 488 Decimal instance, and if either operand is a NaN then the result is a 489 NaN:: 490 491 a or b is a NaN ==> Decimal('NaN') 492 a < b ==> Decimal('-1') 493 a == b ==> Decimal('0') 494 a > b ==> Decimal('1') 495 496 .. method:: compare_signal(other, context=None) 497 498 This operation is identical to the :meth:`compare` method, except that all 499 NaNs signal. That is, if neither operand is a signaling NaN then any 500 quiet NaN operand is treated as though it were a signaling NaN. 501 502 .. method:: compare_total(other, context=None) 503 504 Compare two operands using their abstract representation rather than their 505 numerical value. Similar to the :meth:`compare` method, but the result 506 gives a total ordering on :class:`Decimal` instances. Two 507 :class:`Decimal` instances with the same numeric value but different 508 representations compare unequal in this ordering: 509 510 >>> Decimal('12.0').compare_total(Decimal('12')) 511 Decimal('-1') 512 513 Quiet and signaling NaNs are also included in the total ordering. The 514 result of this function is ``Decimal('0')`` if both operands have the same 515 representation, ``Decimal('-1')`` if the first operand is lower in the 516 total order than the second, and ``Decimal('1')`` if the first operand is 517 higher in the total order than the second operand. See the specification 518 for details of the total order. 519 520 This operation is unaffected by context and is quiet: no flags are changed 521 and no rounding is performed. As an exception, the C version may raise 522 InvalidOperation if the second operand cannot be converted exactly. 523 524 .. method:: compare_total_mag(other, context=None) 525 526 Compare two operands using their abstract representation rather than their 527 value as in :meth:`compare_total`, but ignoring the sign of each operand. 528 ``x.compare_total_mag(y)`` is equivalent to 529 ``x.copy_abs().compare_total(y.copy_abs())``. 530 531 This operation is unaffected by context and is quiet: no flags are changed 532 and no rounding is performed. As an exception, the C version may raise 533 InvalidOperation if the second operand cannot be converted exactly. 534 535 .. method:: conjugate() 536 537 Just returns self, this method is only to comply with the Decimal 538 Specification. 539 540 .. method:: copy_abs() 541 542 Return the absolute value of the argument. This operation is unaffected 543 by the context and is quiet: no flags are changed and no rounding is 544 performed. 545 546 .. method:: copy_negate() 547 548 Return the negation of the argument. This operation is unaffected by the 549 context and is quiet: no flags are changed and no rounding is performed. 550 551 .. method:: copy_sign(other, context=None) 552 553 Return a copy of the first operand with the sign set to be the same as the 554 sign of the second operand. For example: 555 556 >>> Decimal('2.3').copy_sign(Decimal('-1.5')) 557 Decimal('-2.3') 558 559 This operation is unaffected by context and is quiet: no flags are changed 560 and no rounding is performed. As an exception, the C version may raise 561 InvalidOperation if the second operand cannot be converted exactly. 562 563 .. method:: exp(context=None) 564 565 Return the value of the (natural) exponential function ``e**x`` at the 566 given number. The result is correctly rounded using the 567 :const:`ROUND_HALF_EVEN` rounding mode. 568 569 >>> Decimal(1).exp() 570 Decimal('2.718281828459045235360287471') 571 >>> Decimal(321).exp() 572 Decimal('2.561702493119680037517373933E+139') 573 574 .. classmethod:: from_float(f) 575 576 Alternative constructor that only accepts instances of :class:`float` or 577 :class:`int`. 578 579 Note ``Decimal.from_float(0.1)`` is not the same as ``Decimal('0.1')``. 580 Since 0.1 is not exactly representable in binary floating point, the 581 value is stored as the nearest representable value which is 582 ``0x1.999999999999ap-4``. That equivalent value in decimal is 583 ``0.1000000000000000055511151231257827021181583404541015625``. 584 585 .. note:: From Python 3.2 onwards, a :class:`Decimal` instance 586 can also be constructed directly from a :class:`float`. 587 588 .. doctest:: 589 590 >>> Decimal.from_float(0.1) 591 Decimal('0.1000000000000000055511151231257827021181583404541015625') 592 >>> Decimal.from_float(float('nan')) 593 Decimal('NaN') 594 >>> Decimal.from_float(float('inf')) 595 Decimal('Infinity') 596 >>> Decimal.from_float(float('-inf')) 597 Decimal('-Infinity') 598 599 .. versionadded:: 3.1 600 601 .. method:: fma(other, third, context=None) 602 603 Fused multiply-add. Return self*other+third with no rounding of the 604 intermediate product self*other. 605 606 >>> Decimal(2).fma(3, 5) 607 Decimal('11') 608 609 .. method:: is_canonical() 610 611 Return :const:`True` if the argument is canonical and :const:`False` 612 otherwise. Currently, a :class:`Decimal` instance is always canonical, so 613 this operation always returns :const:`True`. 614 615 .. method:: is_finite() 616 617 Return :const:`True` if the argument is a finite number, and 618 :const:`False` if the argument is an infinity or a NaN. 619 620 .. method:: is_infinite() 621 622 Return :const:`True` if the argument is either positive or negative 623 infinity and :const:`False` otherwise. 624 625 .. method:: is_nan() 626 627 Return :const:`True` if the argument is a (quiet or signaling) NaN and 628 :const:`False` otherwise. 629 630 .. method:: is_normal(context=None) 631 632 Return :const:`True` if the argument is a *normal* finite number. Return 633 :const:`False` if the argument is zero, subnormal, infinite or a NaN. 634 635 .. method:: is_qnan() 636 637 Return :const:`True` if the argument is a quiet NaN, and 638 :const:`False` otherwise. 639 640 .. method:: is_signed() 641 642 Return :const:`True` if the argument has a negative sign and 643 :const:`False` otherwise. Note that zeros and NaNs can both carry signs. 644 645 .. method:: is_snan() 646 647 Return :const:`True` if the argument is a signaling NaN and :const:`False` 648 otherwise. 649 650 .. method:: is_subnormal(context=None) 651 652 Return :const:`True` if the argument is subnormal, and :const:`False` 653 otherwise. 654 655 .. method:: is_zero() 656 657 Return :const:`True` if the argument is a (positive or negative) zero and 658 :const:`False` otherwise. 659 660 .. method:: ln(context=None) 661 662 Return the natural (base e) logarithm of the operand. The result is 663 correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode. 664 665 .. method:: log10(context=None) 666 667 Return the base ten logarithm of the operand. The result is correctly 668 rounded using the :const:`ROUND_HALF_EVEN` rounding mode. 669 670 .. method:: logb(context=None) 671 672 For a nonzero number, return the adjusted exponent of its operand as a 673 :class:`Decimal` instance. If the operand is a zero then 674 ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag 675 is raised. If the operand is an infinity then ``Decimal('Infinity')`` is 676 returned. 677 678 .. method:: logical_and(other, context=None) 679 680 :meth:`logical_and` is a logical operation which takes two *logical 681 operands* (see :ref:`logical_operands_label`). The result is the 682 digit-wise ``and`` of the two operands. 683 684 .. method:: logical_invert(context=None) 685 686 :meth:`logical_invert` is a logical operation. The 687 result is the digit-wise inversion of the operand. 688 689 .. method:: logical_or(other, context=None) 690 691 :meth:`logical_or` is a logical operation which takes two *logical 692 operands* (see :ref:`logical_operands_label`). The result is the 693 digit-wise ``or`` of the two operands. 694 695 .. method:: logical_xor(other, context=None) 696 697 :meth:`logical_xor` is a logical operation which takes two *logical 698 operands* (see :ref:`logical_operands_label`). The result is the 699 digit-wise exclusive or of the two operands. 700 701 .. method:: max(other, context=None) 702 703 Like ``max(self, other)`` except that the context rounding rule is applied 704 before returning and that ``NaN`` values are either signaled or 705 ignored (depending on the context and whether they are signaling or 706 quiet). 707 708 .. method:: max_mag(other, context=None) 709 710 Similar to the :meth:`.max` method, but the comparison is done using the 711 absolute values of the operands. 712 713 .. method:: min(other, context=None) 714 715 Like ``min(self, other)`` except that the context rounding rule is applied 716 before returning and that ``NaN`` values are either signaled or 717 ignored (depending on the context and whether they are signaling or 718 quiet). 719 720 .. method:: min_mag(other, context=None) 721 722 Similar to the :meth:`.min` method, but the comparison is done using the 723 absolute values of the operands. 724 725 .. method:: next_minus(context=None) 726 727 Return the largest number representable in the given context (or in the 728 current thread's context if no context is given) that is smaller than the 729 given operand. 730 731 .. method:: next_plus(context=None) 732 733 Return the smallest number representable in the given context (or in the 734 current thread's context if no context is given) that is larger than the 735 given operand. 736 737 .. method:: next_toward(other, context=None) 738 739 If the two operands are unequal, return the number closest to the first 740 operand in the direction of the second operand. If both operands are 741 numerically equal, return a copy of the first operand with the sign set to 742 be the same as the sign of the second operand. 743 744 .. method:: normalize(context=None) 745 746 Normalize the number by stripping the rightmost trailing zeros and 747 converting any result equal to ``Decimal('0')`` to 748 ``Decimal('0e0')``. Used for producing canonical values for attributes 749 of an equivalence class. For example, ``Decimal('32.100')`` and 750 ``Decimal('0.321000e+2')`` both normalize to the equivalent value 751 ``Decimal('32.1')``. 752 753 .. method:: number_class(context=None) 754 755 Return a string describing the *class* of the operand. The returned value 756 is one of the following ten strings. 757 758 * ``"-Infinity"``, indicating that the operand is negative infinity. 759 * ``"-Normal"``, indicating that the operand is a negative normal number. 760 * ``"-Subnormal"``, indicating that the operand is negative and subnormal. 761 * ``"-Zero"``, indicating that the operand is a negative zero. 762 * ``"+Zero"``, indicating that the operand is a positive zero. 763 * ``"+Subnormal"``, indicating that the operand is positive and subnormal. 764 * ``"+Normal"``, indicating that the operand is a positive normal number. 765 * ``"+Infinity"``, indicating that the operand is positive infinity. 766 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). 767 * ``"sNaN"``, indicating that the operand is a signaling NaN. 768 769 .. method:: quantize(exp, rounding=None, context=None) 770 771 Return a value equal to the first operand after rounding and having the 772 exponent of the second operand. 773 774 >>> Decimal('1.41421356').quantize(Decimal('1.000')) 775 Decimal('1.414') 776 777 Unlike other operations, if the length of the coefficient after the 778 quantize operation would be greater than precision, then an 779 :const:`InvalidOperation` is signaled. This guarantees that, unless there 780 is an error condition, the quantized exponent is always equal to that of 781 the right-hand operand. 782 783 Also unlike other operations, quantize never signals Underflow, even if 784 the result is subnormal and inexact. 785 786 If the exponent of the second operand is larger than that of the first 787 then rounding may be necessary. In this case, the rounding mode is 788 determined by the ``rounding`` argument if given, else by the given 789 ``context`` argument; if neither argument is given the rounding mode of 790 the current thread's context is used. 791 792 An error is returned whenever the resulting exponent is greater than 793 :attr:`~Context.Emax` or less than :meth:`~Context.Etiny`. 794 795 .. method:: radix() 796 797 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal` 798 class does all its arithmetic. Included for compatibility with the 799 specification. 800 801 .. method:: remainder_near(other, context=None) 802 803 Return the remainder from dividing *self* by *other*. This differs from 804 ``self % other`` in that the sign of the remainder is chosen so as to 805 minimize its absolute value. More precisely, the return value is 806 ``self - n * other`` where ``n`` is the integer nearest to the exact 807 value of ``self / other``, and if two integers are equally near then the 808 even one is chosen. 809 810 If the result is zero then its sign will be the sign of *self*. 811 812 >>> Decimal(18).remainder_near(Decimal(10)) 813 Decimal('-2') 814 >>> Decimal(25).remainder_near(Decimal(10)) 815 Decimal('5') 816 >>> Decimal(35).remainder_near(Decimal(10)) 817 Decimal('-5') 818 819 .. method:: rotate(other, context=None) 820 821 Return the result of rotating the digits of the first operand by an amount 822 specified by the second operand. The second operand must be an integer in 823 the range -precision through precision. The absolute value of the second 824 operand gives the number of places to rotate. If the second operand is 825 positive then rotation is to the left; otherwise rotation is to the right. 826 The coefficient of the first operand is padded on the left with zeros to 827 length precision if necessary. The sign and exponent of the first operand 828 are unchanged. 829 830 .. method:: same_quantum(other, context=None) 831 832 Test whether self and other have the same exponent or whether both are 833 ``NaN``. 834 835 This operation is unaffected by context and is quiet: no flags are changed 836 and no rounding is performed. As an exception, the C version may raise 837 InvalidOperation if the second operand cannot be converted exactly. 838 839 .. method:: scaleb(other, context=None) 840 841 Return the first operand with exponent adjusted by the second. 842 Equivalently, return the first operand multiplied by ``10**other``. The 843 second operand must be an integer. 844 845 .. method:: shift(other, context=None) 846 847 Return the result of shifting the digits of the first operand by an amount 848 specified by the second operand. The second operand must be an integer in 849 the range -precision through precision. The absolute value of the second 850 operand gives the number of places to shift. If the second operand is 851 positive then the shift is to the left; otherwise the shift is to the 852 right. Digits shifted into the coefficient are zeros. The sign and 853 exponent of the first operand are unchanged. 854 855 .. method:: sqrt(context=None) 856 857 Return the square root of the argument to full precision. 858 859 860 .. method:: to_eng_string(context=None) 861 862 Convert to a string, using engineering notation if an exponent is needed. 863 864 Engineering notation has an exponent which is a multiple of 3. This 865 can leave up to 3 digits to the left of the decimal place and may 866 require the addition of either one or two trailing zeros. 867 868 For example, this converts ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``. 869 870 .. method:: to_integral(rounding=None, context=None) 871 872 Identical to the :meth:`to_integral_value` method. The ``to_integral`` 873 name has been kept for compatibility with older versions. 874 875 .. method:: to_integral_exact(rounding=None, context=None) 876 877 Round to the nearest integer, signaling :const:`Inexact` or 878 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is 879 determined by the ``rounding`` parameter if given, else by the given 880 ``context``. If neither parameter is given then the rounding mode of the 881 current context is used. 882 883 .. method:: to_integral_value(rounding=None, context=None) 884 885 Round to the nearest integer without signaling :const:`Inexact` or 886 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the 887 rounding method in either the supplied *context* or the current context. 888 889 890.. _logical_operands_label: 891 892Logical operands 893^^^^^^^^^^^^^^^^ 894 895The :meth:`~Decimal.logical_and`, :meth:`~Decimal.logical_invert`, :meth:`~Decimal.logical_or`, 896and :meth:`~Decimal.logical_xor` methods expect their arguments to be *logical 897operands*. A *logical operand* is a :class:`Decimal` instance whose 898exponent and sign are both zero, and whose digits are all either 899``0`` or ``1``. 900 901.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 902 903 904.. _decimal-context: 905 906Context objects 907--------------- 908 909Contexts are environments for arithmetic operations. They govern precision, set 910rules for rounding, determine which signals are treated as exceptions, and limit 911the range for exponents. 912 913Each thread has its own current context which is accessed or changed using the 914:func:`getcontext` and :func:`setcontext` functions: 915 916 917.. function:: getcontext() 918 919 Return the current context for the active thread. 920 921 922.. function:: setcontext(c) 923 924 Set the current context for the active thread to *c*. 925 926You can also use the :keyword:`with` statement and the :func:`localcontext` 927function to temporarily change the active context. 928 929.. function:: localcontext(ctx=None, \*\*kwargs) 930 931 Return a context manager that will set the current context for the active thread 932 to a copy of *ctx* on entry to the with-statement and restore the previous context 933 when exiting the with-statement. If no context is specified, a copy of the 934 current context is used. The *kwargs* argument is used to set the attributes 935 of the new context. 936 937 For example, the following code sets the current decimal precision to 42 places, 938 performs a calculation, and then automatically restores the previous context:: 939 940 from decimal import localcontext 941 942 with localcontext() as ctx: 943 ctx.prec = 42 # Perform a high precision calculation 944 s = calculate_something() 945 s = +s # Round the final result back to the default precision 946 947 Using keyword arguments, the code would be the following:: 948 949 from decimal import localcontext 950 951 with localcontext(prec=42) as ctx: 952 s = calculate_something() 953 s = +s 954 955 Raises :exc:`TypeError` if *kwargs* supplies an attribute that :class:`Context` doesn't 956 support. Raises either :exc:`TypeError` or :exc:`ValueError` if *kwargs* supplies an 957 invalid value for an attribute. 958 959 .. versionchanged:: 3.11 960 :meth:`localcontext` now supports setting context attributes through the use of keyword arguments. 961 962New contexts can also be created using the :class:`Context` constructor 963described below. In addition, the module provides three pre-made contexts: 964 965 966.. class:: BasicContext 967 968 This is a standard context defined by the General Decimal Arithmetic 969 Specification. Precision is set to nine. Rounding is set to 970 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated 971 as exceptions) except :const:`Inexact`, :const:`Rounded`, and 972 :const:`Subnormal`. 973 974 Because many of the traps are enabled, this context is useful for debugging. 975 976 977.. class:: ExtendedContext 978 979 This is a standard context defined by the General Decimal Arithmetic 980 Specification. Precision is set to nine. Rounding is set to 981 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that 982 exceptions are not raised during computations). 983 984 Because the traps are disabled, this context is useful for applications that 985 prefer to have result value of ``NaN`` or ``Infinity`` instead of 986 raising exceptions. This allows an application to complete a run in the 987 presence of conditions that would otherwise halt the program. 988 989 990.. class:: DefaultContext 991 992 This context is used by the :class:`Context` constructor as a prototype for new 993 contexts. Changing a field (such a precision) has the effect of changing the 994 default for new contexts created by the :class:`Context` constructor. 995 996 This context is most useful in multi-threaded environments. Changing one of the 997 fields before threads are started has the effect of setting system-wide 998 defaults. Changing the fields after threads have started is not recommended as 999 it would require thread synchronization to prevent race conditions. 1000 1001 In single threaded environments, it is preferable to not use this context at 1002 all. Instead, simply create contexts explicitly as described below. 1003 1004 The default values are :attr:`Context.prec`\ =\ ``28``, 1005 :attr:`Context.rounding`\ =\ :const:`ROUND_HALF_EVEN`, 1006 and enabled traps for :class:`Overflow`, :class:`InvalidOperation`, and 1007 :class:`DivisionByZero`. 1008 1009In addition to the three supplied contexts, new contexts can be created with the 1010:class:`Context` constructor. 1011 1012 1013.. class:: Context(prec=None, rounding=None, Emin=None, Emax=None, capitals=None, clamp=None, flags=None, traps=None) 1014 1015 Creates a new context. If a field is not specified or is :const:`None`, the 1016 default values are copied from the :const:`DefaultContext`. If the *flags* 1017 field is not specified or is :const:`None`, all flags are cleared. 1018 1019 *prec* is an integer in the range [``1``, :const:`MAX_PREC`] that sets 1020 the precision for arithmetic operations in the context. 1021 1022 The *rounding* option is one of the constants listed in the section 1023 `Rounding Modes`_. 1024 1025 The *traps* and *flags* fields list any signals to be set. Generally, new 1026 contexts should only set traps and leave the flags clear. 1027 1028 The *Emin* and *Emax* fields are integers specifying the outer limits allowable 1029 for exponents. *Emin* must be in the range [:const:`MIN_EMIN`, ``0``], 1030 *Emax* in the range [``0``, :const:`MAX_EMAX`]. 1031 1032 The *capitals* field is either ``0`` or ``1`` (the default). If set to 1033 ``1``, exponents are printed with a capital ``E``; otherwise, a 1034 lowercase ``e`` is used: ``Decimal('6.02e+23')``. 1035 1036 The *clamp* field is either ``0`` (the default) or ``1``. 1037 If set to ``1``, the exponent ``e`` of a :class:`Decimal` 1038 instance representable in this context is strictly limited to the 1039 range ``Emin - prec + 1 <= e <= Emax - prec + 1``. If *clamp* is 1040 ``0`` then a weaker condition holds: the adjusted exponent of 1041 the :class:`Decimal` instance is at most :attr:`~Context.Emax`. When *clamp* is 1042 ``1``, a large normal number will, where possible, have its 1043 exponent reduced and a corresponding number of zeros added to its 1044 coefficient, in order to fit the exponent constraints; this 1045 preserves the value of the number but loses information about 1046 significant trailing zeros. For example:: 1047 1048 >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999') 1049 Decimal('1.23000E+999') 1050 1051 A *clamp* value of ``1`` allows compatibility with the 1052 fixed-width decimal interchange formats specified in IEEE 754. 1053 1054 The :class:`Context` class defines several general purpose methods as well as 1055 a large number of methods for doing arithmetic directly in a given context. 1056 In addition, for each of the :class:`Decimal` methods described above (with 1057 the exception of the :meth:`~Decimal.adjusted` and :meth:`~Decimal.as_tuple` methods) there is 1058 a corresponding :class:`Context` method. For example, for a :class:`Context` 1059 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is 1060 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a 1061 Python integer (an instance of :class:`int`) anywhere that a 1062 Decimal instance is accepted. 1063 1064 1065 .. method:: clear_flags() 1066 1067 Resets all of the flags to ``0``. 1068 1069 .. method:: clear_traps() 1070 1071 Resets all of the traps to ``0``. 1072 1073 .. versionadded:: 3.3 1074 1075 .. method:: copy() 1076 1077 Return a duplicate of the context. 1078 1079 .. method:: copy_decimal(num) 1080 1081 Return a copy of the Decimal instance num. 1082 1083 .. method:: create_decimal(num) 1084 1085 Creates a new Decimal instance from *num* but using *self* as 1086 context. Unlike the :class:`Decimal` constructor, the context precision, 1087 rounding method, flags, and traps are applied to the conversion. 1088 1089 This is useful because constants are often given to a greater precision 1090 than is needed by the application. Another benefit is that rounding 1091 immediately eliminates unintended effects from digits beyond the current 1092 precision. In the following example, using unrounded inputs means that 1093 adding zero to a sum can change the result: 1094 1095 .. doctest:: newcontext 1096 1097 >>> getcontext().prec = 3 1098 >>> Decimal('3.4445') + Decimal('1.0023') 1099 Decimal('4.45') 1100 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023') 1101 Decimal('4.44') 1102 1103 This method implements the to-number operation of the IBM specification. 1104 If the argument is a string, no leading or trailing whitespace or 1105 underscores are permitted. 1106 1107 .. method:: create_decimal_from_float(f) 1108 1109 Creates a new Decimal instance from a float *f* but rounding using *self* 1110 as the context. Unlike the :meth:`Decimal.from_float` class method, 1111 the context precision, rounding method, flags, and traps are applied to 1112 the conversion. 1113 1114 .. doctest:: 1115 1116 >>> context = Context(prec=5, rounding=ROUND_DOWN) 1117 >>> context.create_decimal_from_float(math.pi) 1118 Decimal('3.1415') 1119 >>> context = Context(prec=5, traps=[Inexact]) 1120 >>> context.create_decimal_from_float(math.pi) 1121 Traceback (most recent call last): 1122 ... 1123 decimal.Inexact: None 1124 1125 .. versionadded:: 3.1 1126 1127 .. method:: Etiny() 1128 1129 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent 1130 value for subnormal results. When underflow occurs, the exponent is set 1131 to :const:`Etiny`. 1132 1133 .. method:: Etop() 1134 1135 Returns a value equal to ``Emax - prec + 1``. 1136 1137 The usual approach to working with decimals is to create :class:`Decimal` 1138 instances and then apply arithmetic operations which take place within the 1139 current context for the active thread. An alternative approach is to use 1140 context methods for calculating within a specific context. The methods are 1141 similar to those for the :class:`Decimal` class and are only briefly 1142 recounted here. 1143 1144 1145 .. method:: abs(x) 1146 1147 Returns the absolute value of *x*. 1148 1149 1150 .. method:: add(x, y) 1151 1152 Return the sum of *x* and *y*. 1153 1154 1155 .. method:: canonical(x) 1156 1157 Returns the same Decimal object *x*. 1158 1159 1160 .. method:: compare(x, y) 1161 1162 Compares *x* and *y* numerically. 1163 1164 1165 .. method:: compare_signal(x, y) 1166 1167 Compares the values of the two operands numerically. 1168 1169 1170 .. method:: compare_total(x, y) 1171 1172 Compares two operands using their abstract representation. 1173 1174 1175 .. method:: compare_total_mag(x, y) 1176 1177 Compares two operands using their abstract representation, ignoring sign. 1178 1179 1180 .. method:: copy_abs(x) 1181 1182 Returns a copy of *x* with the sign set to 0. 1183 1184 1185 .. method:: copy_negate(x) 1186 1187 Returns a copy of *x* with the sign inverted. 1188 1189 1190 .. method:: copy_sign(x, y) 1191 1192 Copies the sign from *y* to *x*. 1193 1194 1195 .. method:: divide(x, y) 1196 1197 Return *x* divided by *y*. 1198 1199 1200 .. method:: divide_int(x, y) 1201 1202 Return *x* divided by *y*, truncated to an integer. 1203 1204 1205 .. method:: divmod(x, y) 1206 1207 Divides two numbers and returns the integer part of the result. 1208 1209 1210 .. method:: exp(x) 1211 1212 Returns ``e ** x``. 1213 1214 1215 .. method:: fma(x, y, z) 1216 1217 Returns *x* multiplied by *y*, plus *z*. 1218 1219 1220 .. method:: is_canonical(x) 1221 1222 Returns ``True`` if *x* is canonical; otherwise returns ``False``. 1223 1224 1225 .. method:: is_finite(x) 1226 1227 Returns ``True`` if *x* is finite; otherwise returns ``False``. 1228 1229 1230 .. method:: is_infinite(x) 1231 1232 Returns ``True`` if *x* is infinite; otherwise returns ``False``. 1233 1234 1235 .. method:: is_nan(x) 1236 1237 Returns ``True`` if *x* is a qNaN or sNaN; otherwise returns ``False``. 1238 1239 1240 .. method:: is_normal(x) 1241 1242 Returns ``True`` if *x* is a normal number; otherwise returns ``False``. 1243 1244 1245 .. method:: is_qnan(x) 1246 1247 Returns ``True`` if *x* is a quiet NaN; otherwise returns ``False``. 1248 1249 1250 .. method:: is_signed(x) 1251 1252 Returns ``True`` if *x* is negative; otherwise returns ``False``. 1253 1254 1255 .. method:: is_snan(x) 1256 1257 Returns ``True`` if *x* is a signaling NaN; otherwise returns ``False``. 1258 1259 1260 .. method:: is_subnormal(x) 1261 1262 Returns ``True`` if *x* is subnormal; otherwise returns ``False``. 1263 1264 1265 .. method:: is_zero(x) 1266 1267 Returns ``True`` if *x* is a zero; otherwise returns ``False``. 1268 1269 1270 .. method:: ln(x) 1271 1272 Returns the natural (base e) logarithm of *x*. 1273 1274 1275 .. method:: log10(x) 1276 1277 Returns the base 10 logarithm of *x*. 1278 1279 1280 .. method:: logb(x) 1281 1282 Returns the exponent of the magnitude of the operand's MSD. 1283 1284 1285 .. method:: logical_and(x, y) 1286 1287 Applies the logical operation *and* between each operand's digits. 1288 1289 1290 .. method:: logical_invert(x) 1291 1292 Invert all the digits in *x*. 1293 1294 1295 .. method:: logical_or(x, y) 1296 1297 Applies the logical operation *or* between each operand's digits. 1298 1299 1300 .. method:: logical_xor(x, y) 1301 1302 Applies the logical operation *xor* between each operand's digits. 1303 1304 1305 .. method:: max(x, y) 1306 1307 Compares two values numerically and returns the maximum. 1308 1309 1310 .. method:: max_mag(x, y) 1311 1312 Compares the values numerically with their sign ignored. 1313 1314 1315 .. method:: min(x, y) 1316 1317 Compares two values numerically and returns the minimum. 1318 1319 1320 .. method:: min_mag(x, y) 1321 1322 Compares the values numerically with their sign ignored. 1323 1324 1325 .. method:: minus(x) 1326 1327 Minus corresponds to the unary prefix minus operator in Python. 1328 1329 1330 .. method:: multiply(x, y) 1331 1332 Return the product of *x* and *y*. 1333 1334 1335 .. method:: next_minus(x) 1336 1337 Returns the largest representable number smaller than *x*. 1338 1339 1340 .. method:: next_plus(x) 1341 1342 Returns the smallest representable number larger than *x*. 1343 1344 1345 .. method:: next_toward(x, y) 1346 1347 Returns the number closest to *x*, in direction towards *y*. 1348 1349 1350 .. method:: normalize(x) 1351 1352 Reduces *x* to its simplest form. 1353 1354 1355 .. method:: number_class(x) 1356 1357 Returns an indication of the class of *x*. 1358 1359 1360 .. method:: plus(x) 1361 1362 Plus corresponds to the unary prefix plus operator in Python. This 1363 operation applies the context precision and rounding, so it is *not* an 1364 identity operation. 1365 1366 1367 .. method:: power(x, y, modulo=None) 1368 1369 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given. 1370 1371 With two arguments, compute ``x**y``. If ``x`` is negative then ``y`` 1372 must be integral. The result will be inexact unless ``y`` is integral and 1373 the result is finite and can be expressed exactly in 'precision' digits. 1374 The rounding mode of the context is used. Results are always correctly rounded 1375 in the Python version. 1376 1377 ``Decimal(0) ** Decimal(0)`` results in ``InvalidOperation``, and if ``InvalidOperation`` 1378 is not trapped, then results in ``Decimal('NaN')``. 1379 1380 .. versionchanged:: 3.3 1381 The C module computes :meth:`power` in terms of the correctly rounded 1382 :meth:`exp` and :meth:`ln` functions. The result is well-defined but 1383 only "almost always correctly rounded". 1384 1385 With three arguments, compute ``(x**y) % modulo``. For the three argument 1386 form, the following restrictions on the arguments hold: 1387 1388 - all three arguments must be integral 1389 - ``y`` must be nonnegative 1390 - at least one of ``x`` or ``y`` must be nonzero 1391 - ``modulo`` must be nonzero and have at most 'precision' digits 1392 1393 The value resulting from ``Context.power(x, y, modulo)`` is 1394 equal to the value that would be obtained by computing ``(x**y) 1395 % modulo`` with unbounded precision, but is computed more 1396 efficiently. The exponent of the result is zero, regardless of 1397 the exponents of ``x``, ``y`` and ``modulo``. The result is 1398 always exact. 1399 1400 1401 .. method:: quantize(x, y) 1402 1403 Returns a value equal to *x* (rounded), having the exponent of *y*. 1404 1405 1406 .. method:: radix() 1407 1408 Just returns 10, as this is Decimal, :) 1409 1410 1411 .. method:: remainder(x, y) 1412 1413 Returns the remainder from integer division. 1414 1415 The sign of the result, if non-zero, is the same as that of the original 1416 dividend. 1417 1418 1419 .. method:: remainder_near(x, y) 1420 1421 Returns ``x - y * n``, where *n* is the integer nearest the exact value 1422 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*). 1423 1424 1425 .. method:: rotate(x, y) 1426 1427 Returns a rotated copy of *x*, *y* times. 1428 1429 1430 .. method:: same_quantum(x, y) 1431 1432 Returns ``True`` if the two operands have the same exponent. 1433 1434 1435 .. method:: scaleb (x, y) 1436 1437 Returns the first operand after adding the second value its exp. 1438 1439 1440 .. method:: shift(x, y) 1441 1442 Returns a shifted copy of *x*, *y* times. 1443 1444 1445 .. method:: sqrt(x) 1446 1447 Square root of a non-negative number to context precision. 1448 1449 1450 .. method:: subtract(x, y) 1451 1452 Return the difference between *x* and *y*. 1453 1454 1455 .. method:: to_eng_string(x) 1456 1457 Convert to a string, using engineering notation if an exponent is needed. 1458 1459 Engineering notation has an exponent which is a multiple of 3. This 1460 can leave up to 3 digits to the left of the decimal place and may 1461 require the addition of either one or two trailing zeros. 1462 1463 1464 .. method:: to_integral_exact(x) 1465 1466 Rounds to an integer. 1467 1468 1469 .. method:: to_sci_string(x) 1470 1471 Converts a number to a string using scientific notation. 1472 1473.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1474 1475.. _decimal-rounding-modes: 1476 1477Constants 1478--------- 1479 1480The constants in this section are only relevant for the C module. They 1481are also included in the pure Python version for compatibility. 1482 1483+---------------------+---------------------+-------------------------------+ 1484| | 32-bit | 64-bit | 1485+=====================+=====================+===============================+ 1486| .. data:: MAX_PREC | ``425000000`` | ``999999999999999999`` | 1487+---------------------+---------------------+-------------------------------+ 1488| .. data:: MAX_EMAX | ``425000000`` | ``999999999999999999`` | 1489+---------------------+---------------------+-------------------------------+ 1490| .. data:: MIN_EMIN | ``-425000000`` | ``-999999999999999999`` | 1491+---------------------+---------------------+-------------------------------+ 1492| .. data:: MIN_ETINY | ``-849999999`` | ``-1999999999999999997`` | 1493+---------------------+---------------------+-------------------------------+ 1494 1495 1496.. data:: HAVE_THREADS 1497 1498 The value is ``True``. Deprecated, because Python now always has threads. 1499 1500.. deprecated:: 3.9 1501 1502.. data:: HAVE_CONTEXTVAR 1503 1504 The default value is ``True``. If Python is :option:`configured using 1505 the --without-decimal-contextvar option <--without-decimal-contextvar>`, 1506 the C version uses a thread-local rather than a coroutine-local context and the value 1507 is ``False``. This is slightly faster in some nested context scenarios. 1508 1509.. versionadded:: 3.9 backported to 3.7 and 3.8. 1510 1511 1512Rounding modes 1513-------------- 1514 1515.. data:: ROUND_CEILING 1516 1517 Round towards ``Infinity``. 1518 1519.. data:: ROUND_DOWN 1520 1521 Round towards zero. 1522 1523.. data:: ROUND_FLOOR 1524 1525 Round towards ``-Infinity``. 1526 1527.. data:: ROUND_HALF_DOWN 1528 1529 Round to nearest with ties going towards zero. 1530 1531.. data:: ROUND_HALF_EVEN 1532 1533 Round to nearest with ties going to nearest even integer. 1534 1535.. data:: ROUND_HALF_UP 1536 1537 Round to nearest with ties going away from zero. 1538 1539.. data:: ROUND_UP 1540 1541 Round away from zero. 1542 1543.. data:: ROUND_05UP 1544 1545 Round away from zero if last digit after rounding towards zero would have 1546 been 0 or 5; otherwise round towards zero. 1547 1548 1549.. _decimal-signals: 1550 1551Signals 1552------- 1553 1554Signals represent conditions that arise during computation. Each corresponds to 1555one context flag and one context trap enabler. 1556 1557The context flag is set whenever the condition is encountered. After the 1558computation, flags may be checked for informational purposes (for instance, to 1559determine whether a computation was exact). After checking the flags, be sure to 1560clear all flags before starting the next computation. 1561 1562If the context's trap enabler is set for the signal, then the condition causes a 1563Python exception to be raised. For example, if the :class:`DivisionByZero` trap 1564is set, then a :exc:`DivisionByZero` exception is raised upon encountering the 1565condition. 1566 1567 1568.. class:: Clamped 1569 1570 Altered an exponent to fit representation constraints. 1571 1572 Typically, clamping occurs when an exponent falls outside the context's 1573 :attr:`~Context.Emin` and :attr:`~Context.Emax` limits. If possible, the exponent is reduced to 1574 fit by adding zeros to the coefficient. 1575 1576 1577.. class:: DecimalException 1578 1579 Base class for other signals and a subclass of :exc:`ArithmeticError`. 1580 1581 1582.. class:: DivisionByZero 1583 1584 Signals the division of a non-infinite number by zero. 1585 1586 Can occur with division, modulo division, or when raising a number to a negative 1587 power. If this signal is not trapped, returns ``Infinity`` or 1588 ``-Infinity`` with the sign determined by the inputs to the calculation. 1589 1590 1591.. class:: Inexact 1592 1593 Indicates that rounding occurred and the result is not exact. 1594 1595 Signals when non-zero digits were discarded during rounding. The rounded result 1596 is returned. The signal flag or trap is used to detect when results are 1597 inexact. 1598 1599 1600.. class:: InvalidOperation 1601 1602 An invalid operation was performed. 1603 1604 Indicates that an operation was requested that does not make sense. If not 1605 trapped, returns ``NaN``. Possible causes include:: 1606 1607 Infinity - Infinity 1608 0 * Infinity 1609 Infinity / Infinity 1610 x % 0 1611 Infinity % x 1612 sqrt(-x) and x > 0 1613 0 ** 0 1614 x ** (non-integer) 1615 x ** Infinity 1616 1617 1618.. class:: Overflow 1619 1620 Numerical overflow. 1621 1622 Indicates the exponent is larger than :attr:`Context.Emax` after rounding has 1623 occurred. If not trapped, the result depends on the rounding mode, either 1624 pulling inward to the largest representable finite number or rounding outward 1625 to ``Infinity``. In either case, :class:`Inexact` and :class:`Rounded` 1626 are also signaled. 1627 1628 1629.. class:: Rounded 1630 1631 Rounding occurred though possibly no information was lost. 1632 1633 Signaled whenever rounding discards digits; even if those digits are zero 1634 (such as rounding ``5.00`` to ``5.0``). If not trapped, returns 1635 the result unchanged. This signal is used to detect loss of significant 1636 digits. 1637 1638 1639.. class:: Subnormal 1640 1641 Exponent was lower than :attr:`~Context.Emin` prior to rounding. 1642 1643 Occurs when an operation result is subnormal (the exponent is too small). If 1644 not trapped, returns the result unchanged. 1645 1646 1647.. class:: Underflow 1648 1649 Numerical underflow with result rounded to zero. 1650 1651 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact` 1652 and :class:`Subnormal` are also signaled. 1653 1654 1655.. class:: FloatOperation 1656 1657 Enable stricter semantics for mixing floats and Decimals. 1658 1659 If the signal is not trapped (default), mixing floats and Decimals is 1660 permitted in the :class:`~decimal.Decimal` constructor, 1661 :meth:`~decimal.Context.create_decimal` and all comparison operators. 1662 Both conversion and comparisons are exact. Any occurrence of a mixed 1663 operation is silently recorded by setting :exc:`FloatOperation` in the 1664 context flags. Explicit conversions with :meth:`~decimal.Decimal.from_float` 1665 or :meth:`~decimal.Context.create_decimal_from_float` do not set the flag. 1666 1667 Otherwise (the signal is trapped), only equality comparisons and explicit 1668 conversions are silent. All other mixed operations raise :exc:`FloatOperation`. 1669 1670 1671The following table summarizes the hierarchy of signals:: 1672 1673 exceptions.ArithmeticError(exceptions.Exception) 1674 DecimalException 1675 Clamped 1676 DivisionByZero(DecimalException, exceptions.ZeroDivisionError) 1677 Inexact 1678 Overflow(Inexact, Rounded) 1679 Underflow(Inexact, Rounded, Subnormal) 1680 InvalidOperation 1681 Rounded 1682 Subnormal 1683 FloatOperation(DecimalException, exceptions.TypeError) 1684 1685.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1686 1687 1688 1689.. _decimal-notes: 1690 1691Floating Point Notes 1692-------------------- 1693 1694 1695Mitigating round-off error with increased precision 1696^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1697 1698The use of decimal floating point eliminates decimal representation error 1699(making it possible to represent ``0.1`` exactly); however, some operations 1700can still incur round-off error when non-zero digits exceed the fixed precision. 1701 1702The effects of round-off error can be amplified by the addition or subtraction 1703of nearly offsetting quantities resulting in loss of significance. Knuth 1704provides two instructive examples where rounded floating point arithmetic with 1705insufficient precision causes the breakdown of the associative and distributive 1706properties of addition: 1707 1708.. doctest:: newcontext 1709 1710 # Examples from Seminumerical Algorithms, Section 4.2.2. 1711 >>> from decimal import Decimal, getcontext 1712 >>> getcontext().prec = 8 1713 1714 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') 1715 >>> (u + v) + w 1716 Decimal('9.5111111') 1717 >>> u + (v + w) 1718 Decimal('10') 1719 1720 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') 1721 >>> (u*v) + (u*w) 1722 Decimal('0.01') 1723 >>> u * (v+w) 1724 Decimal('0.0060000') 1725 1726The :mod:`decimal` module makes it possible to restore the identities by 1727expanding the precision sufficiently to avoid loss of significance: 1728 1729.. doctest:: newcontext 1730 1731 >>> getcontext().prec = 20 1732 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') 1733 >>> (u + v) + w 1734 Decimal('9.51111111') 1735 >>> u + (v + w) 1736 Decimal('9.51111111') 1737 >>> 1738 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') 1739 >>> (u*v) + (u*w) 1740 Decimal('0.0060000') 1741 >>> u * (v+w) 1742 Decimal('0.0060000') 1743 1744 1745Special values 1746^^^^^^^^^^^^^^ 1747 1748The number system for the :mod:`decimal` module provides special values 1749including ``NaN``, ``sNaN``, ``-Infinity``, ``Infinity``, 1750and two zeros, ``+0`` and ``-0``. 1751 1752Infinities can be constructed directly with: ``Decimal('Infinity')``. Also, 1753they can arise from dividing by zero when the :exc:`DivisionByZero` signal is 1754not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity 1755can result from rounding beyond the limits of the largest representable number. 1756 1757The infinities are signed (affine) and can be used in arithmetic operations 1758where they get treated as very large, indeterminate numbers. For instance, 1759adding a constant to infinity gives another infinite result. 1760 1761Some operations are indeterminate and return ``NaN``, or if the 1762:exc:`InvalidOperation` signal is trapped, raise an exception. For example, 1763``0/0`` returns ``NaN`` which means "not a number". This variety of 1764``NaN`` is quiet and, once created, will flow through other computations 1765always resulting in another ``NaN``. This behavior can be useful for a 1766series of computations that occasionally have missing inputs --- it allows the 1767calculation to proceed while flagging specific results as invalid. 1768 1769A variant is ``sNaN`` which signals rather than remaining quiet after every 1770operation. This is a useful return value when an invalid result needs to 1771interrupt a calculation for special handling. 1772 1773The behavior of Python's comparison operators can be a little surprising where a 1774``NaN`` is involved. A test for equality where one of the operands is a 1775quiet or signaling ``NaN`` always returns :const:`False` (even when doing 1776``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns 1777:const:`True`. An attempt to compare two Decimals using any of the ``<``, 1778``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal 1779if either operand is a ``NaN``, and return :const:`False` if this signal is 1780not trapped. Note that the General Decimal Arithmetic specification does not 1781specify the behavior of direct comparisons; these rules for comparisons 1782involving a ``NaN`` were taken from the IEEE 854 standard (see Table 3 in 1783section 5.7). To ensure strict standards-compliance, use the :meth:`~Decimal.compare` 1784and :meth:`~Decimal.compare_signal` methods instead. 1785 1786The signed zeros can result from calculations that underflow. They keep the sign 1787that would have resulted if the calculation had been carried out to greater 1788precision. Since their magnitude is zero, both positive and negative zeros are 1789treated as equal and their sign is informational. 1790 1791In addition to the two signed zeros which are distinct yet equal, there are 1792various representations of zero with differing precisions yet equivalent in 1793value. This takes a bit of getting used to. For an eye accustomed to 1794normalized floating point representations, it is not immediately obvious that 1795the following calculation returns a value equal to zero: 1796 1797 >>> 1 / Decimal('Infinity') 1798 Decimal('0E-1000026') 1799 1800.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1801 1802 1803.. _decimal-threads: 1804 1805Working with threads 1806-------------------- 1807 1808The :func:`getcontext` function accesses a different :class:`Context` object for 1809each thread. Having separate thread contexts means that threads may make 1810changes (such as ``getcontext().prec=10``) without interfering with other threads. 1811 1812Likewise, the :func:`setcontext` function automatically assigns its target to 1813the current thread. 1814 1815If :func:`setcontext` has not been called before :func:`getcontext`, then 1816:func:`getcontext` will automatically create a new context for use in the 1817current thread. 1818 1819The new context is copied from a prototype context called *DefaultContext*. To 1820control the defaults so that each thread will use the same values throughout the 1821application, directly modify the *DefaultContext* object. This should be done 1822*before* any threads are started so that there won't be a race condition between 1823threads calling :func:`getcontext`. For example:: 1824 1825 # Set applicationwide defaults for all threads about to be launched 1826 DefaultContext.prec = 12 1827 DefaultContext.rounding = ROUND_DOWN 1828 DefaultContext.traps = ExtendedContext.traps.copy() 1829 DefaultContext.traps[InvalidOperation] = 1 1830 setcontext(DefaultContext) 1831 1832 # Afterwards, the threads can be started 1833 t1.start() 1834 t2.start() 1835 t3.start() 1836 . . . 1837 1838.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1839 1840 1841.. _decimal-recipes: 1842 1843Recipes 1844------- 1845 1846Here are a few recipes that serve as utility functions and that demonstrate ways 1847to work with the :class:`Decimal` class:: 1848 1849 def moneyfmt(value, places=2, curr='', sep=',', dp='.', 1850 pos='', neg='-', trailneg=''): 1851 """Convert Decimal to a money formatted string. 1852 1853 places: required number of places after the decimal point 1854 curr: optional currency symbol before the sign (may be blank) 1855 sep: optional grouping separator (comma, period, space, or blank) 1856 dp: decimal point indicator (comma or period) 1857 only specify as blank when places is zero 1858 pos: optional sign for positive numbers: '+', space or blank 1859 neg: optional sign for negative numbers: '-', '(', space or blank 1860 trailneg:optional trailing minus indicator: '-', ')', space or blank 1861 1862 >>> d = Decimal('-1234567.8901') 1863 >>> moneyfmt(d, curr='$') 1864 '-$1,234,567.89' 1865 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-') 1866 '1.234.568-' 1867 >>> moneyfmt(d, curr='$', neg='(', trailneg=')') 1868 '($1,234,567.89)' 1869 >>> moneyfmt(Decimal(123456789), sep=' ') 1870 '123 456 789.00' 1871 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>') 1872 '<0.02>' 1873 1874 """ 1875 q = Decimal(10) ** -places # 2 places --> '0.01' 1876 sign, digits, exp = value.quantize(q).as_tuple() 1877 result = [] 1878 digits = list(map(str, digits)) 1879 build, next = result.append, digits.pop 1880 if sign: 1881 build(trailneg) 1882 for i in range(places): 1883 build(next() if digits else '0') 1884 if places: 1885 build(dp) 1886 if not digits: 1887 build('0') 1888 i = 0 1889 while digits: 1890 build(next()) 1891 i += 1 1892 if i == 3 and digits: 1893 i = 0 1894 build(sep) 1895 build(curr) 1896 build(neg if sign else pos) 1897 return ''.join(reversed(result)) 1898 1899 def pi(): 1900 """Compute Pi to the current precision. 1901 1902 >>> print(pi()) 1903 3.141592653589793238462643383 1904 1905 """ 1906 getcontext().prec += 2 # extra digits for intermediate steps 1907 three = Decimal(3) # substitute "three=3.0" for regular floats 1908 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 1909 while s != lasts: 1910 lasts = s 1911 n, na = n+na, na+8 1912 d, da = d+da, da+32 1913 t = (t * n) / d 1914 s += t 1915 getcontext().prec -= 2 1916 return +s # unary plus applies the new precision 1917 1918 def exp(x): 1919 """Return e raised to the power of x. Result type matches input type. 1920 1921 >>> print(exp(Decimal(1))) 1922 2.718281828459045235360287471 1923 >>> print(exp(Decimal(2))) 1924 7.389056098930650227230427461 1925 >>> print(exp(2.0)) 1926 7.38905609893 1927 >>> print(exp(2+0j)) 1928 (7.38905609893+0j) 1929 1930 """ 1931 getcontext().prec += 2 1932 i, lasts, s, fact, num = 0, 0, 1, 1, 1 1933 while s != lasts: 1934 lasts = s 1935 i += 1 1936 fact *= i 1937 num *= x 1938 s += num / fact 1939 getcontext().prec -= 2 1940 return +s 1941 1942 def cos(x): 1943 """Return the cosine of x as measured in radians. 1944 1945 The Taylor series approximation works best for a small value of x. 1946 For larger values, first compute x = x % (2 * pi). 1947 1948 >>> print(cos(Decimal('0.5'))) 1949 0.8775825618903727161162815826 1950 >>> print(cos(0.5)) 1951 0.87758256189 1952 >>> print(cos(0.5+0j)) 1953 (0.87758256189+0j) 1954 1955 """ 1956 getcontext().prec += 2 1957 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1 1958 while s != lasts: 1959 lasts = s 1960 i += 2 1961 fact *= i * (i-1) 1962 num *= x * x 1963 sign *= -1 1964 s += num / fact * sign 1965 getcontext().prec -= 2 1966 return +s 1967 1968 def sin(x): 1969 """Return the sine of x as measured in radians. 1970 1971 The Taylor series approximation works best for a small value of x. 1972 For larger values, first compute x = x % (2 * pi). 1973 1974 >>> print(sin(Decimal('0.5'))) 1975 0.4794255386042030002732879352 1976 >>> print(sin(0.5)) 1977 0.479425538604 1978 >>> print(sin(0.5+0j)) 1979 (0.479425538604+0j) 1980 1981 """ 1982 getcontext().prec += 2 1983 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1 1984 while s != lasts: 1985 lasts = s 1986 i += 2 1987 fact *= i * (i-1) 1988 num *= x * x 1989 sign *= -1 1990 s += num / fact * sign 1991 getcontext().prec -= 2 1992 return +s 1993 1994 1995.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1996 1997 1998.. _decimal-faq: 1999 2000Decimal FAQ 2001----------- 2002 2003Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to 2004minimize typing when using the interactive interpreter? 2005 2006A. Some users abbreviate the constructor to just a single letter: 2007 2008 >>> D = decimal.Decimal 2009 >>> D('1.23') + D('3.45') 2010 Decimal('4.68') 2011 2012Q. In a fixed-point application with two decimal places, some inputs have many 2013places and need to be rounded. Others are not supposed to have excess digits 2014and need to be validated. What methods should be used? 2015 2016A. The :meth:`~Decimal.quantize` method rounds to a fixed number of decimal places. If 2017the :const:`Inexact` trap is set, it is also useful for validation: 2018 2019 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01') 2020 2021 >>> # Round to two places 2022 >>> Decimal('3.214').quantize(TWOPLACES) 2023 Decimal('3.21') 2024 2025 >>> # Validate that a number does not exceed two places 2026 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact])) 2027 Decimal('3.21') 2028 2029 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact])) 2030 Traceback (most recent call last): 2031 ... 2032 Inexact: None 2033 2034Q. Once I have valid two place inputs, how do I maintain that invariant 2035throughout an application? 2036 2037A. Some operations like addition, subtraction, and multiplication by an integer 2038will automatically preserve fixed point. Others operations, like division and 2039non-integer multiplication, will change the number of decimal places and need to 2040be followed-up with a :meth:`~Decimal.quantize` step: 2041 2042 >>> a = Decimal('102.72') # Initial fixed-point values 2043 >>> b = Decimal('3.17') 2044 >>> a + b # Addition preserves fixed-point 2045 Decimal('105.89') 2046 >>> a - b 2047 Decimal('99.55') 2048 >>> a * 42 # So does integer multiplication 2049 Decimal('4314.24') 2050 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication 2051 Decimal('325.62') 2052 >>> (b / a).quantize(TWOPLACES) # And quantize division 2053 Decimal('0.03') 2054 2055In developing fixed-point applications, it is convenient to define functions 2056to handle the :meth:`~Decimal.quantize` step: 2057 2058 >>> def mul(x, y, fp=TWOPLACES): 2059 ... return (x * y).quantize(fp) 2060 >>> def div(x, y, fp=TWOPLACES): 2061 ... return (x / y).quantize(fp) 2062 2063 >>> mul(a, b) # Automatically preserve fixed-point 2064 Decimal('325.62') 2065 >>> div(b, a) 2066 Decimal('0.03') 2067 2068Q. There are many ways to express the same value. The numbers ``200``, 2069``200.000``, ``2E2``, and ``.02E+4`` all have the same value at 2070various precisions. Is there a way to transform them to a single recognizable 2071canonical value? 2072 2073A. The :meth:`~Decimal.normalize` method maps all equivalent values to a single 2074representative: 2075 2076 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split()) 2077 >>> [v.normalize() for v in values] 2078 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')] 2079 2080Q. Some decimal values always print with exponential notation. Is there a way 2081to get a non-exponential representation? 2082 2083A. For some values, exponential notation is the only way to express the number 2084of significant places in the coefficient. For example, expressing 2085``5.0E+3`` as ``5000`` keeps the value constant but cannot show the 2086original's two-place significance. 2087 2088If an application does not care about tracking significance, it is easy to 2089remove the exponent and trailing zeroes, losing significance, but keeping the 2090value unchanged: 2091 2092 >>> def remove_exponent(d): 2093 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize() 2094 2095 >>> remove_exponent(Decimal('5E+3')) 2096 Decimal('5000') 2097 2098Q. Is there a way to convert a regular float to a :class:`Decimal`? 2099 2100A. Yes, any binary floating point number can be exactly expressed as a 2101Decimal though an exact conversion may take more precision than intuition would 2102suggest: 2103 2104.. doctest:: 2105 2106 >>> Decimal(math.pi) 2107 Decimal('3.141592653589793115997963468544185161590576171875') 2108 2109Q. Within a complex calculation, how can I make sure that I haven't gotten a 2110spurious result because of insufficient precision or rounding anomalies. 2111 2112A. The decimal module makes it easy to test results. A best practice is to 2113re-run calculations using greater precision and with various rounding modes. 2114Widely differing results indicate insufficient precision, rounding mode issues, 2115ill-conditioned inputs, or a numerically unstable algorithm. 2116 2117Q. I noticed that context precision is applied to the results of operations but 2118not to the inputs. Is there anything to watch out for when mixing values of 2119different precisions? 2120 2121A. Yes. The principle is that all values are considered to be exact and so is 2122the arithmetic on those values. Only the results are rounded. The advantage 2123for inputs is that "what you type is what you get". A disadvantage is that the 2124results can look odd if you forget that the inputs haven't been rounded: 2125 2126.. doctest:: newcontext 2127 2128 >>> getcontext().prec = 3 2129 >>> Decimal('3.104') + Decimal('2.104') 2130 Decimal('5.21') 2131 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104') 2132 Decimal('5.20') 2133 2134The solution is either to increase precision or to force rounding of inputs 2135using the unary plus operation: 2136 2137.. doctest:: newcontext 2138 2139 >>> getcontext().prec = 3 2140 >>> +Decimal('1.23456789') # unary plus triggers rounding 2141 Decimal('1.23') 2142 2143Alternatively, inputs can be rounded upon creation using the 2144:meth:`Context.create_decimal` method: 2145 2146 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678') 2147 Decimal('1.2345') 2148 2149Q. Is the CPython implementation fast for large numbers? 2150 2151A. Yes. In the CPython and PyPy3 implementations, the C/CFFI versions of 2152the decimal module integrate the high speed `libmpdec 2153<https://www.bytereef.org/mpdecimal/doc/libmpdec/index.html>`_ library for 2154arbitrary precision correctly rounded decimal floating point arithmetic [#]_. 2155``libmpdec`` uses `Karatsuba multiplication 2156<https://en.wikipedia.org/wiki/Karatsuba_algorithm>`_ 2157for medium-sized numbers and the `Number Theoretic Transform 2158<https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform>`_ 2159for very large numbers. 2160 2161The context must be adapted for exact arbitrary precision arithmetic. :attr:`~Context.Emin` 2162and :attr:`~Context.Emax` should always be set to the maximum values, :attr:`~Context.clamp` 2163should always be 0 (the default). Setting :attr:`~Context.prec` requires some care. 2164 2165The easiest approach for trying out bignum arithmetic is to use the maximum 2166value for :attr:`~Context.prec` as well [#]_:: 2167 2168 >>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN)) 2169 >>> x = Decimal(2) ** 256 2170 >>> x / 128 2171 Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312') 2172 2173 2174For inexact results, :attr:`MAX_PREC` is far too large on 64-bit platforms and 2175the available memory will be insufficient:: 2176 2177 >>> Decimal(1) / 3 2178 Traceback (most recent call last): 2179 File "<stdin>", line 1, in <module> 2180 MemoryError 2181 2182On systems with overallocation (e.g. Linux), a more sophisticated approach is to 2183adjust :attr:`~Context.prec` to the amount of available RAM. Suppose that you have 8GB of 2184RAM and expect 10 simultaneous operands using a maximum of 500MB each:: 2185 2186 >>> import sys 2187 >>> 2188 >>> # Maximum number of digits for a single operand using 500MB in 8-byte words 2189 >>> # with 19 digits per word (4-byte and 9 digits for the 32-bit build): 2190 >>> maxdigits = 19 * ((500 * 1024**2) // 8) 2191 >>> 2192 >>> # Check that this works: 2193 >>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN) 2194 >>> c.traps[Inexact] = True 2195 >>> setcontext(c) 2196 >>> 2197 >>> # Fill the available precision with nines: 2198 >>> x = Decimal(0).logical_invert() * 9 2199 >>> sys.getsizeof(x) 2200 524288112 2201 >>> x + 2 2202 Traceback (most recent call last): 2203 File "<stdin>", line 1, in <module> 2204 decimal.Inexact: [<class 'decimal.Inexact'>] 2205 2206In general (and especially on systems without overallocation), it is recommended 2207to estimate even tighter bounds and set the :attr:`Inexact` trap if all calculations 2208are expected to be exact. 2209 2210 2211.. [#] 2212 .. versionadded:: 3.3 2213 2214.. [#] 2215 .. versionchanged:: 3.9 2216 This approach now works for all exact results except for non-integer powers. 2217