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 Used for producing canonical values of an equivalence 747 class within either the current context or the specified context. 748 749 This has the same semantics as the unary plus operation, except that if 750 the final result is finite it is reduced to its simplest form, with all 751 trailing zeros removed and its sign preserved. That is, while the 752 coefficient is non-zero and a multiple of ten the coefficient is divided 753 by ten and the exponent is incremented by 1. Otherwise (the coefficient is 754 zero) the exponent is set to 0. In all cases the sign is unchanged. 755 756 For example, ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both 757 normalize to the equivalent value ``Decimal('32.1')``. 758 759 Note that rounding is applied *before* reducing to simplest form. 760 761 In the latest versions of the specification, this operation is also known 762 as ``reduce``. 763 764 .. method:: number_class(context=None) 765 766 Return a string describing the *class* of the operand. The returned value 767 is one of the following ten strings. 768 769 * ``"-Infinity"``, indicating that the operand is negative infinity. 770 * ``"-Normal"``, indicating that the operand is a negative normal number. 771 * ``"-Subnormal"``, indicating that the operand is negative and subnormal. 772 * ``"-Zero"``, indicating that the operand is a negative zero. 773 * ``"+Zero"``, indicating that the operand is a positive zero. 774 * ``"+Subnormal"``, indicating that the operand is positive and subnormal. 775 * ``"+Normal"``, indicating that the operand is a positive normal number. 776 * ``"+Infinity"``, indicating that the operand is positive infinity. 777 * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). 778 * ``"sNaN"``, indicating that the operand is a signaling NaN. 779 780 .. method:: quantize(exp, rounding=None, context=None) 781 782 Return a value equal to the first operand after rounding and having the 783 exponent of the second operand. 784 785 >>> Decimal('1.41421356').quantize(Decimal('1.000')) 786 Decimal('1.414') 787 788 Unlike other operations, if the length of the coefficient after the 789 quantize operation would be greater than precision, then an 790 :const:`InvalidOperation` is signaled. This guarantees that, unless there 791 is an error condition, the quantized exponent is always equal to that of 792 the right-hand operand. 793 794 Also unlike other operations, quantize never signals Underflow, even if 795 the result is subnormal and inexact. 796 797 If the exponent of the second operand is larger than that of the first 798 then rounding may be necessary. In this case, the rounding mode is 799 determined by the ``rounding`` argument if given, else by the given 800 ``context`` argument; if neither argument is given the rounding mode of 801 the current thread's context is used. 802 803 An error is returned whenever the resulting exponent is greater than 804 :attr:`~Context.Emax` or less than :meth:`~Context.Etiny`. 805 806 .. method:: radix() 807 808 Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal` 809 class does all its arithmetic. Included for compatibility with the 810 specification. 811 812 .. method:: remainder_near(other, context=None) 813 814 Return the remainder from dividing *self* by *other*. This differs from 815 ``self % other`` in that the sign of the remainder is chosen so as to 816 minimize its absolute value. More precisely, the return value is 817 ``self - n * other`` where ``n`` is the integer nearest to the exact 818 value of ``self / other``, and if two integers are equally near then the 819 even one is chosen. 820 821 If the result is zero then its sign will be the sign of *self*. 822 823 >>> Decimal(18).remainder_near(Decimal(10)) 824 Decimal('-2') 825 >>> Decimal(25).remainder_near(Decimal(10)) 826 Decimal('5') 827 >>> Decimal(35).remainder_near(Decimal(10)) 828 Decimal('-5') 829 830 .. method:: rotate(other, context=None) 831 832 Return the result of rotating the digits of the first operand by an amount 833 specified by the second operand. The second operand must be an integer in 834 the range -precision through precision. The absolute value of the second 835 operand gives the number of places to rotate. If the second operand is 836 positive then rotation is to the left; otherwise rotation is to the right. 837 The coefficient of the first operand is padded on the left with zeros to 838 length precision if necessary. The sign and exponent of the first operand 839 are unchanged. 840 841 .. method:: same_quantum(other, context=None) 842 843 Test whether self and other have the same exponent or whether both are 844 ``NaN``. 845 846 This operation is unaffected by context and is quiet: no flags are changed 847 and no rounding is performed. As an exception, the C version may raise 848 InvalidOperation if the second operand cannot be converted exactly. 849 850 .. method:: scaleb(other, context=None) 851 852 Return the first operand with exponent adjusted by the second. 853 Equivalently, return the first operand multiplied by ``10**other``. The 854 second operand must be an integer. 855 856 .. method:: shift(other, context=None) 857 858 Return the result of shifting the digits of the first operand by an amount 859 specified by the second operand. The second operand must be an integer in 860 the range -precision through precision. The absolute value of the second 861 operand gives the number of places to shift. If the second operand is 862 positive then the shift is to the left; otherwise the shift is to the 863 right. Digits shifted into the coefficient are zeros. The sign and 864 exponent of the first operand are unchanged. 865 866 .. method:: sqrt(context=None) 867 868 Return the square root of the argument to full precision. 869 870 871 .. method:: to_eng_string(context=None) 872 873 Convert to a string, using engineering notation if an exponent is needed. 874 875 Engineering notation has an exponent which is a multiple of 3. This 876 can leave up to 3 digits to the left of the decimal place and may 877 require the addition of either one or two trailing zeros. 878 879 For example, this converts ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``. 880 881 .. method:: to_integral(rounding=None, context=None) 882 883 Identical to the :meth:`to_integral_value` method. The ``to_integral`` 884 name has been kept for compatibility with older versions. 885 886 .. method:: to_integral_exact(rounding=None, context=None) 887 888 Round to the nearest integer, signaling :const:`Inexact` or 889 :const:`Rounded` as appropriate if rounding occurs. The rounding mode is 890 determined by the ``rounding`` parameter if given, else by the given 891 ``context``. If neither parameter is given then the rounding mode of the 892 current context is used. 893 894 .. method:: to_integral_value(rounding=None, context=None) 895 896 Round to the nearest integer without signaling :const:`Inexact` or 897 :const:`Rounded`. If given, applies *rounding*; otherwise, uses the 898 rounding method in either the supplied *context* or the current context. 899 900 Decimal numbers can be rounded using the :func:`.round` function: 901 902 .. describe:: round(number) 903 .. describe:: round(number, ndigits) 904 905 If *ndigits* is not given or ``None``, 906 returns the nearest :class:`int` to *number*, 907 rounding ties to even, and ignoring the rounding mode of the 908 :class:`Decimal` context. Raises :exc:`OverflowError` if *number* is an 909 infinity or :exc:`ValueError` if it is a (quiet or signaling) NaN. 910 911 If *ndigits* is an :class:`int`, the context's rounding mode is respected 912 and a :class:`Decimal` representing *number* rounded to the nearest 913 multiple of ``Decimal('1E-ndigits')`` is returned; in this case, 914 ``round(number, ndigits)`` is equivalent to 915 ``self.quantize(Decimal('1E-ndigits'))``. Returns ``Decimal('NaN')`` if 916 *number* is a quiet NaN. Raises :class:`InvalidOperation` if *number* 917 is an infinity, a signaling NaN, or if the length of the coefficient after 918 the quantize operation would be greater than the current context's 919 precision. In other words, for the non-corner cases: 920 921 * if *ndigits* is positive, return *number* rounded to *ndigits* decimal 922 places; 923 * if *ndigits* is zero, return *number* rounded to the nearest integer; 924 * if *ndigits* is negative, return *number* rounded to the nearest 925 multiple of ``10**abs(ndigits)``. 926 927 For example:: 928 929 >>> from decimal import Decimal, getcontext, ROUND_DOWN 930 >>> getcontext().rounding = ROUND_DOWN 931 >>> round(Decimal('3.75')) # context rounding ignored 932 4 933 >>> round(Decimal('3.5')) # round-ties-to-even 934 4 935 >>> round(Decimal('3.75'), 0) # uses the context rounding 936 Decimal('3') 937 >>> round(Decimal('3.75'), 1) 938 Decimal('3.7') 939 >>> round(Decimal('3.75'), -1) 940 Decimal('0E+1') 941 942 943.. _logical_operands_label: 944 945Logical operands 946^^^^^^^^^^^^^^^^ 947 948The :meth:`~Decimal.logical_and`, :meth:`~Decimal.logical_invert`, :meth:`~Decimal.logical_or`, 949and :meth:`~Decimal.logical_xor` methods expect their arguments to be *logical 950operands*. A *logical operand* is a :class:`Decimal` instance whose 951exponent and sign are both zero, and whose digits are all either 952``0`` or ``1``. 953 954.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 955 956 957.. _decimal-context: 958 959Context objects 960--------------- 961 962Contexts are environments for arithmetic operations. They govern precision, set 963rules for rounding, determine which signals are treated as exceptions, and limit 964the range for exponents. 965 966Each thread has its own current context which is accessed or changed using the 967:func:`getcontext` and :func:`setcontext` functions: 968 969 970.. function:: getcontext() 971 972 Return the current context for the active thread. 973 974 975.. function:: setcontext(c) 976 977 Set the current context for the active thread to *c*. 978 979You can also use the :keyword:`with` statement and the :func:`localcontext` 980function to temporarily change the active context. 981 982.. function:: localcontext(ctx=None, **kwargs) 983 984 Return a context manager that will set the current context for the active thread 985 to a copy of *ctx* on entry to the with-statement and restore the previous context 986 when exiting the with-statement. If no context is specified, a copy of the 987 current context is used. The *kwargs* argument is used to set the attributes 988 of the new context. 989 990 For example, the following code sets the current decimal precision to 42 places, 991 performs a calculation, and then automatically restores the previous context:: 992 993 from decimal import localcontext 994 995 with localcontext() as ctx: 996 ctx.prec = 42 # Perform a high precision calculation 997 s = calculate_something() 998 s = +s # Round the final result back to the default precision 999 1000 Using keyword arguments, the code would be the following:: 1001 1002 from decimal import localcontext 1003 1004 with localcontext(prec=42) as ctx: 1005 s = calculate_something() 1006 s = +s 1007 1008 Raises :exc:`TypeError` if *kwargs* supplies an attribute that :class:`Context` doesn't 1009 support. Raises either :exc:`TypeError` or :exc:`ValueError` if *kwargs* supplies an 1010 invalid value for an attribute. 1011 1012 .. versionchanged:: 3.11 1013 :meth:`localcontext` now supports setting context attributes through the use of keyword arguments. 1014 1015New contexts can also be created using the :class:`Context` constructor 1016described below. In addition, the module provides three pre-made contexts: 1017 1018 1019.. class:: BasicContext 1020 1021 This is a standard context defined by the General Decimal Arithmetic 1022 Specification. Precision is set to nine. Rounding is set to 1023 :const:`ROUND_HALF_UP`. All flags are cleared. All traps are enabled (treated 1024 as exceptions) except :const:`Inexact`, :const:`Rounded`, and 1025 :const:`Subnormal`. 1026 1027 Because many of the traps are enabled, this context is useful for debugging. 1028 1029 1030.. class:: ExtendedContext 1031 1032 This is a standard context defined by the General Decimal Arithmetic 1033 Specification. Precision is set to nine. Rounding is set to 1034 :const:`ROUND_HALF_EVEN`. All flags are cleared. No traps are enabled (so that 1035 exceptions are not raised during computations). 1036 1037 Because the traps are disabled, this context is useful for applications that 1038 prefer to have result value of ``NaN`` or ``Infinity`` instead of 1039 raising exceptions. This allows an application to complete a run in the 1040 presence of conditions that would otherwise halt the program. 1041 1042 1043.. class:: DefaultContext 1044 1045 This context is used by the :class:`Context` constructor as a prototype for new 1046 contexts. Changing a field (such a precision) has the effect of changing the 1047 default for new contexts created by the :class:`Context` constructor. 1048 1049 This context is most useful in multi-threaded environments. Changing one of the 1050 fields before threads are started has the effect of setting system-wide 1051 defaults. Changing the fields after threads have started is not recommended as 1052 it would require thread synchronization to prevent race conditions. 1053 1054 In single threaded environments, it is preferable to not use this context at 1055 all. Instead, simply create contexts explicitly as described below. 1056 1057 The default values are :attr:`Context.prec`\ =\ ``28``, 1058 :attr:`Context.rounding`\ =\ :const:`ROUND_HALF_EVEN`, 1059 and enabled traps for :class:`Overflow`, :class:`InvalidOperation`, and 1060 :class:`DivisionByZero`. 1061 1062In addition to the three supplied contexts, new contexts can be created with the 1063:class:`Context` constructor. 1064 1065 1066.. class:: Context(prec=None, rounding=None, Emin=None, Emax=None, capitals=None, clamp=None, flags=None, traps=None) 1067 1068 Creates a new context. If a field is not specified or is :const:`None`, the 1069 default values are copied from the :const:`DefaultContext`. If the *flags* 1070 field is not specified or is :const:`None`, all flags are cleared. 1071 1072 *prec* is an integer in the range [``1``, :const:`MAX_PREC`] that sets 1073 the precision for arithmetic operations in the context. 1074 1075 The *rounding* option is one of the constants listed in the section 1076 `Rounding Modes`_. 1077 1078 The *traps* and *flags* fields list any signals to be set. Generally, new 1079 contexts should only set traps and leave the flags clear. 1080 1081 The *Emin* and *Emax* fields are integers specifying the outer limits allowable 1082 for exponents. *Emin* must be in the range [:const:`MIN_EMIN`, ``0``], 1083 *Emax* in the range [``0``, :const:`MAX_EMAX`]. 1084 1085 The *capitals* field is either ``0`` or ``1`` (the default). If set to 1086 ``1``, exponents are printed with a capital ``E``; otherwise, a 1087 lowercase ``e`` is used: ``Decimal('6.02e+23')``. 1088 1089 The *clamp* field is either ``0`` (the default) or ``1``. 1090 If set to ``1``, the exponent ``e`` of a :class:`Decimal` 1091 instance representable in this context is strictly limited to the 1092 range ``Emin - prec + 1 <= e <= Emax - prec + 1``. If *clamp* is 1093 ``0`` then a weaker condition holds: the adjusted exponent of 1094 the :class:`Decimal` instance is at most :attr:`~Context.Emax`. When *clamp* is 1095 ``1``, a large normal number will, where possible, have its 1096 exponent reduced and a corresponding number of zeros added to its 1097 coefficient, in order to fit the exponent constraints; this 1098 preserves the value of the number but loses information about 1099 significant trailing zeros. For example:: 1100 1101 >>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999') 1102 Decimal('1.23000E+999') 1103 1104 A *clamp* value of ``1`` allows compatibility with the 1105 fixed-width decimal interchange formats specified in IEEE 754. 1106 1107 The :class:`Context` class defines several general purpose methods as well as 1108 a large number of methods for doing arithmetic directly in a given context. 1109 In addition, for each of the :class:`Decimal` methods described above (with 1110 the exception of the :meth:`~Decimal.adjusted` and :meth:`~Decimal.as_tuple` methods) there is 1111 a corresponding :class:`Context` method. For example, for a :class:`Context` 1112 instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is 1113 equivalent to ``x.exp(context=C)``. Each :class:`Context` method accepts a 1114 Python integer (an instance of :class:`int`) anywhere that a 1115 Decimal instance is accepted. 1116 1117 1118 .. method:: clear_flags() 1119 1120 Resets all of the flags to ``0``. 1121 1122 .. method:: clear_traps() 1123 1124 Resets all of the traps to ``0``. 1125 1126 .. versionadded:: 3.3 1127 1128 .. method:: copy() 1129 1130 Return a duplicate of the context. 1131 1132 .. method:: copy_decimal(num) 1133 1134 Return a copy of the Decimal instance num. 1135 1136 .. method:: create_decimal(num) 1137 1138 Creates a new Decimal instance from *num* but using *self* as 1139 context. Unlike the :class:`Decimal` constructor, the context precision, 1140 rounding method, flags, and traps are applied to the conversion. 1141 1142 This is useful because constants are often given to a greater precision 1143 than is needed by the application. Another benefit is that rounding 1144 immediately eliminates unintended effects from digits beyond the current 1145 precision. In the following example, using unrounded inputs means that 1146 adding zero to a sum can change the result: 1147 1148 .. doctest:: newcontext 1149 1150 >>> getcontext().prec = 3 1151 >>> Decimal('3.4445') + Decimal('1.0023') 1152 Decimal('4.45') 1153 >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023') 1154 Decimal('4.44') 1155 1156 This method implements the to-number operation of the IBM specification. 1157 If the argument is a string, no leading or trailing whitespace or 1158 underscores are permitted. 1159 1160 .. method:: create_decimal_from_float(f) 1161 1162 Creates a new Decimal instance from a float *f* but rounding using *self* 1163 as the context. Unlike the :meth:`Decimal.from_float` class method, 1164 the context precision, rounding method, flags, and traps are applied to 1165 the conversion. 1166 1167 .. doctest:: 1168 1169 >>> context = Context(prec=5, rounding=ROUND_DOWN) 1170 >>> context.create_decimal_from_float(math.pi) 1171 Decimal('3.1415') 1172 >>> context = Context(prec=5, traps=[Inexact]) 1173 >>> context.create_decimal_from_float(math.pi) 1174 Traceback (most recent call last): 1175 ... 1176 decimal.Inexact: None 1177 1178 .. versionadded:: 3.1 1179 1180 .. method:: Etiny() 1181 1182 Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent 1183 value for subnormal results. When underflow occurs, the exponent is set 1184 to :const:`Etiny`. 1185 1186 .. method:: Etop() 1187 1188 Returns a value equal to ``Emax - prec + 1``. 1189 1190 The usual approach to working with decimals is to create :class:`Decimal` 1191 instances and then apply arithmetic operations which take place within the 1192 current context for the active thread. An alternative approach is to use 1193 context methods for calculating within a specific context. The methods are 1194 similar to those for the :class:`Decimal` class and are only briefly 1195 recounted here. 1196 1197 1198 .. method:: abs(x) 1199 1200 Returns the absolute value of *x*. 1201 1202 1203 .. method:: add(x, y) 1204 1205 Return the sum of *x* and *y*. 1206 1207 1208 .. method:: canonical(x) 1209 1210 Returns the same Decimal object *x*. 1211 1212 1213 .. method:: compare(x, y) 1214 1215 Compares *x* and *y* numerically. 1216 1217 1218 .. method:: compare_signal(x, y) 1219 1220 Compares the values of the two operands numerically. 1221 1222 1223 .. method:: compare_total(x, y) 1224 1225 Compares two operands using their abstract representation. 1226 1227 1228 .. method:: compare_total_mag(x, y) 1229 1230 Compares two operands using their abstract representation, ignoring sign. 1231 1232 1233 .. method:: copy_abs(x) 1234 1235 Returns a copy of *x* with the sign set to 0. 1236 1237 1238 .. method:: copy_negate(x) 1239 1240 Returns a copy of *x* with the sign inverted. 1241 1242 1243 .. method:: copy_sign(x, y) 1244 1245 Copies the sign from *y* to *x*. 1246 1247 1248 .. method:: divide(x, y) 1249 1250 Return *x* divided by *y*. 1251 1252 1253 .. method:: divide_int(x, y) 1254 1255 Return *x* divided by *y*, truncated to an integer. 1256 1257 1258 .. method:: divmod(x, y) 1259 1260 Divides two numbers and returns the integer part of the result. 1261 1262 1263 .. method:: exp(x) 1264 1265 Returns ``e ** x``. 1266 1267 1268 .. method:: fma(x, y, z) 1269 1270 Returns *x* multiplied by *y*, plus *z*. 1271 1272 1273 .. method:: is_canonical(x) 1274 1275 Returns ``True`` if *x* is canonical; otherwise returns ``False``. 1276 1277 1278 .. method:: is_finite(x) 1279 1280 Returns ``True`` if *x* is finite; otherwise returns ``False``. 1281 1282 1283 .. method:: is_infinite(x) 1284 1285 Returns ``True`` if *x* is infinite; otherwise returns ``False``. 1286 1287 1288 .. method:: is_nan(x) 1289 1290 Returns ``True`` if *x* is a qNaN or sNaN; otherwise returns ``False``. 1291 1292 1293 .. method:: is_normal(x) 1294 1295 Returns ``True`` if *x* is a normal number; otherwise returns ``False``. 1296 1297 1298 .. method:: is_qnan(x) 1299 1300 Returns ``True`` if *x* is a quiet NaN; otherwise returns ``False``. 1301 1302 1303 .. method:: is_signed(x) 1304 1305 Returns ``True`` if *x* is negative; otherwise returns ``False``. 1306 1307 1308 .. method:: is_snan(x) 1309 1310 Returns ``True`` if *x* is a signaling NaN; otherwise returns ``False``. 1311 1312 1313 .. method:: is_subnormal(x) 1314 1315 Returns ``True`` if *x* is subnormal; otherwise returns ``False``. 1316 1317 1318 .. method:: is_zero(x) 1319 1320 Returns ``True`` if *x* is a zero; otherwise returns ``False``. 1321 1322 1323 .. method:: ln(x) 1324 1325 Returns the natural (base e) logarithm of *x*. 1326 1327 1328 .. method:: log10(x) 1329 1330 Returns the base 10 logarithm of *x*. 1331 1332 1333 .. method:: logb(x) 1334 1335 Returns the exponent of the magnitude of the operand's MSD. 1336 1337 1338 .. method:: logical_and(x, y) 1339 1340 Applies the logical operation *and* between each operand's digits. 1341 1342 1343 .. method:: logical_invert(x) 1344 1345 Invert all the digits in *x*. 1346 1347 1348 .. method:: logical_or(x, y) 1349 1350 Applies the logical operation *or* between each operand's digits. 1351 1352 1353 .. method:: logical_xor(x, y) 1354 1355 Applies the logical operation *xor* between each operand's digits. 1356 1357 1358 .. method:: max(x, y) 1359 1360 Compares two values numerically and returns the maximum. 1361 1362 1363 .. method:: max_mag(x, y) 1364 1365 Compares the values numerically with their sign ignored. 1366 1367 1368 .. method:: min(x, y) 1369 1370 Compares two values numerically and returns the minimum. 1371 1372 1373 .. method:: min_mag(x, y) 1374 1375 Compares the values numerically with their sign ignored. 1376 1377 1378 .. method:: minus(x) 1379 1380 Minus corresponds to the unary prefix minus operator in Python. 1381 1382 1383 .. method:: multiply(x, y) 1384 1385 Return the product of *x* and *y*. 1386 1387 1388 .. method:: next_minus(x) 1389 1390 Returns the largest representable number smaller than *x*. 1391 1392 1393 .. method:: next_plus(x) 1394 1395 Returns the smallest representable number larger than *x*. 1396 1397 1398 .. method:: next_toward(x, y) 1399 1400 Returns the number closest to *x*, in direction towards *y*. 1401 1402 1403 .. method:: normalize(x) 1404 1405 Reduces *x* to its simplest form. 1406 1407 1408 .. method:: number_class(x) 1409 1410 Returns an indication of the class of *x*. 1411 1412 1413 .. method:: plus(x) 1414 1415 Plus corresponds to the unary prefix plus operator in Python. This 1416 operation applies the context precision and rounding, so it is *not* an 1417 identity operation. 1418 1419 1420 .. method:: power(x, y, modulo=None) 1421 1422 Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given. 1423 1424 With two arguments, compute ``x**y``. If ``x`` is negative then ``y`` 1425 must be integral. The result will be inexact unless ``y`` is integral and 1426 the result is finite and can be expressed exactly in 'precision' digits. 1427 The rounding mode of the context is used. Results are always correctly rounded 1428 in the Python version. 1429 1430 ``Decimal(0) ** Decimal(0)`` results in ``InvalidOperation``, and if ``InvalidOperation`` 1431 is not trapped, then results in ``Decimal('NaN')``. 1432 1433 .. versionchanged:: 3.3 1434 The C module computes :meth:`power` in terms of the correctly rounded 1435 :meth:`exp` and :meth:`ln` functions. The result is well-defined but 1436 only "almost always correctly rounded". 1437 1438 With three arguments, compute ``(x**y) % modulo``. For the three argument 1439 form, the following restrictions on the arguments hold: 1440 1441 - all three arguments must be integral 1442 - ``y`` must be nonnegative 1443 - at least one of ``x`` or ``y`` must be nonzero 1444 - ``modulo`` must be nonzero and have at most 'precision' digits 1445 1446 The value resulting from ``Context.power(x, y, modulo)`` is 1447 equal to the value that would be obtained by computing ``(x**y) 1448 % modulo`` with unbounded precision, but is computed more 1449 efficiently. The exponent of the result is zero, regardless of 1450 the exponents of ``x``, ``y`` and ``modulo``. The result is 1451 always exact. 1452 1453 1454 .. method:: quantize(x, y) 1455 1456 Returns a value equal to *x* (rounded), having the exponent of *y*. 1457 1458 1459 .. method:: radix() 1460 1461 Just returns 10, as this is Decimal, :) 1462 1463 1464 .. method:: remainder(x, y) 1465 1466 Returns the remainder from integer division. 1467 1468 The sign of the result, if non-zero, is the same as that of the original 1469 dividend. 1470 1471 1472 .. method:: remainder_near(x, y) 1473 1474 Returns ``x - y * n``, where *n* is the integer nearest the exact value 1475 of ``x / y`` (if the result is 0 then its sign will be the sign of *x*). 1476 1477 1478 .. method:: rotate(x, y) 1479 1480 Returns a rotated copy of *x*, *y* times. 1481 1482 1483 .. method:: same_quantum(x, y) 1484 1485 Returns ``True`` if the two operands have the same exponent. 1486 1487 1488 .. method:: scaleb (x, y) 1489 1490 Returns the first operand after adding the second value its exp. 1491 1492 1493 .. method:: shift(x, y) 1494 1495 Returns a shifted copy of *x*, *y* times. 1496 1497 1498 .. method:: sqrt(x) 1499 1500 Square root of a non-negative number to context precision. 1501 1502 1503 .. method:: subtract(x, y) 1504 1505 Return the difference between *x* and *y*. 1506 1507 1508 .. method:: to_eng_string(x) 1509 1510 Convert to a string, using engineering notation if an exponent is needed. 1511 1512 Engineering notation has an exponent which is a multiple of 3. This 1513 can leave up to 3 digits to the left of the decimal place and may 1514 require the addition of either one or two trailing zeros. 1515 1516 1517 .. method:: to_integral_exact(x) 1518 1519 Rounds to an integer. 1520 1521 1522 .. method:: to_sci_string(x) 1523 1524 Converts a number to a string using scientific notation. 1525 1526.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1527 1528.. _decimal-rounding-modes: 1529 1530Constants 1531--------- 1532 1533The constants in this section are only relevant for the C module. They 1534are also included in the pure Python version for compatibility. 1535 1536+---------------------+---------------------+-------------------------------+ 1537| | 32-bit | 64-bit | 1538+=====================+=====================+===============================+ 1539| .. data:: MAX_PREC | ``425000000`` | ``999999999999999999`` | 1540+---------------------+---------------------+-------------------------------+ 1541| .. data:: MAX_EMAX | ``425000000`` | ``999999999999999999`` | 1542+---------------------+---------------------+-------------------------------+ 1543| .. data:: MIN_EMIN | ``-425000000`` | ``-999999999999999999`` | 1544+---------------------+---------------------+-------------------------------+ 1545| .. data:: MIN_ETINY | ``-849999999`` | ``-1999999999999999997`` | 1546+---------------------+---------------------+-------------------------------+ 1547 1548 1549.. data:: HAVE_THREADS 1550 1551 The value is ``True``. Deprecated, because Python now always has threads. 1552 1553 .. deprecated:: 3.9 1554 1555.. data:: HAVE_CONTEXTVAR 1556 1557 The default value is ``True``. If Python is :option:`configured using 1558 the --without-decimal-contextvar option <--without-decimal-contextvar>`, 1559 the C version uses a thread-local rather than a coroutine-local context and the value 1560 is ``False``. This is slightly faster in some nested context scenarios. 1561 1562 .. versionadded:: 3.8.3 1563 1564 1565Rounding modes 1566-------------- 1567 1568.. data:: ROUND_CEILING 1569 1570 Round towards ``Infinity``. 1571 1572.. data:: ROUND_DOWN 1573 1574 Round towards zero. 1575 1576.. data:: ROUND_FLOOR 1577 1578 Round towards ``-Infinity``. 1579 1580.. data:: ROUND_HALF_DOWN 1581 1582 Round to nearest with ties going towards zero. 1583 1584.. data:: ROUND_HALF_EVEN 1585 1586 Round to nearest with ties going to nearest even integer. 1587 1588.. data:: ROUND_HALF_UP 1589 1590 Round to nearest with ties going away from zero. 1591 1592.. data:: ROUND_UP 1593 1594 Round away from zero. 1595 1596.. data:: ROUND_05UP 1597 1598 Round away from zero if last digit after rounding towards zero would have 1599 been 0 or 5; otherwise round towards zero. 1600 1601 1602.. _decimal-signals: 1603 1604Signals 1605------- 1606 1607Signals represent conditions that arise during computation. Each corresponds to 1608one context flag and one context trap enabler. 1609 1610The context flag is set whenever the condition is encountered. After the 1611computation, flags may be checked for informational purposes (for instance, to 1612determine whether a computation was exact). After checking the flags, be sure to 1613clear all flags before starting the next computation. 1614 1615If the context's trap enabler is set for the signal, then the condition causes a 1616Python exception to be raised. For example, if the :class:`DivisionByZero` trap 1617is set, then a :exc:`DivisionByZero` exception is raised upon encountering the 1618condition. 1619 1620 1621.. class:: Clamped 1622 1623 Altered an exponent to fit representation constraints. 1624 1625 Typically, clamping occurs when an exponent falls outside the context's 1626 :attr:`~Context.Emin` and :attr:`~Context.Emax` limits. If possible, the exponent is reduced to 1627 fit by adding zeros to the coefficient. 1628 1629 1630.. class:: DecimalException 1631 1632 Base class for other signals and a subclass of :exc:`ArithmeticError`. 1633 1634 1635.. class:: DivisionByZero 1636 1637 Signals the division of a non-infinite number by zero. 1638 1639 Can occur with division, modulo division, or when raising a number to a negative 1640 power. If this signal is not trapped, returns ``Infinity`` or 1641 ``-Infinity`` with the sign determined by the inputs to the calculation. 1642 1643 1644.. class:: Inexact 1645 1646 Indicates that rounding occurred and the result is not exact. 1647 1648 Signals when non-zero digits were discarded during rounding. The rounded result 1649 is returned. The signal flag or trap is used to detect when results are 1650 inexact. 1651 1652 1653.. class:: InvalidOperation 1654 1655 An invalid operation was performed. 1656 1657 Indicates that an operation was requested that does not make sense. If not 1658 trapped, returns ``NaN``. Possible causes include:: 1659 1660 Infinity - Infinity 1661 0 * Infinity 1662 Infinity / Infinity 1663 x % 0 1664 Infinity % x 1665 sqrt(-x) and x > 0 1666 0 ** 0 1667 x ** (non-integer) 1668 x ** Infinity 1669 1670 1671.. class:: Overflow 1672 1673 Numerical overflow. 1674 1675 Indicates the exponent is larger than :attr:`Context.Emax` after rounding has 1676 occurred. If not trapped, the result depends on the rounding mode, either 1677 pulling inward to the largest representable finite number or rounding outward 1678 to ``Infinity``. In either case, :class:`Inexact` and :class:`Rounded` 1679 are also signaled. 1680 1681 1682.. class:: Rounded 1683 1684 Rounding occurred though possibly no information was lost. 1685 1686 Signaled whenever rounding discards digits; even if those digits are zero 1687 (such as rounding ``5.00`` to ``5.0``). If not trapped, returns 1688 the result unchanged. This signal is used to detect loss of significant 1689 digits. 1690 1691 1692.. class:: Subnormal 1693 1694 Exponent was lower than :attr:`~Context.Emin` prior to rounding. 1695 1696 Occurs when an operation result is subnormal (the exponent is too small). If 1697 not trapped, returns the result unchanged. 1698 1699 1700.. class:: Underflow 1701 1702 Numerical underflow with result rounded to zero. 1703 1704 Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact` 1705 and :class:`Subnormal` are also signaled. 1706 1707 1708.. class:: FloatOperation 1709 1710 Enable stricter semantics for mixing floats and Decimals. 1711 1712 If the signal is not trapped (default), mixing floats and Decimals is 1713 permitted in the :class:`~decimal.Decimal` constructor, 1714 :meth:`~decimal.Context.create_decimal` and all comparison operators. 1715 Both conversion and comparisons are exact. Any occurrence of a mixed 1716 operation is silently recorded by setting :exc:`FloatOperation` in the 1717 context flags. Explicit conversions with :meth:`~decimal.Decimal.from_float` 1718 or :meth:`~decimal.Context.create_decimal_from_float` do not set the flag. 1719 1720 Otherwise (the signal is trapped), only equality comparisons and explicit 1721 conversions are silent. All other mixed operations raise :exc:`FloatOperation`. 1722 1723 1724The following table summarizes the hierarchy of signals:: 1725 1726 exceptions.ArithmeticError(exceptions.Exception) 1727 DecimalException 1728 Clamped 1729 DivisionByZero(DecimalException, exceptions.ZeroDivisionError) 1730 Inexact 1731 Overflow(Inexact, Rounded) 1732 Underflow(Inexact, Rounded, Subnormal) 1733 InvalidOperation 1734 Rounded 1735 Subnormal 1736 FloatOperation(DecimalException, exceptions.TypeError) 1737 1738.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1739 1740 1741 1742.. _decimal-notes: 1743 1744Floating-Point Notes 1745-------------------- 1746 1747 1748Mitigating round-off error with increased precision 1749^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1750 1751The use of decimal floating point eliminates decimal representation error 1752(making it possible to represent ``0.1`` exactly); however, some operations 1753can still incur round-off error when non-zero digits exceed the fixed precision. 1754 1755The effects of round-off error can be amplified by the addition or subtraction 1756of nearly offsetting quantities resulting in loss of significance. Knuth 1757provides two instructive examples where rounded floating-point arithmetic with 1758insufficient precision causes the breakdown of the associative and distributive 1759properties of addition: 1760 1761.. doctest:: newcontext 1762 1763 # Examples from Seminumerical Algorithms, Section 4.2.2. 1764 >>> from decimal import Decimal, getcontext 1765 >>> getcontext().prec = 8 1766 1767 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') 1768 >>> (u + v) + w 1769 Decimal('9.5111111') 1770 >>> u + (v + w) 1771 Decimal('10') 1772 1773 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') 1774 >>> (u*v) + (u*w) 1775 Decimal('0.01') 1776 >>> u * (v+w) 1777 Decimal('0.0060000') 1778 1779The :mod:`decimal` module makes it possible to restore the identities by 1780expanding the precision sufficiently to avoid loss of significance: 1781 1782.. doctest:: newcontext 1783 1784 >>> getcontext().prec = 20 1785 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') 1786 >>> (u + v) + w 1787 Decimal('9.51111111') 1788 >>> u + (v + w) 1789 Decimal('9.51111111') 1790 >>> 1791 >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003') 1792 >>> (u*v) + (u*w) 1793 Decimal('0.0060000') 1794 >>> u * (v+w) 1795 Decimal('0.0060000') 1796 1797 1798Special values 1799^^^^^^^^^^^^^^ 1800 1801The number system for the :mod:`decimal` module provides special values 1802including ``NaN``, ``sNaN``, ``-Infinity``, ``Infinity``, 1803and two zeros, ``+0`` and ``-0``. 1804 1805Infinities can be constructed directly with: ``Decimal('Infinity')``. Also, 1806they can arise from dividing by zero when the :exc:`DivisionByZero` signal is 1807not trapped. Likewise, when the :exc:`Overflow` signal is not trapped, infinity 1808can result from rounding beyond the limits of the largest representable number. 1809 1810The infinities are signed (affine) and can be used in arithmetic operations 1811where they get treated as very large, indeterminate numbers. For instance, 1812adding a constant to infinity gives another infinite result. 1813 1814Some operations are indeterminate and return ``NaN``, or if the 1815:exc:`InvalidOperation` signal is trapped, raise an exception. For example, 1816``0/0`` returns ``NaN`` which means "not a number". This variety of 1817``NaN`` is quiet and, once created, will flow through other computations 1818always resulting in another ``NaN``. This behavior can be useful for a 1819series of computations that occasionally have missing inputs --- it allows the 1820calculation to proceed while flagging specific results as invalid. 1821 1822A variant is ``sNaN`` which signals rather than remaining quiet after every 1823operation. This is a useful return value when an invalid result needs to 1824interrupt a calculation for special handling. 1825 1826The behavior of Python's comparison operators can be a little surprising where a 1827``NaN`` is involved. A test for equality where one of the operands is a 1828quiet or signaling ``NaN`` always returns :const:`False` (even when doing 1829``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns 1830:const:`True`. An attempt to compare two Decimals using any of the ``<``, 1831``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal 1832if either operand is a ``NaN``, and return :const:`False` if this signal is 1833not trapped. Note that the General Decimal Arithmetic specification does not 1834specify the behavior of direct comparisons; these rules for comparisons 1835involving a ``NaN`` were taken from the IEEE 854 standard (see Table 3 in 1836section 5.7). To ensure strict standards-compliance, use the :meth:`~Decimal.compare` 1837and :meth:`~Decimal.compare_signal` methods instead. 1838 1839The signed zeros can result from calculations that underflow. They keep the sign 1840that would have resulted if the calculation had been carried out to greater 1841precision. Since their magnitude is zero, both positive and negative zeros are 1842treated as equal and their sign is informational. 1843 1844In addition to the two signed zeros which are distinct yet equal, there are 1845various representations of zero with differing precisions yet equivalent in 1846value. This takes a bit of getting used to. For an eye accustomed to 1847normalized floating-point representations, it is not immediately obvious that 1848the following calculation returns a value equal to zero: 1849 1850 >>> 1 / Decimal('Infinity') 1851 Decimal('0E-1000026') 1852 1853.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1854 1855 1856.. _decimal-threads: 1857 1858Working with threads 1859-------------------- 1860 1861The :func:`getcontext` function accesses a different :class:`Context` object for 1862each thread. Having separate thread contexts means that threads may make 1863changes (such as ``getcontext().prec=10``) without interfering with other threads. 1864 1865Likewise, the :func:`setcontext` function automatically assigns its target to 1866the current thread. 1867 1868If :func:`setcontext` has not been called before :func:`getcontext`, then 1869:func:`getcontext` will automatically create a new context for use in the 1870current thread. 1871 1872The new context is copied from a prototype context called *DefaultContext*. To 1873control the defaults so that each thread will use the same values throughout the 1874application, directly modify the *DefaultContext* object. This should be done 1875*before* any threads are started so that there won't be a race condition between 1876threads calling :func:`getcontext`. For example:: 1877 1878 # Set applicationwide defaults for all threads about to be launched 1879 DefaultContext.prec = 12 1880 DefaultContext.rounding = ROUND_DOWN 1881 DefaultContext.traps = ExtendedContext.traps.copy() 1882 DefaultContext.traps[InvalidOperation] = 1 1883 setcontext(DefaultContext) 1884 1885 # Afterwards, the threads can be started 1886 t1.start() 1887 t2.start() 1888 t3.start() 1889 . . . 1890 1891.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1892 1893 1894.. _decimal-recipes: 1895 1896Recipes 1897------- 1898 1899Here are a few recipes that serve as utility functions and that demonstrate ways 1900to work with the :class:`Decimal` class:: 1901 1902 def moneyfmt(value, places=2, curr='', sep=',', dp='.', 1903 pos='', neg='-', trailneg=''): 1904 """Convert Decimal to a money formatted string. 1905 1906 places: required number of places after the decimal point 1907 curr: optional currency symbol before the sign (may be blank) 1908 sep: optional grouping separator (comma, period, space, or blank) 1909 dp: decimal point indicator (comma or period) 1910 only specify as blank when places is zero 1911 pos: optional sign for positive numbers: '+', space or blank 1912 neg: optional sign for negative numbers: '-', '(', space or blank 1913 trailneg:optional trailing minus indicator: '-', ')', space or blank 1914 1915 >>> d = Decimal('-1234567.8901') 1916 >>> moneyfmt(d, curr='$') 1917 '-$1,234,567.89' 1918 >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-') 1919 '1.234.568-' 1920 >>> moneyfmt(d, curr='$', neg='(', trailneg=')') 1921 '($1,234,567.89)' 1922 >>> moneyfmt(Decimal(123456789), sep=' ') 1923 '123 456 789.00' 1924 >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>') 1925 '<0.02>' 1926 1927 """ 1928 q = Decimal(10) ** -places # 2 places --> '0.01' 1929 sign, digits, exp = value.quantize(q).as_tuple() 1930 result = [] 1931 digits = list(map(str, digits)) 1932 build, next = result.append, digits.pop 1933 if sign: 1934 build(trailneg) 1935 for i in range(places): 1936 build(next() if digits else '0') 1937 if places: 1938 build(dp) 1939 if not digits: 1940 build('0') 1941 i = 0 1942 while digits: 1943 build(next()) 1944 i += 1 1945 if i == 3 and digits: 1946 i = 0 1947 build(sep) 1948 build(curr) 1949 build(neg if sign else pos) 1950 return ''.join(reversed(result)) 1951 1952 def pi(): 1953 """Compute Pi to the current precision. 1954 1955 >>> print(pi()) 1956 3.141592653589793238462643383 1957 1958 """ 1959 getcontext().prec += 2 # extra digits for intermediate steps 1960 three = Decimal(3) # substitute "three=3.0" for regular floats 1961 lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 1962 while s != lasts: 1963 lasts = s 1964 n, na = n+na, na+8 1965 d, da = d+da, da+32 1966 t = (t * n) / d 1967 s += t 1968 getcontext().prec -= 2 1969 return +s # unary plus applies the new precision 1970 1971 def exp(x): 1972 """Return e raised to the power of x. Result type matches input type. 1973 1974 >>> print(exp(Decimal(1))) 1975 2.718281828459045235360287471 1976 >>> print(exp(Decimal(2))) 1977 7.389056098930650227230427461 1978 >>> print(exp(2.0)) 1979 7.38905609893 1980 >>> print(exp(2+0j)) 1981 (7.38905609893+0j) 1982 1983 """ 1984 getcontext().prec += 2 1985 i, lasts, s, fact, num = 0, 0, 1, 1, 1 1986 while s != lasts: 1987 lasts = s 1988 i += 1 1989 fact *= i 1990 num *= x 1991 s += num / fact 1992 getcontext().prec -= 2 1993 return +s 1994 1995 def cos(x): 1996 """Return the cosine of x as measured in radians. 1997 1998 The Taylor series approximation works best for a small value of x. 1999 For larger values, first compute x = x % (2 * pi). 2000 2001 >>> print(cos(Decimal('0.5'))) 2002 0.8775825618903727161162815826 2003 >>> print(cos(0.5)) 2004 0.87758256189 2005 >>> print(cos(0.5+0j)) 2006 (0.87758256189+0j) 2007 2008 """ 2009 getcontext().prec += 2 2010 i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1 2011 while s != lasts: 2012 lasts = s 2013 i += 2 2014 fact *= i * (i-1) 2015 num *= x * x 2016 sign *= -1 2017 s += num / fact * sign 2018 getcontext().prec -= 2 2019 return +s 2020 2021 def sin(x): 2022 """Return the sine of x as measured in radians. 2023 2024 The Taylor series approximation works best for a small value of x. 2025 For larger values, first compute x = x % (2 * pi). 2026 2027 >>> print(sin(Decimal('0.5'))) 2028 0.4794255386042030002732879352 2029 >>> print(sin(0.5)) 2030 0.479425538604 2031 >>> print(sin(0.5+0j)) 2032 (0.479425538604+0j) 2033 2034 """ 2035 getcontext().prec += 2 2036 i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1 2037 while s != lasts: 2038 lasts = s 2039 i += 2 2040 fact *= i * (i-1) 2041 num *= x * x 2042 sign *= -1 2043 s += num / fact * sign 2044 getcontext().prec -= 2 2045 return +s 2046 2047 2048.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2049 2050 2051.. _decimal-faq: 2052 2053Decimal FAQ 2054----------- 2055 2056Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to 2057minimize typing when using the interactive interpreter? 2058 2059A. Some users abbreviate the constructor to just a single letter: 2060 2061 >>> D = decimal.Decimal 2062 >>> D('1.23') + D('3.45') 2063 Decimal('4.68') 2064 2065Q. In a fixed-point application with two decimal places, some inputs have many 2066places and need to be rounded. Others are not supposed to have excess digits 2067and need to be validated. What methods should be used? 2068 2069A. The :meth:`~Decimal.quantize` method rounds to a fixed number of decimal places. If 2070the :const:`Inexact` trap is set, it is also useful for validation: 2071 2072 >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01') 2073 2074 >>> # Round to two places 2075 >>> Decimal('3.214').quantize(TWOPLACES) 2076 Decimal('3.21') 2077 2078 >>> # Validate that a number does not exceed two places 2079 >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact])) 2080 Decimal('3.21') 2081 2082 >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact])) 2083 Traceback (most recent call last): 2084 ... 2085 Inexact: None 2086 2087Q. Once I have valid two place inputs, how do I maintain that invariant 2088throughout an application? 2089 2090A. Some operations like addition, subtraction, and multiplication by an integer 2091will automatically preserve fixed point. Others operations, like division and 2092non-integer multiplication, will change the number of decimal places and need to 2093be followed-up with a :meth:`~Decimal.quantize` step: 2094 2095 >>> a = Decimal('102.72') # Initial fixed-point values 2096 >>> b = Decimal('3.17') 2097 >>> a + b # Addition preserves fixed-point 2098 Decimal('105.89') 2099 >>> a - b 2100 Decimal('99.55') 2101 >>> a * 42 # So does integer multiplication 2102 Decimal('4314.24') 2103 >>> (a * b).quantize(TWOPLACES) # Must quantize non-integer multiplication 2104 Decimal('325.62') 2105 >>> (b / a).quantize(TWOPLACES) # And quantize division 2106 Decimal('0.03') 2107 2108In developing fixed-point applications, it is convenient to define functions 2109to handle the :meth:`~Decimal.quantize` step: 2110 2111 >>> def mul(x, y, fp=TWOPLACES): 2112 ... return (x * y).quantize(fp) 2113 ... 2114 >>> def div(x, y, fp=TWOPLACES): 2115 ... return (x / y).quantize(fp) 2116 2117 >>> mul(a, b) # Automatically preserve fixed-point 2118 Decimal('325.62') 2119 >>> div(b, a) 2120 Decimal('0.03') 2121 2122Q. There are many ways to express the same value. The numbers ``200``, 2123``200.000``, ``2E2``, and ``.02E+4`` all have the same value at 2124various precisions. Is there a way to transform them to a single recognizable 2125canonical value? 2126 2127A. The :meth:`~Decimal.normalize` method maps all equivalent values to a single 2128representative: 2129 2130 >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split()) 2131 >>> [v.normalize() for v in values] 2132 [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')] 2133 2134Q. When does rounding occur in a computation? 2135 2136A. It occurs *after* the computation. The philosophy of the decimal 2137specification is that numbers are considered exact and are created 2138independent of the current context. They can even have greater 2139precision than current context. Computations process with those 2140exact inputs and then rounding (or other context operations) is 2141applied to the *result* of the computation:: 2142 2143 >>> getcontext().prec = 5 2144 >>> pi = Decimal('3.1415926535') # More than 5 digits 2145 >>> pi # All digits are retained 2146 Decimal('3.1415926535') 2147 >>> pi + 0 # Rounded after an addition 2148 Decimal('3.1416') 2149 >>> pi - Decimal('0.00005') # Subtract unrounded numbers, then round 2150 Decimal('3.1415') 2151 >>> pi + 0 - Decimal('0.00005'). # Intermediate values are rounded 2152 Decimal('3.1416') 2153 2154Q. Some decimal values always print with exponential notation. Is there a way 2155to get a non-exponential representation? 2156 2157A. For some values, exponential notation is the only way to express the number 2158of significant places in the coefficient. For example, expressing 2159``5.0E+3`` as ``5000`` keeps the value constant but cannot show the 2160original's two-place significance. 2161 2162If an application does not care about tracking significance, it is easy to 2163remove the exponent and trailing zeroes, losing significance, but keeping the 2164value unchanged: 2165 2166 >>> def remove_exponent(d): 2167 ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize() 2168 2169 >>> remove_exponent(Decimal('5E+3')) 2170 Decimal('5000') 2171 2172Q. Is there a way to convert a regular float to a :class:`Decimal`? 2173 2174A. Yes, any binary floating-point number can be exactly expressed as a 2175Decimal though an exact conversion may take more precision than intuition would 2176suggest: 2177 2178.. doctest:: 2179 2180 >>> Decimal(math.pi) 2181 Decimal('3.141592653589793115997963468544185161590576171875') 2182 2183Q. Within a complex calculation, how can I make sure that I haven't gotten a 2184spurious result because of insufficient precision or rounding anomalies. 2185 2186A. The decimal module makes it easy to test results. A best practice is to 2187re-run calculations using greater precision and with various rounding modes. 2188Widely differing results indicate insufficient precision, rounding mode issues, 2189ill-conditioned inputs, or a numerically unstable algorithm. 2190 2191Q. I noticed that context precision is applied to the results of operations but 2192not to the inputs. Is there anything to watch out for when mixing values of 2193different precisions? 2194 2195A. Yes. The principle is that all values are considered to be exact and so is 2196the arithmetic on those values. Only the results are rounded. The advantage 2197for inputs is that "what you type is what you get". A disadvantage is that the 2198results can look odd if you forget that the inputs haven't been rounded: 2199 2200.. doctest:: newcontext 2201 2202 >>> getcontext().prec = 3 2203 >>> Decimal('3.104') + Decimal('2.104') 2204 Decimal('5.21') 2205 >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104') 2206 Decimal('5.20') 2207 2208The solution is either to increase precision or to force rounding of inputs 2209using the unary plus operation: 2210 2211.. doctest:: newcontext 2212 2213 >>> getcontext().prec = 3 2214 >>> +Decimal('1.23456789') # unary plus triggers rounding 2215 Decimal('1.23') 2216 2217Alternatively, inputs can be rounded upon creation using the 2218:meth:`Context.create_decimal` method: 2219 2220 >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678') 2221 Decimal('1.2345') 2222 2223Q. Is the CPython implementation fast for large numbers? 2224 2225A. Yes. In the CPython and PyPy3 implementations, the C/CFFI versions of 2226the decimal module integrate the high speed `libmpdec 2227<https://www.bytereef.org/mpdecimal/doc/libmpdec/index.html>`_ library for 2228arbitrary precision correctly rounded decimal floating-point arithmetic [#]_. 2229``libmpdec`` uses `Karatsuba multiplication 2230<https://en.wikipedia.org/wiki/Karatsuba_algorithm>`_ 2231for medium-sized numbers and the `Number Theoretic Transform 2232<https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform>`_ 2233for very large numbers. 2234 2235The context must be adapted for exact arbitrary precision arithmetic. :attr:`~Context.Emin` 2236and :attr:`~Context.Emax` should always be set to the maximum values, :attr:`~Context.clamp` 2237should always be 0 (the default). Setting :attr:`~Context.prec` requires some care. 2238 2239The easiest approach for trying out bignum arithmetic is to use the maximum 2240value for :attr:`~Context.prec` as well [#]_:: 2241 2242 >>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN)) 2243 >>> x = Decimal(2) ** 256 2244 >>> x / 128 2245 Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312') 2246 2247 2248For inexact results, :attr:`MAX_PREC` is far too large on 64-bit platforms and 2249the available memory will be insufficient:: 2250 2251 >>> Decimal(1) / 3 2252 Traceback (most recent call last): 2253 File "<stdin>", line 1, in <module> 2254 MemoryError 2255 2256On systems with overallocation (e.g. Linux), a more sophisticated approach is to 2257adjust :attr:`~Context.prec` to the amount of available RAM. Suppose that you have 8GB of 2258RAM and expect 10 simultaneous operands using a maximum of 500MB each:: 2259 2260 >>> import sys 2261 >>> 2262 >>> # Maximum number of digits for a single operand using 500MB in 8-byte words 2263 >>> # with 19 digits per word (4-byte and 9 digits for the 32-bit build): 2264 >>> maxdigits = 19 * ((500 * 1024**2) // 8) 2265 >>> 2266 >>> # Check that this works: 2267 >>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN) 2268 >>> c.traps[Inexact] = True 2269 >>> setcontext(c) 2270 >>> 2271 >>> # Fill the available precision with nines: 2272 >>> x = Decimal(0).logical_invert() * 9 2273 >>> sys.getsizeof(x) 2274 524288112 2275 >>> x + 2 2276 Traceback (most recent call last): 2277 File "<stdin>", line 1, in <module> 2278 decimal.Inexact: [<class 'decimal.Inexact'>] 2279 2280In general (and especially on systems without overallocation), it is recommended 2281to estimate even tighter bounds and set the :attr:`Inexact` trap if all calculations 2282are expected to be exact. 2283 2284 2285.. [#] 2286 .. versionadded:: 3.3 2287 2288.. [#] 2289 .. versionchanged:: 3.9 2290 This approach now works for all exact results except for non-integer powers. 2291