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