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