1 # Copyright (c) 2004 Python Software Foundation. 2 # All rights reserved. 3 4 # Written by Eric Price <eprice at tjhsst.edu> 5 # and Facundo Batista <facundo at taniquetil.com.ar> 6 # and Raymond Hettinger <python at rcn.com> 7 # and Aahz <aahz at pobox.com> 8 # and Tim Peters 9 10 # This module should be kept in sync with the latest updates of the 11 # IBM specification as it evolves. Those updates will be treated 12 # as bug fixes (deviation from the spec is a compatibility, usability 13 # bug) and will be backported. At this point the spec is stabilizing 14 # and the updates are becoming fewer, smaller, and less significant. 15 16 """ 17 This is an implementation of decimal floating point arithmetic based on 18 the General Decimal Arithmetic Specification: 19 20 http://speleotrove.com/decimal/decarith.html 21 22 and IEEE standard 854-1987: 23 24 http://en.wikipedia.org/wiki/IEEE_854-1987 25 26 Decimal floating point has finite precision with arbitrarily large bounds. 27 28 The purpose of this module is to support arithmetic using familiar 29 "schoolhouse" rules and to avoid some of the tricky representation 30 issues associated with binary floating point. The package is especially 31 useful for financial applications or for contexts where users have 32 expectations that are at odds with binary floating point (for instance, 33 in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead 34 of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected 35 Decimal('0.00')). 36 37 Here are some examples of using the decimal module: 38 39 >>> from decimal import * 40 >>> setcontext(ExtendedContext) 41 >>> Decimal(0) 42 Decimal('0') 43 >>> Decimal('1') 44 Decimal('1') 45 >>> Decimal('-.0123') 46 Decimal('-0.0123') 47 >>> Decimal(123456) 48 Decimal('123456') 49 >>> Decimal('123.45e12345678') 50 Decimal('1.2345E+12345680') 51 >>> Decimal('1.33') + Decimal('1.27') 52 Decimal('2.60') 53 >>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41') 54 Decimal('-2.20') 55 >>> dig = Decimal(1) 56 >>> print(dig / Decimal(3)) 57 0.333333333 58 >>> getcontext().prec = 18 59 >>> print(dig / Decimal(3)) 60 0.333333333333333333 61 >>> print(dig.sqrt()) 62 1 63 >>> print(Decimal(3).sqrt()) 64 1.73205080756887729 65 >>> print(Decimal(3) ** 123) 66 4.85192780976896427E+58 67 >>> inf = Decimal(1) / Decimal(0) 68 >>> print(inf) 69 Infinity 70 >>> neginf = Decimal(-1) / Decimal(0) 71 >>> print(neginf) 72 -Infinity 73 >>> print(neginf + inf) 74 NaN 75 >>> print(neginf * inf) 76 -Infinity 77 >>> print(dig / 0) 78 Infinity 79 >>> getcontext().traps[DivisionByZero] = 1 80 >>> print(dig / 0) 81 Traceback (most recent call last): 82 ... 83 ... 84 ... 85 decimal.DivisionByZero: x / 0 86 >>> c = Context() 87 >>> c.traps[InvalidOperation] = 0 88 >>> print(c.flags[InvalidOperation]) 89 0 90 >>> c.divide(Decimal(0), Decimal(0)) 91 Decimal('NaN') 92 >>> c.traps[InvalidOperation] = 1 93 >>> print(c.flags[InvalidOperation]) 94 1 95 >>> c.flags[InvalidOperation] = 0 96 >>> print(c.flags[InvalidOperation]) 97 0 98 >>> print(c.divide(Decimal(0), Decimal(0))) 99 Traceback (most recent call last): 100 ... 101 ... 102 ... 103 decimal.InvalidOperation: 0 / 0 104 >>> print(c.flags[InvalidOperation]) 105 1 106 >>> c.flags[InvalidOperation] = 0 107 >>> c.traps[InvalidOperation] = 0 108 >>> print(c.divide(Decimal(0), Decimal(0))) 109 NaN 110 >>> print(c.flags[InvalidOperation]) 111 1 112 >>> 113 """ 114 115 __all__ = [ 116 # Two major classes 117 'Decimal', 'Context', 118 119 # Named tuple representation 120 'DecimalTuple', 121 122 # Contexts 123 'DefaultContext', 'BasicContext', 'ExtendedContext', 124 125 # Exceptions 126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero', 127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow', 128 'FloatOperation', 129 130 # Exceptional conditions that trigger InvalidOperation 131 'DivisionImpossible', 'InvalidContext', 'ConversionSyntax', 'DivisionUndefined', 132 133 # Constants for use in setting up contexts 134 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING', 135 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP', 136 137 # Functions for manipulating contexts 138 'setcontext', 'getcontext', 'localcontext', 139 140 # Limits for the C version for compatibility 141 'MAX_PREC', 'MAX_EMAX', 'MIN_EMIN', 'MIN_ETINY', 142 143 # C version: compile time choice that enables the thread local context 144 'HAVE_THREADS' 145 ] 146 147 __xname__ = __name__ # sys.modules lookup (--without-threads) 148 __name__ = 'decimal' # For pickling 149 __version__ = '1.70' # Highest version of the spec this complies with 150 # See http://speleotrove.com/decimal/ 151 __libmpdec_version__ = "2.4.2" # compatible libmpdec version 152 153 import math as _math 154 import numbers as _numbers 155 import sys 156 157 try: 158 from collections import namedtuple as _namedtuple 159 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent') 160 except ImportError: 161 DecimalTuple = lambda *args: args 162 163 # Rounding 164 ROUND_DOWN = 'ROUND_DOWN' 165 ROUND_HALF_UP = 'ROUND_HALF_UP' 166 ROUND_HALF_EVEN = 'ROUND_HALF_EVEN' 167 ROUND_CEILING = 'ROUND_CEILING' 168 ROUND_FLOOR = 'ROUND_FLOOR' 169 ROUND_UP = 'ROUND_UP' 170 ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' 171 ROUND_05UP = 'ROUND_05UP' 172 173 # Compatibility with the C version 174 HAVE_THREADS = True 175 if sys.maxsize == 2**63-1: 176 MAX_PREC = 999999999999999999 177 MAX_EMAX = 999999999999999999 178 MIN_EMIN = -999999999999999999 179 else: 180 MAX_PREC = 425000000 181 MAX_EMAX = 425000000 182 MIN_EMIN = -425000000 183 184 MIN_ETINY = MIN_EMIN - (MAX_PREC-1) 185 186 # Errors 187 188 class DecimalException(ArithmeticError): 189 """Base exception class. 190 191 Used exceptions derive from this. 192 If an exception derives from another exception besides this (such as 193 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only 194 called if the others are present. This isn't actually used for 195 anything, though. 196 197 handle -- Called when context._raise_error is called and the 198 trap_enabler is not set. First argument is self, second is the 199 context. More arguments can be given, those being after 200 the explanation in _raise_error (For example, 201 context._raise_error(NewError, '(-x)!', self._sign) would 202 call NewError().handle(context, self._sign).) 203 204 To define a new exception, it should be sufficient to have it derive 205 from DecimalException. 206 """ 207 def handle(self, context, *args): 208 pass 209 210 211 class Clamped(DecimalException): 212 """Exponent of a 0 changed to fit bounds. 213 214 This occurs and signals clamped if the exponent of a result has been 215 altered in order to fit the constraints of a specific concrete 216 representation. This may occur when the exponent of a zero result would 217 be outside the bounds of a representation, or when a large normal 218 number would have an encoded exponent that cannot be represented. In 219 this latter case, the exponent is reduced to fit and the corresponding 220 number of zero digits are appended to the coefficient ("fold-down"). 221 """ 222 223 class InvalidOperation(DecimalException): 224 """An invalid operation was performed. 225 226 Various bad things cause this: 227 228 Something creates a signaling NaN 229 -INF + INF 230 0 * (+-)INF 231 (+-)INF / (+-)INF 232 x % 0 233 (+-)INF % x 234 x._rescale( non-integer ) 235 sqrt(-x) , x > 0 236 0 ** 0 237 x ** (non-integer) 238 x ** (+-)INF 239 An operand is invalid 240 241 The result of the operation after these is a quiet positive NaN, 242 except when the cause is a signaling NaN, in which case the result is 243 also a quiet NaN, but with the original sign, and an optional 244 diagnostic information. 245 """ 246 def handle(self, context, *args): 247 if args: 248 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True) 249 return ans._fix_nan(context) 250 return _NaN 251 252 class ConversionSyntax(InvalidOperation): 253 """Trying to convert badly formed string. 254 255 This occurs and signals invalid-operation if a string is being 256 converted to a number and it does not conform to the numeric string 257 syntax. The result is [0,qNaN]. 258 """ 259 def handle(self, context, *args): 260 return _NaN 261 262 class DivisionByZero(DecimalException, ZeroDivisionError): 263 """Division by 0. 264 265 This occurs and signals division-by-zero if division of a finite number 266 by zero was attempted (during a divide-integer or divide operation, or a 267 power operation with negative right-hand operand), and the dividend was 268 not zero. 269 270 The result of the operation is [sign,inf], where sign is the exclusive 271 or of the signs of the operands for divide, or is 1 for an odd power of 272 -0, for power. 273 """ 274 275 def handle(self, context, sign, *args): 276 return _SignedInfinity[sign] 277 278 class DivisionImpossible(InvalidOperation): 279 """Cannot perform the division adequately. 280 281 This occurs and signals invalid-operation if the integer result of a 282 divide-integer or remainder operation had too many digits (would be 283 longer than precision). The result is [0,qNaN]. 284 """ 285 286 def handle(self, context, *args): 287 return _NaN 288 289 class DivisionUndefined(InvalidOperation, ZeroDivisionError): 290 """Undefined result of division. 291 292 This occurs and signals invalid-operation if division by zero was 293 attempted (during a divide-integer, divide, or remainder operation), and 294 the dividend is also zero. The result is [0,qNaN]. 295 """ 296 297 def handle(self, context, *args): 298 return _NaN 299 300 class Inexact(DecimalException): 301 """Had to round, losing information. 302 303 This occurs and signals inexact whenever the result of an operation is 304 not exact (that is, it needed to be rounded and any discarded digits 305 were non-zero), or if an overflow or underflow condition occurs. The 306 result in all cases is unchanged. 307 308 The inexact signal may be tested (or trapped) to determine if a given 309 operation (or sequence of operations) was inexact. 310 """ 311 312 class InvalidContext(InvalidOperation): 313 """Invalid context. Unknown rounding, for example. 314 315 This occurs and signals invalid-operation if an invalid context was 316 detected during an operation. This can occur if contexts are not checked 317 on creation and either the precision exceeds the capability of the 318 underlying concrete representation or an unknown or unsupported rounding 319 was specified. These aspects of the context need only be checked when 320 the values are required to be used. The result is [0,qNaN]. 321 """ 322 323 def handle(self, context, *args): 324 return _NaN 325 326 class Rounded(DecimalException): 327 """Number got rounded (not necessarily changed during rounding). 328 329 This occurs and signals rounded whenever the result of an operation is 330 rounded (that is, some zero or non-zero digits were discarded from the 331 coefficient), or if an overflow or underflow condition occurs. The 332 result in all cases is unchanged. 333 334 The rounded signal may be tested (or trapped) to determine if a given 335 operation (or sequence of operations) caused a loss of precision. 336 """ 337 338 class Subnormal(DecimalException): 339 """Exponent < Emin before rounding. 340 341 This occurs and signals subnormal whenever the result of a conversion or 342 operation is subnormal (that is, its adjusted exponent is less than 343 Emin, before any rounding). The result in all cases is unchanged. 344 345 The subnormal signal may be tested (or trapped) to determine if a given 346 or operation (or sequence of operations) yielded a subnormal result. 347 """ 348 349 class Overflow(Inexact, Rounded): 350 """Numerical overflow. 351 352 This occurs and signals overflow if the adjusted exponent of a result 353 (from a conversion or from an operation that is not an attempt to divide 354 by zero), after rounding, would be greater than the largest value that 355 can be handled by the implementation (the value Emax). 356 357 The result depends on the rounding mode: 358 359 For round-half-up and round-half-even (and for round-half-down and 360 round-up, if implemented), the result of the operation is [sign,inf], 361 where sign is the sign of the intermediate result. For round-down, the 362 result is the largest finite number that can be represented in the 363 current precision, with the sign of the intermediate result. For 364 round-ceiling, the result is the same as for round-down if the sign of 365 the intermediate result is 1, or is [0,inf] otherwise. For round-floor, 366 the result is the same as for round-down if the sign of the intermediate 367 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded 368 will also be raised. 369 """ 370 371 def handle(self, context, sign, *args): 372 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, 373 ROUND_HALF_DOWN, ROUND_UP): 374 return _SignedInfinity[sign] 375 if sign == 0: 376 if context.rounding == ROUND_CEILING: 377 return _SignedInfinity[sign] 378 return _dec_from_triple(sign, '9'*context.prec, 379 context.Emax-context.prec+1) 380 if sign == 1: 381 if context.rounding == ROUND_FLOOR: 382 return _SignedInfinity[sign] 383 return _dec_from_triple(sign, '9'*context.prec, 384 context.Emax-context.prec+1) 385 386 387 class Underflow(Inexact, Rounded, Subnormal): 388 """Numerical underflow with result rounded to 0. 389 390 This occurs and signals underflow if a result is inexact and the 391 adjusted exponent of the result would be smaller (more negative) than 392 the smallest value that can be handled by the implementation (the value 393 Emin). That is, the result is both inexact and subnormal. 394 395 The result after an underflow will be a subnormal number rounded, if 396 necessary, so that its exponent is not less than Etiny. This may result 397 in 0 with the sign of the intermediate result and an exponent of Etiny. 398 399 In all cases, Inexact, Rounded, and Subnormal will also be raised. 400 """ 401 402 class FloatOperation(DecimalException, TypeError): 403 """Enable stricter semantics for mixing floats and Decimals. 404 405 If the signal is not trapped (default), mixing floats and Decimals is 406 permitted in the Decimal() constructor, context.create_decimal() and 407 all comparison operators. Both conversion and comparisons are exact. 408 Any occurrence of a mixed operation is silently recorded by setting 409 FloatOperation in the context flags. Explicit conversions with 410 Decimal.from_float() or context.create_decimal_from_float() do not 411 set the flag. 412 413 Otherwise (the signal is trapped), only equality comparisons and explicit 414 conversions are silent. All other mixed operations raise FloatOperation. 415 """ 416 417 # List of public traps and flags 418 _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, 419 Underflow, InvalidOperation, Subnormal, FloatOperation] 420 421 # Map conditions (per the spec) to signals 422 _condition_map = {ConversionSyntax:InvalidOperation, 423 DivisionImpossible:InvalidOperation, 424 DivisionUndefined:InvalidOperation, 425 InvalidContext:InvalidOperation} 426 427 # Valid rounding modes 428 _rounding_modes = (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_CEILING, 429 ROUND_FLOOR, ROUND_UP, ROUND_HALF_DOWN, ROUND_05UP) 430 431 ##### Context Functions ################################################## 432 433 # The getcontext() and setcontext() function manage access to a thread-local 434 # current context. Py2.4 offers direct support for thread locals. If that 435 # is not available, use threading.current_thread() which is slower but will 436 # work for older Pythons. If threads are not part of the build, create a 437 # mock threading object with threading.local() returning the module namespace. 438 439 try: 440 import threading 441 except ImportError: 442 # Python was compiled without threads; create a mock object instead 443 class MockThreading(object): 444 def local(self, sys=sys): 445 return sys.modules[__xname__] 446 threading = MockThreading() 447 del MockThreading 448 449 try: 450 threading.local 451 452 except AttributeError: 453 454 # To fix reloading, force it to create a new context 455 # Old contexts have different exceptions in their dicts, making problems. 456 if hasattr(threading.current_thread(), '__decimal_context__'): 457 del threading.current_thread().__decimal_context__ 458 459 def setcontext(context): 460 """Set this thread's context to context.""" 461 if context in (DefaultContext, BasicContext, ExtendedContext): 462 context = context.copy() 463 context.clear_flags() 464 threading.current_thread().__decimal_context__ = context 465 466 def getcontext(): 467 """Returns this thread's context. 468 469 If this thread does not yet have a context, returns 470 a new context and sets this thread's context. 471 New contexts are copies of DefaultContext. 472 """ 473 try: 474 return threading.current_thread().__decimal_context__ 475 except AttributeError: 476 context = Context() 477 threading.current_thread().__decimal_context__ = context 478 return context 479 480 else: 481 482 local = threading.local() 483 if hasattr(local, '__decimal_context__'): 484 del local.__decimal_context__ 485 486 def getcontext(_local=local): 487 """Returns this thread's context. 488 489 If this thread does not yet have a context, returns 490 a new context and sets this thread's context. 491 New contexts are copies of DefaultContext. 492 """ 493 try: 494 return _local.__decimal_context__ 495 except AttributeError: 496 context = Context() 497 _local.__decimal_context__ = context 498 return context 499 500 def setcontext(context, _local=local): 501 """Set this thread's context to context.""" 502 if context in (DefaultContext, BasicContext, ExtendedContext): 503 context = context.copy() 504 context.clear_flags() 505 _local.__decimal_context__ = context 506 507 del threading, local # Don't contaminate the namespace 508 509 def localcontext(ctx=None): 510 """Return a context manager for a copy of the supplied context 511 512 Uses a copy of the current context if no context is specified 513 The returned context manager creates a local decimal context 514 in a with statement: 515 def sin(x): 516 with localcontext() as ctx: 517 ctx.prec += 2 518 # Rest of sin calculation algorithm 519 # uses a precision 2 greater than normal 520 return +s # Convert result to normal precision 521 522 def sin(x): 523 with localcontext(ExtendedContext): 524 # Rest of sin calculation algorithm 525 # uses the Extended Context from the 526 # General Decimal Arithmetic Specification 527 return +s # Convert result to normal context 528 529 >>> setcontext(DefaultContext) 530 >>> print(getcontext().prec) 531 28 532 >>> with localcontext(): 533 ... ctx = getcontext() 534 ... ctx.prec += 2 535 ... print(ctx.prec) 536 ... 537 30 538 >>> with localcontext(ExtendedContext): 539 ... print(getcontext().prec) 540 ... 541 9 542 >>> print(getcontext().prec) 543 28 544 """ 545 if ctx is None: ctx = getcontext() 546 return _ContextManager(ctx) 547 548 549 ##### Decimal class ####################################################### 550 551 # Do not subclass Decimal from numbers.Real and do not register it as such 552 # (because Decimals are not interoperable with floats). See the notes in 553 # numbers.py for more detail. 554 555 class Decimal(object): 556 """Floating point class for decimal arithmetic.""" 557 558 __slots__ = ('_exp','_int','_sign', '_is_special') 559 # Generally, the value of the Decimal instance is given by 560 # (-1)**_sign * _int * 10**_exp 561 # Special values are signified by _is_special == True 562 563 # We're immutable, so use __new__ not __init__ 564 def __new__(cls, value="0", context=None): 565 """Create a decimal point instance. 566 567 >>> Decimal('3.14') # string input 568 Decimal('3.14') 569 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) 570 Decimal('3.14') 571 >>> Decimal(314) # int 572 Decimal('314') 573 >>> Decimal(Decimal(314)) # another decimal instance 574 Decimal('314') 575 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay 576 Decimal('3.14') 577 """ 578 579 # Note that the coefficient, self._int, is actually stored as 580 # a string rather than as a tuple of digits. This speeds up 581 # the "digits to integer" and "integer to digits" conversions 582 # that are used in almost every arithmetic operation on 583 # Decimals. This is an internal detail: the as_tuple function 584 # and the Decimal constructor still deal with tuples of 585 # digits. 586 587 self = object.__new__(cls) 588 589 # From a string 590 # REs insist on real strings, so we can too. 591 if isinstance(value, str): 592 m = _parser(value.strip().replace("_", "")) 593 if m is None: 594 if context is None: 595 context = getcontext() 596 return context._raise_error(ConversionSyntax, 597 "Invalid literal for Decimal: %r" % value) 598 599 if m.group('sign') == "-": 600 self._sign = 1 601 else: 602 self._sign = 0 603 intpart = m.group('int') 604 if intpart is not None: 605 # finite number 606 fracpart = m.group('frac') or '' 607 exp = int(m.group('exp') or '0') 608 self._int = str(int(intpart+fracpart)) 609 self._exp = exp - len(fracpart) 610 self._is_special = False 611 else: 612 diag = m.group('diag') 613 if diag is not None: 614 # NaN 615 self._int = str(int(diag or '0')).lstrip('0') 616 if m.group('signal'): 617 self._exp = 'N' 618 else: 619 self._exp = 'n' 620 else: 621 # infinity 622 self._int = '0' 623 self._exp = 'F' 624 self._is_special = True 625 return self 626 627 # From an integer 628 if isinstance(value, int): 629 if value >= 0: 630 self._sign = 0 631 else: 632 self._sign = 1 633 self._exp = 0 634 self._int = str(abs(value)) 635 self._is_special = False 636 return self 637 638 # From another decimal 639 if isinstance(value, Decimal): 640 self._exp = value._exp 641 self._sign = value._sign 642 self._int = value._int 643 self._is_special = value._is_special 644 return self 645 646 # From an internal working value 647 if isinstance(value, _WorkRep): 648 self._sign = value.sign 649 self._int = str(value.int) 650 self._exp = int(value.exp) 651 self._is_special = False 652 return self 653 654 # tuple/list conversion (possibly from as_tuple()) 655 if isinstance(value, (list,tuple)): 656 if len(value) != 3: 657 raise ValueError('Invalid tuple size in creation of Decimal ' 658 'from list or tuple. The list or tuple ' 659 'should have exactly three elements.') 660 # process sign. The isinstance test rejects floats 661 if not (isinstance(value[0], int) and value[0] in (0,1)): 662 raise ValueError("Invalid sign. The first value in the tuple " 663 "should be an integer; either 0 for a " 664 "positive number or 1 for a negative number.") 665 self._sign = value[0] 666 if value[2] == 'F': 667 # infinity: value[1] is ignored 668 self._int = '0' 669 self._exp = value[2] 670 self._is_special = True 671 else: 672 # process and validate the digits in value[1] 673 digits = [] 674 for digit in value[1]: 675 if isinstance(digit, int) and 0 <= digit <= 9: 676 # skip leading zeros 677 if digits or digit != 0: 678 digits.append(digit) 679 else: 680 raise ValueError("The second value in the tuple must " 681 "be composed of integers in the range " 682 "0 through 9.") 683 if value[2] in ('n', 'N'): 684 # NaN: digits form the diagnostic 685 self._int = ''.join(map(str, digits)) 686 self._exp = value[2] 687 self._is_special = True 688 elif isinstance(value[2], int): 689 # finite number: digits give the coefficient 690 self._int = ''.join(map(str, digits or [0])) 691 self._exp = value[2] 692 self._is_special = False 693 else: 694 raise ValueError("The third value in the tuple must " 695 "be an integer, or one of the " 696 "strings 'F', 'n', 'N'.") 697 return self 698 699 if isinstance(value, float): 700 if context is None: 701 context = getcontext() 702 context._raise_error(FloatOperation, 703 "strict semantics for mixing floats and Decimals are " 704 "enabled") 705 value = Decimal.from_float(value) 706 self._exp = value._exp 707 self._sign = value._sign 708 self._int = value._int 709 self._is_special = value._is_special 710 return self 711 712 raise TypeError("Cannot convert %r to Decimal" % value) 713 714 @classmethod 715 def from_float(cls, f): 716 """Converts a float to a decimal number, exactly. 717 718 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1'). 719 Since 0.1 is not exactly representable in binary floating point, the 720 value is stored as the nearest representable value which is 721 0x1.999999999999ap-4. The exact equivalent of the value in decimal 722 is 0.1000000000000000055511151231257827021181583404541015625. 723 724 >>> Decimal.from_float(0.1) 725 Decimal('0.1000000000000000055511151231257827021181583404541015625') 726 >>> Decimal.from_float(float('nan')) 727 Decimal('NaN') 728 >>> Decimal.from_float(float('inf')) 729 Decimal('Infinity') 730 >>> Decimal.from_float(-float('inf')) 731 Decimal('-Infinity') 732 >>> Decimal.from_float(-0.0) 733 Decimal('-0') 734 735 """ 736 if isinstance(f, int): # handle integer inputs 737 return cls(f) 738 if not isinstance(f, float): 739 raise TypeError("argument must be int or float.") 740 if _math.isinf(f) or _math.isnan(f): 741 return cls(repr(f)) 742 if _math.copysign(1.0, f) == 1.0: 743 sign = 0 744 else: 745 sign = 1 746 n, d = abs(f).as_integer_ratio() 747 k = d.bit_length() - 1 748 result = _dec_from_triple(sign, str(n*5**k), -k) 749 if cls is Decimal: 750 return result 751 else: 752 return cls(result) 753 754 def _isnan(self): 755 """Returns whether the number is not actually one. 756 757 0 if a number 758 1 if NaN 759 2 if sNaN 760 """ 761 if self._is_special: 762 exp = self._exp 763 if exp == 'n': 764 return 1 765 elif exp == 'N': 766 return 2 767 return 0 768 769 def _isinfinity(self): 770 """Returns whether the number is infinite 771 772 0 if finite or not a number 773 1 if +INF 774 -1 if -INF 775 """ 776 if self._exp == 'F': 777 if self._sign: 778 return -1 779 return 1 780 return 0 781 782 def _check_nans(self, other=None, context=None): 783 """Returns whether the number is not actually one. 784 785 if self, other are sNaN, signal 786 if self, other are NaN return nan 787 return 0 788 789 Done before operations. 790 """ 791 792 self_is_nan = self._isnan() 793 if other is None: 794 other_is_nan = False 795 else: 796 other_is_nan = other._isnan() 797 798 if self_is_nan or other_is_nan: 799 if context is None: 800 context = getcontext() 801 802 if self_is_nan == 2: 803 return context._raise_error(InvalidOperation, 'sNaN', 804 self) 805 if other_is_nan == 2: 806 return context._raise_error(InvalidOperation, 'sNaN', 807 other) 808 if self_is_nan: 809 return self._fix_nan(context) 810 811 return other._fix_nan(context) 812 return 0 813 814 def _compare_check_nans(self, other, context): 815 """Version of _check_nans used for the signaling comparisons 816 compare_signal, __le__, __lt__, __ge__, __gt__. 817 818 Signal InvalidOperation if either self or other is a (quiet 819 or signaling) NaN. Signaling NaNs take precedence over quiet 820 NaNs. 821 822 Return 0 if neither operand is a NaN. 823 824 """ 825 if context is None: 826 context = getcontext() 827 828 if self._is_special or other._is_special: 829 if self.is_snan(): 830 return context._raise_error(InvalidOperation, 831 'comparison involving sNaN', 832 self) 833 elif other.is_snan(): 834 return context._raise_error(InvalidOperation, 835 'comparison involving sNaN', 836 other) 837 elif self.is_qnan(): 838 return context._raise_error(InvalidOperation, 839 'comparison involving NaN', 840 self) 841 elif other.is_qnan(): 842 return context._raise_error(InvalidOperation, 843 'comparison involving NaN', 844 other) 845 return 0 846 847 def __bool__(self): 848 """Return True if self is nonzero; otherwise return False. 849 850 NaNs and infinities are considered nonzero. 851 """ 852 return self._is_special or self._int != '0' 853 854 def _cmp(self, other): 855 """Compare the two non-NaN decimal instances self and other. 856 857 Returns -1 if self < other, 0 if self == other and 1 858 if self > other. This routine is for internal use only.""" 859 860 if self._is_special or other._is_special: 861 self_inf = self._isinfinity() 862 other_inf = other._isinfinity() 863 if self_inf == other_inf: 864 return 0 865 elif self_inf < other_inf: 866 return -1 867 else: 868 return 1 869 870 # check for zeros; Decimal('0') == Decimal('-0') 871 if not self: 872 if not other: 873 return 0 874 else: 875 return -((-1)**other._sign) 876 if not other: 877 return (-1)**self._sign 878 879 # If different signs, neg one is less 880 if other._sign < self._sign: 881 return -1 882 if self._sign < other._sign: 883 return 1 884 885 self_adjusted = self.adjusted() 886 other_adjusted = other.adjusted() 887 if self_adjusted == other_adjusted: 888 self_padded = self._int + '0'*(self._exp - other._exp) 889 other_padded = other._int + '0'*(other._exp - self._exp) 890 if self_padded == other_padded: 891 return 0 892 elif self_padded < other_padded: 893 return -(-1)**self._sign 894 else: 895 return (-1)**self._sign 896 elif self_adjusted > other_adjusted: 897 return (-1)**self._sign 898 else: # self_adjusted < other_adjusted 899 return -((-1)**self._sign) 900 901 # Note: The Decimal standard doesn't cover rich comparisons for 902 # Decimals. In particular, the specification is silent on the 903 # subject of what should happen for a comparison involving a NaN. 904 # We take the following approach: 905 # 906 # == comparisons involving a quiet NaN always return False 907 # != comparisons involving a quiet NaN always return True 908 # == or != comparisons involving a signaling NaN signal 909 # InvalidOperation, and return False or True as above if the 910 # InvalidOperation is not trapped. 911 # <, >, <= and >= comparisons involving a (quiet or signaling) 912 # NaN signal InvalidOperation, and return False if the 913 # InvalidOperation is not trapped. 914 # 915 # This behavior is designed to conform as closely as possible to 916 # that specified by IEEE 754. 917 918 def __eq__(self, other, context=None): 919 self, other = _convert_for_comparison(self, other, equality_op=True) 920 if other is NotImplemented: 921 return other 922 if self._check_nans(other, context): 923 return False 924 return self._cmp(other) == 0 925 926 def __lt__(self, other, context=None): 927 self, other = _convert_for_comparison(self, other) 928 if other is NotImplemented: 929 return other 930 ans = self._compare_check_nans(other, context) 931 if ans: 932 return False 933 return self._cmp(other) < 0 934 935 def __le__(self, other, context=None): 936 self, other = _convert_for_comparison(self, other) 937 if other is NotImplemented: 938 return other 939 ans = self._compare_check_nans(other, context) 940 if ans: 941 return False 942 return self._cmp(other) <= 0 943 944 def __gt__(self, other, context=None): 945 self, other = _convert_for_comparison(self, other) 946 if other is NotImplemented: 947 return other 948 ans = self._compare_check_nans(other, context) 949 if ans: 950 return False 951 return self._cmp(other) > 0 952 953 def __ge__(self, other, context=None): 954 self, other = _convert_for_comparison(self, other) 955 if other is NotImplemented: 956 return other 957 ans = self._compare_check_nans(other, context) 958 if ans: 959 return False 960 return self._cmp(other) >= 0 961 962 def compare(self, other, context=None): 963 """Compare self to other. Return a decimal value: 964 965 a or b is a NaN ==> Decimal('NaN') 966 a < b ==> Decimal('-1') 967 a == b ==> Decimal('0') 968 a > b ==> Decimal('1') 969 """ 970 other = _convert_other(other, raiseit=True) 971 972 # Compare(NaN, NaN) = NaN 973 if (self._is_special or other and other._is_special): 974 ans = self._check_nans(other, context) 975 if ans: 976 return ans 977 978 return Decimal(self._cmp(other)) 979 980 def __hash__(self): 981 """x.__hash__() <==> hash(x)""" 982 983 # In order to make sure that the hash of a Decimal instance 984 # agrees with the hash of a numerically equal integer, float 985 # or Fraction, we follow the rules for numeric hashes outlined 986 # in the documentation. (See library docs, 'Built-in Types'). 987 if self._is_special: 988 if self.is_snan(): 989 raise TypeError('Cannot hash a signaling NaN value.') 990 elif self.is_nan(): 991 return _PyHASH_NAN 992 else: 993 if self._sign: 994 return -_PyHASH_INF 995 else: 996 return _PyHASH_INF 997 998 if self._exp >= 0: 999 exp_hash = pow(10, self._exp, _PyHASH_MODULUS) 1000 else: 1001 exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS) 1002 hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS 1003 ans = hash_ if self >= 0 else -hash_ 1004 return -2 if ans == -1 else ans 1005 1006 def as_tuple(self): 1007 """Represents the number as a triple tuple. 1008 1009 To show the internals exactly as they are. 1010 """ 1011 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp) 1012 1013 def as_integer_ratio(self): 1014 """Express a finite Decimal instance in the form n / d. 1015 1016 Returns a pair (n, d) of integers. When called on an infinity 1017 or NaN, raises OverflowError or ValueError respectively. 1018 1019 >>> Decimal('3.14').as_integer_ratio() 1020 (157, 50) 1021 >>> Decimal('-123e5').as_integer_ratio() 1022 (-12300000, 1) 1023 >>> Decimal('0.00').as_integer_ratio() 1024 (0, 1) 1025 1026 """ 1027 if self._is_special: 1028 if self.is_nan(): 1029 raise ValueError("cannot convert NaN to integer ratio") 1030 else: 1031 raise OverflowError("cannot convert Infinity to integer ratio") 1032 1033 if not self: 1034 return 0, 1 1035 1036 # Find n, d in lowest terms such that abs(self) == n / d; 1037 # we'll deal with the sign later. 1038 n = int(self._int) 1039 if self._exp >= 0: 1040 # self is an integer. 1041 n, d = n * 10**self._exp, 1 1042 else: 1043 # Find d2, d5 such that abs(self) = n / (2**d2 * 5**d5). 1044 d5 = -self._exp 1045 while d5 > 0 and n % 5 == 0: 1046 n //= 5 1047 d5 -= 1 1048 1049 # (n & -n).bit_length() - 1 counts trailing zeros in binary 1050 # representation of n (provided n is nonzero). 1051 d2 = -self._exp 1052 shift2 = min((n & -n).bit_length() - 1, d2) 1053 if shift2: 1054 n >>= shift2 1055 d2 -= shift2 1056 1057 d = 5**d5 << d2 1058 1059 if self._sign: 1060 n = -n 1061 return n, d 1062 1063 def __repr__(self): 1064 """Represents the number as an instance of Decimal.""" 1065 # Invariant: eval(repr(d)) == d 1066 return "Decimal('%s')" % str(self) 1067 1068 def __str__(self, eng=False, context=None): 1069 """Return string representation of the number in scientific notation. 1070 1071 Captures all of the information in the underlying representation. 1072 """ 1073 1074 sign = ['', '-'][self._sign] 1075 if self._is_special: 1076 if self._exp == 'F': 1077 return sign + 'Infinity' 1078 elif self._exp == 'n': 1079 return sign + 'NaN' + self._int 1080 else: # self._exp == 'N' 1081 return sign + 'sNaN' + self._int 1082 1083 # number of digits of self._int to left of decimal point 1084 leftdigits = self._exp + len(self._int) 1085 1086 # dotplace is number of digits of self._int to the left of the 1087 # decimal point in the mantissa of the output string (that is, 1088 # after adjusting the exponent) 1089 if self._exp <= 0 and leftdigits > -6: 1090 # no exponent required 1091 dotplace = leftdigits 1092 elif not eng: 1093 # usual scientific notation: 1 digit on left of the point 1094 dotplace = 1 1095 elif self._int == '0': 1096 # engineering notation, zero 1097 dotplace = (leftdigits + 1) % 3 - 1 1098 else: 1099 # engineering notation, nonzero 1100 dotplace = (leftdigits - 1) % 3 + 1 1101 1102 if dotplace <= 0: 1103 intpart = '0' 1104 fracpart = '.' + '0'*(-dotplace) + self._int 1105 elif dotplace >= len(self._int): 1106 intpart = self._int+'0'*(dotplace-len(self._int)) 1107 fracpart = '' 1108 else: 1109 intpart = self._int[:dotplace] 1110 fracpart = '.' + self._int[dotplace:] 1111 if leftdigits == dotplace: 1112 exp = '' 1113 else: 1114 if context is None: 1115 context = getcontext() 1116 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace) 1117 1118 return sign + intpart + fracpart + exp 1119 1120 def to_eng_string(self, context=None): 1121 """Convert to a string, using engineering notation if an exponent is needed. 1122 1123 Engineering notation has an exponent which is a multiple of 3. This 1124 can leave up to 3 digits to the left of the decimal place and may 1125 require the addition of either one or two trailing zeros. 1126 """ 1127 return self.__str__(eng=True, context=context) 1128 1129 def __neg__(self, context=None): 1130 """Returns a copy with the sign switched. 1131 1132 Rounds, if it has reason. 1133 """ 1134 if self._is_special: 1135 ans = self._check_nans(context=context) 1136 if ans: 1137 return ans 1138 1139 if context is None: 1140 context = getcontext() 1141 1142 if not self and context.rounding != ROUND_FLOOR: 1143 # -Decimal('0') is Decimal('0'), not Decimal('-0'), except 1144 # in ROUND_FLOOR rounding mode. 1145 ans = self.copy_abs() 1146 else: 1147 ans = self.copy_negate() 1148 1149 return ans._fix(context) 1150 1151 def __pos__(self, context=None): 1152 """Returns a copy, unless it is a sNaN. 1153 1154 Rounds the number (if more than precision digits) 1155 """ 1156 if self._is_special: 1157 ans = self._check_nans(context=context) 1158 if ans: 1159 return ans 1160 1161 if context is None: 1162 context = getcontext() 1163 1164 if not self and context.rounding != ROUND_FLOOR: 1165 # + (-0) = 0, except in ROUND_FLOOR rounding mode. 1166 ans = self.copy_abs() 1167 else: 1168 ans = Decimal(self) 1169 1170 return ans._fix(context) 1171 1172 def __abs__(self, round=True, context=None): 1173 """Returns the absolute value of self. 1174 1175 If the keyword argument 'round' is false, do not round. The 1176 expression self.__abs__(round=False) is equivalent to 1177 self.copy_abs(). 1178 """ 1179 if not round: 1180 return self.copy_abs() 1181 1182 if self._is_special: 1183 ans = self._check_nans(context=context) 1184 if ans: 1185 return ans 1186 1187 if self._sign: 1188 ans = self.__neg__(context=context) 1189 else: 1190 ans = self.__pos__(context=context) 1191 1192 return ans 1193 1194 def __add__(self, other, context=None): 1195 """Returns self + other. 1196 1197 -INF + INF (or the reverse) cause InvalidOperation errors. 1198 """ 1199 other = _convert_other(other) 1200 if other is NotImplemented: 1201 return other 1202 1203 if context is None: 1204 context = getcontext() 1205 1206 if self._is_special or other._is_special: 1207 ans = self._check_nans(other, context) 1208 if ans: 1209 return ans 1210 1211 if self._isinfinity(): 1212 # If both INF, same sign => same as both, opposite => error. 1213 if self._sign != other._sign and other._isinfinity(): 1214 return context._raise_error(InvalidOperation, '-INF + INF') 1215 return Decimal(self) 1216 if other._isinfinity(): 1217 return Decimal(other) # Can't both be infinity here 1218 1219 exp = min(self._exp, other._exp) 1220 negativezero = 0 1221 if context.rounding == ROUND_FLOOR and self._sign != other._sign: 1222 # If the answer is 0, the sign should be negative, in this case. 1223 negativezero = 1 1224 1225 if not self and not other: 1226 sign = min(self._sign, other._sign) 1227 if negativezero: 1228 sign = 1 1229 ans = _dec_from_triple(sign, '0', exp) 1230 ans = ans._fix(context) 1231 return ans 1232 if not self: 1233 exp = max(exp, other._exp - context.prec-1) 1234 ans = other._rescale(exp, context.rounding) 1235 ans = ans._fix(context) 1236 return ans 1237 if not other: 1238 exp = max(exp, self._exp - context.prec-1) 1239 ans = self._rescale(exp, context.rounding) 1240 ans = ans._fix(context) 1241 return ans 1242 1243 op1 = _WorkRep(self) 1244 op2 = _WorkRep(other) 1245 op1, op2 = _normalize(op1, op2, context.prec) 1246 1247 result = _WorkRep() 1248 if op1.sign != op2.sign: 1249 # Equal and opposite 1250 if op1.int == op2.int: 1251 ans = _dec_from_triple(negativezero, '0', exp) 1252 ans = ans._fix(context) 1253 return ans 1254 if op1.int < op2.int: 1255 op1, op2 = op2, op1 1256 # OK, now abs(op1) > abs(op2) 1257 if op1.sign == 1: 1258 result.sign = 1 1259 op1.sign, op2.sign = op2.sign, op1.sign 1260 else: 1261 result.sign = 0 1262 # So we know the sign, and op1 > 0. 1263 elif op1.sign == 1: 1264 result.sign = 1 1265 op1.sign, op2.sign = (0, 0) 1266 else: 1267 result.sign = 0 1268 # Now, op1 > abs(op2) > 0 1269 1270 if op2.sign == 0: 1271 result.int = op1.int + op2.int 1272 else: 1273 result.int = op1.int - op2.int 1274 1275 result.exp = op1.exp 1276 ans = Decimal(result) 1277 ans = ans._fix(context) 1278 return ans 1279 1280 __radd__ = __add__ 1281 1282 def __sub__(self, other, context=None): 1283 """Return self - other""" 1284 other = _convert_other(other) 1285 if other is NotImplemented: 1286 return other 1287 1288 if self._is_special or other._is_special: 1289 ans = self._check_nans(other, context=context) 1290 if ans: 1291 return ans 1292 1293 # self - other is computed as self + other.copy_negate() 1294 return self.__add__(other.copy_negate(), context=context) 1295 1296 def __rsub__(self, other, context=None): 1297 """Return other - self""" 1298 other = _convert_other(other) 1299 if other is NotImplemented: 1300 return other 1301 1302 return other.__sub__(self, context=context) 1303 1304 def __mul__(self, other, context=None): 1305 """Return self * other. 1306 1307 (+-) INF * 0 (or its reverse) raise InvalidOperation. 1308 """ 1309 other = _convert_other(other) 1310 if other is NotImplemented: 1311 return other 1312 1313 if context is None: 1314 context = getcontext() 1315 1316 resultsign = self._sign ^ other._sign 1317 1318 if self._is_special or other._is_special: 1319 ans = self._check_nans(other, context) 1320 if ans: 1321 return ans 1322 1323 if self._isinfinity(): 1324 if not other: 1325 return context._raise_error(InvalidOperation, '(+-)INF * 0') 1326 return _SignedInfinity[resultsign] 1327 1328 if other._isinfinity(): 1329 if not self: 1330 return context._raise_error(InvalidOperation, '0 * (+-)INF') 1331 return _SignedInfinity[resultsign] 1332 1333 resultexp = self._exp + other._exp 1334 1335 # Special case for multiplying by zero 1336 if not self or not other: 1337 ans = _dec_from_triple(resultsign, '0', resultexp) 1338 # Fixing in case the exponent is out of bounds 1339 ans = ans._fix(context) 1340 return ans 1341 1342 # Special case for multiplying by power of 10 1343 if self._int == '1': 1344 ans = _dec_from_triple(resultsign, other._int, resultexp) 1345 ans = ans._fix(context) 1346 return ans 1347 if other._int == '1': 1348 ans = _dec_from_triple(resultsign, self._int, resultexp) 1349 ans = ans._fix(context) 1350 return ans 1351 1352 op1 = _WorkRep(self) 1353 op2 = _WorkRep(other) 1354 1355 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp) 1356 ans = ans._fix(context) 1357 1358 return ans 1359 __rmul__ = __mul__ 1360 1361 def __truediv__(self, other, context=None): 1362 """Return self / other.""" 1363 other = _convert_other(other) 1364 if other is NotImplemented: 1365 return NotImplemented 1366 1367 if context is None: 1368 context = getcontext() 1369 1370 sign = self._sign ^ other._sign 1371 1372 if self._is_special or other._is_special: 1373 ans = self._check_nans(other, context) 1374 if ans: 1375 return ans 1376 1377 if self._isinfinity() and other._isinfinity(): 1378 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') 1379 1380 if self._isinfinity(): 1381 return _SignedInfinity[sign] 1382 1383 if other._isinfinity(): 1384 context._raise_error(Clamped, 'Division by infinity') 1385 return _dec_from_triple(sign, '0', context.Etiny()) 1386 1387 # Special cases for zeroes 1388 if not other: 1389 if not self: 1390 return context._raise_error(DivisionUndefined, '0 / 0') 1391 return context._raise_error(DivisionByZero, 'x / 0', sign) 1392 1393 if not self: 1394 exp = self._exp - other._exp 1395 coeff = 0 1396 else: 1397 # OK, so neither = 0, INF or NaN 1398 shift = len(other._int) - len(self._int) + context.prec + 1 1399 exp = self._exp - other._exp - shift 1400 op1 = _WorkRep(self) 1401 op2 = _WorkRep(other) 1402 if shift >= 0: 1403 coeff, remainder = divmod(op1.int * 10**shift, op2.int) 1404 else: 1405 coeff, remainder = divmod(op1.int, op2.int * 10**-shift) 1406 if remainder: 1407 # result is not exact; adjust to ensure correct rounding 1408 if coeff % 5 == 0: 1409 coeff += 1 1410 else: 1411 # result is exact; get as close to ideal exponent as possible 1412 ideal_exp = self._exp - other._exp 1413 while exp < ideal_exp and coeff % 10 == 0: 1414 coeff //= 10 1415 exp += 1 1416 1417 ans = _dec_from_triple(sign, str(coeff), exp) 1418 return ans._fix(context) 1419 1420 def _divide(self, other, context): 1421 """Return (self // other, self % other), to context.prec precision. 1422 1423 Assumes that neither self nor other is a NaN, that self is not 1424 infinite and that other is nonzero. 1425 """ 1426 sign = self._sign ^ other._sign 1427 if other._isinfinity(): 1428 ideal_exp = self._exp 1429 else: 1430 ideal_exp = min(self._exp, other._exp) 1431 1432 expdiff = self.adjusted() - other.adjusted() 1433 if not self or other._isinfinity() or expdiff <= -2: 1434 return (_dec_from_triple(sign, '0', 0), 1435 self._rescale(ideal_exp, context.rounding)) 1436 if expdiff <= context.prec: 1437 op1 = _WorkRep(self) 1438 op2 = _WorkRep(other) 1439 if op1.exp >= op2.exp: 1440 op1.int *= 10**(op1.exp - op2.exp) 1441 else: 1442 op2.int *= 10**(op2.exp - op1.exp) 1443 q, r = divmod(op1.int, op2.int) 1444 if q < 10**context.prec: 1445 return (_dec_from_triple(sign, str(q), 0), 1446 _dec_from_triple(self._sign, str(r), ideal_exp)) 1447 1448 # Here the quotient is too large to be representable 1449 ans = context._raise_error(DivisionImpossible, 1450 'quotient too large in //, % or divmod') 1451 return ans, ans 1452 1453 def __rtruediv__(self, other, context=None): 1454 """Swaps self/other and returns __truediv__.""" 1455 other = _convert_other(other) 1456 if other is NotImplemented: 1457 return other 1458 return other.__truediv__(self, context=context) 1459 1460 def __divmod__(self, other, context=None): 1461 """ 1462 Return (self // other, self % other) 1463 """ 1464 other = _convert_other(other) 1465 if other is NotImplemented: 1466 return other 1467 1468 if context is None: 1469 context = getcontext() 1470 1471 ans = self._check_nans(other, context) 1472 if ans: 1473 return (ans, ans) 1474 1475 sign = self._sign ^ other._sign 1476 if self._isinfinity(): 1477 if other._isinfinity(): 1478 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') 1479 return ans, ans 1480 else: 1481 return (_SignedInfinity[sign], 1482 context._raise_error(InvalidOperation, 'INF % x')) 1483 1484 if not other: 1485 if not self: 1486 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') 1487 return ans, ans 1488 else: 1489 return (context._raise_error(DivisionByZero, 'x // 0', sign), 1490 context._raise_error(InvalidOperation, 'x % 0')) 1491 1492 quotient, remainder = self._divide(other, context) 1493 remainder = remainder._fix(context) 1494 return quotient, remainder 1495 1496 def __rdivmod__(self, other, context=None): 1497 """Swaps self/other and returns __divmod__.""" 1498 other = _convert_other(other) 1499 if other is NotImplemented: 1500 return other 1501 return other.__divmod__(self, context=context) 1502 1503 def __mod__(self, other, context=None): 1504 """ 1505 self % other 1506 """ 1507 other = _convert_other(other) 1508 if other is NotImplemented: 1509 return other 1510 1511 if context is None: 1512 context = getcontext() 1513 1514 ans = self._check_nans(other, context) 1515 if ans: 1516 return ans 1517 1518 if self._isinfinity(): 1519 return context._raise_error(InvalidOperation, 'INF % x') 1520 elif not other: 1521 if self: 1522 return context._raise_error(InvalidOperation, 'x % 0') 1523 else: 1524 return context._raise_error(DivisionUndefined, '0 % 0') 1525 1526 remainder = self._divide(other, context)[1] 1527 remainder = remainder._fix(context) 1528 return remainder 1529 1530 def __rmod__(self, other, context=None): 1531 """Swaps self/other and returns __mod__.""" 1532 other = _convert_other(other) 1533 if other is NotImplemented: 1534 return other 1535 return other.__mod__(self, context=context) 1536 1537 def remainder_near(self, other, context=None): 1538 """ 1539 Remainder nearest to 0- abs(remainder-near) <= other/2 1540 """ 1541 if context is None: 1542 context = getcontext() 1543 1544 other = _convert_other(other, raiseit=True) 1545 1546 ans = self._check_nans(other, context) 1547 if ans: 1548 return ans 1549 1550 # self == +/-infinity -> InvalidOperation 1551 if self._isinfinity(): 1552 return context._raise_error(InvalidOperation, 1553 'remainder_near(infinity, x)') 1554 1555 # other == 0 -> either InvalidOperation or DivisionUndefined 1556 if not other: 1557 if self: 1558 return context._raise_error(InvalidOperation, 1559 'remainder_near(x, 0)') 1560 else: 1561 return context._raise_error(DivisionUndefined, 1562 'remainder_near(0, 0)') 1563 1564 # other = +/-infinity -> remainder = self 1565 if other._isinfinity(): 1566 ans = Decimal(self) 1567 return ans._fix(context) 1568 1569 # self = 0 -> remainder = self, with ideal exponent 1570 ideal_exponent = min(self._exp, other._exp) 1571 if not self: 1572 ans = _dec_from_triple(self._sign, '0', ideal_exponent) 1573 return ans._fix(context) 1574 1575 # catch most cases of large or small quotient 1576 expdiff = self.adjusted() - other.adjusted() 1577 if expdiff >= context.prec + 1: 1578 # expdiff >= prec+1 => abs(self/other) > 10**prec 1579 return context._raise_error(DivisionImpossible) 1580 if expdiff <= -2: 1581 # expdiff <= -2 => abs(self/other) < 0.1 1582 ans = self._rescale(ideal_exponent, context.rounding) 1583 return ans._fix(context) 1584 1585 # adjust both arguments to have the same exponent, then divide 1586 op1 = _WorkRep(self) 1587 op2 = _WorkRep(other) 1588 if op1.exp >= op2.exp: 1589 op1.int *= 10**(op1.exp - op2.exp) 1590 else: 1591 op2.int *= 10**(op2.exp - op1.exp) 1592 q, r = divmod(op1.int, op2.int) 1593 # remainder is r*10**ideal_exponent; other is +/-op2.int * 1594 # 10**ideal_exponent. Apply correction to ensure that 1595 # abs(remainder) <= abs(other)/2 1596 if 2*r + (q&1) > op2.int: 1597 r -= op2.int 1598 q += 1 1599 1600 if q >= 10**context.prec: 1601 return context._raise_error(DivisionImpossible) 1602 1603 # result has same sign as self unless r is negative 1604 sign = self._sign 1605 if r < 0: 1606 sign = 1-sign 1607 r = -r 1608 1609 ans = _dec_from_triple(sign, str(r), ideal_exponent) 1610 return ans._fix(context) 1611 1612 def __floordiv__(self, other, context=None): 1613 """self // other""" 1614 other = _convert_other(other) 1615 if other is NotImplemented: 1616 return other 1617 1618 if context is None: 1619 context = getcontext() 1620 1621 ans = self._check_nans(other, context) 1622 if ans: 1623 return ans 1624 1625 if self._isinfinity(): 1626 if other._isinfinity(): 1627 return context._raise_error(InvalidOperation, 'INF // INF') 1628 else: 1629 return _SignedInfinity[self._sign ^ other._sign] 1630 1631 if not other: 1632 if self: 1633 return context._raise_error(DivisionByZero, 'x // 0', 1634 self._sign ^ other._sign) 1635 else: 1636 return context._raise_error(DivisionUndefined, '0 // 0') 1637 1638 return self._divide(other, context)[0] 1639 1640 def __rfloordiv__(self, other, context=None): 1641 """Swaps self/other and returns __floordiv__.""" 1642 other = _convert_other(other) 1643 if other is NotImplemented: 1644 return other 1645 return other.__floordiv__(self, context=context) 1646 1647 def __float__(self): 1648 """Float representation.""" 1649 if self._isnan(): 1650 if self.is_snan(): 1651 raise ValueError("Cannot convert signaling NaN to float") 1652 s = "-nan" if self._sign else "nan" 1653 else: 1654 s = str(self) 1655 return float(s) 1656 1657 def __int__(self): 1658 """Converts self to an int, truncating if necessary.""" 1659 if self._is_special: 1660 if self._isnan(): 1661 raise ValueError("Cannot convert NaN to integer") 1662 elif self._isinfinity(): 1663 raise OverflowError("Cannot convert infinity to integer") 1664 s = (-1)**self._sign 1665 if self._exp >= 0: 1666 return s*int(self._int)*10**self._exp 1667 else: 1668 return s*int(self._int[:self._exp] or '0') 1669 1670 __trunc__ = __int__ 1671 1672 def real(self): 1673 return self 1674 real = property(real) 1675 1676 def imag(self): 1677 return Decimal(0) 1678 imag = property(imag) 1679 1680 def conjugate(self): 1681 return self 1682 1683 def __complex__(self): 1684 return complex(float(self)) 1685 1686 def _fix_nan(self, context): 1687 """Decapitate the payload of a NaN to fit the context""" 1688 payload = self._int 1689 1690 # maximum length of payload is precision if clamp=0, 1691 # precision-1 if clamp=1. 1692 max_payload_len = context.prec - context.clamp 1693 if len(payload) > max_payload_len: 1694 payload = payload[len(payload)-max_payload_len:].lstrip('0') 1695 return _dec_from_triple(self._sign, payload, self._exp, True) 1696 return Decimal(self) 1697 1698 def _fix(self, context): 1699 """Round if it is necessary to keep self within prec precision. 1700 1701 Rounds and fixes the exponent. Does not raise on a sNaN. 1702 1703 Arguments: 1704 self - Decimal instance 1705 context - context used. 1706 """ 1707 1708 if self._is_special: 1709 if self._isnan(): 1710 # decapitate payload if necessary 1711 return self._fix_nan(context) 1712 else: 1713 # self is +/-Infinity; return unaltered 1714 return Decimal(self) 1715 1716 # if self is zero then exponent should be between Etiny and 1717 # Emax if clamp==0, and between Etiny and Etop if clamp==1. 1718 Etiny = context.Etiny() 1719 Etop = context.Etop() 1720 if not self: 1721 exp_max = [context.Emax, Etop][context.clamp] 1722 new_exp = min(max(self._exp, Etiny), exp_max) 1723 if new_exp != self._exp: 1724 context._raise_error(Clamped) 1725 return _dec_from_triple(self._sign, '0', new_exp) 1726 else: 1727 return Decimal(self) 1728 1729 # exp_min is the smallest allowable exponent of the result, 1730 # equal to max(self.adjusted()-context.prec+1, Etiny) 1731 exp_min = len(self._int) + self._exp - context.prec 1732 if exp_min > Etop: 1733 # overflow: exp_min > Etop iff self.adjusted() > Emax 1734 ans = context._raise_error(Overflow, 'above Emax', self._sign) 1735 context._raise_error(Inexact) 1736 context._raise_error(Rounded) 1737 return ans 1738 1739 self_is_subnormal = exp_min < Etiny 1740 if self_is_subnormal: 1741 exp_min = Etiny 1742 1743 # round if self has too many digits 1744 if self._exp < exp_min: 1745 digits = len(self._int) + self._exp - exp_min 1746 if digits < 0: 1747 self = _dec_from_triple(self._sign, '1', exp_min-1) 1748 digits = 0 1749 rounding_method = self._pick_rounding_function[context.rounding] 1750 changed = rounding_method(self, digits) 1751 coeff = self._int[:digits] or '0' 1752 if changed > 0: 1753 coeff = str(int(coeff)+1) 1754 if len(coeff) > context.prec: 1755 coeff = coeff[:-1] 1756 exp_min += 1 1757 1758 # check whether the rounding pushed the exponent out of range 1759 if exp_min > Etop: 1760 ans = context._raise_error(Overflow, 'above Emax', self._sign) 1761 else: 1762 ans = _dec_from_triple(self._sign, coeff, exp_min) 1763 1764 # raise the appropriate signals, taking care to respect 1765 # the precedence described in the specification 1766 if changed and self_is_subnormal: 1767 context._raise_error(Underflow) 1768 if self_is_subnormal: 1769 context._raise_error(Subnormal) 1770 if changed: 1771 context._raise_error(Inexact) 1772 context._raise_error(Rounded) 1773 if not ans: 1774 # raise Clamped on underflow to 0 1775 context._raise_error(Clamped) 1776 return ans 1777 1778 if self_is_subnormal: 1779 context._raise_error(Subnormal) 1780 1781 # fold down if clamp == 1 and self has too few digits 1782 if context.clamp == 1 and self._exp > Etop: 1783 context._raise_error(Clamped) 1784 self_padded = self._int + '0'*(self._exp - Etop) 1785 return _dec_from_triple(self._sign, self_padded, Etop) 1786 1787 # here self was representable to begin with; return unchanged 1788 return Decimal(self) 1789 1790 # for each of the rounding functions below: 1791 # self is a finite, nonzero Decimal 1792 # prec is an integer satisfying 0 <= prec < len(self._int) 1793 # 1794 # each function returns either -1, 0, or 1, as follows: 1795 # 1 indicates that self should be rounded up (away from zero) 1796 # 0 indicates that self should be truncated, and that all the 1797 # digits to be truncated are zeros (so the value is unchanged) 1798 # -1 indicates that there are nonzero digits to be truncated 1799 1800 def _round_down(self, prec): 1801 """Also known as round-towards-0, truncate.""" 1802 if _all_zeros(self._int, prec): 1803 return 0 1804 else: 1805 return -1 1806 1807 def _round_up(self, prec): 1808 """Rounds away from 0.""" 1809 return -self._round_down(prec) 1810 1811 def _round_half_up(self, prec): 1812 """Rounds 5 up (away from 0)""" 1813 if self._int[prec] in '56789': 1814 return 1 1815 elif _all_zeros(self._int, prec): 1816 return 0 1817 else: 1818 return -1 1819 1820 def _round_half_down(self, prec): 1821 """Round 5 down""" 1822 if _exact_half(self._int, prec): 1823 return -1 1824 else: 1825 return self._round_half_up(prec) 1826 1827 def _round_half_even(self, prec): 1828 """Round 5 to even, rest to nearest.""" 1829 if _exact_half(self._int, prec) and \ 1830 (prec == 0 or self._int[prec-1] in '02468'): 1831 return -1 1832 else: 1833 return self._round_half_up(prec) 1834 1835 def _round_ceiling(self, prec): 1836 """Rounds up (not away from 0 if negative.)""" 1837 if self._sign: 1838 return self._round_down(prec) 1839 else: 1840 return -self._round_down(prec) 1841 1842 def _round_floor(self, prec): 1843 """Rounds down (not towards 0 if negative)""" 1844 if not self._sign: 1845 return self._round_down(prec) 1846 else: 1847 return -self._round_down(prec) 1848 1849 def _round_05up(self, prec): 1850 """Round down unless digit prec-1 is 0 or 5.""" 1851 if prec and self._int[prec-1] not in '05': 1852 return self._round_down(prec) 1853 else: 1854 return -self._round_down(prec) 1855 1856 _pick_rounding_function = dict( 1857 ROUND_DOWN = _round_down, 1858 ROUND_UP = _round_up, 1859 ROUND_HALF_UP = _round_half_up, 1860 ROUND_HALF_DOWN = _round_half_down, 1861 ROUND_HALF_EVEN = _round_half_even, 1862 ROUND_CEILING = _round_ceiling, 1863 ROUND_FLOOR = _round_floor, 1864 ROUND_05UP = _round_05up, 1865 ) 1866 1867 def __round__(self, n=None): 1868 """Round self to the nearest integer, or to a given precision. 1869 1870 If only one argument is supplied, round a finite Decimal 1871 instance self to the nearest integer. If self is infinite or 1872 a NaN then a Python exception is raised. If self is finite 1873 and lies exactly halfway between two integers then it is 1874 rounded to the integer with even last digit. 1875 1876 >>> round(Decimal('123.456')) 1877 123 1878 >>> round(Decimal('-456.789')) 1879 -457 1880 >>> round(Decimal('-3.0')) 1881 -3 1882 >>> round(Decimal('2.5')) 1883 2 1884 >>> round(Decimal('3.5')) 1885 4 1886 >>> round(Decimal('Inf')) 1887 Traceback (most recent call last): 1888 ... 1889 OverflowError: cannot round an infinity 1890 >>> round(Decimal('NaN')) 1891 Traceback (most recent call last): 1892 ... 1893 ValueError: cannot round a NaN 1894 1895 If a second argument n is supplied, self is rounded to n 1896 decimal places using the rounding mode for the current 1897 context. 1898 1899 For an integer n, round(self, -n) is exactly equivalent to 1900 self.quantize(Decimal('1En')). 1901 1902 >>> round(Decimal('123.456'), 0) 1903 Decimal('123') 1904 >>> round(Decimal('123.456'), 2) 1905 Decimal('123.46') 1906 >>> round(Decimal('123.456'), -2) 1907 Decimal('1E+2') 1908 >>> round(Decimal('-Infinity'), 37) 1909 Decimal('NaN') 1910 >>> round(Decimal('sNaN123'), 0) 1911 Decimal('NaN123') 1912 1913 """ 1914 if n is not None: 1915 # two-argument form: use the equivalent quantize call 1916 if not isinstance(n, int): 1917 raise TypeError('Second argument to round should be integral') 1918 exp = _dec_from_triple(0, '1', -n) 1919 return self.quantize(exp) 1920 1921 # one-argument form 1922 if self._is_special: 1923 if self.is_nan(): 1924 raise ValueError("cannot round a NaN") 1925 else: 1926 raise OverflowError("cannot round an infinity") 1927 return int(self._rescale(0, ROUND_HALF_EVEN)) 1928 1929 def __floor__(self): 1930 """Return the floor of self, as an integer. 1931 1932 For a finite Decimal instance self, return the greatest 1933 integer n such that n <= self. If self is infinite or a NaN 1934 then a Python exception is raised. 1935 1936 """ 1937 if self._is_special: 1938 if self.is_nan(): 1939 raise ValueError("cannot round a NaN") 1940 else: 1941 raise OverflowError("cannot round an infinity") 1942 return int(self._rescale(0, ROUND_FLOOR)) 1943 1944 def __ceil__(self): 1945 """Return the ceiling of self, as an integer. 1946 1947 For a finite Decimal instance self, return the least integer n 1948 such that n >= self. If self is infinite or a NaN then a 1949 Python exception is raised. 1950 1951 """ 1952 if self._is_special: 1953 if self.is_nan(): 1954 raise ValueError("cannot round a NaN") 1955 else: 1956 raise OverflowError("cannot round an infinity") 1957 return int(self._rescale(0, ROUND_CEILING)) 1958 1959 def fma(self, other, third, context=None): 1960 """Fused multiply-add. 1961 1962 Returns self*other+third with no rounding of the intermediate 1963 product self*other. 1964 1965 self and other are multiplied together, with no rounding of 1966 the result. The third operand is then added to the result, 1967 and a single final rounding is performed. 1968 """ 1969 1970 other = _convert_other(other, raiseit=True) 1971 third = _convert_other(third, raiseit=True) 1972 1973 # compute product; raise InvalidOperation if either operand is 1974 # a signaling NaN or if the product is zero times infinity. 1975 if self._is_special or other._is_special: 1976 if context is None: 1977 context = getcontext() 1978 if self._exp == 'N': 1979 return context._raise_error(InvalidOperation, 'sNaN', self) 1980 if other._exp == 'N': 1981 return context._raise_error(InvalidOperation, 'sNaN', other) 1982 if self._exp == 'n': 1983 product = self 1984 elif other._exp == 'n': 1985 product = other 1986 elif self._exp == 'F': 1987 if not other: 1988 return context._raise_error(InvalidOperation, 1989 'INF * 0 in fma') 1990 product = _SignedInfinity[self._sign ^ other._sign] 1991 elif other._exp == 'F': 1992 if not self: 1993 return context._raise_error(InvalidOperation, 1994 '0 * INF in fma') 1995 product = _SignedInfinity[self._sign ^ other._sign] 1996 else: 1997 product = _dec_from_triple(self._sign ^ other._sign, 1998 str(int(self._int) * int(other._int)), 1999 self._exp + other._exp) 2000 2001 return product.__add__(third, context) 2002 2003 def _power_modulo(self, other, modulo, context=None): 2004 """Three argument version of __pow__""" 2005 2006 other = _convert_other(other) 2007 if other is NotImplemented: 2008 return other 2009 modulo = _convert_other(modulo) 2010 if modulo is NotImplemented: 2011 return modulo 2012 2013 if context is None: 2014 context = getcontext() 2015 2016 # deal with NaNs: if there are any sNaNs then first one wins, 2017 # (i.e. behaviour for NaNs is identical to that of fma) 2018 self_is_nan = self._isnan() 2019 other_is_nan = other._isnan() 2020 modulo_is_nan = modulo._isnan() 2021 if self_is_nan or other_is_nan or modulo_is_nan: 2022 if self_is_nan == 2: 2023 return context._raise_error(InvalidOperation, 'sNaN', 2024 self) 2025 if other_is_nan == 2: 2026 return context._raise_error(InvalidOperation, 'sNaN', 2027 other) 2028 if modulo_is_nan == 2: 2029 return context._raise_error(InvalidOperation, 'sNaN', 2030 modulo) 2031 if self_is_nan: 2032 return self._fix_nan(context) 2033 if other_is_nan: 2034 return other._fix_nan(context) 2035 return modulo._fix_nan(context) 2036 2037 # check inputs: we apply same restrictions as Python's pow() 2038 if not (self._isinteger() and 2039 other._isinteger() and 2040 modulo._isinteger()): 2041 return context._raise_error(InvalidOperation, 2042 'pow() 3rd argument not allowed ' 2043 'unless all arguments are integers') 2044 if other < 0: 2045 return context._raise_error(InvalidOperation, 2046 'pow() 2nd argument cannot be ' 2047 'negative when 3rd argument specified') 2048 if not modulo: 2049 return context._raise_error(InvalidOperation, 2050 'pow() 3rd argument cannot be 0') 2051 2052 # additional restriction for decimal: the modulus must be less 2053 # than 10**prec in absolute value 2054 if modulo.adjusted() >= context.prec: 2055 return context._raise_error(InvalidOperation, 2056 'insufficient precision: pow() 3rd ' 2057 'argument must not have more than ' 2058 'precision digits') 2059 2060 # define 0**0 == NaN, for consistency with two-argument pow 2061 # (even though it hurts!) 2062 if not other and not self: 2063 return context._raise_error(InvalidOperation, 2064 'at least one of pow() 1st argument ' 2065 'and 2nd argument must be nonzero ;' 2066 '0**0 is not defined') 2067 2068 # compute sign of result 2069 if other._iseven(): 2070 sign = 0 2071 else: 2072 sign = self._sign 2073 2074 # convert modulo to a Python integer, and self and other to 2075 # Decimal integers (i.e. force their exponents to be >= 0) 2076 modulo = abs(int(modulo)) 2077 base = _WorkRep(self.to_integral_value()) 2078 exponent = _WorkRep(other.to_integral_value()) 2079 2080 # compute result using integer pow() 2081 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo 2082 for i in range(exponent.exp): 2083 base = pow(base, 10, modulo) 2084 base = pow(base, exponent.int, modulo) 2085 2086 return _dec_from_triple(sign, str(base), 0) 2087 2088 def _power_exact(self, other, p): 2089 """Attempt to compute self**other exactly. 2090 2091 Given Decimals self and other and an integer p, attempt to 2092 compute an exact result for the power self**other, with p 2093 digits of precision. Return None if self**other is not 2094 exactly representable in p digits. 2095 2096 Assumes that elimination of special cases has already been 2097 performed: self and other must both be nonspecial; self must 2098 be positive and not numerically equal to 1; other must be 2099 nonzero. For efficiency, other._exp should not be too large, 2100 so that 10**abs(other._exp) is a feasible calculation.""" 2101 2102 # In the comments below, we write x for the value of self and y for the 2103 # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc 2104 # and yc positive integers not divisible by 10. 2105 2106 # The main purpose of this method is to identify the *failure* 2107 # of x**y to be exactly representable with as little effort as 2108 # possible. So we look for cheap and easy tests that 2109 # eliminate the possibility of x**y being exact. Only if all 2110 # these tests are passed do we go on to actually compute x**y. 2111 2112 # Here's the main idea. Express y as a rational number m/n, with m and 2113 # n relatively prime and n>0. Then for x**y to be exactly 2114 # representable (at *any* precision), xc must be the nth power of a 2115 # positive integer and xe must be divisible by n. If y is negative 2116 # then additionally xc must be a power of either 2 or 5, hence a power 2117 # of 2**n or 5**n. 2118 # 2119 # There's a limit to how small |y| can be: if y=m/n as above 2120 # then: 2121 # 2122 # (1) if xc != 1 then for the result to be representable we 2123 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So 2124 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <= 2125 # 2**(1/|y|), hence xc**|y| < 2 and the result is not 2126 # representable. 2127 # 2128 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if 2129 # |y| < 1/|xe| then the result is not representable. 2130 # 2131 # Note that since x is not equal to 1, at least one of (1) and 2132 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) < 2133 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye. 2134 # 2135 # There's also a limit to how large y can be, at least if it's 2136 # positive: the normalized result will have coefficient xc**y, 2137 # so if it's representable then xc**y < 10**p, and y < 2138 # p/log10(xc). Hence if y*log10(xc) >= p then the result is 2139 # not exactly representable. 2140 2141 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye, 2142 # so |y| < 1/xe and the result is not representable. 2143 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y| 2144 # < 1/nbits(xc). 2145 2146 x = _WorkRep(self) 2147 xc, xe = x.int, x.exp 2148 while xc % 10 == 0: 2149 xc //= 10 2150 xe += 1 2151 2152 y = _WorkRep(other) 2153 yc, ye = y.int, y.exp 2154 while yc % 10 == 0: 2155 yc //= 10 2156 ye += 1 2157 2158 # case where xc == 1: result is 10**(xe*y), with xe*y 2159 # required to be an integer 2160 if xc == 1: 2161 xe *= yc 2162 # result is now 10**(xe * 10**ye); xe * 10**ye must be integral 2163 while xe % 10 == 0: 2164 xe //= 10 2165 ye += 1 2166 if ye < 0: 2167 return None 2168 exponent = xe * 10**ye 2169 if y.sign == 1: 2170 exponent = -exponent 2171 # if other is a nonnegative integer, use ideal exponent 2172 if other._isinteger() and other._sign == 0: 2173 ideal_exponent = self._exp*int(other) 2174 zeros = min(exponent-ideal_exponent, p-1) 2175 else: 2176 zeros = 0 2177 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros) 2178 2179 # case where y is negative: xc must be either a power 2180 # of 2 or a power of 5. 2181 if y.sign == 1: 2182 last_digit = xc % 10 2183 if last_digit in (2,4,6,8): 2184 # quick test for power of 2 2185 if xc & -xc != xc: 2186 return None 2187 # now xc is a power of 2; e is its exponent 2188 e = _nbits(xc)-1 2189 2190 # We now have: 2191 # 2192 # x = 2**e * 10**xe, e > 0, and y < 0. 2193 # 2194 # The exact result is: 2195 # 2196 # x**y = 5**(-e*y) * 10**(e*y + xe*y) 2197 # 2198 # provided that both e*y and xe*y are integers. Note that if 2199 # 5**(-e*y) >= 10**p, then the result can't be expressed 2200 # exactly with p digits of precision. 2201 # 2202 # Using the above, we can guard against large values of ye. 2203 # 93/65 is an upper bound for log(10)/log(5), so if 2204 # 2205 # ye >= len(str(93*p//65)) 2206 # 2207 # then 2208 # 2209 # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5), 2210 # 2211 # so 5**(-e*y) >= 10**p, and the coefficient of the result 2212 # can't be expressed in p digits. 2213 2214 # emax >= largest e such that 5**e < 10**p. 2215 emax = p*93//65 2216 if ye >= len(str(emax)): 2217 return None 2218 2219 # Find -e*y and -xe*y; both must be integers 2220 e = _decimal_lshift_exact(e * yc, ye) 2221 xe = _decimal_lshift_exact(xe * yc, ye) 2222 if e is None or xe is None: 2223 return None 2224 2225 if e > emax: 2226 return None 2227 xc = 5**e 2228 2229 elif last_digit == 5: 2230 # e >= log_5(xc) if xc is a power of 5; we have 2231 # equality all the way up to xc=5**2658 2232 e = _nbits(xc)*28//65 2233 xc, remainder = divmod(5**e, xc) 2234 if remainder: 2235 return None 2236 while xc % 5 == 0: 2237 xc //= 5 2238 e -= 1 2239 2240 # Guard against large values of ye, using the same logic as in 2241 # the 'xc is a power of 2' branch. 10/3 is an upper bound for 2242 # log(10)/log(2). 2243 emax = p*10//3 2244 if ye >= len(str(emax)): 2245 return None 2246 2247 e = _decimal_lshift_exact(e * yc, ye) 2248 xe = _decimal_lshift_exact(xe * yc, ye) 2249 if e is None or xe is None: 2250 return None 2251 2252 if e > emax: 2253 return None 2254 xc = 2**e 2255 else: 2256 return None 2257 2258 if xc >= 10**p: 2259 return None 2260 xe = -e-xe 2261 return _dec_from_triple(0, str(xc), xe) 2262 2263 # now y is positive; find m and n such that y = m/n 2264 if ye >= 0: 2265 m, n = yc*10**ye, 1 2266 else: 2267 if xe != 0 and len(str(abs(yc*xe))) <= -ye: 2268 return None 2269 xc_bits = _nbits(xc) 2270 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye: 2271 return None 2272 m, n = yc, 10**(-ye) 2273 while m % 2 == n % 2 == 0: 2274 m //= 2 2275 n //= 2 2276 while m % 5 == n % 5 == 0: 2277 m //= 5 2278 n //= 5 2279 2280 # compute nth root of xc*10**xe 2281 if n > 1: 2282 # if 1 < xc < 2**n then xc isn't an nth power 2283 if xc != 1 and xc_bits <= n: 2284 return None 2285 2286 xe, rem = divmod(xe, n) 2287 if rem != 0: 2288 return None 2289 2290 # compute nth root of xc using Newton's method 2291 a = 1 << -(-_nbits(xc)//n) # initial estimate 2292 while True: 2293 q, r = divmod(xc, a**(n-1)) 2294 if a <= q: 2295 break 2296 else: 2297 a = (a*(n-1) + q)//n 2298 if not (a == q and r == 0): 2299 return None 2300 xc = a 2301 2302 # now xc*10**xe is the nth root of the original xc*10**xe 2303 # compute mth power of xc*10**xe 2304 2305 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m > 2306 # 10**p and the result is not representable. 2307 if xc > 1 and m > p*100//_log10_lb(xc): 2308 return None 2309 xc = xc**m 2310 xe *= m 2311 if xc > 10**p: 2312 return None 2313 2314 # by this point the result *is* exactly representable 2315 # adjust the exponent to get as close as possible to the ideal 2316 # exponent, if necessary 2317 str_xc = str(xc) 2318 if other._isinteger() and other._sign == 0: 2319 ideal_exponent = self._exp*int(other) 2320 zeros = min(xe-ideal_exponent, p-len(str_xc)) 2321 else: 2322 zeros = 0 2323 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros) 2324 2325 def __pow__(self, other, modulo=None, context=None): 2326 """Return self ** other [ % modulo]. 2327 2328 With two arguments, compute self**other. 2329 2330 With three arguments, compute (self**other) % modulo. For the 2331 three argument form, the following restrictions on the 2332 arguments hold: 2333 2334 - all three arguments must be integral 2335 - other must be nonnegative 2336 - either self or other (or both) must be nonzero 2337 - modulo must be nonzero and must have at most p digits, 2338 where p is the context precision. 2339 2340 If any of these restrictions is violated the InvalidOperation 2341 flag is raised. 2342 2343 The result of pow(self, other, modulo) is identical to the 2344 result that would be obtained by computing (self**other) % 2345 modulo with unbounded precision, but is computed more 2346 efficiently. It is always exact. 2347 """ 2348 2349 if modulo is not None: 2350 return self._power_modulo(other, modulo, context) 2351 2352 other = _convert_other(other) 2353 if other is NotImplemented: 2354 return other 2355 2356 if context is None: 2357 context = getcontext() 2358 2359 # either argument is a NaN => result is NaN 2360 ans = self._check_nans(other, context) 2361 if ans: 2362 return ans 2363 2364 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity) 2365 if not other: 2366 if not self: 2367 return context._raise_error(InvalidOperation, '0 ** 0') 2368 else: 2369 return _One 2370 2371 # result has sign 1 iff self._sign is 1 and other is an odd integer 2372 result_sign = 0 2373 if self._sign == 1: 2374 if other._isinteger(): 2375 if not other._iseven(): 2376 result_sign = 1 2377 else: 2378 # -ve**noninteger = NaN 2379 # (-0)**noninteger = 0**noninteger 2380 if self: 2381 return context._raise_error(InvalidOperation, 2382 'x ** y with x negative and y not an integer') 2383 # negate self, without doing any unwanted rounding 2384 self = self.copy_negate() 2385 2386 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity 2387 if not self: 2388 if other._sign == 0: 2389 return _dec_from_triple(result_sign, '0', 0) 2390 else: 2391 return _SignedInfinity[result_sign] 2392 2393 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 2394 if self._isinfinity(): 2395 if other._sign == 0: 2396 return _SignedInfinity[result_sign] 2397 else: 2398 return _dec_from_triple(result_sign, '0', 0) 2399 2400 # 1**other = 1, but the choice of exponent and the flags 2401 # depend on the exponent of self, and on whether other is a 2402 # positive integer, a negative integer, or neither 2403 if self == _One: 2404 if other._isinteger(): 2405 # exp = max(self._exp*max(int(other), 0), 2406 # 1-context.prec) but evaluating int(other) directly 2407 # is dangerous until we know other is small (other 2408 # could be 1e999999999) 2409 if other._sign == 1: 2410 multiplier = 0 2411 elif other > context.prec: 2412 multiplier = context.prec 2413 else: 2414 multiplier = int(other) 2415 2416 exp = self._exp * multiplier 2417 if exp < 1-context.prec: 2418 exp = 1-context.prec 2419 context._raise_error(Rounded) 2420 else: 2421 context._raise_error(Inexact) 2422 context._raise_error(Rounded) 2423 exp = 1-context.prec 2424 2425 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp) 2426 2427 # compute adjusted exponent of self 2428 self_adj = self.adjusted() 2429 2430 # self ** infinity is infinity if self > 1, 0 if self < 1 2431 # self ** -infinity is infinity if self < 1, 0 if self > 1 2432 if other._isinfinity(): 2433 if (other._sign == 0) == (self_adj < 0): 2434 return _dec_from_triple(result_sign, '0', 0) 2435 else: 2436 return _SignedInfinity[result_sign] 2437 2438 # from here on, the result always goes through the call 2439 # to _fix at the end of this function. 2440 ans = None 2441 exact = False 2442 2443 # crude test to catch cases of extreme overflow/underflow. If 2444 # log10(self)*other >= 10**bound and bound >= len(str(Emax)) 2445 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence 2446 # self**other >= 10**(Emax+1), so overflow occurs. The test 2447 # for underflow is similar. 2448 bound = self._log10_exp_bound() + other.adjusted() 2449 if (self_adj >= 0) == (other._sign == 0): 2450 # self > 1 and other +ve, or self < 1 and other -ve 2451 # possibility of overflow 2452 if bound >= len(str(context.Emax)): 2453 ans = _dec_from_triple(result_sign, '1', context.Emax+1) 2454 else: 2455 # self > 1 and other -ve, or self < 1 and other +ve 2456 # possibility of underflow to 0 2457 Etiny = context.Etiny() 2458 if bound >= len(str(-Etiny)): 2459 ans = _dec_from_triple(result_sign, '1', Etiny-1) 2460 2461 # try for an exact result with precision +1 2462 if ans is None: 2463 ans = self._power_exact(other, context.prec + 1) 2464 if ans is not None: 2465 if result_sign == 1: 2466 ans = _dec_from_triple(1, ans._int, ans._exp) 2467 exact = True 2468 2469 # usual case: inexact result, x**y computed directly as exp(y*log(x)) 2470 if ans is None: 2471 p = context.prec 2472 x = _WorkRep(self) 2473 xc, xe = x.int, x.exp 2474 y = _WorkRep(other) 2475 yc, ye = y.int, y.exp 2476 if y.sign == 1: 2477 yc = -yc 2478 2479 # compute correctly rounded result: start with precision +3, 2480 # then increase precision until result is unambiguously roundable 2481 extra = 3 2482 while True: 2483 coeff, exp = _dpower(xc, xe, yc, ye, p+extra) 2484 if coeff % (5*10**(len(str(coeff))-p-1)): 2485 break 2486 extra += 3 2487 2488 ans = _dec_from_triple(result_sign, str(coeff), exp) 2489 2490 # unlike exp, ln and log10, the power function respects the 2491 # rounding mode; no need to switch to ROUND_HALF_EVEN here 2492 2493 # There's a difficulty here when 'other' is not an integer and 2494 # the result is exact. In this case, the specification 2495 # requires that the Inexact flag be raised (in spite of 2496 # exactness), but since the result is exact _fix won't do this 2497 # for us. (Correspondingly, the Underflow signal should also 2498 # be raised for subnormal results.) We can't directly raise 2499 # these signals either before or after calling _fix, since 2500 # that would violate the precedence for signals. So we wrap 2501 # the ._fix call in a temporary context, and reraise 2502 # afterwards. 2503 if exact and not other._isinteger(): 2504 # pad with zeros up to length context.prec+1 if necessary; this 2505 # ensures that the Rounded signal will be raised. 2506 if len(ans._int) <= context.prec: 2507 expdiff = context.prec + 1 - len(ans._int) 2508 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff, 2509 ans._exp-expdiff) 2510 2511 # create a copy of the current context, with cleared flags/traps 2512 newcontext = context.copy() 2513 newcontext.clear_flags() 2514 for exception in _signals: 2515 newcontext.traps[exception] = 0 2516 2517 # round in the new context 2518 ans = ans._fix(newcontext) 2519 2520 # raise Inexact, and if necessary, Underflow 2521 newcontext._raise_error(Inexact) 2522 if newcontext.flags[Subnormal]: 2523 newcontext._raise_error(Underflow) 2524 2525 # propagate signals to the original context; _fix could 2526 # have raised any of Overflow, Underflow, Subnormal, 2527 # Inexact, Rounded, Clamped. Overflow needs the correct 2528 # arguments. Note that the order of the exceptions is 2529 # important here. 2530 if newcontext.flags[Overflow]: 2531 context._raise_error(Overflow, 'above Emax', ans._sign) 2532 for exception in Underflow, Subnormal, Inexact, Rounded, Clamped: 2533 if newcontext.flags[exception]: 2534 context._raise_error(exception) 2535 2536 else: 2537 ans = ans._fix(context) 2538 2539 return ans 2540 2541 def __rpow__(self, other, context=None): 2542 """Swaps self/other and returns __pow__.""" 2543 other = _convert_other(other) 2544 if other is NotImplemented: 2545 return other 2546 return other.__pow__(self, context=context) 2547 2548 def normalize(self, context=None): 2549 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" 2550 2551 if context is None: 2552 context = getcontext() 2553 2554 if self._is_special: 2555 ans = self._check_nans(context=context) 2556 if ans: 2557 return ans 2558 2559 dup = self._fix(context) 2560 if dup._isinfinity(): 2561 return dup 2562 2563 if not dup: 2564 return _dec_from_triple(dup._sign, '0', 0) 2565 exp_max = [context.Emax, context.Etop()][context.clamp] 2566 end = len(dup._int) 2567 exp = dup._exp 2568 while dup._int[end-1] == '0' and exp < exp_max: 2569 exp += 1 2570 end -= 1 2571 return _dec_from_triple(dup._sign, dup._int[:end], exp) 2572 2573 def quantize(self, exp, rounding=None, context=None): 2574 """Quantize self so its exponent is the same as that of exp. 2575 2576 Similar to self._rescale(exp._exp) but with error checking. 2577 """ 2578 exp = _convert_other(exp, raiseit=True) 2579 2580 if context is None: 2581 context = getcontext() 2582 if rounding is None: 2583 rounding = context.rounding 2584 2585 if self._is_special or exp._is_special: 2586 ans = self._check_nans(exp, context) 2587 if ans: 2588 return ans 2589 2590 if exp._isinfinity() or self._isinfinity(): 2591 if exp._isinfinity() and self._isinfinity(): 2592 return Decimal(self) # if both are inf, it is OK 2593 return context._raise_error(InvalidOperation, 2594 'quantize with one INF') 2595 2596 # exp._exp should be between Etiny and Emax 2597 if not (context.Etiny() <= exp._exp <= context.Emax): 2598 return context._raise_error(InvalidOperation, 2599 'target exponent out of bounds in quantize') 2600 2601 if not self: 2602 ans = _dec_from_triple(self._sign, '0', exp._exp) 2603 return ans._fix(context) 2604 2605 self_adjusted = self.adjusted() 2606 if self_adjusted > context.Emax: 2607 return context._raise_error(InvalidOperation, 2608 'exponent of quantize result too large for current context') 2609 if self_adjusted - exp._exp + 1 > context.prec: 2610 return context._raise_error(InvalidOperation, 2611 'quantize result has too many digits for current context') 2612 2613 ans = self._rescale(exp._exp, rounding) 2614 if ans.adjusted() > context.Emax: 2615 return context._raise_error(InvalidOperation, 2616 'exponent of quantize result too large for current context') 2617 if len(ans._int) > context.prec: 2618 return context._raise_error(InvalidOperation, 2619 'quantize result has too many digits for current context') 2620 2621 # raise appropriate flags 2622 if ans and ans.adjusted() < context.Emin: 2623 context._raise_error(Subnormal) 2624 if ans._exp > self._exp: 2625 if ans != self: 2626 context._raise_error(Inexact) 2627 context._raise_error(Rounded) 2628 2629 # call to fix takes care of any necessary folddown, and 2630 # signals Clamped if necessary 2631 ans = ans._fix(context) 2632 return ans 2633 2634 def same_quantum(self, other, context=None): 2635 """Return True if self and other have the same exponent; otherwise 2636 return False. 2637 2638 If either operand is a special value, the following rules are used: 2639 * return True if both operands are infinities 2640 * return True if both operands are NaNs 2641 * otherwise, return False. 2642 """ 2643 other = _convert_other(other, raiseit=True) 2644 if self._is_special or other._is_special: 2645 return (self.is_nan() and other.is_nan() or 2646 self.is_infinite() and other.is_infinite()) 2647 return self._exp == other._exp 2648 2649 def _rescale(self, exp, rounding): 2650 """Rescale self so that the exponent is exp, either by padding with zeros 2651 or by truncating digits, using the given rounding mode. 2652 2653 Specials are returned without change. This operation is 2654 quiet: it raises no flags, and uses no information from the 2655 context. 2656 2657 exp = exp to scale to (an integer) 2658 rounding = rounding mode 2659 """ 2660 if self._is_special: 2661 return Decimal(self) 2662 if not self: 2663 return _dec_from_triple(self._sign, '0', exp) 2664 2665 if self._exp >= exp: 2666 # pad answer with zeros if necessary 2667 return _dec_from_triple(self._sign, 2668 self._int + '0'*(self._exp - exp), exp) 2669 2670 # too many digits; round and lose data. If self.adjusted() < 2671 # exp-1, replace self by 10**(exp-1) before rounding 2672 digits = len(self._int) + self._exp - exp 2673 if digits < 0: 2674 self = _dec_from_triple(self._sign, '1', exp-1) 2675 digits = 0 2676 this_function = self._pick_rounding_function[rounding] 2677 changed = this_function(self, digits) 2678 coeff = self._int[:digits] or '0' 2679 if changed == 1: 2680 coeff = str(int(coeff)+1) 2681 return _dec_from_triple(self._sign, coeff, exp) 2682 2683 def _round(self, places, rounding): 2684 """Round a nonzero, nonspecial Decimal to a fixed number of 2685 significant figures, using the given rounding mode. 2686 2687 Infinities, NaNs and zeros are returned unaltered. 2688 2689 This operation is quiet: it raises no flags, and uses no 2690 information from the context. 2691 2692 """ 2693 if places <= 0: 2694 raise ValueError("argument should be at least 1 in _round") 2695 if self._is_special or not self: 2696 return Decimal(self) 2697 ans = self._rescale(self.adjusted()+1-places, rounding) 2698 # it can happen that the rescale alters the adjusted exponent; 2699 # for example when rounding 99.97 to 3 significant figures. 2700 # When this happens we end up with an extra 0 at the end of 2701 # the number; a second rescale fixes this. 2702 if ans.adjusted() != self.adjusted(): 2703 ans = ans._rescale(ans.adjusted()+1-places, rounding) 2704 return ans 2705 2706 def to_integral_exact(self, rounding=None, context=None): 2707 """Rounds to a nearby integer. 2708 2709 If no rounding mode is specified, take the rounding mode from 2710 the context. This method raises the Rounded and Inexact flags 2711 when appropriate. 2712 2713 See also: to_integral_value, which does exactly the same as 2714 this method except that it doesn't raise Inexact or Rounded. 2715 """ 2716 if self._is_special: 2717 ans = self._check_nans(context=context) 2718 if ans: 2719 return ans 2720 return Decimal(self) 2721 if self._exp >= 0: 2722 return Decimal(self) 2723 if not self: 2724 return _dec_from_triple(self._sign, '0', 0) 2725 if context is None: 2726 context = getcontext() 2727 if rounding is None: 2728 rounding = context.rounding 2729 ans = self._rescale(0, rounding) 2730 if ans != self: 2731 context._raise_error(Inexact) 2732 context._raise_error(Rounded) 2733 return ans 2734 2735 def to_integral_value(self, rounding=None, context=None): 2736 """Rounds to the nearest integer, without raising inexact, rounded.""" 2737 if context is None: 2738 context = getcontext() 2739 if rounding is None: 2740 rounding = context.rounding 2741 if self._is_special: 2742 ans = self._check_nans(context=context) 2743 if ans: 2744 return ans 2745 return Decimal(self) 2746 if self._exp >= 0: 2747 return Decimal(self) 2748 else: 2749 return self._rescale(0, rounding) 2750 2751 # the method name changed, but we provide also the old one, for compatibility 2752 to_integral = to_integral_value 2753 2754 def sqrt(self, context=None): 2755 """Return the square root of self.""" 2756 if context is None: 2757 context = getcontext() 2758 2759 if self._is_special: 2760 ans = self._check_nans(context=context) 2761 if ans: 2762 return ans 2763 2764 if self._isinfinity() and self._sign == 0: 2765 return Decimal(self) 2766 2767 if not self: 2768 # exponent = self._exp // 2. sqrt(-0) = -0 2769 ans = _dec_from_triple(self._sign, '0', self._exp // 2) 2770 return ans._fix(context) 2771 2772 if self._sign == 1: 2773 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') 2774 2775 # At this point self represents a positive number. Let p be 2776 # the desired precision and express self in the form c*100**e 2777 # with c a positive real number and e an integer, c and e 2778 # being chosen so that 100**(p-1) <= c < 100**p. Then the 2779 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1) 2780 # <= sqrt(c) < 10**p, so the closest representable Decimal at 2781 # precision p is n*10**e where n = round_half_even(sqrt(c)), 2782 # the closest integer to sqrt(c) with the even integer chosen 2783 # in the case of a tie. 2784 # 2785 # To ensure correct rounding in all cases, we use the 2786 # following trick: we compute the square root to an extra 2787 # place (precision p+1 instead of precision p), rounding down. 2788 # Then, if the result is inexact and its last digit is 0 or 5, 2789 # we increase the last digit to 1 or 6 respectively; if it's 2790 # exact we leave the last digit alone. Now the final round to 2791 # p places (or fewer in the case of underflow) will round 2792 # correctly and raise the appropriate flags. 2793 2794 # use an extra digit of precision 2795 prec = context.prec+1 2796 2797 # write argument in the form c*100**e where e = self._exp//2 2798 # is the 'ideal' exponent, to be used if the square root is 2799 # exactly representable. l is the number of 'digits' of c in 2800 # base 100, so that 100**(l-1) <= c < 100**l. 2801 op = _WorkRep(self) 2802 e = op.exp >> 1 2803 if op.exp & 1: 2804 c = op.int * 10 2805 l = (len(self._int) >> 1) + 1 2806 else: 2807 c = op.int 2808 l = len(self._int)+1 >> 1 2809 2810 # rescale so that c has exactly prec base 100 'digits' 2811 shift = prec-l 2812 if shift >= 0: 2813 c *= 100**shift 2814 exact = True 2815 else: 2816 c, remainder = divmod(c, 100**-shift) 2817 exact = not remainder 2818 e -= shift 2819 2820 # find n = floor(sqrt(c)) using Newton's method 2821 n = 10**prec 2822 while True: 2823 q = c//n 2824 if n <= q: 2825 break 2826 else: 2827 n = n + q >> 1 2828 exact = exact and n*n == c 2829 2830 if exact: 2831 # result is exact; rescale to use ideal exponent e 2832 if shift >= 0: 2833 # assert n % 10**shift == 0 2834 n //= 10**shift 2835 else: 2836 n *= 10**-shift 2837 e += shift 2838 else: 2839 # result is not exact; fix last digit as described above 2840 if n % 5 == 0: 2841 n += 1 2842 2843 ans = _dec_from_triple(0, str(n), e) 2844 2845 # round, and fit to current context 2846 context = context._shallow_copy() 2847 rounding = context._set_rounding(ROUND_HALF_EVEN) 2848 ans = ans._fix(context) 2849 context.rounding = rounding 2850 2851 return ans 2852 2853 def max(self, other, context=None): 2854 """Returns the larger value. 2855 2856 Like max(self, other) except if one is not a number, returns 2857 NaN (and signals if one is sNaN). Also rounds. 2858 """ 2859 other = _convert_other(other, raiseit=True) 2860 2861 if context is None: 2862 context = getcontext() 2863 2864 if self._is_special or other._is_special: 2865 # If one operand is a quiet NaN and the other is number, then the 2866 # number is always returned 2867 sn = self._isnan() 2868 on = other._isnan() 2869 if sn or on: 2870 if on == 1 and sn == 0: 2871 return self._fix(context) 2872 if sn == 1 and on == 0: 2873 return other._fix(context) 2874 return self._check_nans(other, context) 2875 2876 c = self._cmp(other) 2877 if c == 0: 2878 # If both operands are finite and equal in numerical value 2879 # then an ordering is applied: 2880 # 2881 # If the signs differ then max returns the operand with the 2882 # positive sign and min returns the operand with the negative sign 2883 # 2884 # If the signs are the same then the exponent is used to select 2885 # the result. This is exactly the ordering used in compare_total. 2886 c = self.compare_total(other) 2887 2888 if c == -1: 2889 ans = other 2890 else: 2891 ans = self 2892 2893 return ans._fix(context) 2894 2895 def min(self, other, context=None): 2896 """Returns the smaller value. 2897 2898 Like min(self, other) except if one is not a number, returns 2899 NaN (and signals if one is sNaN). Also rounds. 2900 """ 2901 other = _convert_other(other, raiseit=True) 2902 2903 if context is None: 2904 context = getcontext() 2905 2906 if self._is_special or other._is_special: 2907 # If one operand is a quiet NaN and the other is number, then the 2908 # number is always returned 2909 sn = self._isnan() 2910 on = other._isnan() 2911 if sn or on: 2912 if on == 1 and sn == 0: 2913 return self._fix(context) 2914 if sn == 1 and on == 0: 2915 return other._fix(context) 2916 return self._check_nans(other, context) 2917 2918 c = self._cmp(other) 2919 if c == 0: 2920 c = self.compare_total(other) 2921 2922 if c == -1: 2923 ans = self 2924 else: 2925 ans = other 2926 2927 return ans._fix(context) 2928 2929 def _isinteger(self): 2930 """Returns whether self is an integer""" 2931 if self._is_special: 2932 return False 2933 if self._exp >= 0: 2934 return True 2935 rest = self._int[self._exp:] 2936 return rest == '0'*len(rest) 2937 2938 def _iseven(self): 2939 """Returns True if self is even. Assumes self is an integer.""" 2940 if not self or self._exp > 0: 2941 return True 2942 return self._int[-1+self._exp] in '02468' 2943 2944 def adjusted(self): 2945 """Return the adjusted exponent of self""" 2946 try: 2947 return self._exp + len(self._int) - 1 2948 # If NaN or Infinity, self._exp is string 2949 except TypeError: 2950 return 0 2951 2952 def canonical(self): 2953 """Returns the same Decimal object. 2954 2955 As we do not have different encodings for the same number, the 2956 received object already is in its canonical form. 2957 """ 2958 return self 2959 2960 def compare_signal(self, other, context=None): 2961 """Compares self to the other operand numerically. 2962 2963 It's pretty much like compare(), but all NaNs signal, with signaling 2964 NaNs taking precedence over quiet NaNs. 2965 """ 2966 other = _convert_other(other, raiseit = True) 2967 ans = self._compare_check_nans(other, context) 2968 if ans: 2969 return ans 2970 return self.compare(other, context=context) 2971 2972 def compare_total(self, other, context=None): 2973 """Compares self to other using the abstract representations. 2974 2975 This is not like the standard compare, which use their numerical 2976 value. Note that a total ordering is defined for all possible abstract 2977 representations. 2978 """ 2979 other = _convert_other(other, raiseit=True) 2980 2981 # if one is negative and the other is positive, it's easy 2982 if self._sign and not other._sign: 2983 return _NegativeOne 2984 if not self._sign and other._sign: 2985 return _One 2986 sign = self._sign 2987 2988 # let's handle both NaN types 2989 self_nan = self._isnan() 2990 other_nan = other._isnan() 2991 if self_nan or other_nan: 2992 if self_nan == other_nan: 2993 # compare payloads as though they're integers 2994 self_key = len(self._int), self._int 2995 other_key = len(other._int), other._int 2996 if self_key < other_key: 2997 if sign: 2998 return _One 2999 else: 3000 return _NegativeOne 3001 if self_key > other_key: 3002 if sign: 3003 return _NegativeOne 3004 else: 3005 return _One 3006 return _Zero 3007 3008 if sign: 3009 if self_nan == 1: 3010 return _NegativeOne 3011 if other_nan == 1: 3012 return _One 3013 if self_nan == 2: 3014 return _NegativeOne 3015 if other_nan == 2: 3016 return _One 3017 else: 3018 if self_nan == 1: 3019 return _One 3020 if other_nan == 1: 3021 return _NegativeOne 3022 if self_nan == 2: 3023 return _One 3024 if other_nan == 2: 3025 return _NegativeOne 3026 3027 if self < other: 3028 return _NegativeOne 3029 if self > other: 3030 return _One 3031 3032 if self._exp < other._exp: 3033 if sign: 3034 return _One 3035 else: 3036 return _NegativeOne 3037 if self._exp > other._exp: 3038 if sign: 3039 return _NegativeOne 3040 else: 3041 return _One 3042 return _Zero 3043 3044 3045 def compare_total_mag(self, other, context=None): 3046 """Compares self to other using abstract repr., ignoring sign. 3047 3048 Like compare_total, but with operand's sign ignored and assumed to be 0. 3049 """ 3050 other = _convert_other(other, raiseit=True) 3051 3052 s = self.copy_abs() 3053 o = other.copy_abs() 3054 return s.compare_total(o) 3055 3056 def copy_abs(self): 3057 """Returns a copy with the sign set to 0. """ 3058 return _dec_from_triple(0, self._int, self._exp, self._is_special) 3059 3060 def copy_negate(self): 3061 """Returns a copy with the sign inverted.""" 3062 if self._sign: 3063 return _dec_from_triple(0, self._int, self._exp, self._is_special) 3064 else: 3065 return _dec_from_triple(1, self._int, self._exp, self._is_special) 3066 3067 def copy_sign(self, other, context=None): 3068 """Returns self with the sign of other.""" 3069 other = _convert_other(other, raiseit=True) 3070 return _dec_from_triple(other._sign, self._int, 3071 self._exp, self._is_special) 3072 3073 def exp(self, context=None): 3074 """Returns e ** self.""" 3075 3076 if context is None: 3077 context = getcontext() 3078 3079 # exp(NaN) = NaN 3080 ans = self._check_nans(context=context) 3081 if ans: 3082 return ans 3083 3084 # exp(-Infinity) = 0 3085 if self._isinfinity() == -1: 3086 return _Zero 3087 3088 # exp(0) = 1 3089 if not self: 3090 return _One 3091 3092 # exp(Infinity) = Infinity 3093 if self._isinfinity() == 1: 3094 return Decimal(self) 3095 3096 # the result is now guaranteed to be inexact (the true 3097 # mathematical result is transcendental). There's no need to 3098 # raise Rounded and Inexact here---they'll always be raised as 3099 # a result of the call to _fix. 3100 p = context.prec 3101 adj = self.adjusted() 3102 3103 # we only need to do any computation for quite a small range 3104 # of adjusted exponents---for example, -29 <= adj <= 10 for 3105 # the default context. For smaller exponent the result is 3106 # indistinguishable from 1 at the given precision, while for 3107 # larger exponent the result either overflows or underflows. 3108 if self._sign == 0 and adj > len(str((context.Emax+1)*3)): 3109 # overflow 3110 ans = _dec_from_triple(0, '1', context.Emax+1) 3111 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)): 3112 # underflow to 0 3113 ans = _dec_from_triple(0, '1', context.Etiny()-1) 3114 elif self._sign == 0 and adj < -p: 3115 # p+1 digits; final round will raise correct flags 3116 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p) 3117 elif self._sign == 1 and adj < -p-1: 3118 # p+1 digits; final round will raise correct flags 3119 ans = _dec_from_triple(0, '9'*(p+1), -p-1) 3120 # general case 3121 else: 3122 op = _WorkRep(self) 3123 c, e = op.int, op.exp 3124 if op.sign == 1: 3125 c = -c 3126 3127 # compute correctly rounded result: increase precision by 3128 # 3 digits at a time until we get an unambiguously 3129 # roundable result 3130 extra = 3 3131 while True: 3132 coeff, exp = _dexp(c, e, p+extra) 3133 if coeff % (5*10**(len(str(coeff))-p-1)): 3134 break 3135 extra += 3 3136 3137 ans = _dec_from_triple(0, str(coeff), exp) 3138 3139 # at this stage, ans should round correctly with *any* 3140 # rounding mode, not just with ROUND_HALF_EVEN 3141 context = context._shallow_copy() 3142 rounding = context._set_rounding(ROUND_HALF_EVEN) 3143 ans = ans._fix(context) 3144 context.rounding = rounding 3145 3146 return ans 3147 3148 def is_canonical(self): 3149 """Return True if self is canonical; otherwise return False. 3150 3151 Currently, the encoding of a Decimal instance is always 3152 canonical, so this method returns True for any Decimal. 3153 """ 3154 return True 3155 3156 def is_finite(self): 3157 """Return True if self is finite; otherwise return False. 3158 3159 A Decimal instance is considered finite if it is neither 3160 infinite nor a NaN. 3161 """ 3162 return not self._is_special 3163 3164 def is_infinite(self): 3165 """Return True if self is infinite; otherwise return False.""" 3166 return self._exp == 'F' 3167 3168 def is_nan(self): 3169 """Return True if self is a qNaN or sNaN; otherwise return False.""" 3170 return self._exp in ('n', 'N') 3171 3172 def is_normal(self, context=None): 3173 """Return True if self is a normal number; otherwise return False.""" 3174 if self._is_special or not self: 3175 return False 3176 if context is None: 3177 context = getcontext() 3178 return context.Emin <= self.adjusted() 3179 3180 def is_qnan(self): 3181 """Return True if self is a quiet NaN; otherwise return False.""" 3182 return self._exp == 'n' 3183 3184 def is_signed(self): 3185 """Return True if self is negative; otherwise return False.""" 3186 return self._sign == 1 3187 3188 def is_snan(self): 3189 """Return True if self is a signaling NaN; otherwise return False.""" 3190 return self._exp == 'N' 3191 3192 def is_subnormal(self, context=None): 3193 """Return True if self is subnormal; otherwise return False.""" 3194 if self._is_special or not self: 3195 return False 3196 if context is None: 3197 context = getcontext() 3198 return self.adjusted() < context.Emin 3199 3200 def is_zero(self): 3201 """Return True if self is a zero; otherwise return False.""" 3202 return not self._is_special and self._int == '0' 3203 3204 def _ln_exp_bound(self): 3205 """Compute a lower bound for the adjusted exponent of self.ln(). 3206 In other words, compute r such that self.ln() >= 10**r. Assumes 3207 that self is finite and positive and that self != 1. 3208 """ 3209 3210 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1 3211 adj = self._exp + len(self._int) - 1 3212 if adj >= 1: 3213 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10) 3214 return len(str(adj*23//10)) - 1 3215 if adj <= -2: 3216 # argument <= 0.1 3217 return len(str((-1-adj)*23//10)) - 1 3218 op = _WorkRep(self) 3219 c, e = op.int, op.exp 3220 if adj == 0: 3221 # 1 < self < 10 3222 num = str(c-10**-e) 3223 den = str(c) 3224 return len(num) - len(den) - (num < den) 3225 # adj == -1, 0.1 <= self < 1 3226 return e + len(str(10**-e - c)) - 1 3227 3228 3229 def ln(self, context=None): 3230 """Returns the natural (base e) logarithm of self.""" 3231 3232 if context is None: 3233 context = getcontext() 3234 3235 # ln(NaN) = NaN 3236 ans = self._check_nans(context=context) 3237 if ans: 3238 return ans 3239 3240 # ln(0.0) == -Infinity 3241 if not self: 3242 return _NegativeInfinity 3243 3244 # ln(Infinity) = Infinity 3245 if self._isinfinity() == 1: 3246 return _Infinity 3247 3248 # ln(1.0) == 0.0 3249 if self == _One: 3250 return _Zero 3251 3252 # ln(negative) raises InvalidOperation 3253 if self._sign == 1: 3254 return context._raise_error(InvalidOperation, 3255 'ln of a negative value') 3256 3257 # result is irrational, so necessarily inexact 3258 op = _WorkRep(self) 3259 c, e = op.int, op.exp 3260 p = context.prec 3261 3262 # correctly rounded result: repeatedly increase precision by 3 3263 # until we get an unambiguously roundable result 3264 places = p - self._ln_exp_bound() + 2 # at least p+3 places 3265 while True: 3266 coeff = _dlog(c, e, places) 3267 # assert len(str(abs(coeff)))-p >= 1 3268 if coeff % (5*10**(len(str(abs(coeff)))-p-1)): 3269 break 3270 places += 3 3271 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) 3272 3273 context = context._shallow_copy() 3274 rounding = context._set_rounding(ROUND_HALF_EVEN) 3275 ans = ans._fix(context) 3276 context.rounding = rounding 3277 return ans 3278 3279 def _log10_exp_bound(self): 3280 """Compute a lower bound for the adjusted exponent of self.log10(). 3281 In other words, find r such that self.log10() >= 10**r. 3282 Assumes that self is finite and positive and that self != 1. 3283 """ 3284 3285 # For x >= 10 or x < 0.1 we only need a bound on the integer 3286 # part of log10(self), and this comes directly from the 3287 # exponent of x. For 0.1 <= x <= 10 we use the inequalities 3288 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| > 3289 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0 3290 3291 adj = self._exp + len(self._int) - 1 3292 if adj >= 1: 3293 # self >= 10 3294 return len(str(adj))-1 3295 if adj <= -2: 3296 # self < 0.1 3297 return len(str(-1-adj))-1 3298 op = _WorkRep(self) 3299 c, e = op.int, op.exp 3300 if adj == 0: 3301 # 1 < self < 10 3302 num = str(c-10**-e) 3303 den = str(231*c) 3304 return len(num) - len(den) - (num < den) + 2 3305 # adj == -1, 0.1 <= self < 1 3306 num = str(10**-e-c) 3307 return len(num) + e - (num < "231") - 1 3308 3309 def log10(self, context=None): 3310 """Returns the base 10 logarithm of self.""" 3311 3312 if context is None: 3313 context = getcontext() 3314 3315 # log10(NaN) = NaN 3316 ans = self._check_nans(context=context) 3317 if ans: 3318 return ans 3319 3320 # log10(0.0) == -Infinity 3321 if not self: 3322 return _NegativeInfinity 3323 3324 # log10(Infinity) = Infinity 3325 if self._isinfinity() == 1: 3326 return _Infinity 3327 3328 # log10(negative or -Infinity) raises InvalidOperation 3329 if self._sign == 1: 3330 return context._raise_error(InvalidOperation, 3331 'log10 of a negative value') 3332 3333 # log10(10**n) = n 3334 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1): 3335 # answer may need rounding 3336 ans = Decimal(self._exp + len(self._int) - 1) 3337 else: 3338 # result is irrational, so necessarily inexact 3339 op = _WorkRep(self) 3340 c, e = op.int, op.exp 3341 p = context.prec 3342 3343 # correctly rounded result: repeatedly increase precision 3344 # until result is unambiguously roundable 3345 places = p-self._log10_exp_bound()+2 3346 while True: 3347 coeff = _dlog10(c, e, places) 3348 # assert len(str(abs(coeff)))-p >= 1 3349 if coeff % (5*10**(len(str(abs(coeff)))-p-1)): 3350 break 3351 places += 3 3352 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places) 3353 3354 context = context._shallow_copy() 3355 rounding = context._set_rounding(ROUND_HALF_EVEN) 3356 ans = ans._fix(context) 3357 context.rounding = rounding 3358 return ans 3359 3360 def logb(self, context=None): 3361 """ Returns the exponent of the magnitude of self's MSD. 3362 3363 The result is the integer which is the exponent of the magnitude 3364 of the most significant digit of self (as though it were truncated 3365 to a single digit while maintaining the value of that digit and 3366 without limiting the resulting exponent). 3367 """ 3368 # logb(NaN) = NaN 3369 ans = self._check_nans(context=context) 3370 if ans: 3371 return ans 3372 3373 if context is None: 3374 context = getcontext() 3375 3376 # logb(+/-Inf) = +Inf 3377 if self._isinfinity(): 3378 return _Infinity 3379 3380 # logb(0) = -Inf, DivisionByZero 3381 if not self: 3382 return context._raise_error(DivisionByZero, 'logb(0)', 1) 3383 3384 # otherwise, simply return the adjusted exponent of self, as a 3385 # Decimal. Note that no attempt is made to fit the result 3386 # into the current context. 3387 ans = Decimal(self.adjusted()) 3388 return ans._fix(context) 3389 3390 def _islogical(self): 3391 """Return True if self is a logical operand. 3392 3393 For being logical, it must be a finite number with a sign of 0, 3394 an exponent of 0, and a coefficient whose digits must all be 3395 either 0 or 1. 3396 """ 3397 if self._sign != 0 or self._exp != 0: 3398 return False 3399 for dig in self._int: 3400 if dig not in '01': 3401 return False 3402 return True 3403 3404 def _fill_logical(self, context, opa, opb): 3405 dif = context.prec - len(opa) 3406 if dif > 0: 3407 opa = '0'*dif + opa 3408 elif dif < 0: 3409 opa = opa[-context.prec:] 3410 dif = context.prec - len(opb) 3411 if dif > 0: 3412 opb = '0'*dif + opb 3413 elif dif < 0: 3414 opb = opb[-context.prec:] 3415 return opa, opb 3416 3417 def logical_and(self, other, context=None): 3418 """Applies an 'and' operation between self and other's digits.""" 3419 if context is None: 3420 context = getcontext() 3421 3422 other = _convert_other(other, raiseit=True) 3423 3424 if not self._islogical() or not other._islogical(): 3425 return context._raise_error(InvalidOperation) 3426 3427 # fill to context.prec 3428 (opa, opb) = self._fill_logical(context, self._int, other._int) 3429 3430 # make the operation, and clean starting zeroes 3431 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)]) 3432 return _dec_from_triple(0, result.lstrip('0') or '0', 0) 3433 3434 def logical_invert(self, context=None): 3435 """Invert all its digits.""" 3436 if context is None: 3437 context = getcontext() 3438 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0), 3439 context) 3440 3441 def logical_or(self, other, context=None): 3442 """Applies an 'or' operation between self and other's digits.""" 3443 if context is None: 3444 context = getcontext() 3445 3446 other = _convert_other(other, raiseit=True) 3447 3448 if not self._islogical() or not other._islogical(): 3449 return context._raise_error(InvalidOperation) 3450 3451 # fill to context.prec 3452 (opa, opb) = self._fill_logical(context, self._int, other._int) 3453 3454 # make the operation, and clean starting zeroes 3455 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)]) 3456 return _dec_from_triple(0, result.lstrip('0') or '0', 0) 3457 3458 def logical_xor(self, other, context=None): 3459 """Applies an 'xor' operation between self and other's digits.""" 3460 if context is None: 3461 context = getcontext() 3462 3463 other = _convert_other(other, raiseit=True) 3464 3465 if not self._islogical() or not other._islogical(): 3466 return context._raise_error(InvalidOperation) 3467 3468 # fill to context.prec 3469 (opa, opb) = self._fill_logical(context, self._int, other._int) 3470 3471 # make the operation, and clean starting zeroes 3472 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)]) 3473 return _dec_from_triple(0, result.lstrip('0') or '0', 0) 3474 3475 def max_mag(self, other, context=None): 3476 """Compares the values numerically with their sign ignored.""" 3477 other = _convert_other(other, raiseit=True) 3478 3479 if context is None: 3480 context = getcontext() 3481 3482 if self._is_special or other._is_special: 3483 # If one operand is a quiet NaN and the other is number, then the 3484 # number is always returned 3485 sn = self._isnan() 3486 on = other._isnan() 3487 if sn or on: 3488 if on == 1 and sn == 0: 3489 return self._fix(context) 3490 if sn == 1 and on == 0: 3491 return other._fix(context) 3492 return self._check_nans(other, context) 3493 3494 c = self.copy_abs()._cmp(other.copy_abs()) 3495 if c == 0: 3496 c = self.compare_total(other) 3497 3498 if c == -1: 3499 ans = other 3500 else: 3501 ans = self 3502 3503 return ans._fix(context) 3504 3505 def min_mag(self, other, context=None): 3506 """Compares the values numerically with their sign ignored.""" 3507 other = _convert_other(other, raiseit=True) 3508 3509 if context is None: 3510 context = getcontext() 3511 3512 if self._is_special or other._is_special: 3513 # If one operand is a quiet NaN and the other is number, then the 3514 # number is always returned 3515 sn = self._isnan() 3516 on = other._isnan() 3517 if sn or on: 3518 if on == 1 and sn == 0: 3519 return self._fix(context) 3520 if sn == 1 and on == 0: 3521 return other._fix(context) 3522 return self._check_nans(other, context) 3523 3524 c = self.copy_abs()._cmp(other.copy_abs()) 3525 if c == 0: 3526 c = self.compare_total(other) 3527 3528 if c == -1: 3529 ans = self 3530 else: 3531 ans = other 3532 3533 return ans._fix(context) 3534 3535 def next_minus(self, context=None): 3536 """Returns the largest representable number smaller than itself.""" 3537 if context is None: 3538 context = getcontext() 3539 3540 ans = self._check_nans(context=context) 3541 if ans: 3542 return ans 3543 3544 if self._isinfinity() == -1: 3545 return _NegativeInfinity 3546 if self._isinfinity() == 1: 3547 return _dec_from_triple(0, '9'*context.prec, context.Etop()) 3548 3549 context = context.copy() 3550 context._set_rounding(ROUND_FLOOR) 3551 context._ignore_all_flags() 3552 new_self = self._fix(context) 3553 if new_self != self: 3554 return new_self 3555 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1), 3556 context) 3557 3558 def next_plus(self, context=None): 3559 """Returns the smallest representable number larger than itself.""" 3560 if context is None: 3561 context = getcontext() 3562 3563 ans = self._check_nans(context=context) 3564 if ans: 3565 return ans 3566 3567 if self._isinfinity() == 1: 3568 return _Infinity 3569 if self._isinfinity() == -1: 3570 return _dec_from_triple(1, '9'*context.prec, context.Etop()) 3571 3572 context = context.copy() 3573 context._set_rounding(ROUND_CEILING) 3574 context._ignore_all_flags() 3575 new_self = self._fix(context) 3576 if new_self != self: 3577 return new_self 3578 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1), 3579 context) 3580 3581 def next_toward(self, other, context=None): 3582 """Returns the number closest to self, in the direction towards other. 3583 3584 The result is the closest representable number to self 3585 (excluding self) that is in the direction towards other, 3586 unless both have the same value. If the two operands are 3587 numerically equal, then the result is a copy of self with the 3588 sign set to be the same as the sign of other. 3589 """ 3590 other = _convert_other(other, raiseit=True) 3591 3592 if context is None: 3593 context = getcontext() 3594 3595 ans = self._check_nans(other, context) 3596 if ans: 3597 return ans 3598 3599 comparison = self._cmp(other) 3600 if comparison == 0: 3601 return self.copy_sign(other) 3602 3603 if comparison == -1: 3604 ans = self.next_plus(context) 3605 else: # comparison == 1 3606 ans = self.next_minus(context) 3607 3608 # decide which flags to raise using value of ans 3609 if ans._isinfinity(): 3610 context._raise_error(Overflow, 3611 'Infinite result from next_toward', 3612 ans._sign) 3613 context._raise_error(Inexact) 3614 context._raise_error(Rounded) 3615 elif ans.adjusted() < context.Emin: 3616 context._raise_error(Underflow) 3617 context._raise_error(Subnormal) 3618 context._raise_error(Inexact) 3619 context._raise_error(Rounded) 3620 # if precision == 1 then we don't raise Clamped for a 3621 # result 0E-Etiny. 3622 if not ans: 3623 context._raise_error(Clamped) 3624 3625 return ans 3626 3627 def number_class(self, context=None): 3628 """Returns an indication of the class of self. 3629 3630 The class is one of the following strings: 3631 sNaN 3632 NaN 3633 -Infinity 3634 -Normal 3635 -Subnormal 3636 -Zero 3637 +Zero 3638 +Subnormal 3639 +Normal 3640 +Infinity 3641 """ 3642 if self.is_snan(): 3643 return "sNaN" 3644 if self.is_qnan(): 3645 return "NaN" 3646 inf = self._isinfinity() 3647 if inf == 1: 3648 return "+Infinity" 3649 if inf == -1: 3650 return "-Infinity" 3651 if self.is_zero(): 3652 if self._sign: 3653 return "-Zero" 3654 else: 3655 return "+Zero" 3656 if context is None: 3657 context = getcontext() 3658 if self.is_subnormal(context=context): 3659 if self._sign: 3660 return "-Subnormal" 3661 else: 3662 return "+Subnormal" 3663 # just a normal, regular, boring number, :) 3664 if self._sign: 3665 return "-Normal" 3666 else: 3667 return "+Normal" 3668 3669 def radix(self): 3670 """Just returns 10, as this is Decimal, :)""" 3671 return Decimal(10) 3672 3673 def rotate(self, other, context=None): 3674 """Returns a rotated copy of self, value-of-other times.""" 3675 if context is None: 3676 context = getcontext() 3677 3678 other = _convert_other(other, raiseit=True) 3679 3680 ans = self._check_nans(other, context) 3681 if ans: 3682 return ans 3683 3684 if other._exp != 0: 3685 return context._raise_error(InvalidOperation) 3686 if not (-context.prec <= int(other) <= context.prec): 3687 return context._raise_error(InvalidOperation) 3688 3689 if self._isinfinity(): 3690 return Decimal(self) 3691 3692 # get values, pad if necessary 3693 torot = int(other) 3694 rotdig = self._int 3695 topad = context.prec - len(rotdig) 3696 if topad > 0: 3697 rotdig = '0'*topad + rotdig 3698 elif topad < 0: 3699 rotdig = rotdig[-topad:] 3700 3701 # let's rotate! 3702 rotated = rotdig[torot:] + rotdig[:torot] 3703 return _dec_from_triple(self._sign, 3704 rotated.lstrip('0') or '0', self._exp) 3705 3706 def scaleb(self, other, context=None): 3707 """Returns self operand after adding the second value to its exp.""" 3708 if context is None: 3709 context = getcontext() 3710 3711 other = _convert_other(other, raiseit=True) 3712 3713 ans = self._check_nans(other, context) 3714 if ans: 3715 return ans 3716 3717 if other._exp != 0: 3718 return context._raise_error(InvalidOperation) 3719 liminf = -2 * (context.Emax + context.prec) 3720 limsup = 2 * (context.Emax + context.prec) 3721 if not (liminf <= int(other) <= limsup): 3722 return context._raise_error(InvalidOperation) 3723 3724 if self._isinfinity(): 3725 return Decimal(self) 3726 3727 d = _dec_from_triple(self._sign, self._int, self._exp + int(other)) 3728 d = d._fix(context) 3729 return d 3730 3731 def shift(self, other, context=None): 3732 """Returns a shifted copy of self, value-of-other times.""" 3733 if context is None: 3734 context = getcontext() 3735 3736 other = _convert_other(other, raiseit=True) 3737 3738 ans = self._check_nans(other, context) 3739 if ans: 3740 return ans 3741 3742 if other._exp != 0: 3743 return context._raise_error(InvalidOperation) 3744 if not (-context.prec <= int(other) <= context.prec): 3745 return context._raise_error(InvalidOperation) 3746 3747 if self._isinfinity(): 3748 return Decimal(self) 3749 3750 # get values, pad if necessary 3751 torot = int(other) 3752 rotdig = self._int 3753 topad = context.prec - len(rotdig) 3754 if topad > 0: 3755 rotdig = '0'*topad + rotdig 3756 elif topad < 0: 3757 rotdig = rotdig[-topad:] 3758 3759 # let's shift! 3760 if torot < 0: 3761 shifted = rotdig[:torot] 3762 else: 3763 shifted = rotdig + '0'*torot 3764 shifted = shifted[-context.prec:] 3765 3766 return _dec_from_triple(self._sign, 3767 shifted.lstrip('0') or '0', self._exp) 3768 3769 # Support for pickling, copy, and deepcopy 3770 def __reduce__(self): 3771 return (self.__class__, (str(self),)) 3772 3773 def __copy__(self): 3774 if type(self) is Decimal: 3775 return self # I'm immutable; therefore I am my own clone 3776 return self.__class__(str(self)) 3777 3778 def __deepcopy__(self, memo): 3779 if type(self) is Decimal: 3780 return self # My components are also immutable 3781 return self.__class__(str(self)) 3782 3783 # PEP 3101 support. the _localeconv keyword argument should be 3784 # considered private: it's provided for ease of testing only. 3785 def __format__(self, specifier, context=None, _localeconv=None): 3786 """Format a Decimal instance according to the given specifier. 3787 3788 The specifier should be a standard format specifier, with the 3789 form described in PEP 3101. Formatting types 'e', 'E', 'f', 3790 'F', 'g', 'G', 'n' and '%' are supported. If the formatting 3791 type is omitted it defaults to 'g' or 'G', depending on the 3792 value of context.capitals. 3793 """ 3794 3795 # Note: PEP 3101 says that if the type is not present then 3796 # there should be at least one digit after the decimal point. 3797 # We take the liberty of ignoring this requirement for 3798 # Decimal---it's presumably there to make sure that 3799 # format(float, '') behaves similarly to str(float). 3800 if context is None: 3801 context = getcontext() 3802 3803 spec = _parse_format_specifier(specifier, _localeconv=_localeconv) 3804 3805 # special values don't care about the type or precision 3806 if self._is_special: 3807 sign = _format_sign(self._sign, spec) 3808 body = str(self.copy_abs()) 3809 if spec['type'] == '%': 3810 body += '%' 3811 return _format_align(sign, body, spec) 3812 3813 # a type of None defaults to 'g' or 'G', depending on context 3814 if spec['type'] is None: 3815 spec['type'] = ['g', 'G'][context.capitals] 3816 3817 # if type is '%', adjust exponent of self accordingly 3818 if spec['type'] == '%': 3819 self = _dec_from_triple(self._sign, self._int, self._exp+2) 3820 3821 # round if necessary, taking rounding mode from the context 3822 rounding = context.rounding 3823 precision = spec['precision'] 3824 if precision is not None: 3825 if spec['type'] in 'eE': 3826 self = self._round(precision+1, rounding) 3827 elif spec['type'] in 'fF%': 3828 self = self._rescale(-precision, rounding) 3829 elif spec['type'] in 'gG' and len(self._int) > precision: 3830 self = self._round(precision, rounding) 3831 # special case: zeros with a positive exponent can't be 3832 # represented in fixed point; rescale them to 0e0. 3833 if not self and self._exp > 0 and spec['type'] in 'fF%': 3834 self = self._rescale(0, rounding) 3835 3836 # figure out placement of the decimal point 3837 leftdigits = self._exp + len(self._int) 3838 if spec['type'] in 'eE': 3839 if not self and precision is not None: 3840 dotplace = 1 - precision 3841 else: 3842 dotplace = 1 3843 elif spec['type'] in 'fF%': 3844 dotplace = leftdigits 3845 elif spec['type'] in 'gG': 3846 if self._exp <= 0 and leftdigits > -6: 3847 dotplace = leftdigits 3848 else: 3849 dotplace = 1 3850 3851 # find digits before and after decimal point, and get exponent 3852 if dotplace < 0: 3853 intpart = '0' 3854 fracpart = '0'*(-dotplace) + self._int 3855 elif dotplace > len(self._int): 3856 intpart = self._int + '0'*(dotplace-len(self._int)) 3857 fracpart = '' 3858 else: 3859 intpart = self._int[:dotplace] or '0' 3860 fracpart = self._int[dotplace:] 3861 exp = leftdigits-dotplace 3862 3863 # done with the decimal-specific stuff; hand over the rest 3864 # of the formatting to the _format_number function 3865 return _format_number(self._sign, intpart, fracpart, exp, spec) 3866 3867 def _dec_from_triple(sign, coefficient, exponent, special=False): 3868 """Create a decimal instance directly, without any validation, 3869 normalization (e.g. removal of leading zeros) or argument 3870 conversion. 3871 3872 This function is for *internal use only*. 3873 """ 3874 3875 self = object.__new__(Decimal) 3876 self._sign = sign 3877 self._int = coefficient 3878 self._exp = exponent 3879 self._is_special = special 3880 3881 return self 3882 3883 # Register Decimal as a kind of Number (an abstract base class). 3884 # However, do not register it as Real (because Decimals are not 3885 # interoperable with floats). 3886 _numbers.Number.register(Decimal) 3887 3888 3889 ##### Context class ####################################################### 3890 3891 class _ContextManager(object): 3892 """Context manager class to support localcontext(). 3893 3894 Sets a copy of the supplied context in __enter__() and restores 3895 the previous decimal context in __exit__() 3896 """ 3897 def __init__(self, new_context): 3898 self.new_context = new_context.copy() 3899 def __enter__(self): 3900 self.saved_context = getcontext() 3901 setcontext(self.new_context) 3902 return self.new_context 3903 def __exit__(self, t, v, tb): 3904 setcontext(self.saved_context) 3905 3906 class Context(object): 3907 """Contains the context for a Decimal instance. 3908 3909 Contains: 3910 prec - precision (for use in rounding, division, square roots..) 3911 rounding - rounding type (how you round) 3912 traps - If traps[exception] = 1, then the exception is 3913 raised when it is caused. Otherwise, a value is 3914 substituted in. 3915 flags - When an exception is caused, flags[exception] is set. 3916 (Whether or not the trap_enabler is set) 3917 Should be reset by user of Decimal instance. 3918 Emin - Minimum exponent 3919 Emax - Maximum exponent 3920 capitals - If 1, 1*10^1 is printed as 1E+1. 3921 If 0, printed as 1e1 3922 clamp - If 1, change exponents if too high (Default 0) 3923 """ 3924 3925 def __init__(self, prec=None, rounding=None, Emin=None, Emax=None, 3926 capitals=None, clamp=None, flags=None, traps=None, 3927 _ignored_flags=None): 3928 # Set defaults; for everything except flags and _ignored_flags, 3929 # inherit from DefaultContext. 3930 try: 3931 dc = DefaultContext 3932 except NameError: 3933 pass 3934 3935 self.prec = prec if prec is not None else dc.prec 3936 self.rounding = rounding if rounding is not None else dc.rounding 3937 self.Emin = Emin if Emin is not None else dc.Emin 3938 self.Emax = Emax if Emax is not None else dc.Emax 3939 self.capitals = capitals if capitals is not None else dc.capitals 3940 self.clamp = clamp if clamp is not None else dc.clamp 3941 3942 if _ignored_flags is None: 3943 self._ignored_flags = [] 3944 else: 3945 self._ignored_flags = _ignored_flags 3946 3947 if traps is None: 3948 self.traps = dc.traps.copy() 3949 elif not isinstance(traps, dict): 3950 self.traps = dict((s, int(s in traps)) for s in _signals + traps) 3951 else: 3952 self.traps = traps 3953 3954 if flags is None: 3955 self.flags = dict.fromkeys(_signals, 0) 3956 elif not isinstance(flags, dict): 3957 self.flags = dict((s, int(s in flags)) for s in _signals + flags) 3958 else: 3959 self.flags = flags 3960 3961 def _set_integer_check(self, name, value, vmin, vmax): 3962 if not isinstance(value, int): 3963 raise TypeError("%s must be an integer" % name) 3964 if vmin == '-inf': 3965 if value > vmax: 3966 raise ValueError("%s must be in [%s, %d]. got: %s" % (name, vmin, vmax, value)) 3967 elif vmax == 'inf': 3968 if value < vmin: 3969 raise ValueError("%s must be in [%d, %s]. got: %s" % (name, vmin, vmax, value)) 3970 else: 3971 if value < vmin or value > vmax: 3972 raise ValueError("%s must be in [%d, %d]. got %s" % (name, vmin, vmax, value)) 3973 return object.__setattr__(self, name, value) 3974 3975 def _set_signal_dict(self, name, d): 3976 if not isinstance(d, dict): 3977 raise TypeError("%s must be a signal dict" % d) 3978 for key in d: 3979 if not key in _signals: 3980 raise KeyError("%s is not a valid signal dict" % d) 3981 for key in _signals: 3982 if not key in d: 3983 raise KeyError("%s is not a valid signal dict" % d) 3984 return object.__setattr__(self, name, d) 3985 3986 def __setattr__(self, name, value): 3987 if name == 'prec': 3988 return self._set_integer_check(name, value, 1, 'inf') 3989 elif name == 'Emin': 3990 return self._set_integer_check(name, value, '-inf', 0) 3991 elif name == 'Emax': 3992 return self._set_integer_check(name, value, 0, 'inf') 3993 elif name == 'capitals': 3994 return self._set_integer_check(name, value, 0, 1) 3995 elif name == 'clamp': 3996 return self._set_integer_check(name, value, 0, 1) 3997 elif name == 'rounding': 3998 if not value in _rounding_modes: 3999 # raise TypeError even for strings to have consistency 4000 # among various implementations. 4001 raise TypeError("%s: invalid rounding mode" % value) 4002 return object.__setattr__(self, name, value) 4003 elif name == 'flags' or name == 'traps': 4004 return self._set_signal_dict(name, value) 4005 elif name == '_ignored_flags': 4006 return object.__setattr__(self, name, value) 4007 else: 4008 raise AttributeError( 4009 "'decimal.Context' object has no attribute '%s'" % name) 4010 4011 def __delattr__(self, name): 4012 raise AttributeError("%s cannot be deleted" % name) 4013 4014 # Support for pickling, copy, and deepcopy 4015 def __reduce__(self): 4016 flags = [sig for sig, v in self.flags.items() if v] 4017 traps = [sig for sig, v in self.traps.items() if v] 4018 return (self.__class__, 4019 (self.prec, self.rounding, self.Emin, self.Emax, 4020 self.capitals, self.clamp, flags, traps)) 4021 4022 def __repr__(self): 4023 """Show the current context.""" 4024 s = [] 4025 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, ' 4026 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, ' 4027 'clamp=%(clamp)d' 4028 % vars(self)) 4029 names = [f.__name__ for f, v in self.flags.items() if v] 4030 s.append('flags=[' + ', '.join(names) + ']') 4031 names = [t.__name__ for t, v in self.traps.items() if v] 4032 s.append('traps=[' + ', '.join(names) + ']') 4033 return ', '.join(s) + ')' 4034 4035 def clear_flags(self): 4036 """Reset all flags to zero""" 4037 for flag in self.flags: 4038 self.flags[flag] = 0 4039 4040 def clear_traps(self): 4041 """Reset all traps to zero""" 4042 for flag in self.traps: 4043 self.traps[flag] = 0 4044 4045 def _shallow_copy(self): 4046 """Returns a shallow copy from self.""" 4047 nc = Context(self.prec, self.rounding, self.Emin, self.Emax, 4048 self.capitals, self.clamp, self.flags, self.traps, 4049 self._ignored_flags) 4050 return nc 4051 4052 def copy(self): 4053 """Returns a deep copy from self.""" 4054 nc = Context(self.prec, self.rounding, self.Emin, self.Emax, 4055 self.capitals, self.clamp, 4056 self.flags.copy(), self.traps.copy(), 4057 self._ignored_flags) 4058 return nc 4059 __copy__ = copy 4060 4061 def _raise_error(self, condition, explanation = None, *args): 4062 """Handles an error 4063 4064 If the flag is in _ignored_flags, returns the default response. 4065 Otherwise, it sets the flag, then, if the corresponding 4066 trap_enabler is set, it reraises the exception. Otherwise, it returns 4067 the default value after setting the flag. 4068 """ 4069 error = _condition_map.get(condition, condition) 4070 if error in self._ignored_flags: 4071 # Don't touch the flag 4072 return error().handle(self, *args) 4073 4074 self.flags[error] = 1 4075 if not self.traps[error]: 4076 # The errors define how to handle themselves. 4077 return condition().handle(self, *args) 4078 4079 # Errors should only be risked on copies of the context 4080 # self._ignored_flags = [] 4081 raise error(explanation) 4082 4083 def _ignore_all_flags(self): 4084 """Ignore all flags, if they are raised""" 4085 return self._ignore_flags(*_signals) 4086 4087 def _ignore_flags(self, *flags): 4088 """Ignore the flags, if they are raised""" 4089 # Do not mutate-- This way, copies of a context leave the original 4090 # alone. 4091 self._ignored_flags = (self._ignored_flags + list(flags)) 4092 return list(flags) 4093 4094 def _regard_flags(self, *flags): 4095 """Stop ignoring the flags, if they are raised""" 4096 if flags and isinstance(flags[0], (tuple,list)): 4097 flags = flags[0] 4098 for flag in flags: 4099 self._ignored_flags.remove(flag) 4100 4101 # We inherit object.__hash__, so we must deny this explicitly 4102 __hash__ = None 4103 4104 def Etiny(self): 4105 """Returns Etiny (= Emin - prec + 1)""" 4106 return int(self.Emin - self.prec + 1) 4107 4108 def Etop(self): 4109 """Returns maximum exponent (= Emax - prec + 1)""" 4110 return int(self.Emax - self.prec + 1) 4111 4112 def _set_rounding(self, type): 4113 """Sets the rounding type. 4114 4115 Sets the rounding type, and returns the current (previous) 4116 rounding type. Often used like: 4117 4118 context = context.copy() 4119 # so you don't change the calling context 4120 # if an error occurs in the middle. 4121 rounding = context._set_rounding(ROUND_UP) 4122 val = self.__sub__(other, context=context) 4123 context._set_rounding(rounding) 4124 4125 This will make it round up for that operation. 4126 """ 4127 rounding = self.rounding 4128 self.rounding = type 4129 return rounding 4130 4131 def create_decimal(self, num='0'): 4132 """Creates a new Decimal instance but using self as context. 4133 4134 This method implements the to-number operation of the 4135 IBM Decimal specification.""" 4136 4137 if isinstance(num, str) and (num != num.strip() or '_' in num): 4138 return self._raise_error(ConversionSyntax, 4139 "trailing or leading whitespace and " 4140 "underscores are not permitted.") 4141 4142 d = Decimal(num, context=self) 4143 if d._isnan() and len(d._int) > self.prec - self.clamp: 4144 return self._raise_error(ConversionSyntax, 4145 "diagnostic info too long in NaN") 4146 return d._fix(self) 4147 4148 def create_decimal_from_float(self, f): 4149 """Creates a new Decimal instance from a float but rounding using self 4150 as the context. 4151 4152 >>> context = Context(prec=5, rounding=ROUND_DOWN) 4153 >>> context.create_decimal_from_float(3.1415926535897932) 4154 Decimal('3.1415') 4155 >>> context = Context(prec=5, traps=[Inexact]) 4156 >>> context.create_decimal_from_float(3.1415926535897932) 4157 Traceback (most recent call last): 4158 ... 4159 decimal.Inexact: None 4160 4161 """ 4162 d = Decimal.from_float(f) # An exact conversion 4163 return d._fix(self) # Apply the context rounding 4164 4165 # Methods 4166 def abs(self, a): 4167 """Returns the absolute value of the operand. 4168 4169 If the operand is negative, the result is the same as using the minus 4170 operation on the operand. Otherwise, the result is the same as using 4171 the plus operation on the operand. 4172 4173 >>> ExtendedContext.abs(Decimal('2.1')) 4174 Decimal('2.1') 4175 >>> ExtendedContext.abs(Decimal('-100')) 4176 Decimal('100') 4177 >>> ExtendedContext.abs(Decimal('101.5')) 4178 Decimal('101.5') 4179 >>> ExtendedContext.abs(Decimal('-101.5')) 4180 Decimal('101.5') 4181 >>> ExtendedContext.abs(-1) 4182 Decimal('1') 4183 """ 4184 a = _convert_other(a, raiseit=True) 4185 return a.__abs__(context=self) 4186 4187 def add(self, a, b): 4188 """Return the sum of the two operands. 4189 4190 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00')) 4191 Decimal('19.00') 4192 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4')) 4193 Decimal('1.02E+4') 4194 >>> ExtendedContext.add(1, Decimal(2)) 4195 Decimal('3') 4196 >>> ExtendedContext.add(Decimal(8), 5) 4197 Decimal('13') 4198 >>> ExtendedContext.add(5, 5) 4199 Decimal('10') 4200 """ 4201 a = _convert_other(a, raiseit=True) 4202 r = a.__add__(b, context=self) 4203 if r is NotImplemented: 4204 raise TypeError("Unable to convert %s to Decimal" % b) 4205 else: 4206 return r 4207 4208 def _apply(self, a): 4209 return str(a._fix(self)) 4210 4211 def canonical(self, a): 4212 """Returns the same Decimal object. 4213 4214 As we do not have different encodings for the same number, the 4215 received object already is in its canonical form. 4216 4217 >>> ExtendedContext.canonical(Decimal('2.50')) 4218 Decimal('2.50') 4219 """ 4220 if not isinstance(a, Decimal): 4221 raise TypeError("canonical requires a Decimal as an argument.") 4222 return a.canonical() 4223 4224 def compare(self, a, b): 4225 """Compares values numerically. 4226 4227 If the signs of the operands differ, a value representing each operand 4228 ('-1' if the operand is less than zero, '0' if the operand is zero or 4229 negative zero, or '1' if the operand is greater than zero) is used in 4230 place of that operand for the comparison instead of the actual 4231 operand. 4232 4233 The comparison is then effected by subtracting the second operand from 4234 the first and then returning a value according to the result of the 4235 subtraction: '-1' if the result is less than zero, '0' if the result is 4236 zero or negative zero, or '1' if the result is greater than zero. 4237 4238 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3')) 4239 Decimal('-1') 4240 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1')) 4241 Decimal('0') 4242 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10')) 4243 Decimal('0') 4244 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1')) 4245 Decimal('1') 4246 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3')) 4247 Decimal('1') 4248 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1')) 4249 Decimal('-1') 4250 >>> ExtendedContext.compare(1, 2) 4251 Decimal('-1') 4252 >>> ExtendedContext.compare(Decimal(1), 2) 4253 Decimal('-1') 4254 >>> ExtendedContext.compare(1, Decimal(2)) 4255 Decimal('-1') 4256 """ 4257 a = _convert_other(a, raiseit=True) 4258 return a.compare(b, context=self) 4259 4260 def compare_signal(self, a, b): 4261 """Compares the values of the two operands numerically. 4262 4263 It's pretty much like compare(), but all NaNs signal, with signaling 4264 NaNs taking precedence over quiet NaNs. 4265 4266 >>> c = ExtendedContext 4267 >>> c.compare_signal(Decimal('2.1'), Decimal('3')) 4268 Decimal('-1') 4269 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) 4270 Decimal('0') 4271 >>> c.flags[InvalidOperation] = 0 4272 >>> print(c.flags[InvalidOperation]) 4273 0 4274 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) 4275 Decimal('NaN') 4276 >>> print(c.flags[InvalidOperation]) 4277 1 4278 >>> c.flags[InvalidOperation] = 0 4279 >>> print(c.flags[InvalidOperation]) 4280 0 4281 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) 4282 Decimal('NaN') 4283 >>> print(c.flags[InvalidOperation]) 4284 1 4285 >>> c.compare_signal(-1, 2) 4286 Decimal('-1') 4287 >>> c.compare_signal(Decimal(-1), 2) 4288 Decimal('-1') 4289 >>> c.compare_signal(-1, Decimal(2)) 4290 Decimal('-1') 4291 """ 4292 a = _convert_other(a, raiseit=True) 4293 return a.compare_signal(b, context=self) 4294 4295 def compare_total(self, a, b): 4296 """Compares two operands using their abstract representation. 4297 4298 This is not like the standard compare, which use their numerical 4299 value. Note that a total ordering is defined for all possible abstract 4300 representations. 4301 4302 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) 4303 Decimal('-1') 4304 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12')) 4305 Decimal('-1') 4306 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) 4307 Decimal('-1') 4308 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) 4309 Decimal('0') 4310 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300')) 4311 Decimal('1') 4312 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN')) 4313 Decimal('-1') 4314 >>> ExtendedContext.compare_total(1, 2) 4315 Decimal('-1') 4316 >>> ExtendedContext.compare_total(Decimal(1), 2) 4317 Decimal('-1') 4318 >>> ExtendedContext.compare_total(1, Decimal(2)) 4319 Decimal('-1') 4320 """ 4321 a = _convert_other(a, raiseit=True) 4322 return a.compare_total(b) 4323 4324 def compare_total_mag(self, a, b): 4325 """Compares two operands using their abstract representation ignoring sign. 4326 4327 Like compare_total, but with operand's sign ignored and assumed to be 0. 4328 """ 4329 a = _convert_other(a, raiseit=True) 4330 return a.compare_total_mag(b) 4331 4332 def copy_abs(self, a): 4333 """Returns a copy of the operand with the sign set to 0. 4334 4335 >>> ExtendedContext.copy_abs(Decimal('2.1')) 4336 Decimal('2.1') 4337 >>> ExtendedContext.copy_abs(Decimal('-100')) 4338 Decimal('100') 4339 >>> ExtendedContext.copy_abs(-1) 4340 Decimal('1') 4341 """ 4342 a = _convert_other(a, raiseit=True) 4343 return a.copy_abs() 4344 4345 def copy_decimal(self, a): 4346 """Returns a copy of the decimal object. 4347 4348 >>> ExtendedContext.copy_decimal(Decimal('2.1')) 4349 Decimal('2.1') 4350 >>> ExtendedContext.copy_decimal(Decimal('-1.00')) 4351 Decimal('-1.00') 4352 >>> ExtendedContext.copy_decimal(1) 4353 Decimal('1') 4354 """ 4355 a = _convert_other(a, raiseit=True) 4356 return Decimal(a) 4357 4358 def copy_negate(self, a): 4359 """Returns a copy of the operand with the sign inverted. 4360 4361 >>> ExtendedContext.copy_negate(Decimal('101.5')) 4362 Decimal('-101.5') 4363 >>> ExtendedContext.copy_negate(Decimal('-101.5')) 4364 Decimal('101.5') 4365 >>> ExtendedContext.copy_negate(1) 4366 Decimal('-1') 4367 """ 4368 a = _convert_other(a, raiseit=True) 4369 return a.copy_negate() 4370 4371 def copy_sign(self, a, b): 4372 """Copies the second operand's sign to the first one. 4373 4374 In detail, it returns a copy of the first operand with the sign 4375 equal to the sign of the second operand. 4376 4377 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) 4378 Decimal('1.50') 4379 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) 4380 Decimal('1.50') 4381 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) 4382 Decimal('-1.50') 4383 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) 4384 Decimal('-1.50') 4385 >>> ExtendedContext.copy_sign(1, -2) 4386 Decimal('-1') 4387 >>> ExtendedContext.copy_sign(Decimal(1), -2) 4388 Decimal('-1') 4389 >>> ExtendedContext.copy_sign(1, Decimal(-2)) 4390 Decimal('-1') 4391 """ 4392 a = _convert_other(a, raiseit=True) 4393 return a.copy_sign(b) 4394 4395 def divide(self, a, b): 4396 """Decimal division in a specified context. 4397 4398 >>> ExtendedContext.divide(Decimal('1'), Decimal('3')) 4399 Decimal('0.333333333') 4400 >>> ExtendedContext.divide(Decimal('2'), Decimal('3')) 4401 Decimal('0.666666667') 4402 >>> ExtendedContext.divide(Decimal('5'), Decimal('2')) 4403 Decimal('2.5') 4404 >>> ExtendedContext.divide(Decimal('1'), Decimal('10')) 4405 Decimal('0.1') 4406 >>> ExtendedContext.divide(Decimal('12'), Decimal('12')) 4407 Decimal('1') 4408 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2')) 4409 Decimal('4.00') 4410 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0')) 4411 Decimal('1.20') 4412 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100')) 4413 Decimal('10') 4414 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1')) 4415 Decimal('1000') 4416 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2')) 4417 Decimal('1.20E+6') 4418 >>> ExtendedContext.divide(5, 5) 4419 Decimal('1') 4420 >>> ExtendedContext.divide(Decimal(5), 5) 4421 Decimal('1') 4422 >>> ExtendedContext.divide(5, Decimal(5)) 4423 Decimal('1') 4424 """ 4425 a = _convert_other(a, raiseit=True) 4426 r = a.__truediv__(b, context=self) 4427 if r is NotImplemented: 4428 raise TypeError("Unable to convert %s to Decimal" % b) 4429 else: 4430 return r 4431 4432 def divide_int(self, a, b): 4433 """Divides two numbers and returns the integer part of the result. 4434 4435 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3')) 4436 Decimal('0') 4437 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3')) 4438 Decimal('3') 4439 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3')) 4440 Decimal('3') 4441 >>> ExtendedContext.divide_int(10, 3) 4442 Decimal('3') 4443 >>> ExtendedContext.divide_int(Decimal(10), 3) 4444 Decimal('3') 4445 >>> ExtendedContext.divide_int(10, Decimal(3)) 4446 Decimal('3') 4447 """ 4448 a = _convert_other(a, raiseit=True) 4449 r = a.__floordiv__(b, context=self) 4450 if r is NotImplemented: 4451 raise TypeError("Unable to convert %s to Decimal" % b) 4452 else: 4453 return r 4454 4455 def divmod(self, a, b): 4456 """Return (a // b, a % b). 4457 4458 >>> ExtendedContext.divmod(Decimal(8), Decimal(3)) 4459 (Decimal('2'), Decimal('2')) 4460 >>> ExtendedContext.divmod(Decimal(8), Decimal(4)) 4461 (Decimal('2'), Decimal('0')) 4462 >>> ExtendedContext.divmod(8, 4) 4463 (Decimal('2'), Decimal('0')) 4464 >>> ExtendedContext.divmod(Decimal(8), 4) 4465 (Decimal('2'), Decimal('0')) 4466 >>> ExtendedContext.divmod(8, Decimal(4)) 4467 (Decimal('2'), Decimal('0')) 4468 """ 4469 a = _convert_other(a, raiseit=True) 4470 r = a.__divmod__(b, context=self) 4471 if r is NotImplemented: 4472 raise TypeError("Unable to convert %s to Decimal" % b) 4473 else: 4474 return r 4475 4476 def exp(self, a): 4477 """Returns e ** a. 4478 4479 >>> c = ExtendedContext.copy() 4480 >>> c.Emin = -999 4481 >>> c.Emax = 999 4482 >>> c.exp(Decimal('-Infinity')) 4483 Decimal('0') 4484 >>> c.exp(Decimal('-1')) 4485 Decimal('0.367879441') 4486 >>> c.exp(Decimal('0')) 4487 Decimal('1') 4488 >>> c.exp(Decimal('1')) 4489 Decimal('2.71828183') 4490 >>> c.exp(Decimal('0.693147181')) 4491 Decimal('2.00000000') 4492 >>> c.exp(Decimal('+Infinity')) 4493 Decimal('Infinity') 4494 >>> c.exp(10) 4495 Decimal('22026.4658') 4496 """ 4497 a =_convert_other(a, raiseit=True) 4498 return a.exp(context=self) 4499 4500 def fma(self, a, b, c): 4501 """Returns a multiplied by b, plus c. 4502 4503 The first two operands are multiplied together, using multiply, 4504 the third operand is then added to the result of that 4505 multiplication, using add, all with only one final rounding. 4506 4507 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) 4508 Decimal('22') 4509 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) 4510 Decimal('-8') 4511 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) 4512 Decimal('1.38435736E+12') 4513 >>> ExtendedContext.fma(1, 3, 4) 4514 Decimal('7') 4515 >>> ExtendedContext.fma(1, Decimal(3), 4) 4516 Decimal('7') 4517 >>> ExtendedContext.fma(1, 3, Decimal(4)) 4518 Decimal('7') 4519 """ 4520 a = _convert_other(a, raiseit=True) 4521 return a.fma(b, c, context=self) 4522 4523 def is_canonical(self, a): 4524 """Return True if the operand is canonical; otherwise return False. 4525 4526 Currently, the encoding of a Decimal instance is always 4527 canonical, so this method returns True for any Decimal. 4528 4529 >>> ExtendedContext.is_canonical(Decimal('2.50')) 4530 True 4531 """ 4532 if not isinstance(a, Decimal): 4533 raise TypeError("is_canonical requires a Decimal as an argument.") 4534 return a.is_canonical() 4535 4536 def is_finite(self, a): 4537 """Return True if the operand is finite; otherwise return False. 4538 4539 A Decimal instance is considered finite if it is neither 4540 infinite nor a NaN. 4541 4542 >>> ExtendedContext.is_finite(Decimal('2.50')) 4543 True 4544 >>> ExtendedContext.is_finite(Decimal('-0.3')) 4545 True 4546 >>> ExtendedContext.is_finite(Decimal('0')) 4547 True 4548 >>> ExtendedContext.is_finite(Decimal('Inf')) 4549 False 4550 >>> ExtendedContext.is_finite(Decimal('NaN')) 4551 False 4552 >>> ExtendedContext.is_finite(1) 4553 True 4554 """ 4555 a = _convert_other(a, raiseit=True) 4556 return a.is_finite() 4557 4558 def is_infinite(self, a): 4559 """Return True if the operand is infinite; otherwise return False. 4560 4561 >>> ExtendedContext.is_infinite(Decimal('2.50')) 4562 False 4563 >>> ExtendedContext.is_infinite(Decimal('-Inf')) 4564 True 4565 >>> ExtendedContext.is_infinite(Decimal('NaN')) 4566 False 4567 >>> ExtendedContext.is_infinite(1) 4568 False 4569 """ 4570 a = _convert_other(a, raiseit=True) 4571 return a.is_infinite() 4572 4573 def is_nan(self, a): 4574 """Return True if the operand is a qNaN or sNaN; 4575 otherwise return False. 4576 4577 >>> ExtendedContext.is_nan(Decimal('2.50')) 4578 False 4579 >>> ExtendedContext.is_nan(Decimal('NaN')) 4580 True 4581 >>> ExtendedContext.is_nan(Decimal('-sNaN')) 4582 True 4583 >>> ExtendedContext.is_nan(1) 4584 False 4585 """ 4586 a = _convert_other(a, raiseit=True) 4587 return a.is_nan() 4588 4589 def is_normal(self, a): 4590 """Return True if the operand is a normal number; 4591 otherwise return False. 4592 4593 >>> c = ExtendedContext.copy() 4594 >>> c.Emin = -999 4595 >>> c.Emax = 999 4596 >>> c.is_normal(Decimal('2.50')) 4597 True 4598 >>> c.is_normal(Decimal('0.1E-999')) 4599 False 4600 >>> c.is_normal(Decimal('0.00')) 4601 False 4602 >>> c.is_normal(Decimal('-Inf')) 4603 False 4604 >>> c.is_normal(Decimal('NaN')) 4605 False 4606 >>> c.is_normal(1) 4607 True 4608 """ 4609 a = _convert_other(a, raiseit=True) 4610 return a.is_normal(context=self) 4611 4612 def is_qnan(self, a): 4613 """Return True if the operand is a quiet NaN; otherwise return False. 4614 4615 >>> ExtendedContext.is_qnan(Decimal('2.50')) 4616 False 4617 >>> ExtendedContext.is_qnan(Decimal('NaN')) 4618 True 4619 >>> ExtendedContext.is_qnan(Decimal('sNaN')) 4620 False 4621 >>> ExtendedContext.is_qnan(1) 4622 False 4623 """ 4624 a = _convert_other(a, raiseit=True) 4625 return a.is_qnan() 4626 4627 def is_signed(self, a): 4628 """Return True if the operand is negative; otherwise return False. 4629 4630 >>> ExtendedContext.is_signed(Decimal('2.50')) 4631 False 4632 >>> ExtendedContext.is_signed(Decimal('-12')) 4633 True 4634 >>> ExtendedContext.is_signed(Decimal('-0')) 4635 True 4636 >>> ExtendedContext.is_signed(8) 4637 False 4638 >>> ExtendedContext.is_signed(-8) 4639 True 4640 """ 4641 a = _convert_other(a, raiseit=True) 4642 return a.is_signed() 4643 4644 def is_snan(self, a): 4645 """Return True if the operand is a signaling NaN; 4646 otherwise return False. 4647 4648 >>> ExtendedContext.is_snan(Decimal('2.50')) 4649 False 4650 >>> ExtendedContext.is_snan(Decimal('NaN')) 4651 False 4652 >>> ExtendedContext.is_snan(Decimal('sNaN')) 4653 True 4654 >>> ExtendedContext.is_snan(1) 4655 False 4656 """ 4657 a = _convert_other(a, raiseit=True) 4658 return a.is_snan() 4659 4660 def is_subnormal(self, a): 4661 """Return True if the operand is subnormal; otherwise return False. 4662 4663 >>> c = ExtendedContext.copy() 4664 >>> c.Emin = -999 4665 >>> c.Emax = 999 4666 >>> c.is_subnormal(Decimal('2.50')) 4667 False 4668 >>> c.is_subnormal(Decimal('0.1E-999')) 4669 True 4670 >>> c.is_subnormal(Decimal('0.00')) 4671 False 4672 >>> c.is_subnormal(Decimal('-Inf')) 4673 False 4674 >>> c.is_subnormal(Decimal('NaN')) 4675 False 4676 >>> c.is_subnormal(1) 4677 False 4678 """ 4679 a = _convert_other(a, raiseit=True) 4680 return a.is_subnormal(context=self) 4681 4682 def is_zero(self, a): 4683 """Return True if the operand is a zero; otherwise return False. 4684 4685 >>> ExtendedContext.is_zero(Decimal('0')) 4686 True 4687 >>> ExtendedContext.is_zero(Decimal('2.50')) 4688 False 4689 >>> ExtendedContext.is_zero(Decimal('-0E+2')) 4690 True 4691 >>> ExtendedContext.is_zero(1) 4692 False 4693 >>> ExtendedContext.is_zero(0) 4694 True 4695 """ 4696 a = _convert_other(a, raiseit=True) 4697 return a.is_zero() 4698 4699 def ln(self, a): 4700 """Returns the natural (base e) logarithm of the operand. 4701 4702 >>> c = ExtendedContext.copy() 4703 >>> c.Emin = -999 4704 >>> c.Emax = 999 4705 >>> c.ln(Decimal('0')) 4706 Decimal('-Infinity') 4707 >>> c.ln(Decimal('1.000')) 4708 Decimal('0') 4709 >>> c.ln(Decimal('2.71828183')) 4710 Decimal('1.00000000') 4711 >>> c.ln(Decimal('10')) 4712 Decimal('2.30258509') 4713 >>> c.ln(Decimal('+Infinity')) 4714 Decimal('Infinity') 4715 >>> c.ln(1) 4716 Decimal('0') 4717 """ 4718 a = _convert_other(a, raiseit=True) 4719 return a.ln(context=self) 4720 4721 def log10(self, a): 4722 """Returns the base 10 logarithm of the operand. 4723 4724 >>> c = ExtendedContext.copy() 4725 >>> c.Emin = -999 4726 >>> c.Emax = 999 4727 >>> c.log10(Decimal('0')) 4728 Decimal('-Infinity') 4729 >>> c.log10(Decimal('0.001')) 4730 Decimal('-3') 4731 >>> c.log10(Decimal('1.000')) 4732 Decimal('0') 4733 >>> c.log10(Decimal('2')) 4734 Decimal('0.301029996') 4735 >>> c.log10(Decimal('10')) 4736 Decimal('1') 4737 >>> c.log10(Decimal('70')) 4738 Decimal('1.84509804') 4739 >>> c.log10(Decimal('+Infinity')) 4740 Decimal('Infinity') 4741 >>> c.log10(0) 4742 Decimal('-Infinity') 4743 >>> c.log10(1) 4744 Decimal('0') 4745 """ 4746 a = _convert_other(a, raiseit=True) 4747 return a.log10(context=self) 4748 4749 def logb(self, a): 4750 """ Returns the exponent of the magnitude of the operand's MSD. 4751 4752 The result is the integer which is the exponent of the magnitude 4753 of the most significant digit of the operand (as though the 4754 operand were truncated to a single digit while maintaining the 4755 value of that digit and without limiting the resulting exponent). 4756 4757 >>> ExtendedContext.logb(Decimal('250')) 4758 Decimal('2') 4759 >>> ExtendedContext.logb(Decimal('2.50')) 4760 Decimal('0') 4761 >>> ExtendedContext.logb(Decimal('0.03')) 4762 Decimal('-2') 4763 >>> ExtendedContext.logb(Decimal('0')) 4764 Decimal('-Infinity') 4765 >>> ExtendedContext.logb(1) 4766 Decimal('0') 4767 >>> ExtendedContext.logb(10) 4768 Decimal('1') 4769 >>> ExtendedContext.logb(100) 4770 Decimal('2') 4771 """ 4772 a = _convert_other(a, raiseit=True) 4773 return a.logb(context=self) 4774 4775 def logical_and(self, a, b): 4776 """Applies the logical operation 'and' between each operand's digits. 4777 4778 The operands must be both logical numbers. 4779 4780 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) 4781 Decimal('0') 4782 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) 4783 Decimal('0') 4784 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) 4785 Decimal('0') 4786 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) 4787 Decimal('1') 4788 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) 4789 Decimal('1000') 4790 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) 4791 Decimal('10') 4792 >>> ExtendedContext.logical_and(110, 1101) 4793 Decimal('100') 4794 >>> ExtendedContext.logical_and(Decimal(110), 1101) 4795 Decimal('100') 4796 >>> ExtendedContext.logical_and(110, Decimal(1101)) 4797 Decimal('100') 4798 """ 4799 a = _convert_other(a, raiseit=True) 4800 return a.logical_and(b, context=self) 4801 4802 def logical_invert(self, a): 4803 """Invert all the digits in the operand. 4804 4805 The operand must be a logical number. 4806 4807 >>> ExtendedContext.logical_invert(Decimal('0')) 4808 Decimal('111111111') 4809 >>> ExtendedContext.logical_invert(Decimal('1')) 4810 Decimal('111111110') 4811 >>> ExtendedContext.logical_invert(Decimal('111111111')) 4812 Decimal('0') 4813 >>> ExtendedContext.logical_invert(Decimal('101010101')) 4814 Decimal('10101010') 4815 >>> ExtendedContext.logical_invert(1101) 4816 Decimal('111110010') 4817 """ 4818 a = _convert_other(a, raiseit=True) 4819 return a.logical_invert(context=self) 4820 4821 def logical_or(self, a, b): 4822 """Applies the logical operation 'or' between each operand's digits. 4823 4824 The operands must be both logical numbers. 4825 4826 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) 4827 Decimal('0') 4828 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) 4829 Decimal('1') 4830 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) 4831 Decimal('1') 4832 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) 4833 Decimal('1') 4834 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) 4835 Decimal('1110') 4836 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) 4837 Decimal('1110') 4838 >>> ExtendedContext.logical_or(110, 1101) 4839 Decimal('1111') 4840 >>> ExtendedContext.logical_or(Decimal(110), 1101) 4841 Decimal('1111') 4842 >>> ExtendedContext.logical_or(110, Decimal(1101)) 4843 Decimal('1111') 4844 """ 4845 a = _convert_other(a, raiseit=True) 4846 return a.logical_or(b, context=self) 4847 4848 def logical_xor(self, a, b): 4849 """Applies the logical operation 'xor' between each operand's digits. 4850 4851 The operands must be both logical numbers. 4852 4853 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) 4854 Decimal('0') 4855 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) 4856 Decimal('1') 4857 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) 4858 Decimal('1') 4859 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) 4860 Decimal('0') 4861 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) 4862 Decimal('110') 4863 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) 4864 Decimal('1101') 4865 >>> ExtendedContext.logical_xor(110, 1101) 4866 Decimal('1011') 4867 >>> ExtendedContext.logical_xor(Decimal(110), 1101) 4868 Decimal('1011') 4869 >>> ExtendedContext.logical_xor(110, Decimal(1101)) 4870 Decimal('1011') 4871 """ 4872 a = _convert_other(a, raiseit=True) 4873 return a.logical_xor(b, context=self) 4874 4875 def max(self, a, b): 4876 """max compares two values numerically and returns the maximum. 4877 4878 If either operand is a NaN then the general rules apply. 4879 Otherwise, the operands are compared as though by the compare 4880 operation. If they are numerically equal then the left-hand operand 4881 is chosen as the result. Otherwise the maximum (closer to positive 4882 infinity) of the two operands is chosen as the result. 4883 4884 >>> ExtendedContext.max(Decimal('3'), Decimal('2')) 4885 Decimal('3') 4886 >>> ExtendedContext.max(Decimal('-10'), Decimal('3')) 4887 Decimal('3') 4888 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1')) 4889 Decimal('1') 4890 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN')) 4891 Decimal('7') 4892 >>> ExtendedContext.max(1, 2) 4893 Decimal('2') 4894 >>> ExtendedContext.max(Decimal(1), 2) 4895 Decimal('2') 4896 >>> ExtendedContext.max(1, Decimal(2)) 4897 Decimal('2') 4898 """ 4899 a = _convert_other(a, raiseit=True) 4900 return a.max(b, context=self) 4901 4902 def max_mag(self, a, b): 4903 """Compares the values numerically with their sign ignored. 4904 4905 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN')) 4906 Decimal('7') 4907 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10')) 4908 Decimal('-10') 4909 >>> ExtendedContext.max_mag(1, -2) 4910 Decimal('-2') 4911 >>> ExtendedContext.max_mag(Decimal(1), -2) 4912 Decimal('-2') 4913 >>> ExtendedContext.max_mag(1, Decimal(-2)) 4914 Decimal('-2') 4915 """ 4916 a = _convert_other(a, raiseit=True) 4917 return a.max_mag(b, context=self) 4918 4919 def min(self, a, b): 4920 """min compares two values numerically and returns the minimum. 4921 4922 If either operand is a NaN then the general rules apply. 4923 Otherwise, the operands are compared as though by the compare 4924 operation. If they are numerically equal then the left-hand operand 4925 is chosen as the result. Otherwise the minimum (closer to negative 4926 infinity) of the two operands is chosen as the result. 4927 4928 >>> ExtendedContext.min(Decimal('3'), Decimal('2')) 4929 Decimal('2') 4930 >>> ExtendedContext.min(Decimal('-10'), Decimal('3')) 4931 Decimal('-10') 4932 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1')) 4933 Decimal('1.0') 4934 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN')) 4935 Decimal('7') 4936 >>> ExtendedContext.min(1, 2) 4937 Decimal('1') 4938 >>> ExtendedContext.min(Decimal(1), 2) 4939 Decimal('1') 4940 >>> ExtendedContext.min(1, Decimal(29)) 4941 Decimal('1') 4942 """ 4943 a = _convert_other(a, raiseit=True) 4944 return a.min(b, context=self) 4945 4946 def min_mag(self, a, b): 4947 """Compares the values numerically with their sign ignored. 4948 4949 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2')) 4950 Decimal('-2') 4951 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN')) 4952 Decimal('-3') 4953 >>> ExtendedContext.min_mag(1, -2) 4954 Decimal('1') 4955 >>> ExtendedContext.min_mag(Decimal(1), -2) 4956 Decimal('1') 4957 >>> ExtendedContext.min_mag(1, Decimal(-2)) 4958 Decimal('1') 4959 """ 4960 a = _convert_other(a, raiseit=True) 4961 return a.min_mag(b, context=self) 4962 4963 def minus(self, a): 4964 """Minus corresponds to unary prefix minus in Python. 4965 4966 The operation is evaluated using the same rules as subtract; the 4967 operation minus(a) is calculated as subtract('0', a) where the '0' 4968 has the same exponent as the operand. 4969 4970 >>> ExtendedContext.minus(Decimal('1.3')) 4971 Decimal('-1.3') 4972 >>> ExtendedContext.minus(Decimal('-1.3')) 4973 Decimal('1.3') 4974 >>> ExtendedContext.minus(1) 4975 Decimal('-1') 4976 """ 4977 a = _convert_other(a, raiseit=True) 4978 return a.__neg__(context=self) 4979 4980 def multiply(self, a, b): 4981 """multiply multiplies two operands. 4982 4983 If either operand is a special value then the general rules apply. 4984 Otherwise, the operands are multiplied together 4985 ('long multiplication'), resulting in a number which may be as long as 4986 the sum of the lengths of the two operands. 4987 4988 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3')) 4989 Decimal('3.60') 4990 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3')) 4991 Decimal('21') 4992 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8')) 4993 Decimal('0.72') 4994 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0')) 4995 Decimal('-0.0') 4996 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321')) 4997 Decimal('4.28135971E+11') 4998 >>> ExtendedContext.multiply(7, 7) 4999 Decimal('49') 5000 >>> ExtendedContext.multiply(Decimal(7), 7) 5001 Decimal('49') 5002 >>> ExtendedContext.multiply(7, Decimal(7)) 5003 Decimal('49') 5004 """ 5005 a = _convert_other(a, raiseit=True) 5006 r = a.__mul__(b, context=self) 5007 if r is NotImplemented: 5008 raise TypeError("Unable to convert %s to Decimal" % b) 5009 else: 5010 return r 5011 5012 def next_minus(self, a): 5013 """Returns the largest representable number smaller than a. 5014 5015 >>> c = ExtendedContext.copy() 5016 >>> c.Emin = -999 5017 >>> c.Emax = 999 5018 >>> ExtendedContext.next_minus(Decimal('1')) 5019 Decimal('0.999999999') 5020 >>> c.next_minus(Decimal('1E-1007')) 5021 Decimal('0E-1007') 5022 >>> ExtendedContext.next_minus(Decimal('-1.00000003')) 5023 Decimal('-1.00000004') 5024 >>> c.next_minus(Decimal('Infinity')) 5025 Decimal('9.99999999E+999') 5026 >>> c.next_minus(1) 5027 Decimal('0.999999999') 5028 """ 5029 a = _convert_other(a, raiseit=True) 5030 return a.next_minus(context=self) 5031 5032 def next_plus(self, a): 5033 """Returns the smallest representable number larger than a. 5034 5035 >>> c = ExtendedContext.copy() 5036 >>> c.Emin = -999 5037 >>> c.Emax = 999 5038 >>> ExtendedContext.next_plus(Decimal('1')) 5039 Decimal('1.00000001') 5040 >>> c.next_plus(Decimal('-1E-1007')) 5041 Decimal('-0E-1007') 5042 >>> ExtendedContext.next_plus(Decimal('-1.00000003')) 5043 Decimal('-1.00000002') 5044 >>> c.next_plus(Decimal('-Infinity')) 5045 Decimal('-9.99999999E+999') 5046 >>> c.next_plus(1) 5047 Decimal('1.00000001') 5048 """ 5049 a = _convert_other(a, raiseit=True) 5050 return a.next_plus(context=self) 5051 5052 def next_toward(self, a, b): 5053 """Returns the number closest to a, in direction towards b. 5054 5055 The result is the closest representable number from the first 5056 operand (but not the first operand) that is in the direction 5057 towards the second operand, unless the operands have the same 5058 value. 5059 5060 >>> c = ExtendedContext.copy() 5061 >>> c.Emin = -999 5062 >>> c.Emax = 999 5063 >>> c.next_toward(Decimal('1'), Decimal('2')) 5064 Decimal('1.00000001') 5065 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) 5066 Decimal('-0E-1007') 5067 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) 5068 Decimal('-1.00000002') 5069 >>> c.next_toward(Decimal('1'), Decimal('0')) 5070 Decimal('0.999999999') 5071 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) 5072 Decimal('0E-1007') 5073 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) 5074 Decimal('-1.00000004') 5075 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) 5076 Decimal('-0.00') 5077 >>> c.next_toward(0, 1) 5078 Decimal('1E-1007') 5079 >>> c.next_toward(Decimal(0), 1) 5080 Decimal('1E-1007') 5081 >>> c.next_toward(0, Decimal(1)) 5082 Decimal('1E-1007') 5083 """ 5084 a = _convert_other(a, raiseit=True) 5085 return a.next_toward(b, context=self) 5086 5087 def normalize(self, a): 5088 """normalize reduces an operand to its simplest form. 5089 5090 Essentially a plus operation with all trailing zeros removed from the 5091 result. 5092 5093 >>> ExtendedContext.normalize(Decimal('2.1')) 5094 Decimal('2.1') 5095 >>> ExtendedContext.normalize(Decimal('-2.0')) 5096 Decimal('-2') 5097 >>> ExtendedContext.normalize(Decimal('1.200')) 5098 Decimal('1.2') 5099 >>> ExtendedContext.normalize(Decimal('-120')) 5100 Decimal('-1.2E+2') 5101 >>> ExtendedContext.normalize(Decimal('120.00')) 5102 Decimal('1.2E+2') 5103 >>> ExtendedContext.normalize(Decimal('0.00')) 5104 Decimal('0') 5105 >>> ExtendedContext.normalize(6) 5106 Decimal('6') 5107 """ 5108 a = _convert_other(a, raiseit=True) 5109 return a.normalize(context=self) 5110 5111 def number_class(self, a): 5112 """Returns an indication of the class of the operand. 5113 5114 The class is one of the following strings: 5115 -sNaN 5116 -NaN 5117 -Infinity 5118 -Normal 5119 -Subnormal 5120 -Zero 5121 +Zero 5122 +Subnormal 5123 +Normal 5124 +Infinity 5125 5126 >>> c = ExtendedContext.copy() 5127 >>> c.Emin = -999 5128 >>> c.Emax = 999 5129 >>> c.number_class(Decimal('Infinity')) 5130 '+Infinity' 5131 >>> c.number_class(Decimal('1E-10')) 5132 '+Normal' 5133 >>> c.number_class(Decimal('2.50')) 5134 '+Normal' 5135 >>> c.number_class(Decimal('0.1E-999')) 5136 '+Subnormal' 5137 >>> c.number_class(Decimal('0')) 5138 '+Zero' 5139 >>> c.number_class(Decimal('-0')) 5140 '-Zero' 5141 >>> c.number_class(Decimal('-0.1E-999')) 5142 '-Subnormal' 5143 >>> c.number_class(Decimal('-1E-10')) 5144 '-Normal' 5145 >>> c.number_class(Decimal('-2.50')) 5146 '-Normal' 5147 >>> c.number_class(Decimal('-Infinity')) 5148 '-Infinity' 5149 >>> c.number_class(Decimal('NaN')) 5150 'NaN' 5151 >>> c.number_class(Decimal('-NaN')) 5152 'NaN' 5153 >>> c.number_class(Decimal('sNaN')) 5154 'sNaN' 5155 >>> c.number_class(123) 5156 '+Normal' 5157 """ 5158 a = _convert_other(a, raiseit=True) 5159 return a.number_class(context=self) 5160 5161 def plus(self, a): 5162 """Plus corresponds to unary prefix plus in Python. 5163 5164 The operation is evaluated using the same rules as add; the 5165 operation plus(a) is calculated as add('0', a) where the '0' 5166 has the same exponent as the operand. 5167 5168 >>> ExtendedContext.plus(Decimal('1.3')) 5169 Decimal('1.3') 5170 >>> ExtendedContext.plus(Decimal('-1.3')) 5171 Decimal('-1.3') 5172 >>> ExtendedContext.plus(-1) 5173 Decimal('-1') 5174 """ 5175 a = _convert_other(a, raiseit=True) 5176 return a.__pos__(context=self) 5177 5178 def power(self, a, b, modulo=None): 5179 """Raises a to the power of b, to modulo if given. 5180 5181 With two arguments, compute a**b. If a is negative then b 5182 must be integral. The result will be inexact unless b is 5183 integral and the result is finite and can be expressed exactly 5184 in 'precision' digits. 5185 5186 With three arguments, compute (a**b) % modulo. For the 5187 three argument form, the following restrictions on the 5188 arguments hold: 5189 5190 - all three arguments must be integral 5191 - b must be nonnegative 5192 - at least one of a or b must be nonzero 5193 - modulo must be nonzero and have at most 'precision' digits 5194 5195 The result of pow(a, b, modulo) is identical to the result 5196 that would be obtained by computing (a**b) % modulo with 5197 unbounded precision, but is computed more efficiently. It is 5198 always exact. 5199 5200 >>> c = ExtendedContext.copy() 5201 >>> c.Emin = -999 5202 >>> c.Emax = 999 5203 >>> c.power(Decimal('2'), Decimal('3')) 5204 Decimal('8') 5205 >>> c.power(Decimal('-2'), Decimal('3')) 5206 Decimal('-8') 5207 >>> c.power(Decimal('2'), Decimal('-3')) 5208 Decimal('0.125') 5209 >>> c.power(Decimal('1.7'), Decimal('8')) 5210 Decimal('69.7575744') 5211 >>> c.power(Decimal('10'), Decimal('0.301029996')) 5212 Decimal('2.00000000') 5213 >>> c.power(Decimal('Infinity'), Decimal('-1')) 5214 Decimal('0') 5215 >>> c.power(Decimal('Infinity'), Decimal('0')) 5216 Decimal('1') 5217 >>> c.power(Decimal('Infinity'), Decimal('1')) 5218 Decimal('Infinity') 5219 >>> c.power(Decimal('-Infinity'), Decimal('-1')) 5220 Decimal('-0') 5221 >>> c.power(Decimal('-Infinity'), Decimal('0')) 5222 Decimal('1') 5223 >>> c.power(Decimal('-Infinity'), Decimal('1')) 5224 Decimal('-Infinity') 5225 >>> c.power(Decimal('-Infinity'), Decimal('2')) 5226 Decimal('Infinity') 5227 >>> c.power(Decimal('0'), Decimal('0')) 5228 Decimal('NaN') 5229 5230 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) 5231 Decimal('11') 5232 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) 5233 Decimal('-11') 5234 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) 5235 Decimal('1') 5236 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) 5237 Decimal('11') 5238 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) 5239 Decimal('11729830') 5240 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) 5241 Decimal('-0') 5242 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) 5243 Decimal('1') 5244 >>> ExtendedContext.power(7, 7) 5245 Decimal('823543') 5246 >>> ExtendedContext.power(Decimal(7), 7) 5247 Decimal('823543') 5248 >>> ExtendedContext.power(7, Decimal(7), 2) 5249 Decimal('1') 5250 """ 5251 a = _convert_other(a, raiseit=True) 5252 r = a.__pow__(b, modulo, context=self) 5253 if r is NotImplemented: 5254 raise TypeError("Unable to convert %s to Decimal" % b) 5255 else: 5256 return r 5257 5258 def quantize(self, a, b): 5259 """Returns a value equal to 'a' (rounded), having the exponent of 'b'. 5260 5261 The coefficient of the result is derived from that of the left-hand 5262 operand. It may be rounded using the current rounding setting (if the 5263 exponent is being increased), multiplied by a positive power of ten (if 5264 the exponent is being decreased), or is unchanged (if the exponent is 5265 already equal to that of the right-hand operand). 5266 5267 Unlike other operations, if the length of the coefficient after the 5268 quantize operation would be greater than precision then an Invalid 5269 operation condition is raised. This guarantees that, unless there is 5270 an error condition, the exponent of the result of a quantize is always 5271 equal to that of the right-hand operand. 5272 5273 Also unlike other operations, quantize will never raise Underflow, even 5274 if the result is subnormal and inexact. 5275 5276 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001')) 5277 Decimal('2.170') 5278 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01')) 5279 Decimal('2.17') 5280 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1')) 5281 Decimal('2.2') 5282 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0')) 5283 Decimal('2') 5284 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1')) 5285 Decimal('0E+1') 5286 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity')) 5287 Decimal('-Infinity') 5288 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity')) 5289 Decimal('NaN') 5290 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1')) 5291 Decimal('-0') 5292 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5')) 5293 Decimal('-0E+5') 5294 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2')) 5295 Decimal('NaN') 5296 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2')) 5297 Decimal('NaN') 5298 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1')) 5299 Decimal('217.0') 5300 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0')) 5301 Decimal('217') 5302 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1')) 5303 Decimal('2.2E+2') 5304 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2')) 5305 Decimal('2E+2') 5306 >>> ExtendedContext.quantize(1, 2) 5307 Decimal('1') 5308 >>> ExtendedContext.quantize(Decimal(1), 2) 5309 Decimal('1') 5310 >>> ExtendedContext.quantize(1, Decimal(2)) 5311 Decimal('1') 5312 """ 5313 a = _convert_other(a, raiseit=True) 5314 return a.quantize(b, context=self) 5315 5316 def radix(self): 5317 """Just returns 10, as this is Decimal, :) 5318 5319 >>> ExtendedContext.radix() 5320 Decimal('10') 5321 """ 5322 return Decimal(10) 5323 5324 def remainder(self, a, b): 5325 """Returns the remainder from integer division. 5326 5327 The result is the residue of the dividend after the operation of 5328 calculating integer division as described for divide-integer, rounded 5329 to precision digits if necessary. The sign of the result, if 5330 non-zero, is the same as that of the original dividend. 5331 5332 This operation will fail under the same conditions as integer division 5333 (that is, if integer division on the same two operands would fail, the 5334 remainder cannot be calculated). 5335 5336 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3')) 5337 Decimal('2.1') 5338 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3')) 5339 Decimal('1') 5340 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3')) 5341 Decimal('-1') 5342 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1')) 5343 Decimal('0.2') 5344 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3')) 5345 Decimal('0.1') 5346 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3')) 5347 Decimal('1.0') 5348 >>> ExtendedContext.remainder(22, 6) 5349 Decimal('4') 5350 >>> ExtendedContext.remainder(Decimal(22), 6) 5351 Decimal('4') 5352 >>> ExtendedContext.remainder(22, Decimal(6)) 5353 Decimal('4') 5354 """ 5355 a = _convert_other(a, raiseit=True) 5356 r = a.__mod__(b, context=self) 5357 if r is NotImplemented: 5358 raise TypeError("Unable to convert %s to Decimal" % b) 5359 else: 5360 return r 5361 5362 def remainder_near(self, a, b): 5363 """Returns to be "a - b * n", where n is the integer nearest the exact 5364 value of "x / b" (if two integers are equally near then the even one 5365 is chosen). If the result is equal to 0 then its sign will be the 5366 sign of a. 5367 5368 This operation will fail under the same conditions as integer division 5369 (that is, if integer division on the same two operands would fail, the 5370 remainder cannot be calculated). 5371 5372 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3')) 5373 Decimal('-0.9') 5374 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6')) 5375 Decimal('-2') 5376 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3')) 5377 Decimal('1') 5378 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3')) 5379 Decimal('-1') 5380 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1')) 5381 Decimal('0.2') 5382 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3')) 5383 Decimal('0.1') 5384 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3')) 5385 Decimal('-0.3') 5386 >>> ExtendedContext.remainder_near(3, 11) 5387 Decimal('3') 5388 >>> ExtendedContext.remainder_near(Decimal(3), 11) 5389 Decimal('3') 5390 >>> ExtendedContext.remainder_near(3, Decimal(11)) 5391 Decimal('3') 5392 """ 5393 a = _convert_other(a, raiseit=True) 5394 return a.remainder_near(b, context=self) 5395 5396 def rotate(self, a, b): 5397 """Returns a rotated copy of a, b times. 5398 5399 The coefficient of the result is a rotated copy of the digits in 5400 the coefficient of the first operand. The number of places of 5401 rotation is taken from the absolute value of the second operand, 5402 with the rotation being to the left if the second operand is 5403 positive or to the right otherwise. 5404 5405 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8')) 5406 Decimal('400000003') 5407 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9')) 5408 Decimal('12') 5409 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2')) 5410 Decimal('891234567') 5411 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0')) 5412 Decimal('123456789') 5413 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2')) 5414 Decimal('345678912') 5415 >>> ExtendedContext.rotate(1333333, 1) 5416 Decimal('13333330') 5417 >>> ExtendedContext.rotate(Decimal(1333333), 1) 5418 Decimal('13333330') 5419 >>> ExtendedContext.rotate(1333333, Decimal(1)) 5420 Decimal('13333330') 5421 """ 5422 a = _convert_other(a, raiseit=True) 5423 return a.rotate(b, context=self) 5424 5425 def same_quantum(self, a, b): 5426 """Returns True if the two operands have the same exponent. 5427 5428 The result is never affected by either the sign or the coefficient of 5429 either operand. 5430 5431 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001')) 5432 False 5433 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01')) 5434 True 5435 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1')) 5436 False 5437 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf')) 5438 True 5439 >>> ExtendedContext.same_quantum(10000, -1) 5440 True 5441 >>> ExtendedContext.same_quantum(Decimal(10000), -1) 5442 True 5443 >>> ExtendedContext.same_quantum(10000, Decimal(-1)) 5444 True 5445 """ 5446 a = _convert_other(a, raiseit=True) 5447 return a.same_quantum(b) 5448 5449 def scaleb (self, a, b): 5450 """Returns the first operand after adding the second value its exp. 5451 5452 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) 5453 Decimal('0.0750') 5454 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) 5455 Decimal('7.50') 5456 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) 5457 Decimal('7.50E+3') 5458 >>> ExtendedContext.scaleb(1, 4) 5459 Decimal('1E+4') 5460 >>> ExtendedContext.scaleb(Decimal(1), 4) 5461 Decimal('1E+4') 5462 >>> ExtendedContext.scaleb(1, Decimal(4)) 5463 Decimal('1E+4') 5464 """ 5465 a = _convert_other(a, raiseit=True) 5466 return a.scaleb(b, context=self) 5467 5468 def shift(self, a, b): 5469 """Returns a shifted copy of a, b times. 5470 5471 The coefficient of the result is a shifted copy of the digits 5472 in the coefficient of the first operand. The number of places 5473 to shift is taken from the absolute value of the second operand, 5474 with the shift being to the left if the second operand is 5475 positive or to the right otherwise. Digits shifted into the 5476 coefficient are zeros. 5477 5478 >>> ExtendedContext.shift(Decimal('34'), Decimal('8')) 5479 Decimal('400000000') 5480 >>> ExtendedContext.shift(Decimal('12'), Decimal('9')) 5481 Decimal('0') 5482 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2')) 5483 Decimal('1234567') 5484 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0')) 5485 Decimal('123456789') 5486 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2')) 5487 Decimal('345678900') 5488 >>> ExtendedContext.shift(88888888, 2) 5489 Decimal('888888800') 5490 >>> ExtendedContext.shift(Decimal(88888888), 2) 5491 Decimal('888888800') 5492 >>> ExtendedContext.shift(88888888, Decimal(2)) 5493 Decimal('888888800') 5494 """ 5495 a = _convert_other(a, raiseit=True) 5496 return a.shift(b, context=self) 5497 5498 def sqrt(self, a): 5499 """Square root of a non-negative number to context precision. 5500 5501 If the result must be inexact, it is rounded using the round-half-even 5502 algorithm. 5503 5504 >>> ExtendedContext.sqrt(Decimal('0')) 5505 Decimal('0') 5506 >>> ExtendedContext.sqrt(Decimal('-0')) 5507 Decimal('-0') 5508 >>> ExtendedContext.sqrt(Decimal('0.39')) 5509 Decimal('0.624499800') 5510 >>> ExtendedContext.sqrt(Decimal('100')) 5511 Decimal('10') 5512 >>> ExtendedContext.sqrt(Decimal('1')) 5513 Decimal('1') 5514 >>> ExtendedContext.sqrt(Decimal('1.0')) 5515 Decimal('1.0') 5516 >>> ExtendedContext.sqrt(Decimal('1.00')) 5517 Decimal('1.0') 5518 >>> ExtendedContext.sqrt(Decimal('7')) 5519 Decimal('2.64575131') 5520 >>> ExtendedContext.sqrt(Decimal('10')) 5521 Decimal('3.16227766') 5522 >>> ExtendedContext.sqrt(2) 5523 Decimal('1.41421356') 5524 >>> ExtendedContext.prec 5525 9 5526 """ 5527 a = _convert_other(a, raiseit=True) 5528 return a.sqrt(context=self) 5529 5530 def subtract(self, a, b): 5531 """Return the difference between the two operands. 5532 5533 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07')) 5534 Decimal('0.23') 5535 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30')) 5536 Decimal('0.00') 5537 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07')) 5538 Decimal('-0.77') 5539 >>> ExtendedContext.subtract(8, 5) 5540 Decimal('3') 5541 >>> ExtendedContext.subtract(Decimal(8), 5) 5542 Decimal('3') 5543 >>> ExtendedContext.subtract(8, Decimal(5)) 5544 Decimal('3') 5545 """ 5546 a = _convert_other(a, raiseit=True) 5547 r = a.__sub__(b, context=self) 5548 if r is NotImplemented: 5549 raise TypeError("Unable to convert %s to Decimal" % b) 5550 else: 5551 return r 5552 5553 def to_eng_string(self, a): 5554 """Convert to a string, using engineering notation if an exponent is needed. 5555 5556 Engineering notation has an exponent which is a multiple of 3. This 5557 can leave up to 3 digits to the left of the decimal place and may 5558 require the addition of either one or two trailing zeros. 5559 5560 The operation is not affected by the context. 5561 5562 >>> ExtendedContext.to_eng_string(Decimal('123E+1')) 5563 '1.23E+3' 5564 >>> ExtendedContext.to_eng_string(Decimal('123E+3')) 5565 '123E+3' 5566 >>> ExtendedContext.to_eng_string(Decimal('123E-10')) 5567 '12.3E-9' 5568 >>> ExtendedContext.to_eng_string(Decimal('-123E-12')) 5569 '-123E-12' 5570 >>> ExtendedContext.to_eng_string(Decimal('7E-7')) 5571 '700E-9' 5572 >>> ExtendedContext.to_eng_string(Decimal('7E+1')) 5573 '70' 5574 >>> ExtendedContext.to_eng_string(Decimal('0E+1')) 5575 '0.00E+3' 5576 5577 """ 5578 a = _convert_other(a, raiseit=True) 5579 return a.to_eng_string(context=self) 5580 5581 def to_sci_string(self, a): 5582 """Converts a number to a string, using scientific notation. 5583 5584 The operation is not affected by the context. 5585 """ 5586 a = _convert_other(a, raiseit=True) 5587 return a.__str__(context=self) 5588 5589 def to_integral_exact(self, a): 5590 """Rounds to an integer. 5591 5592 When the operand has a negative exponent, the result is the same 5593 as using the quantize() operation using the given operand as the 5594 left-hand-operand, 1E+0 as the right-hand-operand, and the precision 5595 of the operand as the precision setting; Inexact and Rounded flags 5596 are allowed in this operation. The rounding mode is taken from the 5597 context. 5598 5599 >>> ExtendedContext.to_integral_exact(Decimal('2.1')) 5600 Decimal('2') 5601 >>> ExtendedContext.to_integral_exact(Decimal('100')) 5602 Decimal('100') 5603 >>> ExtendedContext.to_integral_exact(Decimal('100.0')) 5604 Decimal('100') 5605 >>> ExtendedContext.to_integral_exact(Decimal('101.5')) 5606 Decimal('102') 5607 >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) 5608 Decimal('-102') 5609 >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) 5610 Decimal('1.0E+6') 5611 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) 5612 Decimal('7.89E+77') 5613 >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) 5614 Decimal('-Infinity') 5615 """ 5616 a = _convert_other(a, raiseit=True) 5617 return a.to_integral_exact(context=self) 5618 5619 def to_integral_value(self, a): 5620 """Rounds to an integer. 5621 5622 When the operand has a negative exponent, the result is the same 5623 as using the quantize() operation using the given operand as the 5624 left-hand-operand, 1E+0 as the right-hand-operand, and the precision 5625 of the operand as the precision setting, except that no flags will 5626 be set. The rounding mode is taken from the context. 5627 5628 >>> ExtendedContext.to_integral_value(Decimal('2.1')) 5629 Decimal('2') 5630 >>> ExtendedContext.to_integral_value(Decimal('100')) 5631 Decimal('100') 5632 >>> ExtendedContext.to_integral_value(Decimal('100.0')) 5633 Decimal('100') 5634 >>> ExtendedContext.to_integral_value(Decimal('101.5')) 5635 Decimal('102') 5636 >>> ExtendedContext.to_integral_value(Decimal('-101.5')) 5637 Decimal('-102') 5638 >>> ExtendedContext.to_integral_value(Decimal('10E+5')) 5639 Decimal('1.0E+6') 5640 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77')) 5641 Decimal('7.89E+77') 5642 >>> ExtendedContext.to_integral_value(Decimal('-Inf')) 5643 Decimal('-Infinity') 5644 """ 5645 a = _convert_other(a, raiseit=True) 5646 return a.to_integral_value(context=self) 5647 5648 # the method name changed, but we provide also the old one, for compatibility 5649 to_integral = to_integral_value 5650 5651 class _WorkRep(object): 5652 __slots__ = ('sign','int','exp') 5653 # sign: 0 or 1 5654 # int: int 5655 # exp: None, int, or string 5656 5657 def __init__(self, value=None): 5658 if value is None: 5659 self.sign = None 5660 self.int = 0 5661 self.exp = None 5662 elif isinstance(value, Decimal): 5663 self.sign = value._sign 5664 self.int = int(value._int) 5665 self.exp = value._exp 5666 else: 5667 # assert isinstance(value, tuple) 5668 self.sign = value[0] 5669 self.int = value[1] 5670 self.exp = value[2] 5671 5672 def __repr__(self): 5673 return "(%r, %r, %r)" % (self.sign, self.int, self.exp) 5674 5675 __str__ = __repr__ 5676 5677 5678 5679 def _normalize(op1, op2, prec = 0): 5680 """Normalizes op1, op2 to have the same exp and length of coefficient. 5681 5682 Done during addition. 5683 """ 5684 if op1.exp < op2.exp: 5685 tmp = op2 5686 other = op1 5687 else: 5688 tmp = op1 5689 other = op2 5690 5691 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1). 5692 # Then adding 10**exp to tmp has the same effect (after rounding) 5693 # as adding any positive quantity smaller than 10**exp; similarly 5694 # for subtraction. So if other is smaller than 10**exp we replace 5695 # it with 10**exp. This avoids tmp.exp - other.exp getting too large. 5696 tmp_len = len(str(tmp.int)) 5697 other_len = len(str(other.int)) 5698 exp = tmp.exp + min(-1, tmp_len - prec - 2) 5699 if other_len + other.exp - 1 < exp: 5700 other.int = 1 5701 other.exp = exp 5702 5703 tmp.int *= 10 ** (tmp.exp - other.exp) 5704 tmp.exp = other.exp 5705 return op1, op2 5706 5707 ##### Integer arithmetic functions used by ln, log10, exp and __pow__ ##### 5708 5709 _nbits = int.bit_length 5710 5711 def _decimal_lshift_exact(n, e): 5712 """ Given integers n and e, return n * 10**e if it's an integer, else None. 5713 5714 The computation is designed to avoid computing large powers of 10 5715 unnecessarily. 5716 5717 >>> _decimal_lshift_exact(3, 4) 5718 30000 5719 >>> _decimal_lshift_exact(300, -999999999) # returns None 5720 5721 """ 5722 if n == 0: 5723 return 0 5724 elif e >= 0: 5725 return n * 10**e 5726 else: 5727 # val_n = largest power of 10 dividing n. 5728 str_n = str(abs(n)) 5729 val_n = len(str_n) - len(str_n.rstrip('0')) 5730 return None if val_n < -e else n // 10**-e 5731 5732 def _sqrt_nearest(n, a): 5733 """Closest integer to the square root of the positive integer n. a is 5734 an initial approximation to the square root. Any positive integer 5735 will do for a, but the closer a is to the square root of n the 5736 faster convergence will be. 5737 5738 """ 5739 if n <= 0 or a <= 0: 5740 raise ValueError("Both arguments to _sqrt_nearest should be positive.") 5741 5742 b=0 5743 while a != b: 5744 b, a = a, a--n//a>>1 5745 return a 5746 5747 def _rshift_nearest(x, shift): 5748 """Given an integer x and a nonnegative integer shift, return closest 5749 integer to x / 2**shift; use round-to-even in case of a tie. 5750 5751 """ 5752 b, q = 1 << shift, x >> shift 5753 return q + (2*(x & (b-1)) + (q&1) > b) 5754 5755 def _div_nearest(a, b): 5756 """Closest integer to a/b, a and b positive integers; rounds to even 5757 in the case of a tie. 5758 5759 """ 5760 q, r = divmod(a, b) 5761 return q + (2*r + (q&1) > b) 5762 5763 def _ilog(x, M, L = 8): 5764 """Integer approximation to M*log(x/M), with absolute error boundable 5765 in terms only of x/M. 5766 5767 Given positive integers x and M, return an integer approximation to 5768 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference 5769 between the approximation and the exact result is at most 22. For 5770 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In 5771 both cases these are upper bounds on the error; it will usually be 5772 much smaller.""" 5773 5774 # The basic algorithm is the following: let log1p be the function 5775 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use 5776 # the reduction 5777 # 5778 # log1p(y) = 2*log1p(y/(1+sqrt(1+y))) 5779 # 5780 # repeatedly until the argument to log1p is small (< 2**-L in 5781 # absolute value). For small y we can use the Taylor series 5782 # expansion 5783 # 5784 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T 5785 # 5786 # truncating at T such that y**T is small enough. The whole 5787 # computation is carried out in a form of fixed-point arithmetic, 5788 # with a real number z being represented by an integer 5789 # approximation to z*M. To avoid loss of precision, the y below 5790 # is actually an integer approximation to 2**R*y*M, where R is the 5791 # number of reductions performed so far. 5792 5793 y = x-M 5794 # argument reduction; R = number of reductions performed 5795 R = 0 5796 while (R <= L and abs(y) << L-R >= M or 5797 R > L and abs(y) >> R-L >= M): 5798 y = _div_nearest((M*y) << 1, 5799 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M)) 5800 R += 1 5801 5802 # Taylor series with T terms 5803 T = -int(-10*len(str(M))//(3*L)) 5804 yshift = _rshift_nearest(y, R) 5805 w = _div_nearest(M, T) 5806 for k in range(T-1, 0, -1): 5807 w = _div_nearest(M, k) - _div_nearest(yshift*w, M) 5808 5809 return _div_nearest(w*y, M) 5810 5811 def _dlog10(c, e, p): 5812 """Given integers c, e and p with c > 0, p >= 0, compute an integer 5813 approximation to 10**p * log10(c*10**e), with an absolute error of 5814 at most 1. Assumes that c*10**e is not exactly 1.""" 5815 5816 # increase precision by 2; compensate for this by dividing 5817 # final result by 100 5818 p += 2 5819 5820 # write c*10**e as d*10**f with either: 5821 # f >= 0 and 1 <= d <= 10, or 5822 # f <= 0 and 0.1 <= d <= 1. 5823 # Thus for c*10**e close to 1, f = 0 5824 l = len(str(c)) 5825 f = e+l - (e+l >= 1) 5826 5827 if p > 0: 5828 M = 10**p 5829 k = e+p-f 5830 if k >= 0: 5831 c *= 10**k 5832 else: 5833 c = _div_nearest(c, 10**-k) 5834 5835 log_d = _ilog(c, M) # error < 5 + 22 = 27 5836 log_10 = _log10_digits(p) # error < 1 5837 log_d = _div_nearest(log_d*M, log_10) 5838 log_tenpower = f*M # exact 5839 else: 5840 log_d = 0 # error < 2.31 5841 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5 5842 5843 return _div_nearest(log_tenpower+log_d, 100) 5844 5845 def _dlog(c, e, p): 5846 """Given integers c, e and p with c > 0, compute an integer 5847 approximation to 10**p * log(c*10**e), with an absolute error of 5848 at most 1. Assumes that c*10**e is not exactly 1.""" 5849 5850 # Increase precision by 2. The precision increase is compensated 5851 # for at the end with a division by 100. 5852 p += 2 5853 5854 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10, 5855 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e) 5856 # as 10**p * log(d) + 10**p*f * log(10). 5857 l = len(str(c)) 5858 f = e+l - (e+l >= 1) 5859 5860 # compute approximation to 10**p*log(d), with error < 27 5861 if p > 0: 5862 k = e+p-f 5863 if k >= 0: 5864 c *= 10**k 5865 else: 5866 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c 5867 5868 # _ilog magnifies existing error in c by a factor of at most 10 5869 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27 5870 else: 5871 # p <= 0: just approximate the whole thing by 0; error < 2.31 5872 log_d = 0 5873 5874 # compute approximation to f*10**p*log(10), with error < 11. 5875 if f: 5876 extra = len(str(abs(f)))-1 5877 if p + extra >= 0: 5878 # error in f * _log10_digits(p+extra) < |f| * 1 = |f| 5879 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11 5880 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra) 5881 else: 5882 f_log_ten = 0 5883 else: 5884 f_log_ten = 0 5885 5886 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1 5887 return _div_nearest(f_log_ten + log_d, 100) 5888 5889 class _Log10Memoize(object): 5890 """Class to compute, store, and allow retrieval of, digits of the 5891 constant log(10) = 2.302585.... This constant is needed by 5892 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__.""" 5893 def __init__(self): 5894 self.digits = "23025850929940456840179914546843642076011014886" 5895 5896 def getdigits(self, p): 5897 """Given an integer p >= 0, return floor(10**p)*log(10). 5898 5899 For example, self.getdigits(3) returns 2302. 5900 """ 5901 # digits are stored as a string, for quick conversion to 5902 # integer in the case that we've already computed enough 5903 # digits; the stored digits should always be correct 5904 # (truncated, not rounded to nearest). 5905 if p < 0: 5906 raise ValueError("p should be nonnegative") 5907 5908 if p >= len(self.digits): 5909 # compute p+3, p+6, p+9, ... digits; continue until at 5910 # least one of the extra digits is nonzero 5911 extra = 3 5912 while True: 5913 # compute p+extra digits, correct to within 1ulp 5914 M = 10**(p+extra+2) 5915 digits = str(_div_nearest(_ilog(10*M, M), 100)) 5916 if digits[-extra:] != '0'*extra: 5917 break 5918 extra += 3 5919 # keep all reliable digits so far; remove trailing zeros 5920 # and next nonzero digit 5921 self.digits = digits.rstrip('0')[:-1] 5922 return int(self.digits[:p+1]) 5923 5924 _log10_digits = _Log10Memoize().getdigits 5925 5926 def _iexp(x, M, L=8): 5927 """Given integers x and M, M > 0, such that x/M is small in absolute 5928 value, compute an integer approximation to M*exp(x/M). For 0 <= 5929 x/M <= 2.4, the absolute error in the result is bounded by 60 (and 5930 is usually much smaller).""" 5931 5932 # Algorithm: to compute exp(z) for a real number z, first divide z 5933 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then 5934 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor 5935 # series 5936 # 5937 # expm1(x) = x + x**2/2! + x**3/3! + ... 5938 # 5939 # Now use the identity 5940 # 5941 # expm1(2x) = expm1(x)*(expm1(x)+2) 5942 # 5943 # R times to compute the sequence expm1(z/2**R), 5944 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z). 5945 5946 # Find R such that x/2**R/M <= 2**-L 5947 R = _nbits((x<<L)//M) 5948 5949 # Taylor series. (2**L)**T > M 5950 T = -int(-10*len(str(M))//(3*L)) 5951 y = _div_nearest(x, T) 5952 Mshift = M<<R 5953 for i in range(T-1, 0, -1): 5954 y = _div_nearest(x*(Mshift + y), Mshift * i) 5955 5956 # Expansion 5957 for k in range(R-1, -1, -1): 5958 Mshift = M<<(k+2) 5959 y = _div_nearest(y*(y+Mshift), Mshift) 5960 5961 return M+y 5962 5963 def _dexp(c, e, p): 5964 """Compute an approximation to exp(c*10**e), with p decimal places of 5965 precision. 5966 5967 Returns integers d, f such that: 5968 5969 10**(p-1) <= d <= 10**p, and 5970 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f 5971 5972 In other words, d*10**f is an approximation to exp(c*10**e) with p 5973 digits of precision, and with an error in d of at most 1. This is 5974 almost, but not quite, the same as the error being < 1ulp: when d 5975 = 10**(p-1) the error could be up to 10 ulp.""" 5976 5977 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision 5978 p += 2 5979 5980 # compute log(10) with extra precision = adjusted exponent of c*10**e 5981 extra = max(0, e + len(str(c)) - 1) 5982 q = p + extra 5983 5984 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q), 5985 # rounding down 5986 shift = e+q 5987 if shift >= 0: 5988 cshift = c*10**shift 5989 else: 5990 cshift = c//10**-shift 5991 quot, rem = divmod(cshift, _log10_digits(q)) 5992 5993 # reduce remainder back to original precision 5994 rem = _div_nearest(rem, 10**extra) 5995 5996 # error in result of _iexp < 120; error after division < 0.62 5997 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3 5998 5999 def _dpower(xc, xe, yc, ye, p): 6000 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and 6001 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: 6002 6003 10**(p-1) <= c <= 10**p, and 6004 (c-1)*10**e < x**y < (c+1)*10**e 6005 6006 in other words, c*10**e is an approximation to x**y with p digits 6007 of precision, and with an error in c of at most 1. (This is 6008 almost, but not quite, the same as the error being < 1ulp: when c 6009 == 10**(p-1) we can only guarantee error < 10ulp.) 6010 6011 We assume that: x is positive and not equal to 1, and y is nonzero. 6012 """ 6013 6014 # Find b such that 10**(b-1) <= |y| <= 10**b 6015 b = len(str(abs(yc))) + ye 6016 6017 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point 6018 lxc = _dlog(xc, xe, p+b+1) 6019 6020 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1) 6021 shift = ye-b 6022 if shift >= 0: 6023 pc = lxc*yc*10**shift 6024 else: 6025 pc = _div_nearest(lxc*yc, 10**-shift) 6026 6027 if pc == 0: 6028 # we prefer a result that isn't exactly 1; this makes it 6029 # easier to compute a correctly rounded result in __pow__ 6030 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1: 6031 coeff, exp = 10**(p-1)+1, 1-p 6032 else: 6033 coeff, exp = 10**p-1, -p 6034 else: 6035 coeff, exp = _dexp(pc, -(p+1), p+1) 6036 coeff = _div_nearest(coeff, 10) 6037 exp += 1 6038 6039 return coeff, exp 6040 6041 def _log10_lb(c, correction = { 6042 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31, 6043 '6': 23, '7': 16, '8': 10, '9': 5}): 6044 """Compute a lower bound for 100*log10(c) for a positive integer c.""" 6045 if c <= 0: 6046 raise ValueError("The argument to _log10_lb should be nonnegative.") 6047 str_c = str(c) 6048 return 100*len(str_c) - correction[str_c[0]] 6049 6050 ##### Helper Functions #################################################### 6051 6052 def _convert_other(other, raiseit=False, allow_float=False): 6053 """Convert other to Decimal. 6054 6055 Verifies that it's ok to use in an implicit construction. 6056 If allow_float is true, allow conversion from float; this 6057 is used in the comparison methods (__eq__ and friends). 6058 6059 """ 6060 if isinstance(other, Decimal): 6061 return other 6062 if isinstance(other, int): 6063 return Decimal(other) 6064 if allow_float and isinstance(other, float): 6065 return Decimal.from_float(other) 6066 6067 if raiseit: 6068 raise TypeError("Unable to convert %s to Decimal" % other) 6069 return NotImplemented 6070 6071 def _convert_for_comparison(self, other, equality_op=False): 6072 """Given a Decimal instance self and a Python object other, return 6073 a pair (s, o) of Decimal instances such that "s op o" is 6074 equivalent to "self op other" for any of the 6 comparison 6075 operators "op". 6076 6077 """ 6078 if isinstance(other, Decimal): 6079 return self, other 6080 6081 # Comparison with a Rational instance (also includes integers): 6082 # self op n/d <=> self*d op n (for n and d integers, d positive). 6083 # A NaN or infinity can be left unchanged without affecting the 6084 # comparison result. 6085 if isinstance(other, _numbers.Rational): 6086 if not self._is_special: 6087 self = _dec_from_triple(self._sign, 6088 str(int(self._int) * other.denominator), 6089 self._exp) 6090 return self, Decimal(other.numerator) 6091 6092 # Comparisons with float and complex types. == and != comparisons 6093 # with complex numbers should succeed, returning either True or False 6094 # as appropriate. Other comparisons return NotImplemented. 6095 if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0: 6096 other = other.real 6097 if isinstance(other, float): 6098 context = getcontext() 6099 if equality_op: 6100 context.flags[FloatOperation] = 1 6101 else: 6102 context._raise_error(FloatOperation, 6103 "strict semantics for mixing floats and Decimals are enabled") 6104 return self, Decimal.from_float(other) 6105 return NotImplemented, NotImplemented 6106 6107 6108 ##### Setup Specific Contexts ############################################ 6109 6110 # The default context prototype used by Context() 6111 # Is mutable, so that new contexts can have different default values 6112 6113 DefaultContext = Context( 6114 prec=28, rounding=ROUND_HALF_EVEN, 6115 traps=[DivisionByZero, Overflow, InvalidOperation], 6116 flags=[], 6117 Emax=999999, 6118 Emin=-999999, 6119 capitals=1, 6120 clamp=0 6121 ) 6122 6123 # Pre-made alternate contexts offered by the specification 6124 # Don't change these; the user should be able to select these 6125 # contexts and be able to reproduce results from other implementations 6126 # of the spec. 6127 6128 BasicContext = Context( 6129 prec=9, rounding=ROUND_HALF_UP, 6130 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow], 6131 flags=[], 6132 ) 6133 6134 ExtendedContext = Context( 6135 prec=9, rounding=ROUND_HALF_EVEN, 6136 traps=[], 6137 flags=[], 6138 ) 6139 6140 6141 ##### crud for parsing strings ############################################# 6142 # 6143 # Regular expression used for parsing numeric strings. Additional 6144 # comments: 6145 # 6146 # 1. Uncomment the two '\s*' lines to allow leading and/or trailing 6147 # whitespace. But note that the specification disallows whitespace in 6148 # a numeric string. 6149 # 6150 # 2. For finite numbers (not infinities and NaNs) the body of the 6151 # number between the optional sign and the optional exponent must have 6152 # at least one decimal digit, possibly after the decimal point. The 6153 # lookahead expression '(?=\d|\.\d)' checks this. 6154 6155 import re 6156 _parser = re.compile(r""" # A numeric string consists of: 6157 # \s* 6158 (?P<sign>[-+])? # an optional sign, followed by either... 6159 ( 6160 (?=\d|\.\d) # ...a number (with at least one digit) 6161 (?P<int>\d*) # having a (possibly empty) integer part 6162 (\.(?P<frac>\d*))? # followed by an optional fractional part 6163 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or... 6164 | 6165 Inf(inity)? # ...an infinity, or... 6166 | 6167 (?P<signal>s)? # ...an (optionally signaling) 6168 NaN # NaN 6169 (?P<diag>\d*) # with (possibly empty) diagnostic info. 6170 ) 6171 # \s* 6172 \Z 6173 """, re.VERBOSE | re.IGNORECASE).match 6174 6175 _all_zeros = re.compile('0*$').match 6176 _exact_half = re.compile('50*$').match 6177 6178 ##### PEP3101 support functions ############################################## 6179 # The functions in this section have little to do with the Decimal 6180 # class, and could potentially be reused or adapted for other pure 6181 # Python numeric classes that want to implement __format__ 6182 # 6183 # A format specifier for Decimal looks like: 6184 # 6185 # [[fill]align][sign][#][0][minimumwidth][,][.precision][type] 6186 6187 _parse_format_specifier_regex = re.compile(r"""\A 6188 (?: 6189 (?P<fill>.)? 6190 (?P<align>[<>=^]) 6191 )? 6192 (?P<sign>[-+ ])? 6193 (?P<alt>\#)? 6194 (?P<zeropad>0)? 6195 (?P<minimumwidth>(?!0)\d+)? 6196 (?P<thousands_sep>,)? 6197 (?:\.(?P<precision>0|(?!0)\d+))? 6198 (?P<type>[eEfFgGn%])? 6199 \Z 6200 """, re.VERBOSE|re.DOTALL) 6201 6202 del re 6203 6204 # The locale module is only needed for the 'n' format specifier. The 6205 # rest of the PEP 3101 code functions quite happily without it, so we 6206 # don't care too much if locale isn't present. 6207 try: 6208 import locale as _locale 6209 except ImportError: 6210 pass 6211 6212 def _parse_format_specifier(format_spec, _localeconv=None): 6213 """Parse and validate a format specifier. 6214 6215 Turns a standard numeric format specifier into a dict, with the 6216 following entries: 6217 6218 fill: fill character to pad field to minimum width 6219 align: alignment type, either '<', '>', '=' or '^' 6220 sign: either '+', '-' or ' ' 6221 minimumwidth: nonnegative integer giving minimum width 6222 zeropad: boolean, indicating whether to pad with zeros 6223 thousands_sep: string to use as thousands separator, or '' 6224 grouping: grouping for thousands separators, in format 6225 used by localeconv 6226 decimal_point: string to use for decimal point 6227 precision: nonnegative integer giving precision, or None 6228 type: one of the characters 'eEfFgG%', or None 6229 6230 """ 6231 m = _parse_format_specifier_regex.match(format_spec) 6232 if m is None: 6233 raise ValueError("Invalid format specifier: " + format_spec) 6234 6235 # get the dictionary 6236 format_dict = m.groupdict() 6237 6238 # zeropad; defaults for fill and alignment. If zero padding 6239 # is requested, the fill and align fields should be absent. 6240 fill = format_dict['fill'] 6241 align = format_dict['align'] 6242 format_dict['zeropad'] = (format_dict['zeropad'] is not None) 6243 if format_dict['zeropad']: 6244 if fill is not None: 6245 raise ValueError("Fill character conflicts with '0'" 6246 " in format specifier: " + format_spec) 6247 if align is not None: 6248 raise ValueError("Alignment conflicts with '0' in " 6249 "format specifier: " + format_spec) 6250 format_dict['fill'] = fill or ' ' 6251 # PEP 3101 originally specified that the default alignment should 6252 # be left; it was later agreed that right-aligned makes more sense 6253 # for numeric types. See http://bugs.python.org/issue6857. 6254 format_dict['align'] = align or '>' 6255 6256 # default sign handling: '-' for negative, '' for positive 6257 if format_dict['sign'] is None: 6258 format_dict['sign'] = '-' 6259 6260 # minimumwidth defaults to 0; precision remains None if not given 6261 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0') 6262 if format_dict['precision'] is not None: 6263 format_dict['precision'] = int(format_dict['precision']) 6264 6265 # if format type is 'g' or 'G' then a precision of 0 makes little 6266 # sense; convert it to 1. Same if format type is unspecified. 6267 if format_dict['precision'] == 0: 6268 if format_dict['type'] is None or format_dict['type'] in 'gGn': 6269 format_dict['precision'] = 1 6270 6271 # determine thousands separator, grouping, and decimal separator, and 6272 # add appropriate entries to format_dict 6273 if format_dict['type'] == 'n': 6274 # apart from separators, 'n' behaves just like 'g' 6275 format_dict['type'] = 'g' 6276 if _localeconv is None: 6277 _localeconv = _locale.localeconv() 6278 if format_dict['thousands_sep'] is not None: 6279 raise ValueError("Explicit thousands separator conflicts with " 6280 "'n' type in format specifier: " + format_spec) 6281 format_dict['thousands_sep'] = _localeconv['thousands_sep'] 6282 format_dict['grouping'] = _localeconv['grouping'] 6283 format_dict['decimal_point'] = _localeconv['decimal_point'] 6284 else: 6285 if format_dict['thousands_sep'] is None: 6286 format_dict['thousands_sep'] = '' 6287 format_dict['grouping'] = [3, 0] 6288 format_dict['decimal_point'] = '.' 6289 6290 return format_dict 6291 6292 def _format_align(sign, body, spec): 6293 """Given an unpadded, non-aligned numeric string 'body' and sign 6294 string 'sign', add padding and alignment conforming to the given 6295 format specifier dictionary 'spec' (as produced by 6296 parse_format_specifier). 6297 6298 """ 6299 # how much extra space do we have to play with? 6300 minimumwidth = spec['minimumwidth'] 6301 fill = spec['fill'] 6302 padding = fill*(minimumwidth - len(sign) - len(body)) 6303 6304 align = spec['align'] 6305 if align == '<': 6306 result = sign + body + padding 6307 elif align == '>': 6308 result = padding + sign + body 6309 elif align == '=': 6310 result = sign + padding + body 6311 elif align == '^': 6312 half = len(padding)//2 6313 result = padding[:half] + sign + body + padding[half:] 6314 else: 6315 raise ValueError('Unrecognised alignment field') 6316 6317 return result 6318 6319 def _group_lengths(grouping): 6320 """Convert a localeconv-style grouping into a (possibly infinite) 6321 iterable of integers representing group lengths. 6322 6323 """ 6324 # The result from localeconv()['grouping'], and the input to this 6325 # function, should be a list of integers in one of the 6326 # following three forms: 6327 # 6328 # (1) an empty list, or 6329 # (2) nonempty list of positive integers + [0] 6330 # (3) list of positive integers + [locale.CHAR_MAX], or 6331 6332 from itertools import chain, repeat 6333 if not grouping: 6334 return [] 6335 elif grouping[-1] == 0 and len(grouping) >= 2: 6336 return chain(grouping[:-1], repeat(grouping[-2])) 6337 elif grouping[-1] == _locale.CHAR_MAX: 6338 return grouping[:-1] 6339 else: 6340 raise ValueError('unrecognised format for grouping') 6341 6342 def _insert_thousands_sep(digits, spec, min_width=1): 6343 """Insert thousands separators into a digit string. 6344 6345 spec is a dictionary whose keys should include 'thousands_sep' and 6346 'grouping'; typically it's the result of parsing the format 6347 specifier using _parse_format_specifier. 6348 6349 The min_width keyword argument gives the minimum length of the 6350 result, which will be padded on the left with zeros if necessary. 6351 6352 If necessary, the zero padding adds an extra '0' on the left to 6353 avoid a leading thousands separator. For example, inserting 6354 commas every three digits in '123456', with min_width=8, gives 6355 '0,123,456', even though that has length 9. 6356 6357 """ 6358 6359 sep = spec['thousands_sep'] 6360 grouping = spec['grouping'] 6361 6362 groups = [] 6363 for l in _group_lengths(grouping): 6364 if l <= 0: 6365 raise ValueError("group length should be positive") 6366 # max(..., 1) forces at least 1 digit to the left of a separator 6367 l = min(max(len(digits), min_width, 1), l) 6368 groups.append('0'*(l - len(digits)) + digits[-l:]) 6369 digits = digits[:-l] 6370 min_width -= l 6371 if not digits and min_width <= 0: 6372 break 6373 min_width -= len(sep) 6374 else: 6375 l = max(len(digits), min_width, 1) 6376 groups.append('0'*(l - len(digits)) + digits[-l:]) 6377 return sep.join(reversed(groups)) 6378 6379 def _format_sign(is_negative, spec): 6380 """Determine sign character.""" 6381 6382 if is_negative: 6383 return '-' 6384 elif spec['sign'] in ' +': 6385 return spec['sign'] 6386 else: 6387 return '' 6388 6389 def _format_number(is_negative, intpart, fracpart, exp, spec): 6390 """Format a number, given the following data: 6391 6392 is_negative: true if the number is negative, else false 6393 intpart: string of digits that must appear before the decimal point 6394 fracpart: string of digits that must come after the point 6395 exp: exponent, as an integer 6396 spec: dictionary resulting from parsing the format specifier 6397 6398 This function uses the information in spec to: 6399 insert separators (decimal separator and thousands separators) 6400 format the sign 6401 format the exponent 6402 add trailing '%' for the '%' type 6403 zero-pad if necessary 6404 fill and align if necessary 6405 """ 6406 6407 sign = _format_sign(is_negative, spec) 6408 6409 if fracpart or spec['alt']: 6410 fracpart = spec['decimal_point'] + fracpart 6411 6412 if exp != 0 or spec['type'] in 'eE': 6413 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']] 6414 fracpart += "{0}{1:+}".format(echar, exp) 6415 if spec['type'] == '%': 6416 fracpart += '%' 6417 6418 if spec['zeropad']: 6419 min_width = spec['minimumwidth'] - len(fracpart) - len(sign) 6420 else: 6421 min_width = 0 6422 intpart = _insert_thousands_sep(intpart, spec, min_width) 6423 6424 return _format_align(sign, intpart+fracpart, spec) 6425 6426 6427 ##### Useful Constants (internal use only) ################################ 6428 6429 # Reusable defaults 6430 _Infinity = Decimal('Inf') 6431 _NegativeInfinity = Decimal('-Inf') 6432 _NaN = Decimal('NaN') 6433 _Zero = Decimal(0) 6434 _One = Decimal(1) 6435 _NegativeOne = Decimal(-1) 6436 6437 # _SignedInfinity[sign] is infinity w/ that sign 6438 _SignedInfinity = (_Infinity, _NegativeInfinity) 6439 6440 # Constants related to the hash implementation; hash(x) is based 6441 # on the reduction of x modulo _PyHASH_MODULUS 6442 _PyHASH_MODULUS = sys.hash_info.modulus 6443 # hash values to use for positive and negative infinities, and nans 6444 _PyHASH_INF = sys.hash_info.inf 6445 _PyHASH_NAN = sys.hash_info.nan 6446 6447 # _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS 6448 _PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS) 6449 del sys 6450