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