~ubuntu-branches/ubuntu/hardy/gnue-common/hardy

« back to all changes in this revision

Viewing changes to src/external/decimal.py

  • Committer: Bazaar Package Importer
  • Author(s): Andrew Mitchell
  • Date: 2005-03-09 11:06:31 UTC
  • Revision ID: james.westby@ubuntu.com-20050309110631-8gvvn39q7tjz1kj6
Tags: upstream-0.5.14
ImportĀ upstreamĀ versionĀ 0.5.14

Show diffs side-by-side

added added

removed removed

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