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