[FIX] the cache key is sorted using, items keys, avoiding to compare items values
[odoo/odoo.git] / bin / tools / decimal.py
1 # -*- encoding: utf-8 -*-
2 # Copyright (c) 2004 Python Software Foundation.
3 # All rights reserved.
4
5 # Written by Eric Price <eprice at tjhsst.edu>
6 #    and Facundo Batista <facundo at taniquetil.com.ar>
7 #    and Raymond Hettinger <python at rcn.com>
8 #    and Aahz <aahz at pobox.com>
9 #    and Tim Peters
10
11 # This module is currently Py2.3 compatible and should be kept that way
12 # unless a major compelling advantage arises.  IOW, 2.3 compatibility is
13 # strongly preferred, but not guaranteed.
14
15 # Also, this module should be kept in sync with the latest updates of
16 # the IBM specification as it evolves.  Those updates will be treated
17 # as bug fixes (deviation from the spec is a compatibility, usability
18 # bug) and will be backported.  At this point the spec is stabilizing
19 # and the updates are becoming fewer, smaller, and less significant.
20
21 """
22 This is a Py2.3 implementation of decimal floating point arithmetic based on
23 the General Decimal Arithmetic Specification:
24
25     www2.hursley.ibm.com/decimal/decarith.html
26
27 and IEEE standard 854-1987:
28
29     www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
30
31 Decimal floating point has finite precision with arbitrarily large bounds.
32
33 The purpose of the module is to support arithmetic using familiar
34 "schoolhouse" rules and to avoid the some of tricky representation
35 issues associated with binary floating point.  The package is especially
36 useful for financial applications or for contexts where users have
37 expectations that are at odds with binary floating point (for instance,
38 in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
39 of the expected Decimal("0.00") returned by decimal floating point).
40
41 Here are some examples of using the decimal module:
42
43 >>> from decimal import *
44 >>> setcontext(ExtendedContext)
45 >>> Decimal(0)
46 Decimal("0")
47 >>> Decimal("1")
48 Decimal("1")
49 >>> Decimal("-.0123")
50 Decimal("-0.0123")
51 >>> Decimal(123456)
52 Decimal("123456")
53 >>> Decimal("123.45e12345678901234567890")
54 Decimal("1.2345E+12345678901234567892")
55 >>> Decimal("1.33") + Decimal("1.27")
56 Decimal("2.60")
57 >>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
58 Decimal("-2.20")
59 >>> dig = Decimal(1)
60 >>> print dig / Decimal(3)
61 0.333333333
62 >>> getcontext().prec = 18
63 >>> print dig / Decimal(3)
64 0.333333333333333333
65 >>> print dig.sqrt()
66 1
67 >>> print Decimal(3).sqrt()
68 1.73205080756887729
69 >>> print Decimal(3) ** 123
70 4.85192780976896427E+58
71 >>> inf = Decimal(1) / Decimal(0)
72 >>> print inf
73 Infinity
74 >>> neginf = Decimal(-1) / Decimal(0)
75 >>> print neginf
76 -Infinity
77 >>> print neginf + inf
78 NaN
79 >>> print neginf * inf
80 -Infinity
81 >>> print dig / 0
82 Infinity
83 >>> getcontext().traps[DivisionByZero] = 1
84 >>> print dig / 0
85 Traceback (most recent call last):
86   ...
87   ...
88   ...
89 DivisionByZero: x / 0
90 >>> c = Context()
91 >>> c.traps[InvalidOperation] = 0
92 >>> print c.flags[InvalidOperation]
93 0
94 >>> c.divide(Decimal(0), Decimal(0))
95 Decimal("NaN")
96 >>> c.traps[InvalidOperation] = 1
97 >>> print c.flags[InvalidOperation]
98 1
99 >>> c.flags[InvalidOperation] = 0
100 >>> print c.flags[InvalidOperation]
101 0
102 >>> print c.divide(Decimal(0), Decimal(0))
103 Traceback (most recent call last):
104   ...
105   ...
106   ...
107 InvalidOperation: 0 / 0
108 >>> print c.flags[InvalidOperation]
109 1
110 >>> c.flags[InvalidOperation] = 0
111 >>> c.traps[InvalidOperation] = 0
112 >>> print c.divide(Decimal(0), Decimal(0))
113 NaN
114 >>> print c.flags[InvalidOperation]
115 1
116 >>>
117 """
118
119 __all__ = [
120     # Two major classes
121     'Decimal', 'Context',
122
123     # Contexts
124     'DefaultContext', 'BasicContext', 'ExtendedContext',
125
126     # Exceptions
127     'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
128     'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
129
130     # Constants for use in setting up contexts
131     'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
132     'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN',
133
134     # Functions for manipulating contexts
135     'setcontext', 'getcontext'
136 ]
137
138 import copy as _copy
139
140 #Rounding
141 ROUND_DOWN = 'ROUND_DOWN'
142 ROUND_HALF_UP = 'ROUND_HALF_UP'
143 ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
144 ROUND_CEILING = 'ROUND_CEILING'
145 ROUND_FLOOR = 'ROUND_FLOOR'
146 ROUND_UP = 'ROUND_UP'
147 ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
148
149 #Rounding decision (not part of the public API)
150 NEVER_ROUND = 'NEVER_ROUND'    # Round in division (non-divmod), sqrt ONLY
151 ALWAYS_ROUND = 'ALWAYS_ROUND'  # Every operation rounds at end.
152
153 #Errors
154
155 class DecimalException(ArithmeticError):
156     """Base exception class.
157
158     Used exceptions derive from this.
159     If an exception derives from another exception besides this (such as
160     Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
161     called if the others are present.  This isn't actually used for
162     anything, though.
163
164     handle  -- Called when context._raise_error is called and the
165                trap_enabler is set.  First argument is self, second is the
166                context.  More arguments can be given, those being after
167                the explanation in _raise_error (For example,
168                context._raise_error(NewError, '(-x)!', self._sign) would
169                call NewError().handle(context, self._sign).)
170
171     To define a new exception, it should be sufficient to have it derive
172     from DecimalException.
173     """
174     def handle(self, context, *args):
175         pass
176
177
178 class Clamped(DecimalException):
179     """Exponent of a 0 changed to fit bounds.
180
181     This occurs and signals clamped if the exponent of a result has been
182     altered in order to fit the constraints of a specific concrete
183     representation. This may occur when the exponent of a zero result would
184     be outside the bounds of a representation, or  when a large normal
185     number would have an encoded exponent that cannot be represented. In
186     this latter case, the exponent is reduced to fit and the corresponding
187     number of zero digits are appended to the coefficient ("fold-down").
188     """
189
190
191 class InvalidOperation(DecimalException):
192     """An invalid operation was performed.
193
194     Various bad things cause this:
195
196     Something creates a signaling NaN
197     -INF + INF
198      0 * (+-)INF
199      (+-)INF / (+-)INF
200     x % 0
201     (+-)INF % x
202     x._rescale( non-integer )
203     sqrt(-x) , x > 0
204     0 ** 0
205     x ** (non-integer)
206     x ** (+-)INF
207     An operand is invalid
208     """
209     def handle(self, context, *args):
210         if args:
211             if args[0] == 1: #sNaN, must drop 's' but keep diagnostics
212                 return Decimal( (args[1]._sign, args[1]._int, 'n') )
213         return NaN
214
215 class 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
223     def handle(self, context, *args):
224         return (0, (0,), 'n') #Passed to something which uses a tuple.
225
226 class DivisionByZero(DecimalException, ZeroDivisionError):
227     """Division by 0.
228
229     This occurs and signals division-by-zero if division of a finite number
230     by zero was attempted (during a divide-integer or divide operation, or a
231     power operation with negative right-hand operand), and the dividend was
232     not zero.
233
234     The result of the operation is [sign,inf], where sign is the exclusive
235     or of the signs of the operands for divide, or is 1 for an odd power of
236     -0, for power.
237     """
238
239     def handle(self, context, sign, double = None, *args):
240         if double is not None:
241             return (Infsign[sign],)*2
242         return Infsign[sign]
243
244 class DivisionImpossible(InvalidOperation):
245     """Cannot perform the division adequately.
246
247     This occurs and signals invalid-operation if the integer result of a
248     divide-integer or remainder operation had too many digits (would be
249     longer than precision). The result is [0,qNaN].
250     """
251
252     def handle(self, context, *args):
253         return (NaN, NaN)
254
255 class DivisionUndefined(InvalidOperation, ZeroDivisionError):
256     """Undefined result of division.
257
258     This occurs and signals invalid-operation if division by zero was
259     attempted (during a divide-integer, divide, or remainder operation), and
260     the dividend is also zero. The result is [0,qNaN].
261     """
262
263     def handle(self, context, tup=None, *args):
264         if tup is not None:
265             return (NaN, NaN) #for 0 %0, 0 // 0
266         return NaN
267
268 class Inexact(DecimalException):
269     """Had to round, losing information.
270
271     This occurs and signals inexact whenever the result of an operation is
272     not exact (that is, it needed to be rounded and any discarded digits
273     were non-zero), or if an overflow or underflow condition occurs. The
274     result in all cases is unchanged.
275
276     The inexact signal may be tested (or trapped) to determine if a given
277     operation (or sequence of operations) was inexact.
278     """
279     pass
280
281 class InvalidContext(InvalidOperation):
282     """Invalid context.  Unknown rounding, for example.
283
284     This occurs and signals invalid-operation if an invalid context was
285     detected during an operation. This can occur if contexts are not checked
286     on creation and either the precision exceeds the capability of the
287     underlying concrete representation or an unknown or unsupported rounding
288     was specified. These aspects of the context need only be checked when
289     the values are required to be used. The result is [0,qNaN].
290     """
291
292     def handle(self, context, *args):
293         return NaN
294
295 class Rounded(DecimalException):
296     """Number got rounded (not  necessarily changed during rounding).
297
298     This occurs and signals rounded whenever the result of an operation is
299     rounded (that is, some zero or non-zero digits were discarded from the
300     coefficient), or if an overflow or underflow condition occurs. The
301     result in all cases is unchanged.
302
303     The rounded signal may be tested (or trapped) to determine if a given
304     operation (or sequence of operations) caused a loss of precision.
305     """
306     pass
307
308 class Subnormal(DecimalException):
309     """Exponent < Emin before rounding.
310
311     This occurs and signals subnormal whenever the result of a conversion or
312     operation is subnormal (that is, its adjusted exponent is less than
313     Emin, before any rounding). The result in all cases is unchanged.
314
315     The subnormal signal may be tested (or trapped) to determine if a given
316     or operation (or sequence of operations) yielded a subnormal result.
317     """
318     pass
319
320 class Overflow(Inexact, Rounded):
321     """Numerical overflow.
322
323     This occurs and signals overflow if the adjusted exponent of a result
324     (from a conversion or from an operation that is not an attempt to divide
325     by zero), after rounding, would be greater than the largest value that
326     can be handled by the implementation (the value Emax).
327
328     The result depends on the rounding mode:
329
330     For round-half-up and round-half-even (and for round-half-down and
331     round-up, if implemented), the result of the operation is [sign,inf],
332     where sign is the sign of the intermediate result. For round-down, the
333     result is the largest finite number that can be represented in the
334     current precision, with the sign of the intermediate result. For
335     round-ceiling, the result is the same as for round-down if the sign of
336     the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
337     the result is the same as for round-down if the sign of the intermediate
338     result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
339     will also be raised.
340    """
341
342     def handle(self, context, sign, *args):
343         if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
344                                      ROUND_HALF_DOWN, ROUND_UP):
345             return Infsign[sign]
346         if sign == 0:
347             if context.rounding == ROUND_CEILING:
348                 return Infsign[sign]
349             return Decimal((sign, (9,)*context.prec,
350                             context.Emax-context.prec+1))
351         if sign == 1:
352             if context.rounding == ROUND_FLOOR:
353                 return Infsign[sign]
354             return Decimal( (sign, (9,)*context.prec,
355                              context.Emax-context.prec+1))
356
357
358 class Underflow(Inexact, Rounded, Subnormal):
359     """Numerical underflow with result rounded to 0.
360
361     This occurs and signals underflow if a result is inexact and the
362     adjusted exponent of the result would be smaller (more negative) than
363     the smallest value that can be handled by the implementation (the value
364     Emin). That is, the result is both inexact and subnormal.
365
366     The result after an underflow will be a subnormal number rounded, if
367     necessary, so that its exponent is not less than Etiny. This may result
368     in 0 with the sign of the intermediate result and an exponent of Etiny.
369
370     In all cases, Inexact, Rounded, and Subnormal will also be raised.
371     """
372
373 # List of public traps and flags
374 _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
375            Underflow, InvalidOperation, Subnormal]
376
377 # Map conditions (per the spec) to signals
378 _condition_map = {ConversionSyntax:InvalidOperation,
379                   DivisionImpossible:InvalidOperation,
380                   DivisionUndefined:InvalidOperation,
381                   InvalidContext:InvalidOperation}
382
383 ##### Context Functions #######################################
384
385 # The getcontext() and setcontext() function manage access to a thread-local
386 # current context.  Py2.4 offers direct support for thread locals.  If that
387 # is not available, use threading.currentThread() which is slower but will
388 # work for older Pythons.  If threads are not part of the build, create a
389 # mock threading object with threading.local() returning the module namespace.
390
391 try:
392     import threading
393 except ImportError:
394     # Python was compiled without threads; create a mock object instead
395     import sys
396     class MockThreading:
397         def local(self, sys=sys):
398             return sys.modules[__name__]
399     threading = MockThreading()
400     del sys, MockThreading
401
402 try:
403     threading.local
404
405 except AttributeError:
406
407     #To fix reloading, force it to create a new context
408     #Old contexts have different exceptions in their dicts, making problems.
409     if hasattr(threading.currentThread(), '__decimal_context__'):
410         del threading.currentThread().__decimal_context__
411
412     def setcontext(context):
413         """Set this thread's context to context."""
414         if context in (DefaultContext, BasicContext, ExtendedContext):
415             context = context.copy()
416             context.clear_flags()
417         threading.currentThread().__decimal_context__ = context
418
419     def getcontext():
420         """Returns this thread's context.
421
422         If this thread does not yet have a context, returns
423         a new context and sets this thread's context.
424         New contexts are copies of DefaultContext.
425         """
426         try:
427             return threading.currentThread().__decimal_context__
428         except AttributeError:
429             context = Context()
430             threading.currentThread().__decimal_context__ = context
431             return context
432
433 else:
434
435     local = threading.local()
436     if hasattr(local, '__decimal_context__'):
437         del local.__decimal_context__
438
439     def getcontext(_local=local):
440         """Returns this thread's context.
441
442         If this thread does not yet have a context, returns
443         a new context and sets this thread's context.
444         New contexts are copies of DefaultContext.
445         """
446         try:
447             return _local.__decimal_context__
448         except AttributeError:
449             context = Context()
450             _local.__decimal_context__ = context
451             return context
452
453     def setcontext(context, _local=local):
454         """Set this thread's context to context."""
455         if context in (DefaultContext, BasicContext, ExtendedContext):
456             context = context.copy()
457             context.clear_flags()
458         _local.__decimal_context__ = context
459
460     del threading, local        # Don't contaminate the namespace
461
462
463 ##### Decimal class ###########################################
464
465 class Decimal(object):
466     """Floating point class for decimal arithmetic."""
467
468     __slots__ = ('_exp','_int','_sign', '_is_special')
469     # Generally, the value of the Decimal instance is given by
470     #  (-1)**_sign * _int * 10**_exp
471     # Special values are signified by _is_special == True
472
473     # We're immutable, so use __new__ not __init__
474     def __new__(cls, value="0", context=None):
475         """Create a decimal point instance.
476
477         >>> Decimal('3.14')              # string input
478         Decimal("3.14")
479         >>> Decimal((0, (3, 1, 4), -2))  # tuple input (sign, digit_tuple, exponent)
480         Decimal("3.14")
481         >>> Decimal(314)                 # int or long
482         Decimal("314")
483         >>> Decimal(Decimal(314))        # another decimal instance
484         Decimal("314")
485         """
486
487         self = object.__new__(cls)
488         self._is_special = False
489
490         # From an internal working value
491         if isinstance(value, _WorkRep):
492             self._sign = value.sign
493             self._int = tuple(map(int, str(value.int)))
494             self._exp = int(value.exp)
495             return self
496
497         # From another decimal
498         if isinstance(value, Decimal):
499             self._exp  = value._exp
500             self._sign = value._sign
501             self._int  = value._int
502             self._is_special  = value._is_special
503             return self
504
505         # From an integer
506         if isinstance(value, (int,long)):
507             if value >= 0:
508                 self._sign = 0
509             else:
510                 self._sign = 1
511             self._exp = 0
512             self._int = tuple(map(int, str(abs(value))))
513             return self
514
515         # tuple/list conversion (possibly from as_tuple())
516         if isinstance(value, (list,tuple)):
517             if len(value) != 3:
518                 raise ValueError, 'Invalid arguments'
519             if value[0] not in (0,1):
520                 raise ValueError, 'Invalid sign'
521             for digit in value[1]:
522                 if not isinstance(digit, (int,long)) or digit < 0:
523                     raise ValueError, "The second value in the tuple must be composed of non negative integer elements."
524
525             self._sign = value[0]
526             self._int  = tuple(value[1])
527             if value[2] in ('F','n','N'):
528                 self._exp = value[2]
529                 self._is_special = True
530             else:
531                 self._exp  = int(value[2])
532             return self
533
534         if isinstance(value, float):
535             raise TypeError("Cannot convert float to Decimal.  " +
536                             "First convert the float to a string")
537
538         # Other argument types may require the context during interpretation
539         if context is None:
540             context = getcontext()
541
542         # From a string
543         # REs insist on real strings, so we can too.
544         if isinstance(value, basestring):
545             if _isinfinity(value):
546                 self._exp = 'F'
547                 self._int = (0,)
548                 self._is_special = True
549                 if _isinfinity(value) == 1:
550                     self._sign = 0
551                 else:
552                     self._sign = 1
553                 return self
554             if _isnan(value):
555                 sig, sign, diag = _isnan(value)
556                 self._is_special = True
557                 if len(diag) > context.prec: #Diagnostic info too long
558                     self._sign, self._int, self._exp = \
559                                 context._raise_error(ConversionSyntax)
560                     return self
561                 if sig == 1:
562                     self._exp = 'n' #qNaN
563                 else: #sig == 2
564                     self._exp = 'N' #sNaN
565                 self._sign = sign
566                 self._int = tuple(map(int, diag)) #Diagnostic info
567                 return self
568             try:
569                 self._sign, self._int, self._exp = _string2exact(value)
570             except ValueError:
571                 self._is_special = True
572                 self._sign, self._int, self._exp = context._raise_error(ConversionSyntax)
573             return self
574
575         raise TypeError("Cannot convert %r to Decimal" % value)
576
577     def _isnan(self):
578         """Returns whether the number is not actually one.
579
580         0 if a number
581         1 if NaN
582         2 if sNaN
583         """
584         if self._is_special:
585             exp = self._exp
586             if exp == 'n':
587                 return 1
588             elif exp == 'N':
589                 return 2
590         return 0
591
592     def _isinfinity(self):
593         """Returns whether the number is infinite
594
595         0 if finite or not a number
596         1 if +INF
597         -1 if -INF
598         """
599         if self._exp == 'F':
600             if self._sign:
601                 return -1
602             return 1
603         return 0
604
605     def _check_nans(self, other = None, context=None):
606         """Returns whether the number is not actually one.
607
608         if self, other are sNaN, signal
609         if self, other are NaN return nan
610         return 0
611
612         Done before operations.
613         """
614
615         self_is_nan = self._isnan()
616         if other is None:
617             other_is_nan = False
618         else:
619             other_is_nan = other._isnan()
620
621         if self_is_nan or other_is_nan:
622             if context is None:
623                 context = getcontext()
624
625             if self_is_nan == 2:
626                 return context._raise_error(InvalidOperation, 'sNaN',
627                                         1, self)
628             if other_is_nan == 2:
629                 return context._raise_error(InvalidOperation, 'sNaN',
630                                         1, other)
631             if self_is_nan:
632                 return self
633
634             return other
635         return 0
636
637     def __nonzero__(self):
638         """Is the number non-zero?
639
640         0 if self == 0
641         1 if self != 0
642         """
643         if self._is_special:
644             return 1
645         return sum(self._int) != 0
646
647     def __cmp__(self, other, context=None):
648         other = _convert_other(other)
649         if other is NotImplemented:
650             return other
651
652         if self._is_special or other._is_special:
653             ans = self._check_nans(other, context)
654             if ans:
655                 return 1 # Comparison involving NaN's always reports self > other
656
657             # INF = INF
658             return cmp(self._isinfinity(), other._isinfinity())
659
660         if not self and not other:
661             return 0 #If both 0, sign comparison isn't certain.
662
663         #If different signs, neg one is less
664         if other._sign < self._sign:
665             return -1
666         if self._sign < other._sign:
667             return 1
668
669         self_adjusted = self.adjusted()
670         other_adjusted = other.adjusted()
671         if self_adjusted == other_adjusted and \
672            self._int + (0,)*(self._exp - other._exp) == \
673            other._int + (0,)*(other._exp - self._exp):
674             return 0 #equal, except in precision. ([0]*(-x) = [])
675         elif self_adjusted > other_adjusted and self._int[0] != 0:
676             return (-1)**self._sign
677         elif self_adjusted < other_adjusted and other._int[0] != 0:
678             return -((-1)**self._sign)
679
680         # Need to round, so make sure we have a valid context
681         if context is None:
682             context = getcontext()
683
684         context = context._shallow_copy()
685         rounding = context._set_rounding(ROUND_UP) #round away from 0
686
687         flags = context._ignore_all_flags()
688         res = self.__sub__(other, context=context)
689
690         context._regard_flags(*flags)
691
692         context.rounding = rounding
693
694         if not res:
695             return 0
696         elif res._sign:
697             return -1
698         return 1
699
700     def __eq__(self, other):
701         if not isinstance(other, (Decimal, int, long)):
702             return NotImplemented
703         return self.__cmp__(other) == 0
704
705     def __ne__(self, other):
706         if not isinstance(other, (Decimal, int, long)):
707             return NotImplemented
708         return self.__cmp__(other) != 0
709
710     def compare(self, other, context=None):
711         """Compares one to another.
712
713         -1 => a < b
714         0  => a = b
715         1  => a > b
716         NaN => one is NaN
717         Like __cmp__, but returns Decimal instances.
718         """
719         other = _convert_other(other)
720         if other is NotImplemented:
721             return other
722
723         #compare(NaN, NaN) = NaN
724         if (self._is_special or other and other._is_special):
725             ans = self._check_nans(other, context)
726             if ans:
727                 return ans
728
729         return Decimal(self.__cmp__(other, context))
730
731     def __hash__(self):
732         """x.__hash__() <==> hash(x)"""
733         # Decimal integers must hash the same as the ints
734         # Non-integer decimals are normalized and hashed as strings
735         # Normalization assures that hast(100E-1) == hash(10)
736         if self._is_special:
737             if self._isnan():
738                 raise TypeError('Cannot hash a NaN value.')
739             return hash(str(self))
740         i = int(self)
741         if self == Decimal(i):
742             return hash(i)
743         assert self.__nonzero__()   # '-0' handled by integer case
744         return hash(str(self.normalize()))
745
746     def as_tuple(self):
747         """Represents the number as a triple tuple.
748
749         To show the internals exactly as they are.
750         """
751         return (self._sign, self._int, self._exp)
752
753     def __repr__(self):
754         """Represents the number as an instance of Decimal."""
755         # Invariant:  eval(repr(d)) == d
756         return 'Decimal("%s")' % str(self)
757
758     def __str__(self, eng = 0, context=None):
759         """Return string representation of the number in scientific notation.
760
761         Captures all of the information in the underlying representation.
762         """
763
764         if self._is_special:
765             if self._isnan():
766                 minus = '-'*self._sign
767                 if self._int == (0,):
768                     info = ''
769                 else:
770                     info = ''.join(map(str, self._int))
771                 if self._isnan() == 2:
772                     return minus + 'sNaN' + info
773                 return minus + 'NaN' + info
774             if self._isinfinity():
775                 minus = '-'*self._sign
776                 return minus + 'Infinity'
777
778         if context is None:
779             context = getcontext()
780
781         tmp = map(str, self._int)
782         numdigits = len(self._int)
783         leftdigits = self._exp + numdigits
784         if eng and not self: #self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
785             if self._exp < 0 and self._exp >= -6: #short, no need for e/E
786                 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
787                 return s
788             #exp is closest mult. of 3 >= self._exp
789             exp = ((self._exp - 1)// 3 + 1) * 3
790             if exp != self._exp:
791                 s = '0.'+'0'*(exp - self._exp)
792             else:
793                 s = '0'
794             if exp != 0:
795                 if context.capitals:
796                     s += 'E'
797                 else:
798                     s += 'e'
799                 if exp > 0:
800                     s += '+' #0.0e+3, not 0.0e3
801                 s += str(exp)
802             s = '-'*self._sign + s
803             return s
804         if eng:
805             dotplace = (leftdigits-1)%3+1
806             adjexp = leftdigits -1 - (leftdigits-1)%3
807         else:
808             adjexp = leftdigits-1
809             dotplace = 1
810         if self._exp == 0:
811             pass
812         elif self._exp < 0 and adjexp >= 0:
813             tmp.insert(leftdigits, '.')
814         elif self._exp < 0 and adjexp >= -6:
815             tmp[0:0] = ['0'] * int(-leftdigits)
816             tmp.insert(0, '0.')
817         else:
818             if numdigits > dotplace:
819                 tmp.insert(dotplace, '.')
820             elif numdigits < dotplace:
821                 tmp.extend(['0']*(dotplace-numdigits))
822             if adjexp:
823                 if not context.capitals:
824                     tmp.append('e')
825                 else:
826                     tmp.append('E')
827                     if adjexp > 0:
828                         tmp.append('+')
829                 tmp.append(str(adjexp))
830         if eng:
831             while tmp[0:1] == ['0']:
832                 tmp[0:1] = []
833             if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
834                 tmp[0:0] = ['0']
835         if self._sign:
836             tmp.insert(0, '-')
837
838         return ''.join(tmp)
839
840     def to_eng_string(self, context=None):
841         """Convert to engineering-type string.
842
843         Engineering notation has an exponent which is a multiple of 3, so there
844         are up to 3 digits left of the decimal place.
845
846         Same rules for when in exponential and when as a value as in __str__.
847         """
848         return self.__str__(eng=1, context=context)
849
850     def __neg__(self, context=None):
851         """Returns a copy with the sign switched.
852
853         Rounds, if it has reason.
854         """
855         if self._is_special:
856             ans = self._check_nans(context=context)
857             if ans:
858                 return ans
859
860         if not self:
861             # -Decimal('0') is Decimal('0'), not Decimal('-0')
862             sign = 0
863         elif self._sign:
864             sign = 0
865         else:
866             sign = 1
867
868         if context is None:
869             context = getcontext()
870         if context._rounding_decision == ALWAYS_ROUND:
871             return Decimal((sign, self._int, self._exp))._fix(context)
872         return Decimal( (sign, self._int, self._exp))
873
874     def __pos__(self, context=None):
875         """Returns a copy, unless it is a sNaN.
876
877         Rounds the number (if more then precision digits)
878         """
879         if self._is_special:
880             ans = self._check_nans(context=context)
881             if ans:
882                 return ans
883
884         sign = self._sign
885         if not self:
886             # + (-0) = 0
887             sign = 0
888
889         if context is None:
890             context = getcontext()
891
892         if context._rounding_decision == ALWAYS_ROUND:
893             ans = self._fix(context)
894         else:
895             ans = Decimal(self)
896         ans._sign = sign
897         return ans
898
899     def __abs__(self, round=1, context=None):
900         """Returns the absolute value of self.
901
902         If the second argument is 0, do not round.
903         """
904         if self._is_special:
905             ans = self._check_nans(context=context)
906             if ans:
907                 return ans
908
909         if not round:
910             if context is None:
911                 context = getcontext()
912             context = context._shallow_copy()
913             context._set_rounding_decision(NEVER_ROUND)
914
915         if self._sign:
916             ans = self.__neg__(context=context)
917         else:
918             ans = self.__pos__(context=context)
919
920         return ans
921
922     def __add__(self, other, context=None):
923         """Returns self + other.
924
925         -INF + INF (or the reverse) cause InvalidOperation errors.
926         """
927         other = _convert_other(other)
928         if other is NotImplemented:
929             return other
930
931         if context is None:
932             context = getcontext()
933
934         if self._is_special or other._is_special:
935             ans = self._check_nans(other, context)
936             if ans:
937                 return ans
938
939             if self._isinfinity():
940                 #If both INF, same sign => same as both, opposite => error.
941                 if self._sign != other._sign and other._isinfinity():
942                     return context._raise_error(InvalidOperation, '-INF + INF')
943                 return Decimal(self)
944             if other._isinfinity():
945                 return Decimal(other)  #Can't both be infinity here
946
947         shouldround = context._rounding_decision == ALWAYS_ROUND
948
949         exp = min(self._exp, other._exp)
950         negativezero = 0
951         if context.rounding == ROUND_FLOOR and self._sign != other._sign:
952             #If the answer is 0, the sign should be negative, in this case.
953             negativezero = 1
954
955         if not self and not other:
956             sign = min(self._sign, other._sign)
957             if negativezero:
958                 sign = 1
959             return Decimal( (sign, (0,), exp))
960         if not self:
961             exp = max(exp, other._exp - context.prec-1)
962             ans = other._rescale(exp, watchexp=0, context=context)
963             if shouldround:
964                 ans = ans._fix(context)
965             return ans
966         if not other:
967             exp = max(exp, self._exp - context.prec-1)
968             ans = self._rescale(exp, watchexp=0, context=context)
969             if shouldround:
970                 ans = ans._fix(context)
971             return ans
972
973         op1 = _WorkRep(self)
974         op2 = _WorkRep(other)
975         op1, op2 = _normalize(op1, op2, shouldround, context.prec)
976
977         result = _WorkRep()
978         if op1.sign != op2.sign:
979             # Equal and opposite
980             if op1.int == op2.int:
981                 if exp < context.Etiny():
982                     exp = context.Etiny()
983                     context._raise_error(Clamped)
984                 return Decimal((negativezero, (0,), exp))
985             if op1.int < op2.int:
986                 op1, op2 = op2, op1
987                 #OK, now abs(op1) > abs(op2)
988             if op1.sign == 1:
989                 result.sign = 1
990                 op1.sign, op2.sign = op2.sign, op1.sign
991             else:
992                 result.sign = 0
993                 #So we know the sign, and op1 > 0.
994         elif op1.sign == 1:
995             result.sign = 1
996             op1.sign, op2.sign = (0, 0)
997         else:
998             result.sign = 0
999         #Now, op1 > abs(op2) > 0
1000
1001         if op2.sign == 0:
1002             result.int = op1.int + op2.int
1003         else:
1004             result.int = op1.int - op2.int
1005
1006         result.exp = op1.exp
1007         ans = Decimal(result)
1008         if shouldround:
1009             ans = ans._fix(context)
1010         return ans
1011
1012     __radd__ = __add__
1013
1014     def __sub__(self, other, context=None):
1015         """Return self + (-other)"""
1016         other = _convert_other(other)
1017         if other is NotImplemented:
1018             return other
1019
1020         if self._is_special or other._is_special:
1021             ans = self._check_nans(other, context=context)
1022             if ans:
1023                 return ans
1024
1025         # -Decimal(0) = Decimal(0), which we don't want since
1026         # (-0 - 0 = -0 + (-0) = -0, but -0 + 0 = 0.)
1027         # so we change the sign directly to a copy
1028         tmp = Decimal(other)
1029         tmp._sign = 1-tmp._sign
1030
1031         return self.__add__(tmp, context=context)
1032
1033     def __rsub__(self, other, context=None):
1034         """Return other + (-self)"""
1035         other = _convert_other(other)
1036         if other is NotImplemented:
1037             return other
1038
1039         tmp = Decimal(self)
1040         tmp._sign = 1 - tmp._sign
1041         return other.__add__(tmp, context=context)
1042
1043     def _increment(self, round=1, context=None):
1044         """Special case of add, adding 1eExponent
1045
1046         Since it is common, (rounding, for example) this adds
1047         (sign)*one E self._exp to the number more efficiently than add.
1048
1049         For example:
1050         Decimal('5.624e10')._increment() == Decimal('5.625e10')
1051         """
1052         if self._is_special:
1053             ans = self._check_nans(context=context)
1054             if ans:
1055                 return ans
1056
1057             return Decimal(self) # Must be infinite, and incrementing makes no difference
1058
1059         L = list(self._int)
1060         L[-1] += 1
1061         spot = len(L)-1
1062         while L[spot] == 10:
1063             L[spot] = 0
1064             if spot == 0:
1065                 L[0:0] = [1]
1066                 break
1067             L[spot-1] += 1
1068             spot -= 1
1069         ans = Decimal((self._sign, L, self._exp))
1070
1071         if context is None:
1072             context = getcontext()
1073         if round and context._rounding_decision == ALWAYS_ROUND:
1074             ans = ans._fix(context)
1075         return ans
1076
1077     def __mul__(self, other, context=None):
1078         """Return self * other.
1079
1080         (+-) INF * 0 (or its reverse) raise InvalidOperation.
1081         """
1082         other = _convert_other(other)
1083         if other is NotImplemented:
1084             return other
1085
1086         if context is None:
1087             context = getcontext()
1088
1089         resultsign = self._sign ^ other._sign
1090
1091         if self._is_special or other._is_special:
1092             ans = self._check_nans(other, context)
1093             if ans:
1094                 return ans
1095
1096             if self._isinfinity():
1097                 if not other:
1098                     return context._raise_error(InvalidOperation, '(+-)INF * 0')
1099                 return Infsign[resultsign]
1100
1101             if other._isinfinity():
1102                 if not self:
1103                     return context._raise_error(InvalidOperation, '0 * (+-)INF')
1104                 return Infsign[resultsign]
1105
1106         resultexp = self._exp + other._exp
1107         shouldround = context._rounding_decision == ALWAYS_ROUND
1108
1109         # Special case for multiplying by zero
1110         if not self or not other:
1111             ans = Decimal((resultsign, (0,), resultexp))
1112             if shouldround:
1113                 #Fixing in case the exponent is out of bounds
1114                 ans = ans._fix(context)
1115             return ans
1116
1117         # Special case for multiplying by power of 10
1118         if self._int == (1,):
1119             ans = Decimal((resultsign, other._int, resultexp))
1120             if shouldround:
1121                 ans = ans._fix(context)
1122             return ans
1123         if other._int == (1,):
1124             ans = Decimal((resultsign, self._int, resultexp))
1125             if shouldround:
1126                 ans = ans._fix(context)
1127             return ans
1128
1129         op1 = _WorkRep(self)
1130         op2 = _WorkRep(other)
1131
1132         ans = Decimal( (resultsign, map(int, str(op1.int * op2.int)), resultexp))
1133         if shouldround:
1134             ans = ans._fix(context)
1135
1136         return ans
1137     __rmul__ = __mul__
1138
1139     def __div__(self, other, context=None):
1140         """Return self / other."""
1141         return self._divide(other, context=context)
1142     __truediv__ = __div__
1143
1144     def _divide(self, other, divmod = 0, context=None):
1145         """Return a / b, to context.prec precision.
1146
1147         divmod:
1148         0 => true division
1149         1 => (a //b, a%b)
1150         2 => a //b
1151         3 => a%b
1152
1153         Actually, if divmod is 2 or 3 a tuple is returned, but errors for
1154         computing the other value are not raised.
1155         """
1156         other = _convert_other(other)
1157         if other is NotImplemented:
1158             if divmod in (0, 1):
1159                 return NotImplemented
1160             return (NotImplemented, NotImplemented)
1161
1162         if context is None:
1163             context = getcontext()
1164
1165         sign = self._sign ^ other._sign
1166
1167         if self._is_special or other._is_special:
1168             ans = self._check_nans(other, context)
1169             if ans:
1170                 if divmod:
1171                     return (ans, ans)
1172                 return ans
1173
1174             if self._isinfinity() and other._isinfinity():
1175                 if divmod:
1176                     return (context._raise_error(InvalidOperation,
1177                                             '(+-)INF // (+-)INF'),
1178                             context._raise_error(InvalidOperation,
1179                                             '(+-)INF % (+-)INF'))
1180                 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
1181
1182             if self._isinfinity():
1183                 if divmod == 1:
1184                     return (Infsign[sign],
1185                             context._raise_error(InvalidOperation, 'INF % x'))
1186                 elif divmod == 2:
1187                     return (Infsign[sign], NaN)
1188                 elif divmod == 3:
1189                     return (Infsign[sign],
1190                             context._raise_error(InvalidOperation, 'INF % x'))
1191                 return Infsign[sign]
1192
1193             if other._isinfinity():
1194                 if divmod:
1195                     return (Decimal((sign, (0,), 0)), Decimal(self))
1196                 context._raise_error(Clamped, 'Division by infinity')
1197                 return Decimal((sign, (0,), context.Etiny()))
1198
1199         # Special cases for zeroes
1200         if not self and not other:
1201             if divmod:
1202                 return context._raise_error(DivisionUndefined, '0 / 0', 1)
1203             return context._raise_error(DivisionUndefined, '0 / 0')
1204
1205         if not self:
1206             if divmod:
1207                 otherside = Decimal(self)
1208                 otherside._exp = min(self._exp, other._exp)
1209                 return (Decimal((sign, (0,), 0)),  otherside)
1210             exp = self._exp - other._exp
1211             if exp < context.Etiny():
1212                 exp = context.Etiny()
1213                 context._raise_error(Clamped, '0e-x / y')
1214             if exp > context.Emax:
1215                 exp = context.Emax
1216                 context._raise_error(Clamped, '0e+x / y')
1217             return Decimal( (sign, (0,), exp) )
1218
1219         if not other:
1220             if divmod:
1221                 return context._raise_error(DivisionByZero, 'divmod(x,0)',
1222                                            sign, 1)
1223             return context._raise_error(DivisionByZero, 'x / 0', sign)
1224
1225         #OK, so neither = 0, INF or NaN
1226
1227         shouldround = context._rounding_decision == ALWAYS_ROUND
1228
1229         #If we're dividing into ints, and self < other, stop.
1230         #self.__abs__(0) does not round.
1231         if divmod and (self.__abs__(0, context) < other.__abs__(0, context)):
1232
1233             if divmod == 1 or divmod == 3:
1234                 exp = min(self._exp, other._exp)
1235                 ans2 = self._rescale(exp, context=context, watchexp=0)
1236                 if shouldround:
1237                     ans2 = ans2._fix(context)
1238                 return (Decimal( (sign, (0,), 0) ),
1239                         ans2)
1240
1241             elif divmod == 2:
1242                 #Don't round the mod part, if we don't need it.
1243                 return (Decimal( (sign, (0,), 0) ), Decimal(self))
1244
1245         op1 = _WorkRep(self)
1246         op2 = _WorkRep(other)
1247         op1, op2, adjust = _adjust_coefficients(op1, op2)
1248         res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) )
1249         if divmod and res.exp > context.prec + 1:
1250             return context._raise_error(DivisionImpossible)
1251
1252         prec_limit = 10 ** context.prec
1253         while 1:
1254             while op2.int <= op1.int:
1255                 res.int += 1
1256                 op1.int -= op2.int
1257             if res.exp == 0 and divmod:
1258                 if res.int >= prec_limit and shouldround:
1259                     return context._raise_error(DivisionImpossible)
1260                 otherside = Decimal(op1)
1261                 frozen = context._ignore_all_flags()
1262
1263                 exp = min(self._exp, other._exp)
1264                 otherside = otherside._rescale(exp, context=context, watchexp=0)
1265                 context._regard_flags(*frozen)
1266                 if shouldround:
1267                     otherside = otherside._fix(context)
1268                 return (Decimal(res), otherside)
1269
1270             if op1.int == 0 and adjust >= 0 and not divmod:
1271                 break
1272             if res.int >= prec_limit and shouldround:
1273                 if divmod:
1274                     return context._raise_error(DivisionImpossible)
1275                 shouldround=1
1276                 # Really, the answer is a bit higher, so adding a one to
1277                 # the end will make sure the rounding is right.
1278                 if op1.int != 0:
1279                     res.int *= 10
1280                     res.int += 1
1281                     res.exp -= 1
1282
1283                 break
1284             res.int *= 10
1285             res.exp -= 1
1286             adjust += 1
1287             op1.int *= 10
1288             op1.exp -= 1
1289
1290             if res.exp == 0 and divmod and op2.int > op1.int:
1291                 #Solves an error in precision.  Same as a previous block.
1292
1293                 if res.int >= prec_limit and shouldround:
1294                     return context._raise_error(DivisionImpossible)
1295                 otherside = Decimal(op1)
1296                 frozen = context._ignore_all_flags()
1297
1298                 exp = min(self._exp, other._exp)
1299                 otherside = otherside._rescale(exp, context=context)
1300
1301                 context._regard_flags(*frozen)
1302
1303                 return (Decimal(res), otherside)
1304
1305         ans = Decimal(res)
1306         if shouldround:
1307             ans = ans._fix(context)
1308         return ans
1309
1310     def __rdiv__(self, other, context=None):
1311         """Swaps self/other and returns __div__."""
1312         other = _convert_other(other)
1313         if other is NotImplemented:
1314             return other
1315         return other.__div__(self, context=context)
1316     __rtruediv__ = __rdiv__
1317
1318     def __divmod__(self, other, context=None):
1319         """
1320         (self // other, self % other)
1321         """
1322         return self._divide(other, 1, context)
1323
1324     def __rdivmod__(self, other, context=None):
1325         """Swaps self/other and returns __divmod__."""
1326         other = _convert_other(other)
1327         if other is NotImplemented:
1328             return other
1329         return other.__divmod__(self, context=context)
1330
1331     def __mod__(self, other, context=None):
1332         """
1333         self % other
1334         """
1335         other = _convert_other(other)
1336         if other is NotImplemented:
1337             return other
1338
1339         if self._is_special or other._is_special:
1340             ans = self._check_nans(other, context)
1341             if ans:
1342                 return ans
1343
1344         if self and not other:
1345             return context._raise_error(InvalidOperation, 'x % 0')
1346
1347         return self._divide(other, 3, context)[1]
1348
1349     def __rmod__(self, other, context=None):
1350         """Swaps self/other and returns __mod__."""
1351         other = _convert_other(other)
1352         if other is NotImplemented:
1353             return other
1354         return other.__mod__(self, context=context)
1355
1356     def remainder_near(self, other, context=None):
1357         """
1358         Remainder nearest to 0-  abs(remainder-near) <= other/2
1359         """
1360         other = _convert_other(other)
1361         if other is NotImplemented:
1362             return other
1363
1364         if self._is_special or other._is_special:
1365             ans = self._check_nans(other, context)
1366             if ans:
1367                 return ans
1368         if self and not other:
1369             return context._raise_error(InvalidOperation, 'x % 0')
1370
1371         if context is None:
1372             context = getcontext()
1373         # If DivisionImpossible causes an error, do not leave Rounded/Inexact
1374         # ignored in the calling function.
1375         context = context._shallow_copy()
1376         flags = context._ignore_flags(Rounded, Inexact)
1377         #keep DivisionImpossible flags
1378         (side, r) = self.__divmod__(other, context=context)
1379
1380         if r._isnan():
1381             context._regard_flags(*flags)
1382             return r
1383
1384         context = context._shallow_copy()
1385         rounding = context._set_rounding_decision(NEVER_ROUND)
1386
1387         if other._sign:
1388             comparison = other.__div__(Decimal(-2), context=context)
1389         else:
1390             comparison = other.__div__(Decimal(2), context=context)
1391
1392         context._set_rounding_decision(rounding)
1393         context._regard_flags(*flags)
1394
1395         s1, s2 = r._sign, comparison._sign
1396         r._sign, comparison._sign = 0, 0
1397
1398         if r < comparison:
1399             r._sign, comparison._sign = s1, s2
1400             #Get flags now
1401             self.__divmod__(other, context=context)
1402             return r._fix(context)
1403         r._sign, comparison._sign = s1, s2
1404
1405         rounding = context._set_rounding_decision(NEVER_ROUND)
1406
1407         (side, r) = self.__divmod__(other, context=context)
1408         context._set_rounding_decision(rounding)
1409         if r._isnan():
1410             return r
1411
1412         decrease = not side._iseven()
1413         rounding = context._set_rounding_decision(NEVER_ROUND)
1414         side = side.__abs__(context=context)
1415         context._set_rounding_decision(rounding)
1416
1417         s1, s2 = r._sign, comparison._sign
1418         r._sign, comparison._sign = 0, 0
1419         if r > comparison or decrease and r == comparison:
1420             r._sign, comparison._sign = s1, s2
1421             context.prec += 1
1422             if len(side.__add__(Decimal(1), context=context)._int) >= context.prec:
1423                 context.prec -= 1
1424                 return context._raise_error(DivisionImpossible)[1]
1425             context.prec -= 1
1426             if self._sign == other._sign:
1427                 r = r.__sub__(other, context=context)
1428             else:
1429                 r = r.__add__(other, context=context)
1430         else:
1431             r._sign, comparison._sign = s1, s2
1432
1433         return r._fix(context)
1434
1435     def __floordiv__(self, other, context=None):
1436         """self // other"""
1437         return self._divide(other, 2, context)[0]
1438
1439     def __rfloordiv__(self, other, context=None):
1440         """Swaps self/other and returns __floordiv__."""
1441         other = _convert_other(other)
1442         if other is NotImplemented:
1443             return other
1444         return other.__floordiv__(self, context=context)
1445
1446     def __float__(self):
1447         """Float representation."""
1448         return float(str(self))
1449
1450     def __int__(self):
1451         """Converts self to an int, truncating if necessary."""
1452         if self._is_special:
1453             if self._isnan():
1454                 context = getcontext()
1455                 return context._raise_error(InvalidContext)
1456             elif self._isinfinity():
1457                 raise OverflowError, "Cannot convert infinity to long"
1458         if self._exp >= 0:
1459             s = ''.join(map(str, self._int)) + '0'*self._exp
1460         else:
1461             s = ''.join(map(str, self._int))[:self._exp]
1462         if s == '':
1463             s = '0'
1464         sign = '-'*self._sign
1465         return int(sign + s)
1466
1467     def __long__(self):
1468         """Converts to a long.
1469
1470         Equivalent to long(int(self))
1471         """
1472         return long(self.__int__())
1473
1474     def _fix(self, context):
1475         """Round if it is necessary to keep self within prec precision.
1476
1477         Rounds and fixes the exponent.  Does not raise on a sNaN.
1478
1479         Arguments:
1480         self - Decimal instance
1481         context - context used.
1482         """
1483         if self._is_special:
1484             return self
1485         if context is None:
1486             context = getcontext()
1487         prec = context.prec
1488         ans = self._fixexponents(context)
1489         if len(ans._int) > prec:
1490             ans = ans._round(prec, context=context)
1491             ans = ans._fixexponents(context)
1492         return ans
1493
1494     def _fixexponents(self, context):
1495         """Fix the exponents and return a copy with the exponent in bounds.
1496         Only call if known to not be a special value.
1497         """
1498         folddown = context._clamp
1499         Emin = context.Emin
1500         ans = self
1501         ans_adjusted = ans.adjusted()
1502         if ans_adjusted < Emin:
1503             Etiny = context.Etiny()
1504             if ans._exp < Etiny:
1505                 if not ans:
1506                     ans = Decimal(self)
1507                     ans._exp = Etiny
1508                     context._raise_error(Clamped)
1509                     return ans
1510                 ans = ans._rescale(Etiny, context=context)
1511                 #It isn't zero, and exp < Emin => subnormal
1512                 context._raise_error(Subnormal)
1513                 if context.flags[Inexact]:
1514                     context._raise_error(Underflow)
1515             else:
1516                 if ans:
1517                     #Only raise subnormal if non-zero.
1518                     context._raise_error(Subnormal)
1519         else:
1520             Etop = context.Etop()
1521             if folddown and ans._exp > Etop:
1522                 context._raise_error(Clamped)
1523                 ans = ans._rescale(Etop, context=context)
1524             else:
1525                 Emax = context.Emax
1526                 if ans_adjusted > Emax:
1527                     if not ans:
1528                         ans = Decimal(self)
1529                         ans._exp = Emax
1530                         context._raise_error(Clamped)
1531                         return ans
1532                     context._raise_error(Inexact)
1533                     context._raise_error(Rounded)
1534                     return context._raise_error(Overflow, 'above Emax', ans._sign)
1535         return ans
1536
1537     def _round(self, prec=None, rounding=None, context=None):
1538         """Returns a rounded version of self.
1539
1540         You can specify the precision or rounding method.  Otherwise, the
1541         context determines it.
1542         """
1543
1544         if self._is_special:
1545             ans = self._check_nans(context=context)
1546             if ans:
1547                 return ans
1548
1549             if self._isinfinity():
1550                 return Decimal(self)
1551
1552         if context is None:
1553             context = getcontext()
1554
1555         if rounding is None:
1556             rounding = context.rounding
1557         if prec is None:
1558             prec = context.prec
1559
1560         if not self:
1561             if prec <= 0:
1562                 dig = (0,)
1563                 exp = len(self._int) - prec + self._exp
1564             else:
1565                 dig = (0,) * prec
1566                 exp = len(self._int) + self._exp - prec
1567             ans = Decimal((self._sign, dig, exp))
1568             context._raise_error(Rounded)
1569             return ans
1570
1571         if prec == 0:
1572             temp = Decimal(self)
1573             temp._int = (0,)+temp._int
1574             prec = 1
1575         elif prec < 0:
1576             exp = self._exp + len(self._int) - prec - 1
1577             temp = Decimal( (self._sign, (0, 1), exp))
1578             prec = 1
1579         else:
1580             temp = Decimal(self)
1581
1582         numdigits = len(temp._int)
1583         if prec == numdigits:
1584             return temp
1585
1586         # See if we need to extend precision
1587         expdiff = prec - numdigits
1588         if expdiff > 0:
1589             tmp = list(temp._int)
1590             tmp.extend([0] * expdiff)
1591             ans =  Decimal( (temp._sign, tmp, temp._exp - expdiff))
1592             return ans
1593
1594         #OK, but maybe all the lost digits are 0.
1595         lostdigits = self._int[expdiff:]
1596         if lostdigits == (0,) * len(lostdigits):
1597             ans = Decimal( (temp._sign, temp._int[:prec], temp._exp - expdiff))
1598             #Rounded, but not Inexact
1599             context._raise_error(Rounded)
1600             return ans
1601
1602         # Okay, let's round and lose data
1603
1604         this_function = getattr(temp, self._pick_rounding_function[rounding])
1605         #Now we've got the rounding function
1606
1607         if prec != context.prec:
1608             context = context._shallow_copy()
1609             context.prec = prec
1610         ans = this_function(prec, expdiff, context)
1611         context._raise_error(Rounded)
1612         context._raise_error(Inexact, 'Changed in rounding')
1613
1614         return ans
1615
1616     _pick_rounding_function = {}
1617
1618     def _round_down(self, prec, expdiff, context):
1619         """Also known as round-towards-0, truncate."""
1620         return Decimal( (self._sign, self._int[:prec], self._exp - expdiff) )
1621
1622     def _round_half_up(self, prec, expdiff, context, tmp = None):
1623         """Rounds 5 up (away from 0)"""
1624
1625         if tmp is None:
1626             tmp = Decimal( (self._sign,self._int[:prec], self._exp - expdiff))
1627         if self._int[prec] >= 5:
1628             tmp = tmp._increment(round=0, context=context)
1629             if len(tmp._int) > prec:
1630                 return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1))
1631         return tmp
1632
1633     def _round_half_even(self, prec, expdiff, context):
1634         """Round 5 to even, rest to nearest."""
1635
1636         tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff))
1637         half = (self._int[prec] == 5)
1638         if half:
1639             for digit in self._int[prec+1:]:
1640                 if digit != 0:
1641                     half = 0
1642                     break
1643         if half:
1644             if self._int[prec-1] & 1 == 0:
1645                 return tmp
1646         return self._round_half_up(prec, expdiff, context, tmp)
1647
1648     def _round_half_down(self, prec, expdiff, context):
1649         """Round 5 down"""
1650
1651         tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff))
1652         half = (self._int[prec] == 5)
1653         if half:
1654             for digit in self._int[prec+1:]:
1655                 if digit != 0:
1656                     half = 0
1657                     break
1658         if half:
1659             return tmp
1660         return self._round_half_up(prec, expdiff, context, tmp)
1661
1662     def _round_up(self, prec, expdiff, context):
1663         """Rounds away from 0."""
1664         tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff) )
1665         for digit in self._int[prec:]:
1666             if digit != 0:
1667                 tmp = tmp._increment(round=1, context=context)
1668                 if len(tmp._int) > prec:
1669                     return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1))
1670                 else:
1671                     return tmp
1672         return tmp
1673
1674     def _round_ceiling(self, prec, expdiff, context):
1675         """Rounds up (not away from 0 if negative.)"""
1676         if self._sign:
1677             return self._round_down(prec, expdiff, context)
1678         else:
1679             return self._round_up(prec, expdiff, context)
1680
1681     def _round_floor(self, prec, expdiff, context):
1682         """Rounds down (not towards 0 if negative)"""
1683         if not self._sign:
1684             return self._round_down(prec, expdiff, context)
1685         else:
1686             return self._round_up(prec, expdiff, context)
1687
1688     def __pow__(self, n, modulo = None, context=None):
1689         """Return self ** n (mod modulo)
1690
1691         If modulo is None (default), don't take it mod modulo.
1692         """
1693         n = _convert_other(n)
1694         if n is NotImplemented:
1695             return n
1696
1697         if context is None:
1698             context = getcontext()
1699
1700         if self._is_special or n._is_special or n.adjusted() > 8:
1701             #Because the spot << doesn't work with really big exponents
1702             if n._isinfinity() or n.adjusted() > 8:
1703                 return context._raise_error(InvalidOperation, 'x ** INF')
1704
1705             ans = self._check_nans(n, context)
1706             if ans:
1707                 return ans
1708
1709         if not n._isinteger():
1710             return context._raise_error(InvalidOperation, 'x ** (non-integer)')
1711
1712         if not self and not n:
1713             return context._raise_error(InvalidOperation, '0 ** 0')
1714
1715         if not n:
1716             return Decimal(1)
1717
1718         if self == Decimal(1):
1719             return Decimal(1)
1720
1721         sign = self._sign and not n._iseven()
1722         n = int(n)
1723
1724         if self._isinfinity():
1725             if modulo:
1726                 return context._raise_error(InvalidOperation, 'INF % x')
1727             if n > 0:
1728                 return Infsign[sign]
1729             return Decimal( (sign, (0,), 0) )
1730
1731         #with ludicrously large exponent, just raise an overflow and return inf.
1732         if not modulo and n > 0 and (self._exp + len(self._int) - 1) * n > context.Emax \
1733            and self:
1734
1735             tmp = Decimal('inf')
1736             tmp._sign = sign
1737             context._raise_error(Rounded)
1738             context._raise_error(Inexact)
1739             context._raise_error(Overflow, 'Big power', sign)
1740             return tmp
1741
1742         elength = len(str(abs(n)))
1743         firstprec = context.prec
1744
1745         if not modulo and firstprec + elength + 1 > DefaultContext.Emax:
1746             return context._raise_error(Overflow, 'Too much precision.', sign)
1747
1748         mul = Decimal(self)
1749         val = Decimal(1)
1750         context = context._shallow_copy()
1751         context.prec = firstprec + elength + 1
1752         if n < 0:
1753             #n is a long now, not Decimal instance
1754             n = -n
1755             mul = Decimal(1).__div__(mul, context=context)
1756
1757         spot = 1
1758         while spot <= n:
1759             spot <<= 1
1760
1761         spot >>= 1
1762         #Spot is the highest power of 2 less than n
1763         while spot:
1764             val = val.__mul__(val, context=context)
1765             if val._isinfinity():
1766                 val = Infsign[sign]
1767                 break
1768             if spot & n:
1769                 val = val.__mul__(mul, context=context)
1770             if modulo is not None:
1771                 val = val.__mod__(modulo, context=context)
1772             spot >>= 1
1773         context.prec = firstprec
1774
1775         if context._rounding_decision == ALWAYS_ROUND:
1776             return val._fix(context)
1777         return val
1778
1779     def __rpow__(self, other, context=None):
1780         """Swaps self/other and returns __pow__."""
1781         other = _convert_other(other)
1782         if other is NotImplemented:
1783             return other
1784         return other.__pow__(self, context=context)
1785
1786     def normalize(self, context=None):
1787         """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
1788
1789         if self._is_special:
1790             ans = self._check_nans(context=context)
1791             if ans:
1792                 return ans
1793
1794         dup = self._fix(context)
1795         if dup._isinfinity():
1796             return dup
1797
1798         if not dup:
1799             return Decimal( (dup._sign, (0,), 0) )
1800         end = len(dup._int)
1801         exp = dup._exp
1802         while dup._int[end-1] == 0:
1803             exp += 1
1804             end -= 1
1805         return Decimal( (dup._sign, dup._int[:end], exp) )
1806
1807
1808     def quantize(self, exp, rounding=None, context=None, watchexp=1):
1809         """Quantize self so its exponent is the same as that of exp.
1810
1811         Similar to self._rescale(exp._exp) but with error checking.
1812         """
1813         if self._is_special or exp._is_special:
1814             ans = self._check_nans(exp, context)
1815             if ans:
1816                 return ans
1817
1818             if exp._isinfinity() or self._isinfinity():
1819                 if exp._isinfinity() and self._isinfinity():
1820                     return self  #if both are inf, it is OK
1821                 if context is None:
1822                     context = getcontext()
1823                 return context._raise_error(InvalidOperation,
1824                                         'quantize with one INF')
1825         return self._rescale(exp._exp, rounding, context, watchexp)
1826
1827     def same_quantum(self, other):
1828         """Test whether self and other have the same exponent.
1829
1830         same as self._exp == other._exp, except NaN == sNaN
1831         """
1832         if self._is_special or other._is_special:
1833             if self._isnan() or other._isnan():
1834                 return self._isnan() and other._isnan() and True
1835             if self._isinfinity() or other._isinfinity():
1836                 return self._isinfinity() and other._isinfinity() and True
1837         return self._exp == other._exp
1838
1839     def _rescale(self, exp, rounding=None, context=None, watchexp=1):
1840         """Rescales so that the exponent is exp.
1841
1842         exp = exp to scale to (an integer)
1843         rounding = rounding version
1844         watchexp: if set (default) an error is returned if exp is greater
1845         than Emax or less than Etiny.
1846         """
1847         if context is None:
1848             context = getcontext()
1849
1850         if self._is_special:
1851             if self._isinfinity():
1852                 return context._raise_error(InvalidOperation, 'rescale with an INF')
1853
1854             ans = self._check_nans(context=context)
1855             if ans:
1856                 return ans
1857
1858         if watchexp and (context.Emax  < exp or context.Etiny() > exp):
1859             return context._raise_error(InvalidOperation, 'rescale(a, INF)')
1860
1861         if not self:
1862             ans = Decimal(self)
1863             ans._int = (0,)
1864             ans._exp = exp
1865             return ans
1866
1867         diff = self._exp - exp
1868         digits = len(self._int) + diff
1869
1870         if watchexp and digits > context.prec:
1871             return context._raise_error(InvalidOperation, 'Rescale > prec')
1872
1873         tmp = Decimal(self)
1874         tmp._int = (0,) + tmp._int
1875         digits += 1
1876
1877         if digits < 0:
1878             tmp._exp = -digits + tmp._exp
1879             tmp._int = (0,1)
1880             digits = 1
1881         tmp = tmp._round(digits, rounding, context=context)
1882
1883         if tmp._int[0] == 0 and len(tmp._int) > 1:
1884             tmp._int = tmp._int[1:]
1885         tmp._exp = exp
1886
1887         tmp_adjusted = tmp.adjusted()
1888         if tmp and tmp_adjusted < context.Emin:
1889             context._raise_error(Subnormal)
1890         elif tmp and tmp_adjusted > context.Emax:
1891             return context._raise_error(InvalidOperation, 'rescale(a, INF)')
1892         return tmp
1893
1894     def to_integral(self, rounding=None, context=None):
1895         """Rounds to the nearest integer, without raising inexact, rounded."""
1896         if self._is_special:
1897             ans = self._check_nans(context=context)
1898             if ans:
1899                 return ans
1900         if self._exp >= 0:
1901             return self
1902         if context is None:
1903             context = getcontext()
1904         flags = context._ignore_flags(Rounded, Inexact)
1905         ans = self._rescale(0, rounding, context=context)
1906         context._regard_flags(flags)
1907         return ans
1908
1909     def sqrt(self, context=None):
1910         """Return the square root of self.
1911
1912         Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn))
1913         Should quadratically approach the right answer.
1914         """
1915         if self._is_special:
1916             ans = self._check_nans(context=context)
1917             if ans:
1918                 return ans
1919
1920             if self._isinfinity() and self._sign == 0:
1921                 return Decimal(self)
1922
1923         if not self:
1924             #exponent = self._exp / 2, using round_down.
1925             #if self._exp < 0:
1926             #    exp = (self._exp+1) // 2
1927             #else:
1928             exp = (self._exp) // 2
1929             if self._sign == 1:
1930                 #sqrt(-0) = -0
1931                 return Decimal( (1, (0,), exp))
1932             else:
1933                 return Decimal( (0, (0,), exp))
1934
1935         if context is None:
1936             context = getcontext()
1937
1938         if self._sign == 1:
1939             return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
1940
1941         tmp = Decimal(self)
1942
1943         expadd = tmp._exp // 2
1944         if tmp._exp & 1:
1945             tmp._int += (0,)
1946             tmp._exp = 0
1947         else:
1948             tmp._exp = 0
1949
1950         context = context._shallow_copy()
1951         flags = context._ignore_all_flags()
1952         firstprec = context.prec
1953         context.prec = 3
1954         if tmp.adjusted() & 1 == 0:
1955             ans = Decimal( (0, (8,1,9), tmp.adjusted()  - 2) )
1956             ans = ans.__add__(tmp.__mul__(Decimal((0, (2,5,9), -2)),
1957                                           context=context), context=context)
1958             ans._exp -= 1 + tmp.adjusted() // 2
1959         else:
1960             ans = Decimal( (0, (2,5,9), tmp._exp + len(tmp._int)- 3) )
1961             ans = ans.__add__(tmp.__mul__(Decimal((0, (8,1,9), -3)),
1962                                           context=context), context=context)
1963             ans._exp -= 1 + tmp.adjusted()  // 2
1964
1965         #ans is now a linear approximation.
1966
1967         Emax, Emin = context.Emax, context.Emin
1968         context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin
1969
1970         half = Decimal('0.5')
1971
1972         maxp = firstprec + 2
1973         rounding = context._set_rounding(ROUND_HALF_EVEN)
1974         while 1:
1975             context.prec = min(2*context.prec - 2, maxp)
1976             ans = half.__mul__(ans.__add__(tmp.__div__(ans, context=context),
1977                                            context=context), context=context)
1978             if context.prec == maxp:
1979                 break
1980
1981         #round to the answer's precision-- the only error can be 1 ulp.
1982         context.prec = firstprec
1983         prevexp = ans.adjusted()
1984         ans = ans._round(context=context)
1985
1986         #Now, check if the other last digits are better.
1987         context.prec = firstprec + 1
1988         # In case we rounded up another digit and we should actually go lower.
1989         if prevexp != ans.adjusted():
1990             ans._int += (0,)
1991             ans._exp -= 1
1992
1993
1994         lower = ans.__sub__(Decimal((0, (5,), ans._exp-1)), context=context)
1995         context._set_rounding(ROUND_UP)
1996         if lower.__mul__(lower, context=context) > (tmp):
1997             ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context)
1998
1999         else:
2000             upper = ans.__add__(Decimal((0, (5,), ans._exp-1)),context=context)
2001             context._set_rounding(ROUND_DOWN)
2002             if upper.__mul__(upper, context=context) < tmp:
2003                 ans = ans.__add__(Decimal((0, (1,), ans._exp)),context=context)
2004
2005         ans._exp += expadd
2006
2007         context.prec = firstprec
2008         context.rounding = rounding
2009         ans = ans._fix(context)
2010
2011         rounding = context._set_rounding_decision(NEVER_ROUND)
2012         if not ans.__mul__(ans, context=context) == self:
2013             # Only rounded/inexact if here.
2014             context._regard_flags(flags)
2015             context._raise_error(Rounded)
2016             context._raise_error(Inexact)
2017         else:
2018             #Exact answer, so let's set the exponent right.
2019             #if self._exp < 0:
2020             #    exp = (self._exp +1)// 2
2021             #else:
2022             exp = self._exp // 2
2023             context.prec += ans._exp - exp
2024             ans = ans._rescale(exp, context=context)
2025             context.prec = firstprec
2026             context._regard_flags(flags)
2027         context.Emax, context.Emin = Emax, Emin
2028
2029         return ans._fix(context)
2030
2031     def max(self, other, context=None):
2032         """Returns the larger value.
2033
2034         like max(self, other) except if one is not a number, returns
2035         NaN (and signals if one is sNaN).  Also rounds.
2036         """
2037         other = _convert_other(other)
2038         if other is NotImplemented:
2039             return other
2040
2041         if self._is_special or other._is_special:
2042             # if one operand is a quiet NaN and the other is number, then the
2043             # number is always returned
2044             sn = self._isnan()
2045             on = other._isnan()
2046             if sn or on:
2047                 if on == 1 and sn != 2:
2048                     return self
2049                 if sn == 1 and on != 2:
2050                     return other
2051                 return self._check_nans(other, context)
2052
2053         ans = self
2054         c = self.__cmp__(other)
2055         if c == 0:
2056             # if both operands are finite and equal in numerical value
2057             # then an ordering is applied:
2058             #
2059             # if the signs differ then max returns the operand with the
2060             # positive sign and min returns the operand with the negative sign
2061             #
2062             # if the signs are the same then the exponent is used to select
2063             # the result.
2064             if self._sign != other._sign:
2065                 if self._sign:
2066                     ans = other
2067             elif self._exp < other._exp and not self._sign:
2068                 ans = other
2069             elif self._exp > other._exp and self._sign:
2070                 ans = other
2071         elif c == -1:
2072             ans = other
2073
2074         if context is None:
2075             context = getcontext()
2076         if context._rounding_decision == ALWAYS_ROUND:
2077             return ans._fix(context)
2078         return ans
2079
2080     def min(self, other, context=None):
2081         """Returns the smaller value.
2082
2083         like min(self, other) except if one is not a number, returns
2084         NaN (and signals if one is sNaN).  Also rounds.
2085         """
2086         other = _convert_other(other)
2087         if other is NotImplemented:
2088             return other
2089
2090         if self._is_special or other._is_special:
2091             # if one operand is a quiet NaN and the other is number, then the
2092             # number is always returned
2093             sn = self._isnan()
2094             on = other._isnan()
2095             if sn or on:
2096                 if on == 1 and sn != 2:
2097                     return self
2098                 if sn == 1 and on != 2:
2099                     return other
2100                 return self._check_nans(other, context)
2101
2102         ans = self
2103         c = self.__cmp__(other)
2104         if c == 0:
2105             # if both operands are finite and equal in numerical value
2106             # then an ordering is applied:
2107             #
2108             # if the signs differ then max returns the operand with the
2109             # positive sign and min returns the operand with the negative sign
2110             #
2111             # if the signs are the same then the exponent is used to select
2112             # the result.
2113             if self._sign != other._sign:
2114                 if other._sign:
2115                     ans = other
2116             elif self._exp > other._exp and not self._sign:
2117                 ans = other
2118             elif self._exp < other._exp and self._sign:
2119                 ans = other
2120         elif c == 1:
2121             ans = other
2122
2123         if context is None:
2124             context = getcontext()
2125         if context._rounding_decision == ALWAYS_ROUND:
2126             return ans._fix(context)
2127         return ans
2128
2129     def _isinteger(self):
2130         """Returns whether self is an integer"""
2131         if self._exp >= 0:
2132             return True
2133         rest = self._int[self._exp:]
2134         return rest == (0,)*len(rest)
2135
2136     def _iseven(self):
2137         """Returns 1 if self is even.  Assumes self is an integer."""
2138         if self._exp > 0:
2139             return 1
2140         return self._int[-1+self._exp] & 1 == 0
2141
2142     def adjusted(self):
2143         """Return the adjusted exponent of self"""
2144         try:
2145             return self._exp + len(self._int) - 1
2146         #If NaN or Infinity, self._exp is string
2147         except TypeError:
2148             return 0
2149
2150     # support for pickling, copy, and deepcopy
2151     def __reduce__(self):
2152         return (self.__class__, (str(self),))
2153
2154     def __copy__(self):
2155         if type(self) == Decimal:
2156             return self     # I'm immutable; therefore I am my own clone
2157         return self.__class__(str(self))
2158
2159     def __deepcopy__(self, memo):
2160         if type(self) == Decimal:
2161             return self     # My components are also immutable
2162         return self.__class__(str(self))
2163
2164 ##### Context class ###########################################
2165
2166
2167 # get rounding method function:
2168 rounding_functions = [name for name in Decimal.__dict__.keys() if name.startswith('_round_')]
2169 for name in rounding_functions:
2170     #name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
2171     globalname = name[1:].upper()
2172     val = globals()[globalname]
2173     Decimal._pick_rounding_function[val] = name
2174
2175 del name, val, globalname, rounding_functions
2176
2177 class Context(object):
2178     """Contains the context for a Decimal instance.
2179
2180     Contains:
2181     prec - precision (for use in rounding, division, square roots..)
2182     rounding - rounding type. (how you round)
2183     _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
2184     traps - If traps[exception] = 1, then the exception is
2185                     raised when it is caused.  Otherwise, a value is
2186                     substituted in.
2187     flags  - When an exception is caused, flags[exception] is incremented.
2188              (Whether or not the trap_enabler is set)
2189              Should be reset by user of Decimal instance.
2190     Emin -   Minimum exponent
2191     Emax -   Maximum exponent
2192     capitals -      If 1, 1*10^1 is printed as 1E+1.
2193                     If 0, printed as 1e1
2194     _clamp - If 1, change exponents if too high (Default 0)
2195     """
2196
2197     def __init__(self, prec=None, rounding=None,
2198                  traps=None, flags=None,
2199                  _rounding_decision=None,
2200                  Emin=None, Emax=None,
2201                  capitals=None, _clamp=0,
2202                  _ignored_flags=None):
2203         if flags is None:
2204             flags = []
2205         if _ignored_flags is None:
2206             _ignored_flags = []
2207         if not isinstance(flags, dict):
2208             flags = dict([(s,s in flags) for s in _signals])
2209             del s
2210         if traps is not None and not isinstance(traps, dict):
2211             traps = dict([(s,s in traps) for s in _signals])
2212             del s
2213         for name, val in locals().items():
2214             if val is None:
2215                 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
2216             else:
2217                 setattr(self, name, val)
2218         del self.self
2219
2220     def __repr__(self):
2221         """Show the current context."""
2222         s = []
2223         s.append('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self))
2224         s.append('flags=[' + ', '.join([f.__name__ for f, v in self.flags.items() if v]) + ']')
2225         s.append('traps=[' + ', '.join([t.__name__ for t, v in self.traps.items() if v]) + ']')
2226         return ', '.join(s) + ')'
2227
2228     def clear_flags(self):
2229         """Reset all flags to zero"""
2230         for flag in self.flags:
2231             self.flags[flag] = 0
2232
2233     def _shallow_copy(self):
2234         """Returns a shallow copy from self."""
2235         nc = Context(self.prec, self.rounding, self.traps, self.flags,
2236                          self._rounding_decision, self.Emin, self.Emax,
2237                          self.capitals, self._clamp, self._ignored_flags)
2238         return nc
2239
2240     def copy(self):
2241         """Returns a deep copy from self."""
2242         nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(),
2243                          self._rounding_decision, self.Emin, self.Emax,
2244                          self.capitals, self._clamp, self._ignored_flags)
2245         return nc
2246     __copy__ = copy
2247
2248     def _raise_error(self, condition, explanation = None, *args):
2249         """Handles an error
2250
2251         If the flag is in _ignored_flags, returns the default response.
2252         Otherwise, it increments the flag, then, if the corresponding
2253         trap_enabler is set, it reaises the exception.  Otherwise, it returns
2254         the default value after incrementing the flag.
2255         """
2256         error = _condition_map.get(condition, condition)
2257         if error in self._ignored_flags:
2258             #Don't touch the flag
2259             return error().handle(self, *args)
2260
2261         self.flags[error] += 1
2262         if not self.traps[error]:
2263             #The errors define how to handle themselves.
2264             return condition().handle(self, *args)
2265
2266         # Errors should only be risked on copies of the context
2267         #self._ignored_flags = []
2268         raise error, explanation
2269
2270     def _ignore_all_flags(self):
2271         """Ignore all flags, if they are raised"""
2272         return self._ignore_flags(*_signals)
2273
2274     def _ignore_flags(self, *flags):
2275         """Ignore the flags, if they are raised"""
2276         # Do not mutate-- This way, copies of a context leave the original
2277         # alone.
2278         self._ignored_flags = (self._ignored_flags + list(flags))
2279         return list(flags)
2280
2281     def _regard_flags(self, *flags):
2282         """Stop ignoring the flags, if they are raised"""
2283         if flags and isinstance(flags[0], (tuple,list)):
2284             flags = flags[0]
2285         for flag in flags:
2286             self._ignored_flags.remove(flag)
2287
2288     def __hash__(self):
2289         """A Context cannot be hashed."""
2290         # We inherit object.__hash__, so we must deny this explicitly
2291         raise TypeError, "Cannot hash a Context."
2292
2293     def Etiny(self):
2294         """Returns Etiny (= Emin - prec + 1)"""
2295         return int(self.Emin - self.prec + 1)
2296
2297     def Etop(self):
2298         """Returns maximum exponent (= Emax - prec + 1)"""
2299         return int(self.Emax - self.prec + 1)
2300
2301     def _set_rounding_decision(self, type):
2302         """Sets the rounding decision.
2303
2304         Sets the rounding decision, and returns the current (previous)
2305         rounding decision.  Often used like:
2306
2307         context = context._shallow_copy()
2308         # That so you don't change the calling context
2309         # if an error occurs in the middle (say DivisionImpossible is raised).
2310
2311         rounding = context._set_rounding_decision(NEVER_ROUND)
2312         instance = instance / Decimal(2)
2313         context._set_rounding_decision(rounding)
2314
2315         This will make it not round for that operation.
2316         """
2317
2318         rounding = self._rounding_decision
2319         self._rounding_decision = type
2320         return rounding
2321
2322     def _set_rounding(self, type):
2323         """Sets the rounding type.
2324
2325         Sets the rounding type, and returns the current (previous)
2326         rounding type.  Often used like:
2327
2328         context = context.copy()
2329         # so you don't change the calling context
2330         # if an error occurs in the middle.
2331         rounding = context._set_rounding(ROUND_UP)
2332         val = self.__sub__(other, context=context)
2333         context._set_rounding(rounding)
2334
2335         This will make it round up for that operation.
2336         """
2337         rounding = self.rounding
2338         self.rounding= type
2339         return rounding
2340
2341     def create_decimal(self, num='0'):
2342         """Creates a new Decimal instance but using self as context."""
2343         d = Decimal(num, context=self)
2344         return d._fix(self)
2345
2346     #Methods
2347     def abs(self, a):
2348         """Returns the absolute value of the operand.
2349
2350         If the operand is negative, the result is the same as using the minus
2351         operation on the operand. Otherwise, the result is the same as using
2352         the plus operation on the operand.
2353
2354         >>> ExtendedContext.abs(Decimal('2.1'))
2355         Decimal("2.1")
2356         >>> ExtendedContext.abs(Decimal('-100'))
2357         Decimal("100")
2358         >>> ExtendedContext.abs(Decimal('101.5'))
2359         Decimal("101.5")
2360         >>> ExtendedContext.abs(Decimal('-101.5'))
2361         Decimal("101.5")
2362         """
2363         return a.__abs__(context=self)
2364
2365     def add(self, a, b):
2366         """Return the sum of the two operands.
2367
2368         >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
2369         Decimal("19.00")
2370         >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
2371         Decimal("1.02E+4")
2372         """
2373         return a.__add__(b, context=self)
2374
2375     def _apply(self, a):
2376         return str(a._fix(self))
2377
2378     def compare(self, a, b):
2379         """Compares values numerically.
2380
2381         If the signs of the operands differ, a value representing each operand
2382         ('-1' if the operand is less than zero, '0' if the operand is zero or
2383         negative zero, or '1' if the operand is greater than zero) is used in
2384         place of that operand for the comparison instead of the actual
2385         operand.
2386
2387         The comparison is then effected by subtracting the second operand from
2388         the first and then returning a value according to the result of the
2389         subtraction: '-1' if the result is less than zero, '0' if the result is
2390         zero or negative zero, or '1' if the result is greater than zero.
2391
2392         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
2393         Decimal("-1")
2394         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
2395         Decimal("0")
2396         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
2397         Decimal("0")
2398         >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
2399         Decimal("1")
2400         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
2401         Decimal("1")
2402         >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
2403         Decimal("-1")
2404         """
2405         return a.compare(b, context=self)
2406
2407     def divide(self, a, b):
2408         """Decimal division in a specified context.
2409
2410         >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
2411         Decimal("0.333333333")
2412         >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
2413         Decimal("0.666666667")
2414         >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
2415         Decimal("2.5")
2416         >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
2417         Decimal("0.1")
2418         >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
2419         Decimal("1")
2420         >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
2421         Decimal("4.00")
2422         >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
2423         Decimal("1.20")
2424         >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
2425         Decimal("10")
2426         >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
2427         Decimal("1000")
2428         >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
2429         Decimal("1.20E+6")
2430         """
2431         return a.__div__(b, context=self)
2432
2433     def divide_int(self, a, b):
2434         """Divides two numbers and returns the integer part of the result.
2435
2436         >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
2437         Decimal("0")
2438         >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
2439         Decimal("3")
2440         >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
2441         Decimal("3")
2442         """
2443         return a.__floordiv__(b, context=self)
2444
2445     def divmod(self, a, b):
2446         return a.__divmod__(b, context=self)
2447
2448     def max(self, a,b):
2449         """max compares two values numerically and returns the maximum.
2450
2451         If either operand is a NaN then the general rules apply.
2452         Otherwise, the operands are compared as as though by the compare
2453         operation. If they are numerically equal then the left-hand operand
2454         is chosen as the result. Otherwise the maximum (closer to positive
2455         infinity) of the two operands is chosen as the result.
2456
2457         >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
2458         Decimal("3")
2459         >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
2460         Decimal("3")
2461         >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
2462         Decimal("1")
2463         >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
2464         Decimal("7")
2465         """
2466         return a.max(b, context=self)
2467
2468     def min(self, a,b):
2469         """min compares two values numerically and returns the minimum.
2470
2471         If either operand is a NaN then the general rules apply.
2472         Otherwise, the operands are compared as as though by the compare
2473         operation. If they are numerically equal then the left-hand operand
2474         is chosen as the result. Otherwise the minimum (closer to negative
2475         infinity) of the two operands is chosen as the result.
2476
2477         >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
2478         Decimal("2")
2479         >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
2480         Decimal("-10")
2481         >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
2482         Decimal("1.0")
2483         >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
2484         Decimal("7")
2485         """
2486         return a.min(b, context=self)
2487
2488     def minus(self, a):
2489         """Minus corresponds to unary prefix minus in Python.
2490
2491         The operation is evaluated using the same rules as subtract; the
2492         operation minus(a) is calculated as subtract('0', a) where the '0'
2493         has the same exponent as the operand.
2494
2495         >>> ExtendedContext.minus(Decimal('1.3'))
2496         Decimal("-1.3")
2497         >>> ExtendedContext.minus(Decimal('-1.3'))
2498         Decimal("1.3")
2499         """
2500         return a.__neg__(context=self)
2501
2502     def multiply(self, a, b):
2503         """multiply multiplies two operands.
2504
2505         If either operand is a special value then the general rules apply.
2506         Otherwise, the operands are multiplied together ('long multiplication'),
2507         resulting in a number which may be as long as the sum of the lengths
2508         of the two operands.
2509
2510         >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
2511         Decimal("3.60")
2512         >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
2513         Decimal("21")
2514         >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
2515         Decimal("0.72")
2516         >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
2517         Decimal("-0.0")
2518         >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
2519         Decimal("4.28135971E+11")
2520         """
2521         return a.__mul__(b, context=self)
2522
2523     def normalize(self, a):
2524         """normalize reduces an operand to its simplest form.
2525
2526         Essentially a plus operation with all trailing zeros removed from the
2527         result.
2528
2529         >>> ExtendedContext.normalize(Decimal('2.1'))
2530         Decimal("2.1")
2531         >>> ExtendedContext.normalize(Decimal('-2.0'))
2532         Decimal("-2")
2533         >>> ExtendedContext.normalize(Decimal('1.200'))
2534         Decimal("1.2")
2535         >>> ExtendedContext.normalize(Decimal('-120'))
2536         Decimal("-1.2E+2")
2537         >>> ExtendedContext.normalize(Decimal('120.00'))
2538         Decimal("1.2E+2")
2539         >>> ExtendedContext.normalize(Decimal('0.00'))
2540         Decimal("0")
2541         """
2542         return a.normalize(context=self)
2543
2544     def plus(self, a):
2545         """Plus corresponds to unary prefix plus in Python.
2546
2547         The operation is evaluated using the same rules as add; the
2548         operation plus(a) is calculated as add('0', a) where the '0'
2549         has the same exponent as the operand.
2550
2551         >>> ExtendedContext.plus(Decimal('1.3'))
2552         Decimal("1.3")
2553         >>> ExtendedContext.plus(Decimal('-1.3'))
2554         Decimal("-1.3")
2555         """
2556         return a.__pos__(context=self)
2557
2558     def power(self, a, b, modulo=None):
2559         """Raises a to the power of b, to modulo if given.
2560
2561         The right-hand operand must be a whole number whose integer part (after
2562         any exponent has been applied) has no more than 9 digits and whose
2563         fractional part (if any) is all zeros before any rounding. The operand
2564         may be positive, negative, or zero; if negative, the absolute value of
2565         the power is used, and the left-hand operand is inverted (divided into
2566         1) before use.
2567
2568         If the increased precision needed for the intermediate calculations
2569         exceeds the capabilities of the implementation then an Invalid operation
2570         condition is raised.
2571
2572         If, when raising to a negative power, an underflow occurs during the
2573         division into 1, the operation is not halted at that point but
2574         continues.
2575
2576         >>> ExtendedContext.power(Decimal('2'), Decimal('3'))
2577         Decimal("8")
2578         >>> ExtendedContext.power(Decimal('2'), Decimal('-3'))
2579         Decimal("0.125")
2580         >>> ExtendedContext.power(Decimal('1.7'), Decimal('8'))
2581         Decimal("69.7575744")
2582         >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-2'))
2583         Decimal("0")
2584         >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-1'))
2585         Decimal("0")
2586         >>> ExtendedContext.power(Decimal('Infinity'), Decimal('0'))
2587         Decimal("1")
2588         >>> ExtendedContext.power(Decimal('Infinity'), Decimal('1'))
2589         Decimal("Infinity")
2590         >>> ExtendedContext.power(Decimal('Infinity'), Decimal('2'))
2591         Decimal("Infinity")
2592         >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-2'))
2593         Decimal("0")
2594         >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-1'))
2595         Decimal("-0")
2596         >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('0'))
2597         Decimal("1")
2598         >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('1'))
2599         Decimal("-Infinity")
2600         >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('2'))
2601         Decimal("Infinity")
2602         >>> ExtendedContext.power(Decimal('0'), Decimal('0'))
2603         Decimal("NaN")
2604         """
2605         return a.__pow__(b, modulo, context=self)
2606
2607     def quantize(self, a, b):
2608         """Returns a value equal to 'a' (rounded) and having the exponent of 'b'.
2609
2610         The coefficient of the result is derived from that of the left-hand
2611         operand. It may be rounded using the current rounding setting (if the
2612         exponent is being increased), multiplied by a positive power of ten (if
2613         the exponent is being decreased), or is unchanged (if the exponent is
2614         already equal to that of the right-hand operand).
2615
2616         Unlike other operations, if the length of the coefficient after the
2617         quantize operation would be greater than precision then an Invalid
2618         operation condition is raised. This guarantees that, unless there is an
2619         error condition, the exponent of the result of a quantize is always
2620         equal to that of the right-hand operand.
2621
2622         Also unlike other operations, quantize will never raise Underflow, even
2623         if the result is subnormal and inexact.
2624
2625         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
2626         Decimal("2.170")
2627         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
2628         Decimal("2.17")
2629         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
2630         Decimal("2.2")
2631         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
2632         Decimal("2")
2633         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
2634         Decimal("0E+1")
2635         >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
2636         Decimal("-Infinity")
2637         >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
2638         Decimal("NaN")
2639         >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
2640         Decimal("-0")
2641         >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
2642         Decimal("-0E+5")
2643         >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
2644         Decimal("NaN")
2645         >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
2646         Decimal("NaN")
2647         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
2648         Decimal("217.0")
2649         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
2650         Decimal("217")
2651         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
2652         Decimal("2.2E+2")
2653         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
2654         Decimal("2E+2")
2655         """
2656         return a.quantize(b, context=self)
2657
2658     def remainder(self, a, b):
2659         """Returns the remainder from integer division.
2660
2661         The result is the residue of the dividend after the operation of
2662         calculating integer division as described for divide-integer, rounded to
2663         precision digits if necessary. The sign of the result, if non-zero, is
2664         the same as that of the original dividend.
2665
2666         This operation will fail under the same conditions as integer division
2667         (that is, if integer division on the same two operands would fail, the
2668         remainder cannot be calculated).
2669
2670         >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
2671         Decimal("2.1")
2672         >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
2673         Decimal("1")
2674         >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
2675         Decimal("-1")
2676         >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
2677         Decimal("0.2")
2678         >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
2679         Decimal("0.1")
2680         >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
2681         Decimal("1.0")
2682         """
2683         return a.__mod__(b, context=self)
2684
2685     def remainder_near(self, a, b):
2686         """Returns to be "a - b * n", where n is the integer nearest the exact
2687         value of "x / b" (if two integers are equally near then the even one
2688         is chosen). If the result is equal to 0 then its sign will be the
2689         sign of a.
2690
2691         This operation will fail under the same conditions as integer division
2692         (that is, if integer division on the same two operands would fail, the
2693         remainder cannot be calculated).
2694
2695         >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
2696         Decimal("-0.9")
2697         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
2698         Decimal("-2")
2699         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
2700         Decimal("1")
2701         >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
2702         Decimal("-1")
2703         >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
2704         Decimal("0.2")
2705         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
2706         Decimal("0.1")
2707         >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
2708         Decimal("-0.3")
2709         """
2710         return a.remainder_near(b, context=self)
2711
2712     def same_quantum(self, a, b):
2713         """Returns True if the two operands have the same exponent.
2714
2715         The result is never affected by either the sign or the coefficient of
2716         either operand.
2717
2718         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
2719         False
2720         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
2721         True
2722         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
2723         False
2724         >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
2725         True
2726         """
2727         return a.same_quantum(b)
2728
2729     def sqrt(self, a):
2730         """Returns the square root of a non-negative number to context precision.
2731
2732         If the result must be inexact, it is rounded using the round-half-even
2733         algorithm.
2734
2735         >>> ExtendedContext.sqrt(Decimal('0'))
2736         Decimal("0")
2737         >>> ExtendedContext.sqrt(Decimal('-0'))
2738         Decimal("-0")
2739         >>> ExtendedContext.sqrt(Decimal('0.39'))
2740         Decimal("0.624499800")
2741         >>> ExtendedContext.sqrt(Decimal('100'))
2742         Decimal("10")
2743         >>> ExtendedContext.sqrt(Decimal('1'))
2744         Decimal("1")
2745         >>> ExtendedContext.sqrt(Decimal('1.0'))
2746         Decimal("1.0")
2747         >>> ExtendedContext.sqrt(Decimal('1.00'))
2748         Decimal("1.0")
2749         >>> ExtendedContext.sqrt(Decimal('7'))
2750         Decimal("2.64575131")
2751         >>> ExtendedContext.sqrt(Decimal('10'))
2752         Decimal("3.16227766")
2753         >>> ExtendedContext.prec
2754         9
2755         """
2756         return a.sqrt(context=self)
2757
2758     def subtract(self, a, b):
2759         """Return the difference between the two operands.
2760
2761         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
2762         Decimal("0.23")
2763         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
2764         Decimal("0.00")
2765         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
2766         Decimal("-0.77")
2767         """
2768         return a.__sub__(b, context=self)
2769
2770     def to_eng_string(self, a):
2771         """Converts a number to a string, using scientific notation.
2772
2773         The operation is not affected by the context.
2774         """
2775         return a.to_eng_string(context=self)
2776
2777     def to_sci_string(self, a):
2778         """Converts a number to a string, using scientific notation.
2779
2780         The operation is not affected by the context.
2781         """
2782         return a.__str__(context=self)
2783
2784     def to_integral(self, a):
2785         """Rounds to an integer.
2786
2787         When the operand has a negative exponent, the result is the same
2788         as using the quantize() operation using the given operand as the
2789         left-hand-operand, 1E+0 as the right-hand-operand, and the precision
2790         of the operand as the precision setting, except that no flags will
2791         be set. The rounding mode is taken from the context.
2792
2793         >>> ExtendedContext.to_integral(Decimal('2.1'))
2794         Decimal("2")
2795         >>> ExtendedContext.to_integral(Decimal('100'))
2796         Decimal("100")
2797         >>> ExtendedContext.to_integral(Decimal('100.0'))
2798         Decimal("100")
2799         >>> ExtendedContext.to_integral(Decimal('101.5'))
2800         Decimal("102")
2801         >>> ExtendedContext.to_integral(Decimal('-101.5'))
2802         Decimal("-102")
2803         >>> ExtendedContext.to_integral(Decimal('10E+5'))
2804         Decimal("1.0E+6")
2805         >>> ExtendedContext.to_integral(Decimal('7.89E+77'))
2806         Decimal("7.89E+77")
2807         >>> ExtendedContext.to_integral(Decimal('-Inf'))
2808         Decimal("-Infinity")
2809         """
2810         return a.to_integral(context=self)
2811
2812 class _WorkRep(object):
2813     __slots__ = ('sign','int','exp')
2814     # sign: 0 or 1
2815     # int:  int or long
2816     # exp:  None, int, or string
2817
2818     def __init__(self, value=None):
2819         if value is None:
2820             self.sign = None
2821             self.int = 0
2822             self.exp = None
2823         elif isinstance(value, Decimal):
2824             self.sign = value._sign
2825             cum = 0
2826             for digit  in value._int:
2827                 cum = cum * 10 + digit
2828             self.int = cum
2829             self.exp = value._exp
2830         else:
2831             # assert isinstance(value, tuple)
2832             self.sign = value[0]
2833             self.int = value[1]
2834             self.exp = value[2]
2835
2836     def __repr__(self):
2837         return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
2838
2839     __str__ = __repr__
2840
2841
2842
2843 def _normalize(op1, op2, shouldround = 0, prec = 0):
2844     """Normalizes op1, op2 to have the same exp and length of coefficient.
2845
2846     Done during addition.
2847     """
2848     # Yes, the exponent is a long, but the difference between exponents
2849     # must be an int-- otherwise you'd get a big memory problem.
2850     numdigits = int(op1.exp - op2.exp)
2851     if numdigits < 0:
2852         numdigits = -numdigits
2853         tmp = op2
2854         other = op1
2855     else:
2856         tmp = op1
2857         other = op2
2858
2859
2860     if shouldround and numdigits > prec + 1:
2861         # Big difference in exponents - check the adjusted exponents
2862         tmp_len = len(str(tmp.int))
2863         other_len = len(str(other.int))
2864         if numdigits > (other_len + prec + 1 - tmp_len):
2865             # If the difference in adjusted exps is > prec+1, we know
2866             # other is insignificant, so might as well put a 1 after the precision.
2867             # (since this is only for addition.)  Also stops use of massive longs.
2868
2869             extend = prec + 2 - tmp_len
2870             if extend <= 0:
2871                 extend = 1
2872             tmp.int *= 10 ** extend
2873             tmp.exp -= extend
2874             other.int = 1
2875             other.exp = tmp.exp
2876             return op1, op2
2877
2878     tmp.int *= 10 ** numdigits
2879     tmp.exp -= numdigits
2880     return op1, op2
2881
2882 def _adjust_coefficients(op1, op2):
2883     """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
2884
2885     Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp.
2886
2887     Used on _WorkRep instances during division.
2888     """
2889     adjust = 0
2890     #If op1 is smaller, make it larger
2891     while op2.int > op1.int:
2892         op1.int *= 10
2893         op1.exp -= 1
2894         adjust += 1
2895
2896     #If op2 is too small, make it larger
2897     while op1.int >= (10 * op2.int):
2898         op2.int *= 10
2899         op2.exp -= 1
2900         adjust -= 1
2901
2902     return op1, op2, adjust
2903
2904 ##### Helper Functions ########################################
2905
2906 def _convert_other(other):
2907     """Convert other to Decimal.
2908
2909     Verifies that it's ok to use in an implicit construction.
2910     """
2911     if isinstance(other, Decimal):
2912         return other
2913     if isinstance(other, (int, long)):
2914         return Decimal(other)
2915     return NotImplemented
2916
2917 _infinity_map = {
2918     'inf' : 1,
2919     'infinity' : 1,
2920     '+inf' : 1,
2921     '+infinity' : 1,
2922     '-inf' : -1,
2923     '-infinity' : -1
2924 }
2925
2926 def _isinfinity(num):
2927     """Determines whether a string or float is infinity.
2928
2929     +1 for negative infinity; 0 for finite ; +1 for positive infinity
2930     """
2931     num = str(num).lower()
2932     return _infinity_map.get(num, 0)
2933
2934 def _isnan(num):
2935     """Determines whether a string or float is NaN
2936
2937     (1, sign, diagnostic info as string) => NaN
2938     (2, sign, diagnostic info as string) => sNaN
2939     0 => not a NaN
2940     """
2941     num = str(num).lower()
2942     if not num:
2943         return 0
2944
2945     #get the sign, get rid of trailing [+-]
2946     sign = 0
2947     if num[0] == '+':
2948         num = num[1:]
2949     elif num[0] == '-':  #elif avoids '+-nan'
2950         num = num[1:]
2951         sign = 1
2952
2953     if num.startswith('nan'):
2954         if len(num) > 3 and not num[3:].isdigit(): #diagnostic info
2955             return 0
2956         return (1, sign, num[3:].lstrip('0'))
2957     if num.startswith('snan'):
2958         if len(num) > 4 and not num[4:].isdigit():
2959             return 0
2960         return (2, sign, num[4:].lstrip('0'))
2961     return 0
2962
2963
2964 ##### Setup Specific Contexts ################################
2965
2966 # The default context prototype used by Context()
2967 # Is mutable, so that new contexts can have different default values
2968
2969 DefaultContext = Context(
2970         prec=28, rounding=ROUND_HALF_EVEN,
2971         traps=[DivisionByZero, Overflow, InvalidOperation],
2972         flags=[],
2973         _rounding_decision=ALWAYS_ROUND,
2974         Emax=999999999,
2975         Emin=-999999999,
2976         capitals=1
2977 )
2978
2979 # Pre-made alternate contexts offered by the specification
2980 # Don't change these; the user should be able to select these
2981 # contexts and be able to reproduce results from other implementations
2982 # of the spec.
2983
2984 BasicContext = Context(
2985         prec=9, rounding=ROUND_HALF_UP,
2986         traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
2987         flags=[],
2988 )
2989
2990 ExtendedContext = Context(
2991         prec=9, rounding=ROUND_HALF_EVEN,
2992         traps=[],
2993         flags=[],
2994 )
2995
2996
2997 ##### Useful Constants (internal use only) ####################
2998
2999 #Reusable defaults
3000 Inf = Decimal('Inf')
3001 negInf = Decimal('-Inf')
3002
3003 #Infsign[sign] is infinity w/ that sign
3004 Infsign = (Inf, negInf)
3005
3006 NaN = Decimal('NaN')
3007
3008
3009 ##### crud for parsing strings #################################
3010 import re
3011
3012 # There's an optional sign at the start, and an optional exponent
3013 # at the end.  The exponent has an optional sign and at least one
3014 # digit.  In between, must have either at least one digit followed
3015 # by an optional fraction, or a decimal point followed by at least
3016 # one digit.  Yuck.
3017
3018 _parser = re.compile(r"""
3019 #    \s*
3020     (?P<sign>[-+])?
3021     (
3022         (?P<int>\d+) (\. (?P<frac>\d*))?
3023     |
3024         \. (?P<onlyfrac>\d+)
3025     )
3026     ([eE](?P<exp>[-+]? \d+))?
3027 #    \s*
3028     $
3029 """, re.VERBOSE).match #Uncomment the \s* to allow leading or trailing spaces.
3030
3031 del re
3032
3033 # return sign, n, p s.t. float string value == -1**sign * n * 10**p exactly
3034
3035 def _string2exact(s):
3036     m = _parser(s)
3037     if m is None:
3038         raise ValueError("invalid literal for Decimal: %r" % s)
3039
3040     if m.group('sign') == "-":
3041         sign = 1
3042     else:
3043         sign = 0
3044
3045     exp = m.group('exp')
3046     if exp is None:
3047         exp = 0
3048     else:
3049         exp = int(exp)
3050
3051     intpart = m.group('int')
3052     if intpart is None:
3053         intpart = ""
3054         fracpart = m.group('onlyfrac')
3055     else:
3056         fracpart = m.group('frac')
3057         if fracpart is None:
3058             fracpart = ""
3059
3060     exp -= len(fracpart)
3061
3062     mantissa = intpart + fracpart
3063     tmp = map(int, mantissa)
3064     backup = tmp
3065     while tmp and tmp[0] == 0:
3066         del tmp[0]
3067
3068     # It's a zero
3069     if not tmp:
3070         if backup:
3071             return (sign, tuple(backup), exp)
3072         return (sign, (0,), exp)
3073     mantissa = tuple(tmp)
3074
3075     return (sign, mantissa, exp)
3076
3077
3078 if __name__ == '__main__':
3079     import doctest, sys
3080     doctest.testmod(sys.modules[__name__])
3081
3082 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
3083