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