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