1
# Copyright (c) 2004 Python Software Foundation.
5
# *********************************************************
6
# NOTE: This includes several patches to make it work
7
# on Python 2.1, so don't simply copy a new decimal.py
9
# *********************************************************
13
# Written by Eric Price <eprice at tjhsst.edu>
14
# and Facundo Batista <facundo at taniquetil.com.ar>
15
# and Raymond Hettinger <python at rcn.com>
16
# and Aahz <aahz at pobox.com>
19
# This module is currently Py2.3 compatible and should be kept that way
20
# unless a major compelling advantage arises. IOW, 2.3 compatibility is
21
# strongly preferred, but not guaranteed.
23
# Also, this module should be kept in sync with the latest updates of
24
# the IBM specification as it evolves. Those updates will be treated
25
# as bug fixes (deviation from the spec is a compatibility, usability
26
# bug) and will be backported. At this point the spec is stabilizing
27
# and the updates are becoming fewer, smaller, and less significant.
30
This is a Py2.3 implementation of decimal floating point arithmetic based on
31
the General Decimal Arithmetic Specification:
33
www2.hursley.ibm.com/decimal/decarith.html
35
and IEEE standard 854-1987:
37
www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
39
Decimal floating point has finite precision with arbitrarily large bounds.
41
The purpose of the module is to support arithmetic using familiar
42
"schoolhouse" rules and to avoid the some of tricky representation
43
issues associated with binary floating point. The package is especially
44
useful for financial applications or for contexts where users have
45
expectations that are at odds with binary floating point (for instance,
46
in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
47
of the expected Decimal("0.00") returned by decimal floating point).
49
Here are some examples of using the decimal module:
51
>>> from decimal import *
52
>>> setcontext(ExtendedContext)
61
>>> Decimal("123.45e12345678901234567890")
62
Decimal("1.2345E+12345678901234567892")
63
>>> Decimal("1.33") + Decimal("1.27")
65
>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
68
>>> print dig / Decimal(3)
70
>>> getcontext().prec = 18
71
>>> print dig / Decimal(3)
75
>>> print Decimal(3).sqrt()
77
>>> print Decimal(3) ** 123
78
4.85192780976896427E+58
79
>>> inf = Decimal(1) / Decimal(0)
82
>>> neginf = Decimal(-1) / Decimal(0)
85
>>> print neginf + inf
87
>>> print neginf * inf
91
>>> getcontext().traps[DivisionByZero] = 1
93
Traceback (most recent call last):
99
>>> c.traps[InvalidOperation] = 0
100
>>> print c.flags[InvalidOperation]
102
>>> c.divide(Decimal(0), Decimal(0))
104
>>> c.traps[InvalidOperation] = 1
105
>>> print c.flags[InvalidOperation]
107
>>> c.flags[InvalidOperation] = 0
108
>>> print c.flags[InvalidOperation]
110
>>> print c.divide(Decimal(0), Decimal(0))
111
Traceback (most recent call last):
115
InvalidOperation: 0 / 0
116
>>> print c.flags[InvalidOperation]
118
>>> c.flags[InvalidOperation] = 0
119
>>> c.traps[InvalidOperation] = 0
120
>>> print c.divide(Decimal(0), Decimal(0))
122
>>> print c.flags[InvalidOperation]
139
basestring = type("")
143
'Decimal', 'Context',
146
'DefaultContext', 'BasicContext', 'ExtendedContext',
149
'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
150
'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
152
# Constants for use in setting up contexts
153
'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
154
'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN',
156
# Functions for manipulating contexts
157
'setcontext', 'getcontext'
164
ROUND_DOWN = 'ROUND_DOWN'
165
ROUND_HALF_UP = 'ROUND_HALF_UP'
166
ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
167
ROUND_CEILING = 'ROUND_CEILING'
168
ROUND_FLOOR = 'ROUND_FLOOR'
169
ROUND_UP = 'ROUND_UP'
170
ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
172
#Rounding decision (not part of the public API)
173
NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY
174
ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end.
178
class DecimalException(ArithmeticError):
179
"""Base exception class.
181
Used exceptions derive from this.
182
If an exception derives from another exception besides this (such as
183
Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
184
called if the others are present. This isn't actually used for
187
handle -- Called when context._raise_error is called and the
188
trap_enabler is set. First argument is self, second is the
189
context. More arguments can be given, those being after
190
the explanation in _raise_error (For example,
191
context._raise_error(NewError, '(-x)!', self._sign) would
192
call NewError().handle(context, self._sign).)
194
To define a new exception, it should be sufficient to have it derive
195
from DecimalException.
197
def handle(self, context, *args):
201
class Clamped(DecimalException):
202
"""Exponent of a 0 changed to fit bounds.
204
This occurs and signals clamped if the exponent of a result has been
205
altered in order to fit the constraints of a specific concrete
206
representation. This may occur when the exponent of a zero result would
207
be outside the bounds of a representation, or when a large normal
208
number would have an encoded exponent that cannot be represented. In
209
this latter case, the exponent is reduced to fit and the corresponding
210
number of zero digits are appended to the coefficient ("fold-down").
214
class InvalidOperation(DecimalException):
215
"""An invalid operation was performed.
217
Various bad things cause this:
219
Something creates a signaling NaN
225
x._rescale( non-integer )
230
An operand is invalid
232
def handle(self, context, *args):
234
if args[0] == 1: #sNaN, must drop 's' but keep diagnostics
235
return Decimal( (args[1]._sign, args[1]._int, 'n') )
238
class ConversionSyntax(InvalidOperation):
239
"""Trying to convert badly formed string.
241
This occurs and signals invalid-operation if an string is being
242
converted to a number and it does not conform to the numeric string
243
syntax. The result is [0,qNaN].
246
def handle(self, context, *args):
247
return (0, (0,), 'n') #Passed to something which uses a tuple.
249
class DivisionByZero(DecimalException, ZeroDivisionError):
252
This occurs and signals division-by-zero if division of a finite number
253
by zero was attempted (during a divide-integer or divide operation, or a
254
power operation with negative right-hand operand), and the dividend was
257
The result of the operation is [sign,inf], where sign is the exclusive
258
or of the signs of the operands for divide, or is 1 for an odd power of
262
def handle(self, context, sign, double = None, *args):
263
if double is not None:
264
return (Infsign[sign],)*2
267
class DivisionImpossible(InvalidOperation):
268
"""Cannot perform the division adequately.
270
This occurs and signals invalid-operation if the integer result of a
271
divide-integer or remainder operation had too many digits (would be
272
longer than precision). The result is [0,qNaN].
275
def handle(self, context, *args):
278
class DivisionUndefined(InvalidOperation, ZeroDivisionError):
279
"""Undefined result of division.
281
This occurs and signals invalid-operation if division by zero was
282
attempted (during a divide-integer, divide, or remainder operation), and
283
the dividend is also zero. The result is [0,qNaN].
286
def handle(self, context, tup=None, *args):
288
return (NaN, NaN) #for 0 %0, 0 // 0
291
class Inexact(DecimalException):
292
"""Had to round, losing information.
294
This occurs and signals inexact whenever the result of an operation is
295
not exact (that is, it needed to be rounded and any discarded digits
296
were non-zero), or if an overflow or underflow condition occurs. The
297
result in all cases is unchanged.
299
The inexact signal may be tested (or trapped) to determine if a given
300
operation (or sequence of operations) was inexact.
304
class InvalidContext(InvalidOperation):
305
"""Invalid context. Unknown rounding, for example.
307
This occurs and signals invalid-operation if an invalid context was
308
detected during an operation. This can occur if contexts are not checked
309
on creation and either the precision exceeds the capability of the
310
underlying concrete representation or an unknown or unsupported rounding
311
was specified. These aspects of the context need only be checked when
312
the values are required to be used. The result is [0,qNaN].
315
def handle(self, context, *args):
318
class Rounded(DecimalException):
319
"""Number got rounded (not necessarily changed during rounding).
321
This occurs and signals rounded whenever the result of an operation is
322
rounded (that is, some zero or non-zero digits were discarded from the
323
coefficient), or if an overflow or underflow condition occurs. The
324
result in all cases is unchanged.
326
The rounded signal may be tested (or trapped) to determine if a given
327
operation (or sequence of operations) caused a loss of precision.
331
class Subnormal(DecimalException):
332
"""Exponent < Emin before rounding.
334
This occurs and signals subnormal whenever the result of a conversion or
335
operation is subnormal (that is, its adjusted exponent is less than
336
Emin, before any rounding). The result in all cases is unchanged.
338
The subnormal signal may be tested (or trapped) to determine if a given
339
or operation (or sequence of operations) yielded a subnormal result.
343
class Overflow(Inexact, Rounded):
344
"""Numerical overflow.
346
This occurs and signals overflow if the adjusted exponent of a result
347
(from a conversion or from an operation that is not an attempt to divide
348
by zero), after rounding, would be greater than the largest value that
349
can be handled by the implementation (the value Emax).
351
The result depends on the rounding mode:
353
For round-half-up and round-half-even (and for round-half-down and
354
round-up, if implemented), the result of the operation is [sign,inf],
355
where sign is the sign of the intermediate result. For round-down, the
356
result is the largest finite number that can be represented in the
357
current precision, with the sign of the intermediate result. For
358
round-ceiling, the result is the same as for round-down if the sign of
359
the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
360
the result is the same as for round-down if the sign of the intermediate
361
result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
365
def handle(self, context, sign, *args):
366
if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
367
ROUND_HALF_DOWN, ROUND_UP):
370
if context.rounding == ROUND_CEILING:
372
return Decimal((sign, (9,)*context.prec,
373
context.Emax-context.prec+1))
375
if context.rounding == ROUND_FLOOR:
377
return Decimal( (sign, (9,)*context.prec,
378
context.Emax-context.prec+1))
381
class Underflow(Inexact, Rounded, Subnormal):
382
"""Numerical underflow with result rounded to 0.
384
This occurs and signals underflow if a result is inexact and the
385
adjusted exponent of the result would be smaller (more negative) than
386
the smallest value that can be handled by the implementation (the value
387
Emin). That is, the result is both inexact and subnormal.
389
The result after an underflow will be a subnormal number rounded, if
390
necessary, so that its exponent is not less than Etiny. This may result
391
in 0 with the sign of the intermediate result and an exponent of Etiny.
393
In all cases, Inexact, Rounded, and Subnormal will also be raised.
396
# List of public traps and flags
397
_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
398
Underflow, InvalidOperation, Subnormal]
400
# Map conditions (per the spec) to signals
401
_condition_map = {ConversionSyntax:InvalidOperation,
402
DivisionImpossible:InvalidOperation,
403
DivisionUndefined:InvalidOperation,
404
InvalidContext:InvalidOperation}
406
##### Context Functions #######################################
408
# The getcontext() and setcontext() function manage access to a thread-local
409
# current context. Py2.4 offers direct support for thread locals. If that
410
# is not available, use threading.currentThread() which is slower but will
411
# work for older Pythons.
416
except AttributeError:
418
#To fix reloading, force it to create a new context
419
#Old contexts have different exceptions in their dicts, making problems.
420
if hasattr(threading.currentThread(), '__decimal_context__'):
421
del threading.currentThread().__decimal_context__
423
def setcontext(context):
424
"""Set this thread's context to context."""
425
if context in (DefaultContext, BasicContext, ExtendedContext):
426
context = context.copy()
427
context.clear_flags()
428
threading.currentThread().__decimal_context__ = context
431
"""Returns this thread's context.
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.
438
return threading.currentThread().__decimal_context__
439
except AttributeError:
441
threading.currentThread().__decimal_context__ = context
446
local = threading.local()
447
if hasattr(local, '__decimal_context__'):
448
del local.__decimal_context__
450
def getcontext(_local=local):
451
"""Returns this thread's context.
453
If this thread does not yet have a context, returns
454
a new context and sets this thread's context.
455
New contexts are copies of DefaultContext.
458
return _local.__decimal_context__
459
except AttributeError:
461
_local.__decimal_context__ = context
464
def setcontext(context, _local=local):
465
"""Set this thread's context to context."""
466
if context in (DefaultContext, BasicContext, ExtendedContext):
467
context = context.copy()
468
context.clear_flags()
469
_local.__decimal_context__ = context
471
del threading, local # Don't contaminate the namespace
473
###############################################################
475
# Patches for old python compatability
478
# Copied from fixedpoint.py ...
479
# 2002-10-20 dougfort - fake classes for pre 2.2 compatibility
490
##### Decimal class ###########################################
492
class Decimal(object):
493
"""Floating point class for decimal arithmetic."""
495
__slots__ = ('_exp','_int','_sign', '_is_special')
496
# Generally, the value of the Decimal instance is given by
497
# (-1)**_sign * _int * 10**_exp
498
# Special values are signified by _is_special == True
500
# We're immutable, so use __new__ not __init__
501
def __new__(cls, value="0", context=None):
502
"""Create a decimal point instance.
504
>>> Decimal('3.14') # string input
506
>>> Decimal((0, (3, 1, 4), -2)) # tuple input (sign, digit_tuple, exponent)
508
>>> Decimal(314) # int or long
510
>>> Decimal(Decimal(314)) # another decimal instance
514
self = object.__new__(cls)
515
self._is_special = False
517
# From an internal working value
518
if isinstance(value, _WorkRep):
519
self._sign = value.sign
520
self._int = tuple(map(int, str(value.int)))
521
self._exp = int(value.exp)
524
# From another decimal
525
if isinstance(value, Decimal):
526
self._exp = value._exp
527
self._sign = value._sign
528
self._int = value._int
529
self._is_special = value._is_special
533
if isinstance(value, (int,long)):
539
self._int = tuple(map(int, str(abs(value))))
542
# tuple/list conversion (possibly from as_tuple())
543
if isinstance(value, (list,tuple)):
545
raise ValueError, 'Invalid arguments'
546
if value[0] not in [0,1]:
547
raise ValueError, 'Invalid sign'
548
for digit in value[1]:
549
if not isinstance(digit, (int,long)) or digit < 0:
550
raise ValueError, "The second value in the tuple must be composed of non negative integer elements."
552
self._sign = value[0]
553
self._int = tuple(value[1])
554
if value[2] in ('F','n','N'):
556
self._is_special = True
558
self._exp = int(value[2])
561
if isinstance(value, float):
562
raise TypeError("Cannot convert float to Decimal. " +
563
"First convert the float to a string")
565
# Other argument types may require the context during interpretation
567
context = getcontext()
570
# REs insist on real strings, so we can too.
571
if isinstance(value, basestring):
572
if _isinfinity(value):
575
self._is_special = True
576
if _isinfinity(value) == 1:
582
sig, sign, diag = _isnan(value)
583
self._is_special = True
584
if len(diag) > context.prec: #Diagnostic info too long
585
self._sign, self._int, self._exp = \
586
context._raise_error(ConversionSyntax)
589
self._exp = 'n' #qNaN
591
self._exp = 'N' #sNaN
593
self._int = tuple(map(int, diag)) #Diagnostic info
596
self._sign, self._int, self._exp = _string2exact(value)
598
self._is_special = True
599
self._sign, self._int, self._exp = context._raise_error(ConversionSyntax)
602
raise TypeError("Cannot convert %r to Decimal" % value)
605
"""Returns whether the number is not actually one.
619
def _isinfinity(self):
620
"""Returns whether the number is infinite
622
0 if finite or not a number
632
def _check_nans(self, other = None, context=None):
633
"""Returns whether the number is not actually one.
635
if self, other are sNaN, signal
636
if self, other are NaN return nan
639
Done before operations.
642
self_is_nan = self._isnan()
646
other_is_nan = other._isnan()
648
if self_is_nan or other_is_nan:
650
context = getcontext()
653
return context._raise_error(InvalidOperation, 'sNaN',
655
if other_is_nan == 2:
656
return context._raise_error(InvalidOperation, 'sNaN',
664
def __nonzero__(self):
665
"""Is the number non-zero?
672
return sum(self._int) != 0
674
def __cmp__(self, other, context=None):
675
other = _convert_other(other)
677
if self._is_special or other._is_special:
678
ans = self._check_nans(other, context)
680
return 1 # Comparison involving NaN's always reports self > other
683
return cmp(self._isinfinity(), other._isinfinity())
685
if not self and not other:
686
return 0 #If both 0, sign comparison isn't certain.
688
#If different signs, neg one is less
689
if other._sign < self._sign:
691
if self._sign < other._sign:
694
self_adjusted = self.adjusted()
695
other_adjusted = other.adjusted()
696
if self_adjusted == other_adjusted and \
697
self._int + (0,)*(self._exp - other._exp) == \
698
other._int + (0,)*(other._exp - self._exp):
699
return 0 #equal, except in precision. ([0]*(-x) = [])
700
elif self_adjusted > other_adjusted and self._int[0] != 0:
701
return (-1)**self._sign
702
elif self_adjusted < other_adjusted and other._int[0] != 0:
703
return -((-1)**self._sign)
705
# Need to round, so make sure we have a valid context
707
context = getcontext()
709
context = context._shallow_copy()
710
rounding = context._set_rounding(ROUND_UP) #round away from 0
712
flags = context._ignore_all_flags()
713
res = self.__sub__(other, context=context)
715
context._regard_flags(*flags)
717
context.rounding = rounding
725
def __eq__(self, other):
726
if not isinstance(other, (Decimal, int, long)):
728
return self.__cmp__(other) == 0
730
def __ne__(self, other):
731
if not isinstance(other, (Decimal, int, long)):
733
return self.__cmp__(other) != 0
735
def compare(self, other, context=None):
736
"""Compares one to another.
742
Like __cmp__, but returns Decimal instances.
744
other = _convert_other(other)
746
#compare(NaN, NaN) = NaN
747
if (self._is_special or other and other._is_special):
748
ans = self._check_nans(other, context)
752
return Decimal(self.__cmp__(other, context))
755
"""x.__hash__() <==> hash(x)"""
756
# Decimal integers must hash the same as the ints
757
# Non-integer decimals are normalized and hashed as strings
758
# Normalization assures that hast(100E-1) == hash(10)
760
if self == Decimal(i):
762
assert self.__nonzero__() # '-0' handled by integer case
763
return hash(str(self.normalize()))
766
"""Represents the number as a triple tuple.
768
To show the internals exactly as they are.
770
return (self._sign, self._int, self._exp)
773
"""Represents the number as an instance of Decimal."""
774
# Invariant: eval(repr(d)) == d
775
return 'Decimal("%s")' % str(self)
777
def __str__(self, eng = 0, context=None):
778
"""Return string representation of the number in scientific notation.
780
Captures all of the information in the underlying representation.
784
minus = '-'*self._sign
785
if self._int == (0,):
788
info = ''.join(map(str, self._int))
789
if self._isnan() == 2:
790
return minus + 'sNaN' + info
791
return minus + 'NaN' + info
792
if self._isinfinity():
793
minus = '-'*self._sign
794
return minus + 'Infinity'
797
context = getcontext()
799
tmp = map(str, self._int)
800
numdigits = len(self._int)
801
leftdigits = self._exp + numdigits
802
if eng and not self: #self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
803
if self._exp < 0 and self._exp >= -6: #short, no need for e/E
804
s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
806
#exp is closest mult. of 3 >= self._exp
807
exp = (int((self._exp - 1)/ 3) + 1) * 3
809
s = '0.'+'0'*(exp - self._exp)
818
s += '+' #0.0e+3, not 0.0e3
820
s = '-'*self._sign + s
823
dotplace = (leftdigits-1)%3+1
824
adjexp = leftdigits -1 - (leftdigits-1)%3
826
adjexp = leftdigits-1
830
elif self._exp < 0 and adjexp >= 0:
831
tmp.insert(leftdigits, '.')
832
elif self._exp < 0 and adjexp >= -6:
833
tmp[0:0] = ['0'] * int(-leftdigits)
836
if numdigits > dotplace:
837
tmp.insert(dotplace, '.')
838
elif numdigits < dotplace:
839
tmp.extend(['0']*(dotplace-numdigits))
841
if not context.capitals:
847
tmp.append(str(adjexp))
849
while tmp[0:1] == ['0']:
851
if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
858
def to_eng_string(self, context=None):
859
"""Convert to engineering-type string.
861
Engineering notation has an exponent which is a multiple of 3, so there
862
are up to 3 digits left of the decimal place.
864
Same rules for when in exponential and when as a value as in __str__.
866
return self.__str__(eng=1, context=context)
868
def __neg__(self, context=None):
869
"""Returns a copy with the sign switched.
871
Rounds, if it has reason.
874
ans = self._check_nans(context=context)
879
# -Decimal('0') is Decimal('0'), not Decimal('-0')
887
context = getcontext()
888
if context._rounding_decision == ALWAYS_ROUND:
889
return Decimal((sign, self._int, self._exp))._fix(context)
890
return Decimal( (sign, self._int, self._exp))
892
def __pos__(self, context=None):
893
"""Returns a copy, unless it is a sNaN.
895
Rounds the number (if more then precision digits)
898
ans = self._check_nans(context=context)
908
context = getcontext()
910
if context._rounding_decision == ALWAYS_ROUND:
911
ans = self._fix(context)
917
def __abs__(self, round=1, context=None):
918
"""Returns the absolute value of self.
920
If the second argument is 0, do not round.
923
ans = self._check_nans(context=context)
929
context = getcontext()
930
context = context._shallow_copy()
931
context._set_rounding_decision(NEVER_ROUND)
934
ans = self.__neg__(context=context)
936
ans = self.__pos__(context=context)
940
def __add__(self, other, context=None):
941
"""Returns self + other.
943
-INF + INF (or the reverse) cause InvalidOperation errors.
945
other = _convert_other(other)
948
context = getcontext()
950
if self._is_special or other._is_special:
951
ans = self._check_nans(other, context)
955
if self._isinfinity():
956
#If both INF, same sign => same as both, opposite => error.
957
if self._sign != other._sign and other._isinfinity():
958
return context._raise_error(InvalidOperation, '-INF + INF')
960
if other._isinfinity():
961
return Decimal(other) #Can't both be infinity here
963
shouldround = context._rounding_decision == ALWAYS_ROUND
965
exp = min(self._exp, other._exp)
967
if context.rounding == ROUND_FLOOR and self._sign != other._sign:
968
#If the answer is 0, the sign should be negative, in this case.
971
if not self and not other:
972
sign = min(self._sign, other._sign)
975
return Decimal( (sign, (0,), exp))
977
exp = max(exp, other._exp - context.prec-1)
978
ans = other._rescale(exp, watchexp=0, context=context)
980
ans = ans._fix(context)
983
exp = max(exp, self._exp - context.prec-1)
984
ans = self._rescale(exp, watchexp=0, context=context)
986
ans = ans._fix(context)
990
op2 = _WorkRep(other)
991
op1, op2 = _normalize(op1, op2, shouldround, context.prec)
994
if op1.sign != op2.sign:
996
if op1.int == op2.int:
997
if exp < context.Etiny():
998
exp = context.Etiny()
999
context._raise_error(Clamped)
1000
return Decimal((negativezero, (0,), exp))
1001
if op1.int < op2.int:
1003
#OK, now abs(op1) > abs(op2)
1006
op1.sign, op2.sign = op2.sign, op1.sign
1009
#So we know the sign, and op1 > 0.
1012
op1.sign, op2.sign = (0, 0)
1015
#Now, op1 > abs(op2) > 0
1018
result.int = op1.int + op2.int
1020
result.int = op1.int - op2.int
1022
result.exp = op1.exp
1023
ans = Decimal(result)
1025
ans = ans._fix(context)
1030
def __sub__(self, other, context=None):
1031
"""Return self + (-other)"""
1032
other = _convert_other(other)
1034
if self._is_special or other._is_special:
1035
ans = self._check_nans(other, context=context)
1039
# -Decimal(0) = Decimal(0), which we don't want since
1040
# (-0 - 0 = -0 + (-0) = -0, but -0 + 0 = 0.)
1041
# so we change the sign directly to a copy
1042
tmp = Decimal(other)
1043
tmp._sign = 1-tmp._sign
1045
return self.__add__(tmp, context=context)
1047
def __rsub__(self, other, context=None):
1048
"""Return other + (-self)"""
1049
other = _convert_other(other)
1052
tmp._sign = 1 - tmp._sign
1053
return other.__add__(tmp, context=context)
1055
def _increment(self, round=1, context=None):
1056
"""Special case of add, adding 1eExponent
1058
Since it is common, (rounding, for example) this adds
1059
(sign)*one E self._exp to the number more efficiently than add.
1062
Decimal('5.624e10')._increment() == Decimal('5.625e10')
1064
if self._is_special:
1065
ans = self._check_nans(context=context)
1069
return Decimal(self) # Must be infinite, and incrementing makes no difference
1074
while L[spot] == 10:
1081
ans = Decimal((self._sign, L, self._exp))
1084
context = getcontext()
1085
if round and context._rounding_decision == ALWAYS_ROUND:
1086
ans = ans._fix(context)
1089
def __mul__(self, other, context=None):
1090
"""Return self * other.
1092
(+-) INF * 0 (or its reverse) raise InvalidOperation.
1094
other = _convert_other(other)
1097
context = getcontext()
1099
resultsign = self._sign ^ other._sign
1101
if self._is_special or other._is_special:
1102
ans = self._check_nans(other, context)
1106
if self._isinfinity():
1108
return context._raise_error(InvalidOperation, '(+-)INF * 0')
1109
return Infsign[resultsign]
1111
if other._isinfinity():
1113
return context._raise_error(InvalidOperation, '0 * (+-)INF')
1114
return Infsign[resultsign]
1116
resultexp = self._exp + other._exp
1117
shouldround = context._rounding_decision == ALWAYS_ROUND
1119
# Special case for multiplying by zero
1120
if not self or not other:
1121
ans = Decimal((resultsign, (0,), resultexp))
1123
#Fixing in case the exponent is out of bounds
1124
ans = ans._fix(context)
1127
# Special case for multiplying by power of 10
1128
if self._int == (1,):
1129
ans = Decimal((resultsign, other._int, resultexp))
1131
ans = ans._fix(context)
1133
if other._int == (1,):
1134
ans = Decimal((resultsign, self._int, resultexp))
1136
ans = ans._fix(context)
1139
op1 = _WorkRep(self)
1140
op2 = _WorkRep(other)
1142
ans = Decimal( (resultsign, map(int, str(op1.int * op2.int)), resultexp))
1144
ans = ans._fix(context)
1149
def __div__(self, other, context=None):
1150
"""Return self / other."""
1151
return self._divide(other, context=context)
1152
__truediv__ = __div__
1154
def _divide(self, other, divmod = 0, context=None):
1155
"""Return a / b, to context.prec precision.
1163
Actually, if divmod is 2 or 3 a tuple is returned, but errors for
1164
computing the other value are not raised.
1166
other = _convert_other(other)
1169
context = getcontext()
1171
sign = self._sign ^ other._sign
1173
if self._is_special or other._is_special:
1174
ans = self._check_nans(other, context)
1180
if self._isinfinity() and other._isinfinity():
1182
return (context._raise_error(InvalidOperation,
1183
'(+-)INF // (+-)INF'),
1184
context._raise_error(InvalidOperation,
1185
'(+-)INF % (+-)INF'))
1186
return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
1188
if self._isinfinity():
1190
return (Infsign[sign],
1191
context._raise_error(InvalidOperation, 'INF % x'))
1193
return (Infsign[sign], NaN)
1195
return (Infsign[sign],
1196
context._raise_error(InvalidOperation, 'INF % x'))
1197
return Infsign[sign]
1199
if other._isinfinity():
1201
return (Decimal((sign, (0,), 0)), Decimal(self))
1202
context._raise_error(Clamped, 'Division by infinity')
1203
return Decimal((sign, (0,), context.Etiny()))
1205
# Special cases for zeroes
1206
if not self and not other:
1208
return context._raise_error(DivisionUndefined, '0 / 0', 1)
1209
return context._raise_error(DivisionUndefined, '0 / 0')
1213
otherside = Decimal(self)
1214
otherside._exp = min(self._exp, other._exp)
1215
return (Decimal((sign, (0,), 0)), otherside)
1216
exp = self._exp - other._exp
1217
if exp < context.Etiny():
1218
exp = context.Etiny()
1219
context._raise_error(Clamped, '0e-x / y')
1220
if exp > context.Emax:
1222
context._raise_error(Clamped, '0e+x / y')
1223
return Decimal( (sign, (0,), exp) )
1227
return context._raise_error(DivisionByZero, 'divmod(x,0)',
1229
return context._raise_error(DivisionByZero, 'x / 0', sign)
1231
#OK, so neither = 0, INF or NaN
1233
shouldround = context._rounding_decision == ALWAYS_ROUND
1235
#If we're dividing into ints, and self < other, stop.
1236
#self.__abs__(0) does not round.
1237
if divmod and (self.__abs__(0, context) < other.__abs__(0, context)):
1239
if divmod == 1 or divmod == 3:
1240
exp = min(self._exp, other._exp)
1241
ans2 = self._rescale(exp, context=context, watchexp=0)
1243
ans2 = ans2._fix(context)
1244
return (Decimal( (sign, (0,), 0) ),
1248
#Don't round the mod part, if we don't need it.
1249
return (Decimal( (sign, (0,), 0) ), Decimal(self))
1251
op1 = _WorkRep(self)
1252
op2 = _WorkRep(other)
1253
op1, op2, adjust = _adjust_coefficients(op1, op2)
1254
res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) )
1255
if divmod and res.exp > context.prec + 1:
1256
return context._raise_error(DivisionImpossible)
1258
prec_limit = 10 ** context.prec
1260
while op2.int <= op1.int:
1263
if res.exp == 0 and divmod:
1264
if res.int >= prec_limit and shouldround:
1265
return context._raise_error(DivisionImpossible)
1266
otherside = Decimal(op1)
1267
frozen = context._ignore_all_flags()
1269
exp = min(self._exp, other._exp)
1270
otherside = otherside._rescale(exp, context=context, watchexp=0)
1271
context._regard_flags(*frozen)
1273
otherside = otherside._fix(context)
1274
return (Decimal(res), otherside)
1276
if op1.int == 0 and adjust >= 0 and not divmod:
1278
if res.int >= prec_limit and shouldround:
1280
return context._raise_error(DivisionImpossible)
1282
# Really, the answer is a bit higher, so adding a one to
1283
# the end will make sure the rounding is right.
1296
if res.exp == 0 and divmod and op2.int > op1.int:
1297
#Solves an error in precision. Same as a previous block.
1299
if res.int >= prec_limit and shouldround:
1300
return context._raise_error(DivisionImpossible)
1301
otherside = Decimal(op1)
1302
frozen = context._ignore_all_flags()
1304
exp = min(self._exp, other._exp)
1305
otherside = otherside._rescale(exp, context=context)
1307
context._regard_flags(*frozen)
1309
return (Decimal(res), otherside)
1313
ans = ans._fix(context)
1316
def __rdiv__(self, other, context=None):
1317
"""Swaps self/other and returns __div__."""
1318
other = _convert_other(other)
1319
return other.__div__(self, context=context)
1320
__rtruediv__ = __rdiv__
1322
def __divmod__(self, other, context=None):
1324
(self // other, self % other)
1326
return self._divide(other, 1, context)
1328
def __rdivmod__(self, other, context=None):
1329
"""Swaps self/other and returns __divmod__."""
1330
other = _convert_other(other)
1331
return other.__divmod__(self, context=context)
1333
def __mod__(self, other, context=None):
1337
other = _convert_other(other)
1339
if self._is_special or other._is_special:
1340
ans = self._check_nans(other, context)
1344
if self and not other:
1345
return context._raise_error(InvalidOperation, 'x % 0')
1347
return self._divide(other, 3, context)[1]
1349
def __rmod__(self, other, context=None):
1350
"""Swaps self/other and returns __mod__."""
1351
other = _convert_other(other)
1352
return other.__mod__(self, context=context)
1354
def remainder_near(self, other, context=None):
1356
Remainder nearest to 0- abs(remainder-near) <= other/2
1358
other = _convert_other(other)
1360
if self._is_special or other._is_special:
1361
ans = self._check_nans(other, context)
1364
if self and not other:
1365
return context._raise_error(InvalidOperation, 'x % 0')
1368
context = getcontext()
1369
# If DivisionImpossible causes an error, do not leave Rounded/Inexact
1370
# ignored in the calling function.
1371
context = context._shallow_copy()
1372
flags = context._ignore_flags(Rounded, Inexact)
1373
#keep DivisionImpossible flags
1374
(side, r) = self.__divmod__(other, context=context)
1377
context._regard_flags(*flags)
1380
context = context._shallow_copy()
1381
rounding = context._set_rounding_decision(NEVER_ROUND)
1384
comparison = other.__div__(Decimal(-2), context=context)
1386
comparison = other.__div__(Decimal(2), context=context)
1388
context._set_rounding_decision(rounding)
1389
context._regard_flags(*flags)
1391
s1, s2 = r._sign, comparison._sign
1392
r._sign, comparison._sign = 0, 0
1395
r._sign, comparison._sign = s1, s2
1397
self.__divmod__(other, context=context)
1398
return r._fix(context)
1399
r._sign, comparison._sign = s1, s2
1401
rounding = context._set_rounding_decision(NEVER_ROUND)
1403
(side, r) = self.__divmod__(other, context=context)
1404
context._set_rounding_decision(rounding)
1408
decrease = not side._iseven()
1409
rounding = context._set_rounding_decision(NEVER_ROUND)
1410
side = side.__abs__(context=context)
1411
context._set_rounding_decision(rounding)
1413
s1, s2 = r._sign, comparison._sign
1414
r._sign, comparison._sign = 0, 0
1415
if r > comparison or decrease and r == comparison:
1416
r._sign, comparison._sign = s1, s2
1418
if len(side.__add__(Decimal(1), context=context)._int) >= context.prec:
1420
return context._raise_error(DivisionImpossible)[1]
1422
if self._sign == other._sign:
1423
r = r.__sub__(other, context=context)
1425
r = r.__add__(other, context=context)
1427
r._sign, comparison._sign = s1, s2
1429
return r._fix(context)
1431
def __floordiv__(self, other, context=None):
1433
return self._divide(other, 2, context)[0]
1435
def __rfloordiv__(self, other, context=None):
1436
"""Swaps self/other and returns __floordiv__."""
1437
other = _convert_other(other)
1438
return other.__floordiv__(self, context=context)
1440
def __float__(self):
1441
"""Float representation."""
1442
return float(str(self))
1445
"""Converts self to a int, truncating if necessary."""
1446
if self._is_special:
1448
context = getcontext()
1449
return context._raise_error(InvalidContext)
1450
elif self._isinfinity():
1451
raise OverflowError, "Cannot convert infinity to long"
1453
s = ''.join(map(str, self._int)) + '0'*self._exp
1455
s = ''.join(map(str, self._int))[:self._exp]
1458
sign = '-'*self._sign
1459
return int(sign + s)
1462
"""Converts to a long.
1464
Equivalent to long(int(self))
1466
return long(self.__int__())
1468
def _fix(self, context):
1469
"""Round if it is necessary to keep self within prec precision.
1471
Rounds and fixes the exponent. Does not raise on a sNaN.
1474
self - Decimal instance
1475
context - context used.
1477
if self._is_special:
1480
context = getcontext()
1482
ans = self._fixexponents(context)
1483
if len(ans._int) > prec:
1484
ans = ans._round(prec, context=context)
1485
ans = ans._fixexponents(context)
1488
def _fixexponents(self, context):
1489
"""Fix the exponents and return a copy with the exponent in bounds.
1490
Only call if known to not be a special value.
1492
folddown = context._clamp
1495
ans_adjusted = ans.adjusted()
1496
if ans_adjusted < Emin:
1497
Etiny = context.Etiny()
1498
if ans._exp < Etiny:
1502
context._raise_error(Clamped)
1504
ans = ans._rescale(Etiny, context=context)
1505
#It isn't zero, and exp < Emin => subnormal
1506
context._raise_error(Subnormal)
1507
if context.flags[Inexact]:
1508
context._raise_error(Underflow)
1511
#Only raise subnormal if non-zero.
1512
context._raise_error(Subnormal)
1514
Etop = context.Etop()
1515
if folddown and ans._exp > Etop:
1516
context._raise_error(Clamped)
1517
ans = ans._rescale(Etop, context=context)
1520
if ans_adjusted > Emax:
1524
context._raise_error(Clamped)
1526
context._raise_error(Inexact)
1527
context._raise_error(Rounded)
1528
return context._raise_error(Overflow, 'above Emax', ans._sign)
1531
def _round(self, prec=None, rounding=None, context=None):
1532
"""Returns a rounded version of self.
1534
You can specify the precision or rounding method. Otherwise, the
1535
context determines it.
1538
if self._is_special:
1539
ans = self._check_nans(context=context)
1543
if self._isinfinity():
1544
return Decimal(self)
1547
context = getcontext()
1549
if rounding is None:
1550
rounding = context.rounding
1557
exp = len(self._int) - prec + self._exp
1560
exp = len(self._int) + self._exp - prec
1561
ans = Decimal((self._sign, dig, exp))
1562
context._raise_error(Rounded)
1566
temp = Decimal(self)
1567
temp._int = (0,)+temp._int
1570
exp = self._exp + len(self._int) - prec - 1
1571
temp = Decimal( (self._sign, (0, 1), exp))
1574
temp = Decimal(self)
1576
numdigits = len(temp._int)
1577
if prec == numdigits:
1580
# See if we need to extend precision
1581
expdiff = prec - numdigits
1583
tmp = list(temp._int)
1584
tmp.extend([0] * expdiff)
1585
ans = Decimal( (temp._sign, tmp, temp._exp - expdiff))
1588
#OK, but maybe all the lost digits are 0.
1589
lostdigits = self._int[expdiff:]
1590
if lostdigits == (0,) * len(lostdigits):
1591
ans = Decimal( (temp._sign, temp._int[:prec], temp._exp - expdiff))
1592
#Rounded, but not Inexact
1593
context._raise_error(Rounded)
1596
# Okay, let's round and lose data
1598
this_function = getattr(temp, self._pick_rounding_function[rounding])
1599
#Now we've got the rounding function
1601
if prec != context.prec:
1602
context = context._shallow_copy()
1604
ans = this_function(prec, expdiff, context)
1605
context._raise_error(Rounded)
1606
context._raise_error(Inexact, 'Changed in rounding')
1610
_pick_rounding_function = {}
1612
def _round_down(self, prec, expdiff, context):
1613
"""Also known as round-towards-0, truncate."""
1614
return Decimal( (self._sign, self._int[:prec], self._exp - expdiff) )
1616
def _round_half_up(self, prec, expdiff, context, tmp = None):
1617
"""Rounds 5 up (away from 0)"""
1620
tmp = Decimal( (self._sign,self._int[:prec], self._exp - expdiff))
1621
if self._int[prec] >= 5:
1622
tmp = tmp._increment(round=0, context=context)
1623
if len(tmp._int) > prec:
1624
return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1))
1627
def _round_half_even(self, prec, expdiff, context):
1628
"""Round 5 to even, rest to nearest."""
1630
tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff))
1631
half = (self._int[prec] == 5)
1633
for digit in self._int[prec+1:]:
1638
if self._int[prec-1] & 1 == 0:
1640
return self._round_half_up(prec, expdiff, context, tmp)
1642
def _round_half_down(self, prec, expdiff, context):
1645
tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff))
1646
half = (self._int[prec] == 5)
1648
for digit in self._int[prec+1:]:
1654
return self._round_half_up(prec, expdiff, context, tmp)
1656
def _round_up(self, prec, expdiff, context):
1657
"""Rounds away from 0."""
1658
tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff) )
1659
for digit in self._int[prec:]:
1661
tmp = tmp._increment(round=1, context=context)
1662
if len(tmp._int) > prec:
1663
return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1))
1668
def _round_ceiling(self, prec, expdiff, context):
1669
"""Rounds up (not away from 0 if negative.)"""
1671
return self._round_down(prec, expdiff, context)
1673
return self._round_up(prec, expdiff, context)
1675
def _round_floor(self, prec, expdiff, context):
1676
"""Rounds down (not towards 0 if negative)"""
1678
return self._round_down(prec, expdiff, context)
1680
return self._round_up(prec, expdiff, context)
1682
def __pow__(self, n, modulo = None, context=None):
1683
"""Return self ** n (mod modulo)
1685
If modulo is None (default), don't take it mod modulo.
1687
n = _convert_other(n)
1690
context = getcontext()
1692
if self._is_special or n._is_special or n.adjusted() > 8:
1693
#Because the spot << doesn't work with really big exponents
1694
if n._isinfinity() or n.adjusted() > 8:
1695
return context._raise_error(InvalidOperation, 'x ** INF')
1697
ans = self._check_nans(n, context)
1701
if not n._isinteger():
1702
return context._raise_error(InvalidOperation, 'x ** (non-integer)')
1704
if not self and not n:
1705
return context._raise_error(InvalidOperation, '0 ** 0')
1710
if self == Decimal(1):
1713
sign = self._sign and not n._iseven()
1716
if self._isinfinity():
1718
return context._raise_error(InvalidOperation, 'INF % x')
1720
return Infsign[sign]
1721
return Decimal( (sign, (0,), 0) )
1723
#with ludicrously large exponent, just raise an overflow and return inf.
1724
if not modulo and n > 0 and (self._exp + len(self._int) - 1) * n > context.Emax \
1727
tmp = Decimal('inf')
1729
context._raise_error(Rounded)
1730
context._raise_error(Inexact)
1731
context._raise_error(Overflow, 'Big power', sign)
1734
elength = len(str(abs(n)))
1735
firstprec = context.prec
1737
if not modulo and firstprec + elength + 1 > DefaultContext.Emax:
1738
return context._raise_error(Overflow, 'Too much precision.', sign)
1742
context = context._shallow_copy()
1743
context.prec = firstprec + elength + 1
1745
#n is a long now, not Decimal instance
1747
mul = Decimal(1).__div__(mul, context=context)
1754
#Spot is the highest power of 2 less than n
1756
val = val.__mul__(val, context=context)
1757
if val._isinfinity():
1761
val = val.__mul__(mul, context=context)
1762
if modulo is not None:
1763
val = val.__mod__(modulo, context=context)
1765
context.prec = firstprec
1767
if context._rounding_decision == ALWAYS_ROUND:
1768
return val._fix(context)
1771
def __rpow__(self, other, context=None):
1772
"""Swaps self/other and returns __pow__."""
1773
other = _convert_other(other)
1774
return other.__pow__(self, context=context)
1776
def normalize(self, context=None):
1777
"""Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
1779
if self._is_special:
1780
ans = self._check_nans(context=context)
1784
dup = self._fix(context)
1785
if dup._isinfinity():
1789
return Decimal( (dup._sign, (0,), 0) )
1792
while dup._int[end-1] == 0:
1795
return Decimal( (dup._sign, dup._int[:end], exp) )
1798
def quantize(self, exp, rounding=None, context=None, watchexp=1):
1799
"""Quantize self so its exponent is the same as that of exp.
1801
Similar to self._rescale(exp._exp) but with error checking.
1803
if self._is_special or exp._is_special:
1804
ans = self._check_nans(exp, context)
1808
if exp._isinfinity() or self._isinfinity():
1809
if exp._isinfinity() and self._isinfinity():
1810
return self #if both are inf, it is OK
1812
context = getcontext()
1813
return context._raise_error(InvalidOperation,
1814
'quantize with one INF')
1815
return self._rescale(exp._exp, rounding, context, watchexp)
1817
def same_quantum(self, other):
1818
"""Test whether self and other have the same exponent.
1820
same as self._exp == other._exp, except NaN == sNaN
1822
if self._is_special or other._is_special:
1823
if self._isnan() or other._isnan():
1824
return self._isnan() and other._isnan() and True
1825
if self._isinfinity() or other._isinfinity():
1826
return self._isinfinity() and other._isinfinity() and True
1827
return self._exp == other._exp
1829
def _rescale(self, exp, rounding=None, context=None, watchexp=1):
1830
"""Rescales so that the exponent is exp.
1832
exp = exp to scale to (an integer)
1833
rounding = rounding version
1834
watchexp: if set (default) an error is returned if exp is greater
1835
than Emax or less than Etiny.
1838
context = getcontext()
1840
if self._is_special:
1841
if self._isinfinity():
1842
return context._raise_error(InvalidOperation, 'rescale with an INF')
1844
ans = self._check_nans(context=context)
1848
if watchexp and (context.Emax < exp or context.Etiny() > exp):
1849
return context._raise_error(InvalidOperation, 'rescale(a, INF)')
1857
diff = self._exp - exp
1858
digits = len(self._int) + diff
1860
if watchexp and digits > context.prec:
1861
return context._raise_error(InvalidOperation, 'Rescale > prec')
1864
tmp._int = (0,) + tmp._int
1868
tmp._exp = -digits + tmp._exp
1871
tmp = tmp._round(digits, rounding, context=context)
1873
if tmp._int[0] == 0 and len(tmp._int) > 1:
1874
tmp._int = tmp._int[1:]
1877
tmp_adjusted = tmp.adjusted()
1878
if tmp and tmp_adjusted < context.Emin:
1879
context._raise_error(Subnormal)
1880
elif tmp and tmp_adjusted > context.Emax:
1881
return context._raise_error(InvalidOperation, 'rescale(a, INF)')
1884
def to_integral(self, rounding=None, context=None):
1885
"""Rounds to the nearest integer, without raising inexact, rounded."""
1886
if self._is_special:
1887
ans = self._check_nans(context=context)
1893
context = getcontext()
1894
flags = context._ignore_flags(Rounded, Inexact)
1895
ans = self._rescale(0, rounding, context=context)
1896
context._regard_flags(flags)
1899
def sqrt(self, context=None):
1900
"""Return the square root of self.
1902
Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn))
1903
Should quadratically approach the right answer.
1905
if self._is_special:
1906
ans = self._check_nans(context=context)
1910
if self._isinfinity() and self._sign == 0:
1911
return Decimal(self)
1914
#exponent = self._exp / 2, using round_down.
1916
# exp = (self._exp+1) // 2
1918
exp = int((self._exp) / 2)
1921
return Decimal( (1, (0,), exp))
1923
return Decimal( (0, (0,), exp))
1926
context = getcontext()
1929
return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
1933
expadd = int(tmp._exp / 2)
1940
context = context._shallow_copy()
1941
flags = context._ignore_all_flags()
1942
firstprec = context.prec
1944
if tmp.adjusted() & 1 == 0:
1945
ans = Decimal( (0, (8,1,9), tmp.adjusted() - 2) )
1946
ans = ans.__add__(tmp.__mul__(Decimal((0, (2,5,9), -2)),
1947
context=context), context=context)
1948
ans._exp -= 1 + int(tmp.adjusted() / 2)
1950
ans = Decimal( (0, (2,5,9), tmp._exp + len(tmp._int)- 3) )
1951
ans = ans.__add__(tmp.__mul__(Decimal((0, (8,1,9), -3)),
1952
context=context), context=context)
1953
ans._exp -= 1 + int(tmp.adjusted() / 2)
1955
#ans is now a linear approximation.
1957
Emax, Emin = context.Emax, context.Emin
1958
context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin
1960
half = Decimal('0.5')
1962
maxp = firstprec + 2
1963
rounding = context._set_rounding(ROUND_HALF_EVEN)
1965
context.prec = min(2*context.prec - 2, maxp)
1966
ans = half.__mul__(ans.__add__(tmp.__div__(ans, context=context),
1967
context=context), context=context)
1968
if context.prec == maxp:
1971
#round to the answer's precision-- the only error can be 1 ulp.
1972
context.prec = firstprec
1973
prevexp = ans.adjusted()
1974
ans = ans._round(context=context)
1976
#Now, check if the other last digits are better.
1977
context.prec = firstprec + 1
1978
# In case we rounded up another digit and we should actually go lower.
1979
if prevexp != ans.adjusted():
1984
lower = ans.__sub__(Decimal((0, (5,), ans._exp-1)), context=context)
1985
context._set_rounding(ROUND_UP)
1986
if lower.__mul__(lower, context=context) > (tmp):
1987
ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context)
1990
upper = ans.__add__(Decimal((0, (5,), ans._exp-1)),context=context)
1991
context._set_rounding(ROUND_DOWN)
1992
if upper.__mul__(upper, context=context) < tmp:
1993
ans = ans.__add__(Decimal((0, (1,), ans._exp)),context=context)
1997
context.prec = firstprec
1998
context.rounding = rounding
1999
ans = ans._fix(context)
2001
rounding = context._set_rounding_decision(NEVER_ROUND)
2002
if not ans.__mul__(ans, context=context) == self:
2003
# Only rounded/inexact if here.
2004
context._regard_flags(flags)
2005
context._raise_error(Rounded)
2006
context._raise_error(Inexact)
2008
#Exact answer, so let's set the exponent right.
2010
# exp = (self._exp +1)// 2
2012
exp = int(self._exp / 2)
2013
context.prec += ans._exp - exp
2014
ans = ans._rescale(exp, context=context)
2015
context.prec = firstprec
2016
context._regard_flags(flags)
2017
context.Emax, context.Emin = Emax, Emin
2019
return ans._fix(context)
2021
def max(self, other, context=None):
2022
"""Returns the larger value.
2024
like max(self, other) except if one is not a number, returns
2025
NaN (and signals if one is sNaN). Also rounds.
2027
other = _convert_other(other)
2029
if self._is_special or other._is_special:
2030
# if one operand is a quiet NaN and the other is number, then the
2031
# number is always returned
2035
if on == 1 and sn != 2:
2037
if sn == 1 and on != 2:
2039
return self._check_nans(other, context)
2042
c = self.__cmp__(other)
2044
# if both operands are finite and equal in numerical value
2045
# then an ordering is applied:
2047
# if the signs differ then max returns the operand with the
2048
# positive sign and min returns the operand with the negative sign
2050
# if the signs are the same then the exponent is used to select
2052
if self._sign != other._sign:
2055
elif self._exp < other._exp and not self._sign:
2057
elif self._exp > other._exp and self._sign:
2063
context = getcontext()
2064
if context._rounding_decision == ALWAYS_ROUND:
2065
return ans._fix(context)
2068
def min(self, other, context=None):
2069
"""Returns the smaller value.
2071
like min(self, other) except if one is not a number, returns
2072
NaN (and signals if one is sNaN). Also rounds.
2074
other = _convert_other(other)
2076
if self._is_special or other._is_special:
2077
# if one operand is a quiet NaN and the other is number, then the
2078
# number is always returned
2082
if on == 1 and sn != 2:
2084
if sn == 1 and on != 2:
2086
return self._check_nans(other, context)
2089
c = self.__cmp__(other)
2091
# if both operands are finite and equal in numerical value
2092
# then an ordering is applied:
2094
# if the signs differ then max returns the operand with the
2095
# positive sign and min returns the operand with the negative sign
2097
# if the signs are the same then the exponent is used to select
2099
if self._sign != other._sign:
2102
elif self._exp > other._exp and not self._sign:
2104
elif self._exp < other._exp and self._sign:
2110
context = getcontext()
2111
if context._rounding_decision == ALWAYS_ROUND:
2112
return ans._fix(context)
2115
def _isinteger(self):
2116
"""Returns whether self is an integer"""
2119
rest = self._int[self._exp:]
2120
return rest == (0,)*len(rest)
2123
"""Returns 1 if self is even. Assumes self is an integer."""
2126
return self._int[-1+self._exp] & 1 == 0
2129
"""Return the adjusted exponent of self"""
2131
return self._exp + len(self._int) - 1
2132
#If NaN or Infinity, self._exp is string
2136
# support for pickling, copy, and deepcopy
2137
def __reduce__(self):
2138
return (self.__class__, (str(self),))
2141
if type(self) == Decimal:
2142
return self # I'm immutable; therefore I am my own clone
2143
return self.__class__(str(self))
2145
def __deepcopy__(self, memo):
2146
if type(self) == Decimal:
2147
return self # My components are also immutable
2148
return self.__class__(str(self))
2151
##### Context class ###########################################
2154
# get rounding method function:
2155
rounding_functions = [name for name in Decimal.__dict__.keys() if name.startswith('_round_')]
2156
for name in rounding_functions:
2157
#name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
2158
globalname = name[1:].upper()
2159
val = globals()[globalname]
2160
Decimal._pick_rounding_function[val] = name
2171
del rounding_functions
2173
class Context(object):
2174
"""Contains the context for a Decimal instance.
2177
prec - precision (for use in rounding, division, square roots..)
2178
rounding - rounding type. (how you round)
2179
_rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
2180
traps - If traps[exception] = 1, then the exception is
2181
raised when it is caused. Otherwise, a value is
2183
flags - When an exception is caused, flags[exception] is incremented.
2184
(Whether or not the trap_enabler is set)
2185
Should be reset by user of Decimal instance.
2186
Emin - Minimum exponent
2187
Emax - Maximum exponent
2188
capitals - If 1, 1*10^1 is printed as 1E+1.
2189
If 0, printed as 1e1
2190
_clamp - If 1, change exponents if too high (Default 0)
2193
def __init__(self, prec=None, rounding=None,
2194
traps=None, flags=None,
2195
_rounding_decision=None,
2196
Emin=None, Emax=None,
2197
capitals=None, _clamp=0,
2198
_ignored_flags=None):
2201
if _ignored_flags is None:
2203
if not isinstance(flags, dict):
2204
flags = bdict([(s,s in flags) for s in _signals])
2206
if traps is not None and not isinstance(traps, dict):
2207
traps = bdict([(s,s in traps) for s in _signals])
2209
for name, val in locals().items():
2211
setattr(self, name, copy.copy(getattr(DefaultContext, name)))
2213
setattr(self, name, val)
2217
"""Show the current context."""
2219
s.append('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self))
2220
s.append('flags=[' + ', '.join([f.__name__ for f, v in self.flags.items() if v]) + ']')
2221
s.append('traps=[' + ', '.join([t.__name__ for t, v in self.traps.items() if v]) + ']')
2222
return ', '.join(s) + ')'
2224
def clear_flags(self):
2225
"""Reset all flags to zero"""
2226
for flag in self.flags:
2227
self.flags[flag] = 0
2229
def _shallow_copy(self):
2230
"""Returns a shallow copy from self."""
2231
nc = Context(self.prec, self.rounding, self.traps, self.flags,
2232
self._rounding_decision, self.Emin, self.Emax,
2233
self.capitals, self._clamp, self._ignored_flags)
2237
"""Returns a deep copy from self."""
2238
nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(),
2239
self._rounding_decision, self.Emin, self.Emax,
2240
self.capitals, self._clamp, self._ignored_flags)
2244
def _raise_error(self, condition, explanation = None, *args):
2247
If the flag is in _ignored_flags, returns the default response.
2248
Otherwise, it increments the flag, then, if the corresponding
2249
trap_enabler is set, it reaises the exception. Otherwise, it returns
2250
the default value after incrementing the flag.
2252
error = _condition_map.get(condition, condition)
2253
if error in self._ignored_flags:
2254
#Don't touch the flag
2255
return error().handle(self, *args)
2257
self.flags[error] += 1
2258
if not self.traps[error]:
2259
#The errors define how to handle themselves.
2260
return condition().handle(self, *args)
2262
# Errors should only be risked on copies of the context
2263
#self._ignored_flags = []
2264
raise error, explanation
2266
def _ignore_all_flags(self):
2267
"""Ignore all flags, if they are raised"""
2268
return self._ignore_flags(*_signals)
2270
def _ignore_flags(self, *flags):
2271
"""Ignore the flags, if they are raised"""
2272
# Do not mutate-- This way, copies of a context leave the original
2274
self._ignored_flags = (self._ignored_flags + list(flags))
2277
def _regard_flags(self, *flags):
2278
"""Stop ignoring the flags, if they are raised"""
2279
if flags and isinstance(flags[0], (tuple,list)):
2282
self._ignored_flags.remove(flag)
2285
"""A Context cannot be hashed."""
2286
# We inherit object.__hash__, so we must deny this explicitly
2287
raise TypeError, "Cannot hash a Context."
2290
"""Returns Etiny (= Emin - prec + 1)"""
2291
return int(self.Emin - self.prec + 1)
2294
"""Returns maximum exponent (= Emax - prec + 1)"""
2295
return int(self.Emax - self.prec + 1)
2297
def _set_rounding_decision(self, type):
2298
"""Sets the rounding decision.
2300
Sets the rounding decision, and returns the current (previous)
2301
rounding decision. Often used like:
2303
context = context._shallow_copy()
2304
# That so you don't change the calling context
2305
# if an error occurs in the middle (say DivisionImpossible is raised).
2307
rounding = context._set_rounding_decision(NEVER_ROUND)
2308
instance = instance / Decimal(2)
2309
context._set_rounding_decision(rounding)
2311
This will make it not round for that operation.
2314
rounding = self._rounding_decision
2315
self._rounding_decision = type
2318
def _set_rounding(self, type):
2319
"""Sets the rounding type.
2321
Sets the rounding type, and returns the current (previous)
2322
rounding type. Often used like:
2324
context = context.copy()
2325
# so you don't change the calling context
2326
# if an error occurs in the middle.
2327
rounding = context._set_rounding(ROUND_UP)
2328
val = self.__sub__(other, context=context)
2329
context._set_rounding(rounding)
2331
This will make it round up for that operation.
2333
rounding = self.rounding
2337
def create_decimal(self, num='0'):
2338
"""Creates a new Decimal instance but using self as context."""
2339
d = Decimal(num, context=self)
2344
"""Returns the absolute value of the operand.
2346
If the operand is negative, the result is the same as using the minus
2347
operation on the operand. Otherwise, the result is the same as using
2348
the plus operation on the operand.
2350
>>> ExtendedContext.abs(Decimal('2.1'))
2352
>>> ExtendedContext.abs(Decimal('-100'))
2354
>>> ExtendedContext.abs(Decimal('101.5'))
2356
>>> ExtendedContext.abs(Decimal('-101.5'))
2359
return a.__abs__(context=self)
2361
def add(self, a, b):
2362
"""Return the sum of the two operands.
2364
>>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
2366
>>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
2369
return a.__add__(b, context=self)
2371
def _apply(self, a):
2372
return str(a._fix(self))
2374
def compare(self, a, b):
2375
"""Compares values numerically.
2377
If the signs of the operands differ, a value representing each operand
2378
('-1' if the operand is less than zero, '0' if the operand is zero or
2379
negative zero, or '1' if the operand is greater than zero) is used in
2380
place of that operand for the comparison instead of the actual
2383
The comparison is then effected by subtracting the second operand from
2384
the first and then returning a value according to the result of the
2385
subtraction: '-1' if the result is less than zero, '0' if the result is
2386
zero or negative zero, or '1' if the result is greater than zero.
2388
>>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
2390
>>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
2392
>>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
2394
>>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
2396
>>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
2398
>>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
2401
return a.compare(b, context=self)
2403
def divide(self, a, b):
2404
"""Decimal division in a specified context.
2406
>>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
2407
Decimal("0.333333333")
2408
>>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
2409
Decimal("0.666666667")
2410
>>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
2412
>>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
2414
>>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
2416
>>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
2418
>>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
2420
>>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
2422
>>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
2424
>>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
2427
return a.__div__(b, context=self)
2429
def divide_int(self, a, b):
2430
"""Divides two numbers and returns the integer part of the result.
2432
>>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
2434
>>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
2436
>>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
2439
return a.__floordiv__(b, context=self)
2441
def divmod(self, a, b):
2442
return a.__divmod__(b, context=self)
2445
"""max compares two values numerically and returns the maximum.
2447
If either operand is a NaN then the general rules apply.
2448
Otherwise, the operands are compared as as though by the compare
2449
operation. If they are numerically equal then the left-hand operand
2450
is chosen as the result. Otherwise the maximum (closer to positive
2451
infinity) of the two operands is chosen as the result.
2453
>>> ExtendedContext.max(Decimal('3'), Decimal('2'))
2455
>>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
2457
>>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
2459
>>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
2462
return a.max(b, context=self)
2465
"""min compares two values numerically and returns the minimum.
2467
If either operand is a NaN then the general rules apply.
2468
Otherwise, the operands are compared as as though by the compare
2469
operation. If they are numerically equal then the left-hand operand
2470
is chosen as the result. Otherwise the minimum (closer to negative
2471
infinity) of the two operands is chosen as the result.
2473
>>> ExtendedContext.min(Decimal('3'), Decimal('2'))
2475
>>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
2477
>>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
2479
>>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
2482
return a.min(b, context=self)
2485
"""Minus corresponds to unary prefix minus in Python.
2487
The operation is evaluated using the same rules as subtract; the
2488
operation minus(a) is calculated as subtract('0', a) where the '0'
2489
has the same exponent as the operand.
2491
>>> ExtendedContext.minus(Decimal('1.3'))
2493
>>> ExtendedContext.minus(Decimal('-1.3'))
2496
return a.__neg__(context=self)
2498
def multiply(self, a, b):
2499
"""multiply multiplies two operands.
2501
If either operand is a special value then the general rules apply.
2502
Otherwise, the operands are multiplied together ('long multiplication'),
2503
resulting in a number which may be as long as the sum of the lengths
2504
of the two operands.
2506
>>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
2508
>>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
2510
>>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
2512
>>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
2514
>>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
2515
Decimal("4.28135971E+11")
2517
return a.__mul__(b, context=self)
2519
def normalize(self, a):
2520
"""normalize reduces an operand to its simplest form.
2522
Essentially a plus operation with all trailing zeros removed from the
2525
>>> ExtendedContext.normalize(Decimal('2.1'))
2527
>>> ExtendedContext.normalize(Decimal('-2.0'))
2529
>>> ExtendedContext.normalize(Decimal('1.200'))
2531
>>> ExtendedContext.normalize(Decimal('-120'))
2533
>>> ExtendedContext.normalize(Decimal('120.00'))
2535
>>> ExtendedContext.normalize(Decimal('0.00'))
2538
return a.normalize(context=self)
2541
"""Plus corresponds to unary prefix plus in Python.
2543
The operation is evaluated using the same rules as add; the
2544
operation plus(a) is calculated as add('0', a) where the '0'
2545
has the same exponent as the operand.
2547
>>> ExtendedContext.plus(Decimal('1.3'))
2549
>>> ExtendedContext.plus(Decimal('-1.3'))
2552
return a.__pos__(context=self)
2554
def power(self, a, b, modulo=None):
2555
"""Raises a to the power of b, to modulo if given.
2557
The right-hand operand must be a whole number whose integer part (after
2558
any exponent has been applied) has no more than 9 digits and whose
2559
fractional part (if any) is all zeros before any rounding. The operand
2560
may be positive, negative, or zero; if negative, the absolute value of
2561
the power is used, and the left-hand operand is inverted (divided into
2564
If the increased precision needed for the intermediate calculations
2565
exceeds the capabilities of the implementation then an Invalid operation
2566
condition is raised.
2568
If, when raising to a negative power, an underflow occurs during the
2569
division into 1, the operation is not halted at that point but
2572
>>> ExtendedContext.power(Decimal('2'), Decimal('3'))
2574
>>> ExtendedContext.power(Decimal('2'), Decimal('-3'))
2576
>>> ExtendedContext.power(Decimal('1.7'), Decimal('8'))
2577
Decimal("69.7575744")
2578
>>> ExtendedContext.power(Decimal('Infinity'), Decimal('-2'))
2580
>>> ExtendedContext.power(Decimal('Infinity'), Decimal('-1'))
2582
>>> ExtendedContext.power(Decimal('Infinity'), Decimal('0'))
2584
>>> ExtendedContext.power(Decimal('Infinity'), Decimal('1'))
2586
>>> ExtendedContext.power(Decimal('Infinity'), Decimal('2'))
2588
>>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-2'))
2590
>>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-1'))
2592
>>> ExtendedContext.power(Decimal('-Infinity'), Decimal('0'))
2594
>>> ExtendedContext.power(Decimal('-Infinity'), Decimal('1'))
2595
Decimal("-Infinity")
2596
>>> ExtendedContext.power(Decimal('-Infinity'), Decimal('2'))
2598
>>> ExtendedContext.power(Decimal('0'), Decimal('0'))
2601
return a.__pow__(b, modulo, context=self)
2603
def quantize(self, a, b):
2604
"""Returns a value equal to 'a' (rounded) and having the exponent of 'b'.
2606
The coefficient of the result is derived from that of the left-hand
2607
operand. It may be rounded using the current rounding setting (if the
2608
exponent is being increased), multiplied by a positive power of ten (if
2609
the exponent is being decreased), or is unchanged (if the exponent is
2610
already equal to that of the right-hand operand).
2612
Unlike other operations, if the length of the coefficient after the
2613
quantize operation would be greater than precision then an Invalid
2614
operation condition is raised. This guarantees that, unless there is an
2615
error condition, the exponent of the result of a quantize is always
2616
equal to that of the right-hand operand.
2618
Also unlike other operations, quantize will never raise Underflow, even
2619
if the result is subnormal and inexact.
2621
>>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
2623
>>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
2625
>>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
2627
>>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
2629
>>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
2631
>>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
2632
Decimal("-Infinity")
2633
>>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
2635
>>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
2637
>>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
2639
>>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
2641
>>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
2643
>>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
2645
>>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
2647
>>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
2649
>>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
2652
return a.quantize(b, context=self)
2654
def remainder(self, a, b):
2655
"""Returns the remainder from integer division.
2657
The result is the residue of the dividend after the operation of
2658
calculating integer division as described for divide-integer, rounded to
2659
precision digits if necessary. The sign of the result, if non-zero, is
2660
the same as that of the original dividend.
2662
This operation will fail under the same conditions as integer division
2663
(that is, if integer division on the same two operands would fail, the
2664
remainder cannot be calculated).
2666
>>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
2668
>>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
2670
>>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
2672
>>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
2674
>>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
2676
>>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
2679
return a.__mod__(b, context=self)
2681
def remainder_near(self, a, b):
2682
"""Returns to be "a - b * n", where n is the integer nearest the exact
2683
value of "x / b" (if two integers are equally near then the even one
2684
is chosen). If the result is equal to 0 then its sign will be the
2687
This operation will fail under the same conditions as integer division
2688
(that is, if integer division on the same two operands would fail, the
2689
remainder cannot be calculated).
2691
>>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
2693
>>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
2695
>>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
2697
>>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
2699
>>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
2701
>>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
2703
>>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
2706
return a.remainder_near(b, context=self)
2708
def same_quantum(self, a, b):
2709
"""Returns True if the two operands have the same exponent.
2711
The result is never affected by either the sign or the coefficient of
2714
>>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
2716
>>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
2718
>>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
2720
>>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
2723
return a.same_quantum(b)
2726
"""Returns the square root of a non-negative number to context precision.
2728
If the result must be inexact, it is rounded using the round-half-even
2731
>>> ExtendedContext.sqrt(Decimal('0'))
2733
>>> ExtendedContext.sqrt(Decimal('-0'))
2735
>>> ExtendedContext.sqrt(Decimal('0.39'))
2736
Decimal("0.624499800")
2737
>>> ExtendedContext.sqrt(Decimal('100'))
2739
>>> ExtendedContext.sqrt(Decimal('1'))
2741
>>> ExtendedContext.sqrt(Decimal('1.0'))
2743
>>> ExtendedContext.sqrt(Decimal('1.00'))
2745
>>> ExtendedContext.sqrt(Decimal('7'))
2746
Decimal("2.64575131")
2747
>>> ExtendedContext.sqrt(Decimal('10'))
2748
Decimal("3.16227766")
2749
>>> ExtendedContext.prec
2752
return a.sqrt(context=self)
2754
def subtract(self, a, b):
2755
"""Return the sum of the two operands.
2757
>>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
2759
>>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
2761
>>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
2764
return a.__sub__(b, context=self)
2766
def to_eng_string(self, a):
2767
"""Converts a number to a string, using scientific notation.
2769
The operation is not affected by the context.
2771
return a.to_eng_string(context=self)
2773
def to_sci_string(self, a):
2774
"""Converts a number to a string, using scientific notation.
2776
The operation is not affected by the context.
2778
return a.__str__(context=self)
2780
def to_integral(self, a):
2781
"""Rounds to an integer.
2783
When the operand has a negative exponent, the result is the same
2784
as using the quantize() operation using the given operand as the
2785
left-hand-operand, 1E+0 as the right-hand-operand, and the precision
2786
of the operand as the precision setting, except that no flags will
2787
be set. The rounding mode is taken from the context.
2789
>>> ExtendedContext.to_integral(Decimal('2.1'))
2791
>>> ExtendedContext.to_integral(Decimal('100'))
2793
>>> ExtendedContext.to_integral(Decimal('100.0'))
2795
>>> ExtendedContext.to_integral(Decimal('101.5'))
2797
>>> ExtendedContext.to_integral(Decimal('-101.5'))
2799
>>> ExtendedContext.to_integral(Decimal('10E+5'))
2801
>>> ExtendedContext.to_integral(Decimal('7.89E+77'))
2803
>>> ExtendedContext.to_integral(Decimal('-Inf'))
2804
Decimal("-Infinity")
2806
return a.to_integral(context=self)
2808
class _WorkRep(object):
2809
__slots__ = ('sign','int','exp')
2812
# exp: None, int, or string
2814
def __init__(self, value=None):
2819
elif isinstance(value, Decimal):
2820
self.sign = value._sign
2822
for digit in value._int:
2823
cum = cum * 10 + digit
2825
self.exp = value._exp
2827
# assert isinstance(value, tuple)
2828
self.sign = value[0]
2833
return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
2839
def _normalize(op1, op2, shouldround = 0, prec = 0):
2840
"""Normalizes op1, op2 to have the same exp and length of coefficient.
2842
Done during addition.
2844
# Yes, the exponent is a long, but the difference between exponents
2845
# must be an int-- otherwise you'd get a big memory problem.
2846
numdigits = int(op1.exp - op2.exp)
2848
numdigits = -numdigits
2856
if shouldround and numdigits > prec + 1:
2857
# Big difference in exponents - check the adjusted exponents
2858
tmp_len = len(str(tmp.int))
2859
other_len = len(str(other.int))
2860
if numdigits > (other_len + prec + 1 - tmp_len):
2861
# If the difference in adjusted exps is > prec+1, we know
2862
# other is insignificant, so might as well put a 1 after the precision.
2863
# (since this is only for addition.) Also stops use of massive longs.
2865
extend = prec + 2 - tmp_len
2868
tmp.int *= 10 ** extend
2874
tmp.int *= 10 ** numdigits
2875
tmp.exp -= numdigits
2878
def _adjust_coefficients(op1, op2):
2879
"""Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
2881
Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp.
2883
Used on _WorkRep instances during division.
2886
#If op1 is smaller, make it larger
2887
while op2.int > op1.int:
2892
#If op2 is too small, make it larger
2893
while op1.int >= (10 * op2.int):
2898
return op1, op2, adjust
2900
##### Helper Functions ########################################
2902
def _convert_other(other):
2903
"""Convert other to Decimal.
2905
Verifies that it's ok to use in an implicit construction.
2907
if isinstance(other, Decimal):
2909
if isinstance(other, (int, long)):
2910
return Decimal(other)
2912
raise TypeError, "You can interact Decimal only with int, long or Decimal data types."
2923
def _isinfinity(num):
2924
"""Determines whether a string or float is infinity.
2926
+1 for negative infinity; 0 for finite ; +1 for positive infinity
2928
num = str(num).lower()
2929
return _infinity_map.get(num, 0)
2932
"""Determines whether a string or float is NaN
2934
(1, sign, diagnostic info as string) => NaN
2935
(2, sign, diagnostic info as string) => sNaN
2938
num = str(num).lower()
2942
#get the sign, get rid of trailing [+-]
2946
elif num[0] == '-': #elif avoids '+-nan'
2950
if num.startswith('nan'):
2951
if len(num) > 3 and not num[3:].isdigit(): #diagnostic info
2953
return (1, sign, num[3:].lstrip('0'))
2954
if num.startswith('snan'):
2955
if len(num) > 4 and not num[4:].isdigit():
2957
return (2, sign, num[4:].lstrip('0'))
2961
##### Setup Specific Contexts ################################
2963
# The default context prototype used by Context()
2964
# Is mutable, so that new contexts can have different default values
2966
DefaultContext = Context(
2967
prec=28, rounding=ROUND_HALF_EVEN,
2968
traps=[DivisionByZero, Overflow, InvalidOperation],
2970
_rounding_decision=ALWAYS_ROUND,
2976
# Pre-made alternate contexts offered by the specification
2977
# Don't change these; the user should be able to select these
2978
# contexts and be able to reproduce results from other implementations
2981
BasicContext = Context(
2982
prec=9, rounding=ROUND_HALF_UP,
2983
traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
2987
ExtendedContext = Context(
2988
prec=9, rounding=ROUND_HALF_EVEN,
2994
##### Useful Constants (internal use only) ####################
2997
Inf = Decimal('Inf')
2998
negInf = Decimal('-Inf')
3000
#Infsign[sign] is infinity w/ that sign
3001
Infsign = (Inf, negInf)
3003
NaN = Decimal('NaN')
3006
##### crud for parsing strings #################################
3009
# There's an optional sign at the start, and an optional exponent
3010
# at the end. The exponent has an optional sign and at least one
3011
# digit. In between, must have either at least one digit followed
3012
# by an optional fraction, or a decimal point followed by at least
3015
_parser = re.compile(r"""
3019
(?P<int>\d+) (\. (?P<frac>\d*))?
3021
\. (?P<onlyfrac>\d+)
3023
([eE](?P<exp>[-+]? \d+))?
3026
""", re.VERBOSE).match #Uncomment the \s* to allow leading or trailing spaces.
3030
# return sign, n, p s.t. float string value == -1**sign * n * 10**p exactly
3032
def _string2exact(s):
3035
raise ValueError("invalid literal for Decimal: %r" % s)
3037
if m.group('sign') == "-":
3042
exp = m.group('exp')
3048
intpart = m.group('int')
3051
fracpart = m.group('onlyfrac')
3053
fracpart = m.group('frac')
3054
if fracpart is None:
3057
exp -= len(fracpart)
3059
mantissa = intpart + fracpart
3060
tmp = map(int, mantissa)
3062
while tmp and tmp[0] == 0:
3068
return (sign, tuple(backup), exp)
3069
return (sign, (0,), exp)
3070
mantissa = tuple(tmp)
3072
return (sign, mantissa, exp)
3075
if __name__ == '__main__':
3077
doctest.testmod(sys.modules[__name__])