blob: ebeb6d72081c5aef34f331e77c8c9712acdd8c0d [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
Raymond Hettinger27dbcf22004-08-19 22:39:55 +000010# This module is currently Py2.3 compatible and should be kept that way
11# unless a major compelling advantage arises. IOW, 2.3 compatibility is
12# strongly preferred, but not guaranteed.
13
14# Also, this module should be kept in sync with the latest updates of
15# the IBM specification as it evolves. Those updates will be treated
16# as bug fixes (deviation from the spec is a compatibility, usability
17# bug) and will be backported. At this point the spec is stabilizing
18# and the updates are becoming fewer, smaller, and less significant.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000019
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000020"""
21This is a Py2.3 implementation of decimal floating point arithmetic based on
22the General Decimal Arithmetic Specification:
23
24 www2.hursley.ibm.com/decimal/decarith.html
25
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000026and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000027
28 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
29
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030Decimal floating point has finite precision with arbitrarily large bounds.
31
Facundo Batista5dfc4802008-01-08 16:20:31 +000032The purpose of this module is to support arithmetic using familiar
33"schoolhouse" rules and to avoid some of the tricky representation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000034issues associated with binary floating point. The package is especially
35useful for financial applications or for contexts where users have
36expectations that are at odds with binary floating point (for instance,
37in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
38of the expected Decimal("0.00") returned by decimal floating point).
39
40Here are some examples of using the decimal module:
41
42>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000043>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000044>>> Decimal(0)
45Decimal("0")
46>>> Decimal("1")
47Decimal("1")
48>>> Decimal("-.0123")
49Decimal("-0.0123")
50>>> Decimal(123456)
51Decimal("123456")
52>>> Decimal("123.45e12345678901234567890")
53Decimal("1.2345E+12345678901234567892")
54>>> Decimal("1.33") + Decimal("1.27")
55Decimal("2.60")
56>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
57Decimal("-2.20")
58>>> dig = Decimal(1)
59>>> print dig / Decimal(3)
600.333333333
61>>> getcontext().prec = 18
62>>> print dig / Decimal(3)
630.333333333333333333
64>>> print dig.sqrt()
651
66>>> print Decimal(3).sqrt()
671.73205080756887729
68>>> print Decimal(3) ** 123
694.85192780976896427E+58
70>>> inf = Decimal(1) / Decimal(0)
71>>> print inf
72Infinity
73>>> neginf = Decimal(-1) / Decimal(0)
74>>> print neginf
75-Infinity
76>>> print neginf + inf
77NaN
78>>> print neginf * inf
79-Infinity
80>>> print dig / 0
81Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000082>>> getcontext().traps[DivisionByZero] = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000083>>> print dig / 0
84Traceback (most recent call last):
85 ...
86 ...
87 ...
88DivisionByZero: x / 0
89>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000090>>> c.traps[InvalidOperation] = 0
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000091>>> print c.flags[InvalidOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000920
93>>> c.divide(Decimal(0), Decimal(0))
94Decimal("NaN")
Raymond Hettingerbf440692004-07-10 14:14:37 +000095>>> c.traps[InvalidOperation] = 1
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000096>>> print c.flags[InvalidOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000098>>> c.flags[InvalidOperation] = 0
99>>> print c.flags[InvalidOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
101>>> print c.divide(Decimal(0), Decimal(0))
102Traceback (most recent call last):
103 ...
104 ...
105 ...
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000106InvalidOperation: 0 / 0
107>>> print c.flags[InvalidOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000109>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000110>>> c.traps[InvalidOperation] = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000111>>> print c.divide(Decimal(0), Decimal(0))
112NaN
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000113>>> print c.flags[InvalidOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
115>>>
116"""
117
118__all__ = [
119 # Two major classes
120 'Decimal', 'Context',
121
122 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000123 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000124
125 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000128
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000129 # Constants for use in setting up contexts
130 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Facundo Batista5dfc4802008-01-08 16:20:31 +0000131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000132
133 # Functions for manipulating contexts
Nick Coghlanc48daf52006-09-03 01:08:30 +0000134 'setcontext', 'getcontext', 'localcontext'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000135]
136
Raymond Hettingereb260842005-06-07 18:52:34 +0000137import copy as _copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000138
Facundo Batista5dfc4802008-01-08 16:20:31 +0000139# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000140ROUND_DOWN = 'ROUND_DOWN'
141ROUND_HALF_UP = 'ROUND_HALF_UP'
142ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
143ROUND_CEILING = 'ROUND_CEILING'
144ROUND_FLOOR = 'ROUND_FLOOR'
145ROUND_UP = 'ROUND_UP'
146ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Facundo Batista5dfc4802008-01-08 16:20:31 +0000147ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000148
Facundo Batista5dfc4802008-01-08 16:20:31 +0000149# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000150
151class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000152 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000153
154 Used exceptions derive from this.
155 If an exception derives from another exception besides this (such as
156 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
157 called if the others are present. This isn't actually used for
158 anything, though.
159
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000160 handle -- Called when context._raise_error is called and the
161 trap_enabler is set. First argument is self, second is the
162 context. More arguments can be given, those being after
163 the explanation in _raise_error (For example,
164 context._raise_error(NewError, '(-x)!', self._sign) would
165 call NewError().handle(context, self._sign).)
166
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000167 To define a new exception, it should be sufficient to have it derive
168 from DecimalException.
169 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000170 def handle(self, context, *args):
171 pass
172
173
174class Clamped(DecimalException):
175 """Exponent of a 0 changed to fit bounds.
176
177 This occurs and signals clamped if the exponent of a result has been
178 altered in order to fit the constraints of a specific concrete
Facundo Batista5dfc4802008-01-08 16:20:31 +0000179 representation. This may occur when the exponent of a zero result would
180 be outside the bounds of a representation, or when a large normal
181 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000182 this latter case, the exponent is reduced to fit and the corresponding
183 number of zero digits are appended to the coefficient ("fold-down").
184 """
185
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000186class InvalidOperation(DecimalException):
187 """An invalid operation was performed.
188
189 Various bad things cause this:
190
191 Something creates a signaling NaN
192 -INF + INF
Facundo Batista5dfc4802008-01-08 16:20:31 +0000193 0 * (+-)INF
194 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000195 x % 0
196 (+-)INF % x
197 x._rescale( non-integer )
198 sqrt(-x) , x > 0
199 0 ** 0
200 x ** (non-integer)
201 x ** (+-)INF
202 An operand is invalid
Facundo Batista5dfc4802008-01-08 16:20:31 +0000203
204 The result of the operation after these is a quiet positive NaN,
205 except when the cause is a signaling NaN, in which case the result is
206 also a quiet NaN, but with the original sign, and an optional
207 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000208 """
209 def handle(self, context, *args):
210 if args:
Facundo Batista5dfc4802008-01-08 16:20:31 +0000211 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
212 return ans._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000213 return NaN
214
215class ConversionSyntax(InvalidOperation):
216 """Trying to convert badly formed string.
217
218 This occurs and signals invalid-operation if an string is being
219 converted to a number and it does not conform to the numeric string
Facundo Batista5dfc4802008-01-08 16:20:31 +0000220 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000222 def handle(self, context, *args):
Facundo Batista5dfc4802008-01-08 16:20:31 +0000223 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224
225class DivisionByZero(DecimalException, ZeroDivisionError):
226 """Division by 0.
227
228 This occurs and signals division-by-zero if division of a finite number
229 by zero was attempted (during a divide-integer or divide operation, or a
230 power operation with negative right-hand operand), and the dividend was
231 not zero.
232
233 The result of the operation is [sign,inf], where sign is the exclusive
234 or of the signs of the operands for divide, or is 1 for an odd power of
235 -0, for power.
236 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000237
Facundo Batista5dfc4802008-01-08 16:20:31 +0000238 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000239 return Infsign[sign]
240
241class DivisionImpossible(InvalidOperation):
242 """Cannot perform the division adequately.
243
244 This occurs and signals invalid-operation if the integer result of a
245 divide-integer or remainder operation had too many digits (would be
Facundo Batista5dfc4802008-01-08 16:20:31 +0000246 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000247 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000248
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000249 def handle(self, context, *args):
Facundo Batista5dfc4802008-01-08 16:20:31 +0000250 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000251
252class DivisionUndefined(InvalidOperation, ZeroDivisionError):
253 """Undefined result of division.
254
255 This occurs and signals invalid-operation if division by zero was
256 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista5dfc4802008-01-08 16:20:31 +0000257 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000258 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000259
Facundo Batista5dfc4802008-01-08 16:20:31 +0000260 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000261 return NaN
262
263class Inexact(DecimalException):
264 """Had to round, losing information.
265
266 This occurs and signals inexact whenever the result of an operation is
267 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista5dfc4802008-01-08 16:20:31 +0000268 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000269 result in all cases is unchanged.
270
271 The inexact signal may be tested (or trapped) to determine if a given
272 operation (or sequence of operations) was inexact.
273 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000274
275class InvalidContext(InvalidOperation):
276 """Invalid context. Unknown rounding, for example.
277
278 This occurs and signals invalid-operation if an invalid context was
Facundo Batista5dfc4802008-01-08 16:20:31 +0000279 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000280 on creation and either the precision exceeds the capability of the
281 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista5dfc4802008-01-08 16:20:31 +0000282 was specified. These aspects of the context need only be checked when
283 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000284 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000285
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000286 def handle(self, context, *args):
287 return NaN
288
289class Rounded(DecimalException):
290 """Number got rounded (not necessarily changed during rounding).
291
292 This occurs and signals rounded whenever the result of an operation is
293 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista5dfc4802008-01-08 16:20:31 +0000294 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000295 result in all cases is unchanged.
296
297 The rounded signal may be tested (or trapped) to determine if a given
298 operation (or sequence of operations) caused a loss of precision.
299 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000300
301class Subnormal(DecimalException):
302 """Exponent < Emin before rounding.
303
304 This occurs and signals subnormal whenever the result of a conversion or
305 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista5dfc4802008-01-08 16:20:31 +0000306 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000307
308 The subnormal signal may be tested (or trapped) to determine if a given
309 or operation (or sequence of operations) yielded a subnormal result.
310 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000311
312class Overflow(Inexact, Rounded):
313 """Numerical overflow.
314
315 This occurs and signals overflow if the adjusted exponent of a result
316 (from a conversion or from an operation that is not an attempt to divide
317 by zero), after rounding, would be greater than the largest value that
318 can be handled by the implementation (the value Emax).
319
320 The result depends on the rounding mode:
321
322 For round-half-up and round-half-even (and for round-half-down and
323 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista5dfc4802008-01-08 16:20:31 +0000324 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000325 result is the largest finite number that can be represented in the
Facundo Batista5dfc4802008-01-08 16:20:31 +0000326 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000327 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista5dfc4802008-01-08 16:20:31 +0000328 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000329 the result is the same as for round-down if the sign of the intermediate
Facundo Batista5dfc4802008-01-08 16:20:31 +0000330 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000331 will also be raised.
Facundo Batista5dfc4802008-01-08 16:20:31 +0000332 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000333
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000334 def handle(self, context, sign, *args):
335 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista5dfc4802008-01-08 16:20:31 +0000336 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 return Infsign[sign]
338 if sign == 0:
339 if context.rounding == ROUND_CEILING:
340 return Infsign[sign]
Facundo Batista5dfc4802008-01-08 16:20:31 +0000341 return _dec_from_triple(sign, '9'*context.prec,
342 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000343 if sign == 1:
344 if context.rounding == ROUND_FLOOR:
345 return Infsign[sign]
Facundo Batista5dfc4802008-01-08 16:20:31 +0000346 return _dec_from_triple(sign, '9'*context.prec,
347 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000348
349
350class Underflow(Inexact, Rounded, Subnormal):
351 """Numerical underflow with result rounded to 0.
352
353 This occurs and signals underflow if a result is inexact and the
354 adjusted exponent of the result would be smaller (more negative) than
355 the smallest value that can be handled by the implementation (the value
Facundo Batista5dfc4802008-01-08 16:20:31 +0000356 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000357
358 The result after an underflow will be a subnormal number rounded, if
Facundo Batista5dfc4802008-01-08 16:20:31 +0000359 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000360 in 0 with the sign of the intermediate result and an exponent of Etiny.
361
362 In all cases, Inexact, Rounded, and Subnormal will also be raised.
363 """
364
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000365# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000366_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000367 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000368
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000369# Map conditions (per the spec) to signals
370_condition_map = {ConversionSyntax:InvalidOperation,
371 DivisionImpossible:InvalidOperation,
372 DivisionUndefined:InvalidOperation,
373 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000374
Facundo Batista5dfc4802008-01-08 16:20:31 +0000375##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000376
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000377# The getcontext() and setcontext() function manage access to a thread-local
378# current context. Py2.4 offers direct support for thread locals. If that
379# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000380# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000381# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000382
383try:
384 import threading
385except ImportError:
386 # Python was compiled without threads; create a mock object instead
387 import sys
Facundo Batista5dfc4802008-01-08 16:20:31 +0000388 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000389 def local(self, sys=sys):
390 return sys.modules[__name__]
391 threading = MockThreading()
392 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000393
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000394try:
395 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000396
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000397except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000398
Facundo Batista5dfc4802008-01-08 16:20:31 +0000399 # To fix reloading, force it to create a new context
400 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000401 if hasattr(threading.currentThread(), '__decimal_context__'):
402 del threading.currentThread().__decimal_context__
403
404 def setcontext(context):
405 """Set this thread's context to context."""
406 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000407 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000408 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000409 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000410
411 def getcontext():
412 """Returns this thread's context.
413
414 If this thread does not yet have a context, returns
415 a new context and sets this thread's context.
416 New contexts are copies of DefaultContext.
417 """
418 try:
419 return threading.currentThread().__decimal_context__
420 except AttributeError:
421 context = Context()
422 threading.currentThread().__decimal_context__ = context
423 return context
424
425else:
426
427 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000428 if hasattr(local, '__decimal_context__'):
429 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000430
431 def getcontext(_local=local):
432 """Returns this thread's context.
433
434 If this thread does not yet have a context, returns
435 a new context and sets this thread's context.
436 New contexts are copies of DefaultContext.
437 """
438 try:
439 return _local.__decimal_context__
440 except AttributeError:
441 context = Context()
442 _local.__decimal_context__ = context
443 return context
444
445 def setcontext(context, _local=local):
446 """Set this thread's context to context."""
447 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000448 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000449 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000450 _local.__decimal_context__ = context
451
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000452 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000453
Nick Coghlanc48daf52006-09-03 01:08:30 +0000454def localcontext(ctx=None):
455 """Return a context manager for a copy of the supplied context
456
457 Uses a copy of the current context if no context is specified
458 The returned context manager creates a local decimal context
459 in a with statement:
460 def sin(x):
461 with localcontext() as ctx:
462 ctx.prec += 2
463 # Rest of sin calculation algorithm
464 # uses a precision 2 greater than normal
Facundo Batista5dfc4802008-01-08 16:20:31 +0000465 return +s # Convert result to normal precision
Nick Coghlanc48daf52006-09-03 01:08:30 +0000466
467 def sin(x):
468 with localcontext(ExtendedContext):
469 # Rest of sin calculation algorithm
470 # uses the Extended Context from the
471 # General Decimal Arithmetic Specification
Facundo Batista5dfc4802008-01-08 16:20:31 +0000472 return +s # Convert result to normal context
Nick Coghlanc48daf52006-09-03 01:08:30 +0000473
474 """
Neal Norwitz665a3ae2006-09-03 20:00:39 +0000475 # The string below can't be included in the docstring until Python 2.6
Nick Coghlanc48daf52006-09-03 01:08:30 +0000476 # as the doctest module doesn't understand __future__ statements
477 """
478 >>> from __future__ import with_statement
479 >>> print getcontext().prec
480 28
481 >>> with localcontext():
482 ... ctx = getcontext()
Raymond Hettinger0bafda42007-02-08 01:37:18 +0000483 ... ctx.prec += 2
Nick Coghlanc48daf52006-09-03 01:08:30 +0000484 ... print ctx.prec
485 ...
486 30
487 >>> with localcontext(ExtendedContext):
488 ... print getcontext().prec
489 ...
490 9
491 >>> print getcontext().prec
492 28
493 """
494 if ctx is None: ctx = getcontext()
495 return _ContextManager(ctx)
496
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000497
Facundo Batista5dfc4802008-01-08 16:20:31 +0000498##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000499
500class Decimal(object):
501 """Floating point class for decimal arithmetic."""
502
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000503 __slots__ = ('_exp','_int','_sign', '_is_special')
504 # Generally, the value of the Decimal instance is given by
505 # (-1)**_sign * _int * 10**_exp
506 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000507
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000508 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000509 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000510 """Create a decimal point instance.
511
512 >>> Decimal('3.14') # string input
513 Decimal("3.14")
Facundo Batista5dfc4802008-01-08 16:20:31 +0000514 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000515 Decimal("3.14")
516 >>> Decimal(314) # int or long
517 Decimal("314")
518 >>> Decimal(Decimal(314)) # another decimal instance
519 Decimal("314")
520 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000521
Facundo Batista5dfc4802008-01-08 16:20:31 +0000522 # Note that the coefficient, self._int, is actually stored as
523 # a string rather than as a tuple of digits. This speeds up
524 # the "digits to integer" and "integer to digits" conversions
525 # that are used in almost every arithmetic operation on
526 # Decimals. This is an internal detail: the as_tuple function
527 # and the Decimal constructor still deal with tuples of
528 # digits.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000529
Facundo Batista5dfc4802008-01-08 16:20:31 +0000530 self = object.__new__(cls)
531
532 # From a string
533 # REs insist on real strings, so we can too.
534 if isinstance(value, basestring):
535 m = _parser(value)
536 if m is None:
537 if context is None:
538 context = getcontext()
539 return context._raise_error(ConversionSyntax,
540 "Invalid literal for Decimal: %r" % value)
541
542 if m.group('sign') == "-":
543 self._sign = 1
544 else:
545 self._sign = 0
546 intpart = m.group('int')
547 if intpart is not None:
548 # finite number
549 fracpart = m.group('frac')
550 exp = int(m.group('exp') or '0')
551 if fracpart is not None:
552 self._int = (intpart+fracpart).lstrip('0') or '0'
553 self._exp = exp - len(fracpart)
554 else:
555 self._int = intpart.lstrip('0') or '0'
556 self._exp = exp
557 self._is_special = False
558 else:
559 diag = m.group('diag')
560 if diag is not None:
561 # NaN
562 self._int = diag.lstrip('0')
563 if m.group('signal'):
564 self._exp = 'N'
565 else:
566 self._exp = 'n'
567 else:
568 # infinity
569 self._int = '0'
570 self._exp = 'F'
571 self._is_special = True
572 return self
573
574 # From an integer
575 if isinstance(value, (int,long)):
576 if value >= 0:
577 self._sign = 0
578 else:
579 self._sign = 1
580 self._exp = 0
581 self._int = str(abs(value))
582 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000583 return self
584
585 # From another decimal
586 if isinstance(value, Decimal):
587 self._exp = value._exp
588 self._sign = value._sign
589 self._int = value._int
590 self._is_special = value._is_special
591 return self
592
Facundo Batista5dfc4802008-01-08 16:20:31 +0000593 # From an internal working value
594 if isinstance(value, _WorkRep):
595 self._sign = value.sign
596 self._int = str(value.int)
597 self._exp = int(value.exp)
598 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000599 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000600
601 # tuple/list conversion (possibly from as_tuple())
602 if isinstance(value, (list,tuple)):
603 if len(value) != 3:
Facundo Batista5dfc4802008-01-08 16:20:31 +0000604 raise ValueError('Invalid tuple size in creation of Decimal '
605 'from list or tuple. The list or tuple '
606 'should have exactly three elements.')
607 # process sign. The isinstance test rejects floats
608 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
609 raise ValueError("Invalid sign. The first value in the tuple "
610 "should be an integer; either 0 for a "
611 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000612 self._sign = value[0]
Facundo Batista5dfc4802008-01-08 16:20:31 +0000613 if value[2] == 'F':
614 # infinity: value[1] is ignored
615 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000616 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000617 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000618 else:
Facundo Batista5dfc4802008-01-08 16:20:31 +0000619 # process and validate the digits in value[1]
620 digits = []
621 for digit in value[1]:
622 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
623 # skip leading zeros
624 if digits or digit != 0:
625 digits.append(digit)
626 else:
627 raise ValueError("The second value in the tuple must "
628 "be composed of integers in the range "
629 "0 through 9.")
630 if value[2] in ('n', 'N'):
631 # NaN: digits form the diagnostic
632 self._int = ''.join(map(str, digits))
633 self._exp = value[2]
634 self._is_special = True
635 elif isinstance(value[2], (int, long)):
636 # finite number: digits give the coefficient
637 self._int = ''.join(map(str, digits or [0]))
638 self._exp = value[2]
639 self._is_special = False
640 else:
641 raise ValueError("The third value in the tuple must "
642 "be an integer, or one of the "
643 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000644 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000645
Raymond Hettingerbf440692004-07-10 14:14:37 +0000646 if isinstance(value, float):
647 raise TypeError("Cannot convert float to Decimal. " +
648 "First convert the float to a string")
649
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000650 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
652 def _isnan(self):
653 """Returns whether the number is not actually one.
654
655 0 if a number
656 1 if NaN
657 2 if sNaN
658 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000659 if self._is_special:
660 exp = self._exp
661 if exp == 'n':
662 return 1
663 elif exp == 'N':
664 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000665 return 0
666
667 def _isinfinity(self):
668 """Returns whether the number is infinite
669
670 0 if finite or not a number
671 1 if +INF
672 -1 if -INF
673 """
674 if self._exp == 'F':
675 if self._sign:
676 return -1
677 return 1
678 return 0
679
Facundo Batista5dfc4802008-01-08 16:20:31 +0000680 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000681 """Returns whether the number is not actually one.
682
683 if self, other are sNaN, signal
684 if self, other are NaN return nan
685 return 0
686
687 Done before operations.
688 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000689
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000690 self_is_nan = self._isnan()
691 if other is None:
692 other_is_nan = False
693 else:
694 other_is_nan = other._isnan()
695
696 if self_is_nan or other_is_nan:
697 if context is None:
698 context = getcontext()
699
700 if self_is_nan == 2:
701 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista5dfc4802008-01-08 16:20:31 +0000702 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000703 if other_is_nan == 2:
704 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista5dfc4802008-01-08 16:20:31 +0000705 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000706 if self_is_nan:
Facundo Batista5dfc4802008-01-08 16:20:31 +0000707 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000708
Facundo Batista5dfc4802008-01-08 16:20:31 +0000709 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000710 return 0
711
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000712 def __nonzero__(self):
Facundo Batista5dfc4802008-01-08 16:20:31 +0000713 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000714
Facundo Batista5dfc4802008-01-08 16:20:31 +0000715 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000716 """
Facundo Batista5dfc4802008-01-08 16:20:31 +0000717 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000718
Facundo Batista5dfc4802008-01-08 16:20:31 +0000719 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000720 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000721 if other is NotImplemented:
Facundo Batista5dfc4802008-01-08 16:20:31 +0000722 # Never return NotImplemented
723 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000724
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000725 if self._is_special or other._is_special:
Facundo Batista5dfc4802008-01-08 16:20:31 +0000726 # check for nans, without raising on a signaling nan
727 if self._isnan() or other._isnan():
728 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000729
730 # INF = INF
731 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000732
Facundo Batista5dfc4802008-01-08 16:20:31 +0000733 # check for zeros; note that cmp(0, -0) should return 0
734 if not self:
735 if not other:
736 return 0
737 else:
738 return -((-1)**other._sign)
739 if not other:
740 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000741
Facundo Batista5dfc4802008-01-08 16:20:31 +0000742 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000743 if other._sign < self._sign:
744 return -1
745 if self._sign < other._sign:
746 return 1
747
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000748 self_adjusted = self.adjusted()
749 other_adjusted = other.adjusted()
Facundo Batista5dfc4802008-01-08 16:20:31 +0000750 if self_adjusted == other_adjusted:
751 self_padded = self._int + '0'*(self._exp - other._exp)
752 other_padded = other._int + '0'*(other._exp - self._exp)
753 return cmp(self_padded, other_padded) * (-1)**self._sign
754 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000755 return (-1)**self._sign
Facundo Batista5dfc4802008-01-08 16:20:31 +0000756 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000757 return -((-1)**self._sign)
758
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000759 def __eq__(self, other):
760 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000761 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000762 return self.__cmp__(other) == 0
763
764 def __ne__(self, other):
765 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000766 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000767 return self.__cmp__(other) != 0
768
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000769 def compare(self, other, context=None):
770 """Compares one to another.
771
772 -1 => a < b
773 0 => a = b
774 1 => a > b
775 NaN => one is NaN
776 Like __cmp__, but returns Decimal instances.
777 """
Facundo Batista5dfc4802008-01-08 16:20:31 +0000778 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000779
Facundo Batista5dfc4802008-01-08 16:20:31 +0000780 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000781 if (self._is_special or other and other._is_special):
782 ans = self._check_nans(other, context)
783 if ans:
784 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000785
Facundo Batista5dfc4802008-01-08 16:20:31 +0000786 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000787
788 def __hash__(self):
789 """x.__hash__() <==> hash(x)"""
790 # Decimal integers must hash the same as the ints
Facundo Batista5dfc4802008-01-08 16:20:31 +0000791 #
792 # The hash of a nonspecial noninteger Decimal must depend only
793 # on the value of that Decimal, and not on its representation.
794 # For example: hash(Decimal("100E-1")) == hash(Decimal("10")).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000795 if self._is_special:
796 if self._isnan():
797 raise TypeError('Cannot hash a NaN value.')
798 return hash(str(self))
Facundo Batista5dfc4802008-01-08 16:20:31 +0000799 if not self:
800 return 0
801 if self._isinteger():
802 op = _WorkRep(self.to_integral_value())
Mark Dickinsond77fedc2008-01-08 21:42:03 +0000803 return hash((-1)**op.sign*op.int*10**op.exp)
Facundo Batista5dfc4802008-01-08 16:20:31 +0000804 # The value of a nonzero nonspecial Decimal instance is
805 # faithfully represented by the triple consisting of its sign,
806 # its adjusted exponent, and its coefficient with trailing
807 # zeros removed.
808 return hash((self._sign,
809 self._exp+len(self._int),
810 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000811
812 def as_tuple(self):
813 """Represents the number as a triple tuple.
814
815 To show the internals exactly as they are.
816 """
Facundo Batista5dfc4802008-01-08 16:20:31 +0000817 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000818
819 def __repr__(self):
820 """Represents the number as an instance of Decimal."""
821 # Invariant: eval(repr(d)) == d
822 return 'Decimal("%s")' % str(self)
823
Facundo Batista5dfc4802008-01-08 16:20:31 +0000824 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000825 """Return string representation of the number in scientific notation.
826
827 Captures all of the information in the underlying representation.
828 """
829
Facundo Batista5dfc4802008-01-08 16:20:31 +0000830 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000831 if self._is_special:
Facundo Batista5dfc4802008-01-08 16:20:31 +0000832 if self._exp == 'F':
833 return sign + 'Infinity'
834 elif self._exp == 'n':
835 return sign + 'NaN' + self._int
836 else: # self._exp == 'N'
837 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000838
Facundo Batista5dfc4802008-01-08 16:20:31 +0000839 # number of digits of self._int to left of decimal point
840 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000841
Facundo Batista5dfc4802008-01-08 16:20:31 +0000842 # dotplace is number of digits of self._int to the left of the
843 # decimal point in the mantissa of the output string (that is,
844 # after adjusting the exponent)
845 if self._exp <= 0 and leftdigits > -6:
846 # no exponent required
847 dotplace = leftdigits
848 elif not eng:
849 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000850 dotplace = 1
Facundo Batista5dfc4802008-01-08 16:20:31 +0000851 elif self._int == '0':
852 # engineering notation, zero
853 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000854 else:
Facundo Batista5dfc4802008-01-08 16:20:31 +0000855 # engineering notation, nonzero
856 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000857
Facundo Batista5dfc4802008-01-08 16:20:31 +0000858 if dotplace <= 0:
859 intpart = '0'
860 fracpart = '.' + '0'*(-dotplace) + self._int
861 elif dotplace >= len(self._int):
862 intpart = self._int+'0'*(dotplace-len(self._int))
863 fracpart = ''
864 else:
865 intpart = self._int[:dotplace]
866 fracpart = '.' + self._int[dotplace:]
867 if leftdigits == dotplace:
868 exp = ''
869 else:
870 if context is None:
871 context = getcontext()
872 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
873
874 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000875
876 def to_eng_string(self, context=None):
877 """Convert to engineering-type string.
878
879 Engineering notation has an exponent which is a multiple of 3, so there
880 are up to 3 digits left of the decimal place.
881
882 Same rules for when in exponential and when as a value as in __str__.
883 """
Facundo Batista5dfc4802008-01-08 16:20:31 +0000884 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000885
886 def __neg__(self, context=None):
887 """Returns a copy with the sign switched.
888
889 Rounds, if it has reason.
890 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000891 if self._is_special:
892 ans = self._check_nans(context=context)
893 if ans:
894 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000895
896 if not self:
897 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista5dfc4802008-01-08 16:20:31 +0000898 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000899 else:
Facundo Batista5dfc4802008-01-08 16:20:31 +0000900 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000901
902 if context is None:
903 context = getcontext()
Facundo Batista5dfc4802008-01-08 16:20:31 +0000904 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000905
906 def __pos__(self, context=None):
907 """Returns a copy, unless it is a sNaN.
908
909 Rounds the number (if more then precision digits)
910 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000911 if self._is_special:
912 ans = self._check_nans(context=context)
913 if ans:
914 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000915
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000916 if not self:
917 # + (-0) = 0
Facundo Batista5dfc4802008-01-08 16:20:31 +0000918 ans = self.copy_abs()
919 else:
920 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000921
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000922 if context is None:
923 context = getcontext()
Facundo Batista5dfc4802008-01-08 16:20:31 +0000924 return ans._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000925
Facundo Batista5dfc4802008-01-08 16:20:31 +0000926 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000927 """Returns the absolute value of self.
928
Facundo Batista5dfc4802008-01-08 16:20:31 +0000929 If the keyword argument 'round' is false, do not round. The
930 expression self.__abs__(round=False) is equivalent to
931 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000932 """
Facundo Batista5dfc4802008-01-08 16:20:31 +0000933 if not round:
934 return self.copy_abs()
935
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000936 if self._is_special:
937 ans = self._check_nans(context=context)
938 if ans:
939 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000940
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000941 if self._sign:
942 ans = self.__neg__(context=context)
943 else:
944 ans = self.__pos__(context=context)
945
946 return ans
947
948 def __add__(self, other, context=None):
949 """Returns self + other.
950
951 -INF + INF (or the reverse) cause InvalidOperation errors.
952 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000953 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000954 if other is NotImplemented:
955 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000956
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000957 if context is None:
958 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000959
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000960 if self._is_special or other._is_special:
961 ans = self._check_nans(other, context)
962 if ans:
963 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000964
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000965 if self._isinfinity():
Facundo Batista5dfc4802008-01-08 16:20:31 +0000966 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000967 if self._sign != other._sign and other._isinfinity():
968 return context._raise_error(InvalidOperation, '-INF + INF')
969 return Decimal(self)
970 if other._isinfinity():
Facundo Batista5dfc4802008-01-08 16:20:31 +0000971 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000972
973 exp = min(self._exp, other._exp)
974 negativezero = 0
975 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista5dfc4802008-01-08 16:20:31 +0000976 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000977 negativezero = 1
978
979 if not self and not other:
980 sign = min(self._sign, other._sign)
981 if negativezero:
982 sign = 1
Facundo Batista5dfc4802008-01-08 16:20:31 +0000983 ans = _dec_from_triple(sign, '0', exp)
984 ans = ans._fix(context)
985 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000986 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +0000987 exp = max(exp, other._exp - context.prec-1)
Facundo Batista5dfc4802008-01-08 16:20:31 +0000988 ans = other._rescale(exp, context.rounding)
989 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000990 return ans
991 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +0000992 exp = max(exp, self._exp - context.prec-1)
Facundo Batista5dfc4802008-01-08 16:20:31 +0000993 ans = self._rescale(exp, context.rounding)
994 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000995 return ans
996
997 op1 = _WorkRep(self)
998 op2 = _WorkRep(other)
Facundo Batista5dfc4802008-01-08 16:20:31 +0000999 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
1001 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001002 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001003 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001004 if op1.int == op2.int:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001005 ans = _dec_from_triple(negativezero, '0', exp)
1006 ans = ans._fix(context)
1007 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001008 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009 op1, op2 = op2, op1
Facundo Batista5dfc4802008-01-08 16:20:31 +00001010 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001011 if op1.sign == 1:
1012 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001013 op1.sign, op2.sign = op2.sign, op1.sign
1014 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001015 result.sign = 0
Facundo Batista5dfc4802008-01-08 16:20:31 +00001016 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001017 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001018 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001019 op1.sign, op2.sign = (0, 0)
1020 else:
1021 result.sign = 0
Facundo Batista5dfc4802008-01-08 16:20:31 +00001022 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023
Raymond Hettinger17931de2004-10-27 06:21:46 +00001024 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001025 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001026 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001027 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001028
1029 result.exp = op1.exp
1030 ans = Decimal(result)
Facundo Batista5dfc4802008-01-08 16:20:31 +00001031 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001032 return ans
1033
1034 __radd__ = __add__
1035
1036 def __sub__(self, other, context=None):
Facundo Batista5dfc4802008-01-08 16:20:31 +00001037 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001038 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001039 if other is NotImplemented:
1040 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001041
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001042 if self._is_special or other._is_special:
1043 ans = self._check_nans(other, context=context)
1044 if ans:
1045 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001046
Facundo Batista5dfc4802008-01-08 16:20:31 +00001047 # self - other is computed as self + other.copy_negate()
1048 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001049
1050 def __rsub__(self, other, context=None):
Facundo Batista5dfc4802008-01-08 16:20:31 +00001051 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001052 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001053 if other is NotImplemented:
1054 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
Facundo Batista5dfc4802008-01-08 16:20:31 +00001056 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001057
1058 def __mul__(self, other, context=None):
1059 """Return self * other.
1060
1061 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1062 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001063 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001064 if other is NotImplemented:
1065 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001066
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067 if context is None:
1068 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001070 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001072 if self._is_special or other._is_special:
1073 ans = self._check_nans(other, context)
1074 if ans:
1075 return ans
1076
1077 if self._isinfinity():
1078 if not other:
1079 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1080 return Infsign[resultsign]
1081
1082 if other._isinfinity():
1083 if not self:
1084 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1085 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001086
1087 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001088
1089 # Special case for multiplying by zero
1090 if not self or not other:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001091 ans = _dec_from_triple(resultsign, '0', resultexp)
1092 # Fixing in case the exponent is out of bounds
1093 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094 return ans
1095
1096 # Special case for multiplying by power of 10
Facundo Batista5dfc4802008-01-08 16:20:31 +00001097 if self._int == '1':
1098 ans = _dec_from_triple(resultsign, other._int, resultexp)
1099 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100 return ans
Facundo Batista5dfc4802008-01-08 16:20:31 +00001101 if other._int == '1':
1102 ans = _dec_from_triple(resultsign, self._int, resultexp)
1103 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001104 return ans
1105
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001106 op1 = _WorkRep(self)
1107 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001108
Facundo Batista5dfc4802008-01-08 16:20:31 +00001109 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
1110 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001111
1112 return ans
1113 __rmul__ = __mul__
1114
1115 def __div__(self, other, context=None):
1116 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001117 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001118 if other is NotImplemented:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001119 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001120
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001121 if context is None:
1122 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001123
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001124 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001125
1126 if self._is_special or other._is_special:
1127 ans = self._check_nans(other, context)
1128 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001129 return ans
1130
1131 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001132 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001133
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001134 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001135 return Infsign[sign]
1136
1137 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001138 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista5dfc4802008-01-08 16:20:31 +00001139 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001140
1141 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001142 if not other:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001143 if not self:
1144 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001145 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001146
Facundo Batista5dfc4802008-01-08 16:20:31 +00001147 if not self:
1148 exp = self._exp - other._exp
1149 coeff = 0
1150 else:
1151 # OK, so neither = 0, INF or NaN
1152 shift = len(other._int) - len(self._int) + context.prec + 1
1153 exp = self._exp - other._exp - shift
1154 op1 = _WorkRep(self)
1155 op2 = _WorkRep(other)
1156 if shift >= 0:
1157 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1158 else:
1159 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1160 if remainder:
1161 # result is not exact; adjust to ensure correct rounding
1162 if coeff % 5 == 0:
1163 coeff += 1
1164 else:
1165 # result is exact; get as close to ideal exponent as possible
1166 ideal_exp = self._exp - other._exp
1167 while exp < ideal_exp and coeff % 10 == 0:
1168 coeff //= 10
1169 exp += 1
Martin v. Löwiscfe31282006-07-19 17:18:32 +00001170
Facundo Batista5dfc4802008-01-08 16:20:31 +00001171 ans = _dec_from_triple(sign, str(coeff), exp)
1172 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173
Facundo Batista5dfc4802008-01-08 16:20:31 +00001174 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001175
Facundo Batista5dfc4802008-01-08 16:20:31 +00001176 def _divide(self, other, context):
1177 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178
Facundo Batista5dfc4802008-01-08 16:20:31 +00001179 Assumes that neither self nor other is a NaN, that self is not
1180 infinite and that other is nonzero.
1181 """
1182 sign = self._sign ^ other._sign
1183 if other._isinfinity():
1184 ideal_exp = self._exp
1185 else:
1186 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001187
Facundo Batista5dfc4802008-01-08 16:20:31 +00001188 expdiff = self.adjusted() - other.adjusted()
1189 if not self or other._isinfinity() or expdiff <= -2:
1190 return (_dec_from_triple(sign, '0', 0),
1191 self._rescale(ideal_exp, context.rounding))
1192 if expdiff <= context.prec:
1193 op1 = _WorkRep(self)
1194 op2 = _WorkRep(other)
1195 if op1.exp >= op2.exp:
1196 op1.int *= 10**(op1.exp - op2.exp)
1197 else:
1198 op2.int *= 10**(op2.exp - op1.exp)
1199 q, r = divmod(op1.int, op2.int)
1200 if q < 10**context.prec:
1201 return (_dec_from_triple(sign, str(q), 0),
1202 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001203
Facundo Batista5dfc4802008-01-08 16:20:31 +00001204 # Here the quotient is too large to be representable
1205 ans = context._raise_error(DivisionImpossible,
1206 'quotient too large in //, % or divmod')
1207 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001208
1209 def __rdiv__(self, other, context=None):
1210 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001211 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001212 if other is NotImplemented:
1213 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001214 return other.__div__(self, context=context)
1215 __rtruediv__ = __rdiv__
1216
1217 def __divmod__(self, other, context=None):
1218 """
Facundo Batista5dfc4802008-01-08 16:20:31 +00001219 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220 """
Facundo Batista5dfc4802008-01-08 16:20:31 +00001221 other = _convert_other(other)
1222 if other is NotImplemented:
1223 return other
1224
1225 if context is None:
1226 context = getcontext()
1227
1228 ans = self._check_nans(other, context)
1229 if ans:
1230 return (ans, ans)
1231
1232 sign = self._sign ^ other._sign
1233 if self._isinfinity():
1234 if other._isinfinity():
1235 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1236 return ans, ans
1237 else:
1238 return (Infsign[sign],
1239 context._raise_error(InvalidOperation, 'INF % x'))
1240
1241 if not other:
1242 if not self:
1243 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1244 return ans, ans
1245 else:
1246 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1247 context._raise_error(InvalidOperation, 'x % 0'))
1248
1249 quotient, remainder = self._divide(other, context)
1250 remainder = remainder._fix(context)
1251 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001252
1253 def __rdivmod__(self, other, context=None):
1254 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001255 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001256 if other is NotImplemented:
1257 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001258 return other.__divmod__(self, context=context)
1259
1260 def __mod__(self, other, context=None):
1261 """
1262 self % other
1263 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001264 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001265 if other is NotImplemented:
1266 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001267
Facundo Batista5dfc4802008-01-08 16:20:31 +00001268 if context is None:
1269 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270
Facundo Batista5dfc4802008-01-08 16:20:31 +00001271 ans = self._check_nans(other, context)
1272 if ans:
1273 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001274
Facundo Batista5dfc4802008-01-08 16:20:31 +00001275 if self._isinfinity():
1276 return context._raise_error(InvalidOperation, 'INF % x')
1277 elif not other:
1278 if self:
1279 return context._raise_error(InvalidOperation, 'x % 0')
1280 else:
1281 return context._raise_error(DivisionUndefined, '0 % 0')
1282
1283 remainder = self._divide(other, context)[1]
1284 remainder = remainder._fix(context)
1285 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001286
1287 def __rmod__(self, other, context=None):
1288 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001289 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001290 if other is NotImplemented:
1291 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001292 return other.__mod__(self, context=context)
1293
1294 def remainder_near(self, other, context=None):
1295 """
1296 Remainder nearest to 0- abs(remainder-near) <= other/2
1297 """
Facundo Batista5dfc4802008-01-08 16:20:31 +00001298 if context is None:
1299 context = getcontext()
1300
1301 other = _convert_other(other, raiseit=True)
1302
1303 ans = self._check_nans(other, context)
1304 if ans:
1305 return ans
1306
1307 # self == +/-infinity -> InvalidOperation
1308 if self._isinfinity():
1309 return context._raise_error(InvalidOperation,
1310 'remainder_near(infinity, x)')
1311
1312 # other == 0 -> either InvalidOperation or DivisionUndefined
1313 if not other:
1314 if self:
1315 return context._raise_error(InvalidOperation,
1316 'remainder_near(x, 0)')
1317 else:
1318 return context._raise_error(DivisionUndefined,
1319 'remainder_near(0, 0)')
1320
1321 # other = +/-infinity -> remainder = self
1322 if other._isinfinity():
1323 ans = Decimal(self)
1324 return ans._fix(context)
1325
1326 # self = 0 -> remainder = self, with ideal exponent
1327 ideal_exponent = min(self._exp, other._exp)
1328 if not self:
1329 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
1330 return ans._fix(context)
1331
1332 # catch most cases of large or small quotient
1333 expdiff = self.adjusted() - other.adjusted()
1334 if expdiff >= context.prec + 1:
1335 # expdiff >= prec+1 => abs(self/other) > 10**prec
1336 return context._raise_error(DivisionImpossible)
1337 if expdiff <= -2:
1338 # expdiff <= -2 => abs(self/other) < 0.1
1339 ans = self._rescale(ideal_exponent, context.rounding)
1340 return ans._fix(context)
1341
1342 # adjust both arguments to have the same exponent, then divide
1343 op1 = _WorkRep(self)
1344 op2 = _WorkRep(other)
1345 if op1.exp >= op2.exp:
1346 op1.int *= 10**(op1.exp - op2.exp)
1347 else:
1348 op2.int *= 10**(op2.exp - op1.exp)
1349 q, r = divmod(op1.int, op2.int)
1350 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1351 # 10**ideal_exponent. Apply correction to ensure that
1352 # abs(remainder) <= abs(other)/2
1353 if 2*r + (q&1) > op2.int:
1354 r -= op2.int
1355 q += 1
1356
1357 if q >= 10**context.prec:
1358 return context._raise_error(DivisionImpossible)
1359
1360 # result has same sign as self unless r is negative
1361 sign = self._sign
1362 if r < 0:
1363 sign = 1-sign
1364 r = -r
1365
1366 ans = _dec_from_triple(sign, str(r), ideal_exponent)
1367 return ans._fix(context)
1368
1369 def __floordiv__(self, other, context=None):
1370 """self // other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001371 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001372 if other is NotImplemented:
1373 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001374
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001375 if context is None:
1376 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001377
Facundo Batista5dfc4802008-01-08 16:20:31 +00001378 ans = self._check_nans(other, context)
1379 if ans:
1380 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001381
Facundo Batista5dfc4802008-01-08 16:20:31 +00001382 if self._isinfinity():
1383 if other._isinfinity():
1384 return context._raise_error(InvalidOperation, 'INF // INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001385 else:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001386 return Infsign[self._sign ^ other._sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001387
Facundo Batista5dfc4802008-01-08 16:20:31 +00001388 if not other:
1389 if self:
1390 return context._raise_error(DivisionByZero, 'x // 0',
1391 self._sign ^ other._sign)
1392 else:
1393 return context._raise_error(DivisionUndefined, '0 // 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001394
Facundo Batista5dfc4802008-01-08 16:20:31 +00001395 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001396
1397 def __rfloordiv__(self, other, context=None):
1398 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001399 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001400 if other is NotImplemented:
1401 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001402 return other.__floordiv__(self, context=context)
1403
1404 def __float__(self):
1405 """Float representation."""
1406 return float(str(self))
1407
1408 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001409 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001410 if self._is_special:
1411 if self._isnan():
1412 context = getcontext()
1413 return context._raise_error(InvalidContext)
1414 elif self._isinfinity():
Facundo Batista5dfc4802008-01-08 16:20:31 +00001415 raise OverflowError("Cannot convert infinity to long")
1416 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001417 if self._exp >= 0:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001418 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001419 else:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001420 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001421
1422 def __long__(self):
1423 """Converts to a long.
1424
1425 Equivalent to long(int(self))
1426 """
1427 return long(self.__int__())
1428
Facundo Batista5dfc4802008-01-08 16:20:31 +00001429 def _fix_nan(self, context):
1430 """Decapitate the payload of a NaN to fit the context"""
1431 payload = self._int
1432
1433 # maximum length of payload is precision if _clamp=0,
1434 # precision-1 if _clamp=1.
1435 max_payload_len = context.prec - context._clamp
1436 if len(payload) > max_payload_len:
1437 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1438 return _dec_from_triple(self._sign, payload, self._exp, True)
1439 return Decimal(self)
1440
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001441 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001442 """Round if it is necessary to keep self within prec precision.
1443
1444 Rounds and fixes the exponent. Does not raise on a sNaN.
1445
1446 Arguments:
1447 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001448 context - context used.
1449 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001450
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001451 if self._is_special:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001452 if self._isnan():
1453 # decapitate payload if necessary
1454 return self._fix_nan(context)
1455 else:
1456 # self is +/-Infinity; return unaltered
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001457 return Decimal(self)
1458
Facundo Batista5dfc4802008-01-08 16:20:31 +00001459 # if self is zero then exponent should be between Etiny and
1460 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1461 Etiny = context.Etiny()
1462 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001463 if not self:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001464 exp_max = [context.Emax, Etop][context._clamp]
1465 new_exp = min(max(self._exp, Etiny), exp_max)
1466 if new_exp != self._exp:
1467 context._raise_error(Clamped)
1468 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001469 else:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001470 return Decimal(self)
1471
1472 # exp_min is the smallest allowable exponent of the result,
1473 # equal to max(self.adjusted()-context.prec+1, Etiny)
1474 exp_min = len(self._int) + self._exp - context.prec
1475 if exp_min > Etop:
1476 # overflow: exp_min > Etop iff self.adjusted() > Emax
1477 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001478 context._raise_error(Rounded)
Facundo Batista5dfc4802008-01-08 16:20:31 +00001479 return context._raise_error(Overflow, 'above Emax', self._sign)
1480 self_is_subnormal = exp_min < Etiny
1481 if self_is_subnormal:
1482 context._raise_error(Subnormal)
1483 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001484
Facundo Batista5dfc4802008-01-08 16:20:31 +00001485 # round if self has too many digits
1486 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001487 context._raise_error(Rounded)
Facundo Batista5dfc4802008-01-08 16:20:31 +00001488 digits = len(self._int) + self._exp - exp_min
1489 if digits < 0:
1490 self = _dec_from_triple(self._sign, '1', exp_min-1)
1491 digits = 0
1492 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1493 changed = this_function(digits)
1494 coeff = self._int[:digits] or '0'
1495 if changed == 1:
1496 coeff = str(int(coeff)+1)
1497 ans = _dec_from_triple(self._sign, coeff, exp_min)
1498
1499 if changed:
1500 context._raise_error(Inexact)
1501 if self_is_subnormal:
1502 context._raise_error(Underflow)
1503 if not ans:
1504 # raise Clamped on underflow to 0
1505 context._raise_error(Clamped)
1506 elif len(ans._int) == context.prec+1:
1507 # we get here only if rescaling rounds the
1508 # cofficient up to exactly 10**context.prec
1509 if ans._exp < Etop:
1510 ans = _dec_from_triple(ans._sign,
1511 ans._int[:-1], ans._exp+1)
1512 else:
1513 # Inexact and Rounded have already been raised
1514 ans = context._raise_error(Overflow, 'above Emax',
1515 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001516 return ans
1517
Facundo Batista5dfc4802008-01-08 16:20:31 +00001518 # fold down if _clamp == 1 and self has too few digits
1519 if context._clamp == 1 and self._exp > Etop:
1520 context._raise_error(Clamped)
1521 self_padded = self._int + '0'*(self._exp - Etop)
1522 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001523
Facundo Batista5dfc4802008-01-08 16:20:31 +00001524 # here self was representable to begin with; return unchanged
1525 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001526
1527 _pick_rounding_function = {}
1528
Facundo Batista5dfc4802008-01-08 16:20:31 +00001529 # for each of the rounding functions below:
1530 # self is a finite, nonzero Decimal
1531 # prec is an integer satisfying 0 <= prec < len(self._int)
1532 #
1533 # each function returns either -1, 0, or 1, as follows:
1534 # 1 indicates that self should be rounded up (away from zero)
1535 # 0 indicates that self should be truncated, and that all the
1536 # digits to be truncated are zeros (so the value is unchanged)
1537 # -1 indicates that there are nonzero digits to be truncated
1538
1539 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001540 """Also known as round-towards-0, truncate."""
Facundo Batista5dfc4802008-01-08 16:20:31 +00001541 if _all_zeros(self._int, prec):
1542 return 0
1543 else:
1544 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001545
Facundo Batista5dfc4802008-01-08 16:20:31 +00001546 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001547 """Rounds away from 0."""
Facundo Batista5dfc4802008-01-08 16:20:31 +00001548 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001549
Facundo Batista5dfc4802008-01-08 16:20:31 +00001550 def _round_half_up(self, prec):
1551 """Rounds 5 up (away from 0)"""
1552 if self._int[prec] in '56789':
1553 return 1
1554 elif _all_zeros(self._int, prec):
1555 return 0
1556 else:
1557 return -1
1558
1559 def _round_half_down(self, prec):
1560 """Round 5 down"""
1561 if _exact_half(self._int, prec):
1562 return -1
1563 else:
1564 return self._round_half_up(prec)
1565
1566 def _round_half_even(self, prec):
1567 """Round 5 to even, rest to nearest."""
1568 if _exact_half(self._int, prec) and \
1569 (prec == 0 or self._int[prec-1] in '02468'):
1570 return -1
1571 else:
1572 return self._round_half_up(prec)
1573
1574 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001575 """Rounds up (not away from 0 if negative.)"""
1576 if self._sign:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001577 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001578 else:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001579 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001580
Facundo Batista5dfc4802008-01-08 16:20:31 +00001581 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001582 """Rounds down (not towards 0 if negative)"""
1583 if not self._sign:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001584 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001585 else:
Facundo Batista5dfc4802008-01-08 16:20:31 +00001586 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001587
Facundo Batista5dfc4802008-01-08 16:20:31 +00001588 def _round_05up(self, prec):
1589 """Round down unless digit prec-1 is 0 or 5."""
1590 if prec and self._int[prec-1] not in '05':
1591 return self._round_down(prec)
1592 else:
1593 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001594
Facundo Batista5dfc4802008-01-08 16:20:31 +00001595 def fma(self, other, third, context=None):
1596 """Fused multiply-add.
1597
1598 Returns self*other+third with no rounding of the intermediate
1599 product self*other.
1600
1601 self and other are multiplied together, with no rounding of
1602 the result. The third operand is then added to the result,
1603 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001604 """
Facundo Batista5dfc4802008-01-08 16:20:31 +00001605
1606 other = _convert_other(other, raiseit=True)
1607
1608 # compute product; raise InvalidOperation if either operand is
1609 # a signaling NaN or if the product is zero times infinity.
1610 if self._is_special or other._is_special:
1611 if context is None:
1612 context = getcontext()
1613 if self._exp == 'N':
1614 return context._raise_error(InvalidOperation, 'sNaN', self)
1615 if other._exp == 'N':
1616 return context._raise_error(InvalidOperation, 'sNaN', other)
1617 if self._exp == 'n':
1618 product = self
1619 elif other._exp == 'n':
1620 product = other
1621 elif self._exp == 'F':
1622 if not other:
1623 return context._raise_error(InvalidOperation,
1624 'INF * 0 in fma')
1625 product = Infsign[self._sign ^ other._sign]
1626 elif other._exp == 'F':
1627 if not self:
1628 return context._raise_error(InvalidOperation,
1629 '0 * INF in fma')
1630 product = Infsign[self._sign ^ other._sign]
1631 else:
1632 product = _dec_from_triple(self._sign ^ other._sign,
1633 str(int(self._int) * int(other._int)),
1634 self._exp + other._exp)
1635
1636 third = _convert_other(third, raiseit=True)
1637 return product.__add__(third, context)
1638
1639 def _power_modulo(self, other, modulo, context=None):
1640 """Three argument version of __pow__"""
1641
1642 # if can't convert other and modulo to Decimal, raise
1643 # TypeError; there's no point returning NotImplemented (no
1644 # equivalent of __rpow__ for three argument pow)
1645 other = _convert_other(other, raiseit=True)
1646 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001647
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001648 if context is None:
1649 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001650
Facundo Batista5dfc4802008-01-08 16:20:31 +00001651 # deal with NaNs: if there are any sNaNs then first one wins,
1652 # (i.e. behaviour for NaNs is identical to that of fma)
1653 self_is_nan = self._isnan()
1654 other_is_nan = other._isnan()
1655 modulo_is_nan = modulo._isnan()
1656 if self_is_nan or other_is_nan or modulo_is_nan:
1657 if self_is_nan == 2:
1658 return context._raise_error(InvalidOperation, 'sNaN',
1659 self)
1660 if other_is_nan == 2:
1661 return context._raise_error(InvalidOperation, 'sNaN',
1662 other)
1663 if modulo_is_nan == 2:
1664 return context._raise_error(InvalidOperation, 'sNaN',
1665 modulo)
1666 if self_is_nan:
1667 return self._fix_nan(context)
1668 if other_is_nan:
1669 return other._fix_nan(context)
1670 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001671
Facundo Batista5dfc4802008-01-08 16:20:31 +00001672 # check inputs: we apply same restrictions as Python's pow()
1673 if not (self._isinteger() and
1674 other._isinteger() and
1675 modulo._isinteger()):
1676 return context._raise_error(InvalidOperation,
1677 'pow() 3rd argument not allowed '
1678 'unless all arguments are integers')
1679 if other < 0:
1680 return context._raise_error(InvalidOperation,
1681 'pow() 2nd argument cannot be '
1682 'negative when 3rd argument specified')
1683 if not modulo:
1684 return context._raise_error(InvalidOperation,
1685 'pow() 3rd argument cannot be 0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001686
Facundo Batista5dfc4802008-01-08 16:20:31 +00001687 # additional restriction for decimal: the modulus must be less
1688 # than 10**prec in absolute value
1689 if modulo.adjusted() >= context.prec:
1690 return context._raise_error(InvalidOperation,
1691 'insufficient precision: pow() 3rd '
1692 'argument must not have more than '
1693 'precision digits')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001694
Facundo Batista5dfc4802008-01-08 16:20:31 +00001695 # define 0**0 == NaN, for consistency with two-argument pow
1696 # (even though it hurts!)
1697 if not other and not self:
1698 return context._raise_error(InvalidOperation,
1699 'at least one of pow() 1st argument '
1700 'and 2nd argument must be nonzero ;'
1701 '0**0 is not defined')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001702
Facundo Batista5dfc4802008-01-08 16:20:31 +00001703 # compute sign of result
1704 if other._iseven():
1705 sign = 0
1706 else:
1707 sign = self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001708
Facundo Batista5dfc4802008-01-08 16:20:31 +00001709 # convert modulo to a Python integer, and self and other to
1710 # Decimal integers (i.e. force their exponents to be >= 0)
1711 modulo = abs(int(modulo))
1712 base = _WorkRep(self.to_integral_value())
1713 exponent = _WorkRep(other.to_integral_value())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001714
Facundo Batista5dfc4802008-01-08 16:20:31 +00001715 # compute result using integer pow()
1716 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1717 for i in xrange(exponent.exp):
1718 base = pow(base, 10, modulo)
1719 base = pow(base, exponent.int, modulo)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001720
Facundo Batista5dfc4802008-01-08 16:20:31 +00001721 return _dec_from_triple(sign, str(base), 0)
1722
1723 def _power_exact(self, other, p):
1724 """Attempt to compute self**other exactly.
1725
1726 Given Decimals self and other and an integer p, attempt to
1727 compute an exact result for the power self**other, with p
1728 digits of precision. Return None if self**other is not
1729 exactly representable in p digits.
1730
1731 Assumes that elimination of special cases has already been
1732 performed: self and other must both be nonspecial; self must
1733 be positive and not numerically equal to 1; other must be
1734 nonzero. For efficiency, other._exp should not be too large,
1735 so that 10**abs(other._exp) is a feasible calculation."""
1736
1737 # In the comments below, we write x for the value of self and
1738 # y for the value of other. Write x = xc*10**xe and y =
1739 # yc*10**ye.
1740
1741 # The main purpose of this method is to identify the *failure*
1742 # of x**y to be exactly representable with as little effort as
1743 # possible. So we look for cheap and easy tests that
1744 # eliminate the possibility of x**y being exact. Only if all
1745 # these tests are passed do we go on to actually compute x**y.
1746
1747 # Here's the main idea. First normalize both x and y. We
1748 # express y as a rational m/n, with m and n relatively prime
1749 # and n>0. Then for x**y to be exactly representable (at
1750 # *any* precision), xc must be the nth power of a positive
1751 # integer and xe must be divisible by n. If m is negative
1752 # then additionally xc must be a power of either 2 or 5, hence
1753 # a power of 2**n or 5**n.
1754 #
1755 # There's a limit to how small |y| can be: if y=m/n as above
1756 # then:
1757 #
1758 # (1) if xc != 1 then for the result to be representable we
1759 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1760 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1761 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1762 # representable.
1763 #
1764 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1765 # |y| < 1/|xe| then the result is not representable.
1766 #
1767 # Note that since x is not equal to 1, at least one of (1) and
1768 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1769 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1770 #
1771 # There's also a limit to how large y can be, at least if it's
1772 # positive: the normalized result will have coefficient xc**y,
1773 # so if it's representable then xc**y < 10**p, and y <
1774 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1775 # not exactly representable.
1776
1777 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1778 # so |y| < 1/xe and the result is not representable.
1779 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1780 # < 1/nbits(xc).
1781
1782 x = _WorkRep(self)
1783 xc, xe = x.int, x.exp
1784 while xc % 10 == 0:
1785 xc //= 10
1786 xe += 1
1787
1788 y = _WorkRep(other)
1789 yc, ye = y.int, y.exp
1790 while yc % 10 == 0:
1791 yc //= 10
1792 ye += 1
1793
1794 # case where xc == 1: result is 10**(xe*y), with xe*y
1795 # required to be an integer
1796 if xc == 1:
1797 if ye >= 0:
1798 exponent = xe*yc*10**ye
1799 else:
1800 exponent, remainder = divmod(xe*yc, 10**-ye)
1801 if remainder:
1802 return None
1803 if y.sign == 1:
1804 exponent = -exponent
1805 # if other is a nonnegative integer, use ideal exponent
1806 if other._isinteger() and other._sign == 0:
1807 ideal_exponent = self._exp*int(other)
1808 zeros = min(exponent-ideal_exponent, p-1)
1809 else:
1810 zeros = 0
1811 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
1812
1813 # case where y is negative: xc must be either a power
1814 # of 2 or a power of 5.
1815 if y.sign == 1:
1816 last_digit = xc % 10
1817 if last_digit in (2,4,6,8):
1818 # quick test for power of 2
1819 if xc & -xc != xc:
1820 return None
1821 # now xc is a power of 2; e is its exponent
1822 e = _nbits(xc)-1
1823 # find e*y and xe*y; both must be integers
1824 if ye >= 0:
1825 y_as_int = yc*10**ye
1826 e = e*y_as_int
1827 xe = xe*y_as_int
1828 else:
1829 ten_pow = 10**-ye
1830 e, remainder = divmod(e*yc, ten_pow)
1831 if remainder:
1832 return None
1833 xe, remainder = divmod(xe*yc, ten_pow)
1834 if remainder:
1835 return None
1836
1837 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1838 return None
1839 xc = 5**e
1840
1841 elif last_digit == 5:
1842 # e >= log_5(xc) if xc is a power of 5; we have
1843 # equality all the way up to xc=5**2658
1844 e = _nbits(xc)*28//65
1845 xc, remainder = divmod(5**e, xc)
1846 if remainder:
1847 return None
1848 while xc % 5 == 0:
1849 xc //= 5
1850 e -= 1
1851 if ye >= 0:
1852 y_as_integer = yc*10**ye
1853 e = e*y_as_integer
1854 xe = xe*y_as_integer
1855 else:
1856 ten_pow = 10**-ye
1857 e, remainder = divmod(e*yc, ten_pow)
1858 if remainder:
1859 return None
1860 xe, remainder = divmod(xe*yc, ten_pow)
1861 if remainder:
1862 return None
1863 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1864 return None
1865 xc = 2**e
1866 else:
1867 return None
1868
1869 if xc >= 10**p:
1870 return None
1871 xe = -e-xe
1872 return _dec_from_triple(0, str(xc), xe)
1873
1874 # now y is positive; find m and n such that y = m/n
1875 if ye >= 0:
1876 m, n = yc*10**ye, 1
1877 else:
1878 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1879 return None
1880 xc_bits = _nbits(xc)
1881 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1882 return None
1883 m, n = yc, 10**(-ye)
1884 while m % 2 == n % 2 == 0:
1885 m //= 2
1886 n //= 2
1887 while m % 5 == n % 5 == 0:
1888 m //= 5
1889 n //= 5
1890
1891 # compute nth root of xc*10**xe
1892 if n > 1:
1893 # if 1 < xc < 2**n then xc isn't an nth power
1894 if xc != 1 and xc_bits <= n:
1895 return None
1896
1897 xe, rem = divmod(xe, n)
1898 if rem != 0:
1899 return None
1900
1901 # compute nth root of xc using Newton's method
1902 a = 1L << -(-_nbits(xc)//n) # initial estimate
1903 while True:
1904 q, r = divmod(xc, a**(n-1))
1905 if a <= q:
1906 break
1907 else:
1908 a = (a*(n-1) + q)//n
1909 if not (a == q and r == 0):
1910 return None
1911 xc = a
1912
1913 # now xc*10**xe is the nth root of the original xc*10**xe
1914 # compute mth power of xc*10**xe
1915
1916 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1917 # 10**p and the result is not representable.
1918 if xc > 1 and m > p*100//_log10_lb(xc):
1919 return None
1920 xc = xc**m
1921 xe *= m
1922 if xc > 10**p:
1923 return None
1924
1925 # by this point the result *is* exactly representable
1926 # adjust the exponent to get as close as possible to the ideal
1927 # exponent, if necessary
1928 str_xc = str(xc)
1929 if other._isinteger() and other._sign == 0:
1930 ideal_exponent = self._exp*int(other)
1931 zeros = min(xe-ideal_exponent, p-len(str_xc))
1932 else:
1933 zeros = 0
1934 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
1935
1936 def __pow__(self, other, modulo=None, context=None):
1937 """Return self ** other [ % modulo].
1938
1939 With two arguments, compute self**other.
1940
1941 With three arguments, compute (self**other) % modulo. For the
1942 three argument form, the following restrictions on the
1943 arguments hold:
1944
1945 - all three arguments must be integral
1946 - other must be nonnegative
1947 - either self or other (or both) must be nonzero
1948 - modulo must be nonzero and must have at most p digits,
1949 where p is the context precision.
1950
1951 If any of these restrictions is violated the InvalidOperation
1952 flag is raised.
1953
1954 The result of pow(self, other, modulo) is identical to the
1955 result that would be obtained by computing (self**other) %
1956 modulo with unbounded precision, but is computed more
1957 efficiently. It is always exact.
1958 """
1959
1960 if modulo is not None:
1961 return self._power_modulo(other, modulo, context)
1962
1963 other = _convert_other(other)
1964 if other is NotImplemented:
1965 return other
1966
1967 if context is None:
1968 context = getcontext()
1969
1970 # either argument is a NaN => result is NaN
1971 ans = self._check_nans(other, context)
1972 if ans:
1973 return ans
1974
1975 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1976 if not other:
1977 if not self:
1978 return context._raise_error(InvalidOperation, '0 ** 0')
1979 else:
1980 return Dec_p1
1981
1982 # result has sign 1 iff self._sign is 1 and other is an odd integer
1983 result_sign = 0
1984 if self._sign == 1:
1985 if other._isinteger():
1986 if not other._iseven():
1987 result_sign = 1
1988 else:
1989 # -ve**noninteger = NaN
1990 # (-0)**noninteger = 0**noninteger
1991 if self:
1992 return context._raise_error(InvalidOperation,
1993 'x ** y with x negative and y not an integer')
1994 # negate self, without doing any unwanted rounding
1995 self = self.copy_negate()
1996
1997 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
1998 if not self:
1999 if other._sign == 0:
2000 return _dec_from_triple(result_sign, '0', 0)
2001 else:
2002 return Infsign[result_sign]
2003
2004 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002005 if self._isinfinity():
Facundo Batista5dfc4802008-01-08 16:20:31 +00002006 if other._sign == 0:
2007 return Infsign[result_sign]
2008 else:
2009 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002010
Facundo Batista5dfc4802008-01-08 16:20:31 +00002011 # 1**other = 1, but the choice of exponent and the flags
2012 # depend on the exponent of self, and on whether other is a
2013 # positive integer, a negative integer, or neither
2014 if self == Dec_p1:
2015 if other._isinteger():
2016 # exp = max(self._exp*max(int(other), 0),
2017 # 1-context.prec) but evaluating int(other) directly
2018 # is dangerous until we know other is small (other
2019 # could be 1e999999999)
2020 if other._sign == 1:
2021 multiplier = 0
2022 elif other > context.prec:
2023 multiplier = context.prec
2024 else:
2025 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002026
Facundo Batista5dfc4802008-01-08 16:20:31 +00002027 exp = self._exp * multiplier
2028 if exp < 1-context.prec:
2029 exp = 1-context.prec
2030 context._raise_error(Rounded)
2031 else:
2032 context._raise_error(Inexact)
2033 context._raise_error(Rounded)
2034 exp = 1-context.prec
2035
2036 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
2037
2038 # compute adjusted exponent of self
2039 self_adj = self.adjusted()
2040
2041 # self ** infinity is infinity if self > 1, 0 if self < 1
2042 # self ** -infinity is infinity if self < 1, 0 if self > 1
2043 if other._isinfinity():
2044 if (other._sign == 0) == (self_adj < 0):
2045 return _dec_from_triple(result_sign, '0', 0)
2046 else:
2047 return Infsign[result_sign]
2048
2049 # from here on, the result always goes through the call
2050 # to _fix at the end of this function.
2051 ans = None
2052
2053 # crude test to catch cases of extreme overflow/underflow. If
2054 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2055 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2056 # self**other >= 10**(Emax+1), so overflow occurs. The test
2057 # for underflow is similar.
2058 bound = self._log10_exp_bound() + other.adjusted()
2059 if (self_adj >= 0) == (other._sign == 0):
2060 # self > 1 and other +ve, or self < 1 and other -ve
2061 # possibility of overflow
2062 if bound >= len(str(context.Emax)):
2063 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
2064 else:
2065 # self > 1 and other -ve, or self < 1 and other +ve
2066 # possibility of underflow to 0
2067 Etiny = context.Etiny()
2068 if bound >= len(str(-Etiny)):
2069 ans = _dec_from_triple(result_sign, '1', Etiny-1)
2070
2071 # try for an exact result with precision +1
2072 if ans is None:
2073 ans = self._power_exact(other, context.prec + 1)
2074 if ans is not None and result_sign == 1:
2075 ans = _dec_from_triple(1, ans._int, ans._exp)
2076
2077 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2078 if ans is None:
2079 p = context.prec
2080 x = _WorkRep(self)
2081 xc, xe = x.int, x.exp
2082 y = _WorkRep(other)
2083 yc, ye = y.int, y.exp
2084 if y.sign == 1:
2085 yc = -yc
2086
2087 # compute correctly rounded result: start with precision +3,
2088 # then increase precision until result is unambiguously roundable
2089 extra = 3
2090 while True:
2091 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2092 if coeff % (5*10**(len(str(coeff))-p-1)):
2093 break
2094 extra += 3
2095
2096 ans = _dec_from_triple(result_sign, str(coeff), exp)
2097
2098 # the specification says that for non-integer other we need to
2099 # raise Inexact, even when the result is actually exact. In
2100 # the same way, we need to raise Underflow here if the result
2101 # is subnormal. (The call to _fix will take care of raising
2102 # Rounded and Subnormal, as usual.)
2103 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002104 context._raise_error(Inexact)
Facundo Batista5dfc4802008-01-08 16:20:31 +00002105 # pad with zeros up to length context.prec+1 if necessary
2106 if len(ans._int) <= context.prec:
2107 expdiff = context.prec+1 - len(ans._int)
2108 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2109 ans._exp-expdiff)
2110 if ans.adjusted() < context.Emin:
2111 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002112
Facundo Batista5dfc4802008-01-08 16:20:31 +00002113 # unlike exp, ln and log10, the power function respects the
2114 # rounding mode; no need to use ROUND_HALF_EVEN here
2115 ans = ans._fix(context)
2116 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002117
2118 def __rpow__(self, other, context=None):
2119 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002120 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002121 if other is NotImplemented:
2122 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002123 return other.__pow__(self, context=context)
2124
2125 def normalize(self, context=None):
2126 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002127
Facundo Batista5dfc4802008-01-08 16:20:31 +00002128 if context is None:
2129 context = getcontext()
2130
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002131 if self._is_special:
2132 ans = self._check_nans(context=context)
2133 if ans:
2134 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002135
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002136 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002137 if dup._isinfinity():
2138 return dup
2139
2140 if not dup:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002141 return _dec_from_triple(dup._sign, '0', 0)
2142 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002143 end = len(dup._int)
2144 exp = dup._exp
Facundo Batista5dfc4802008-01-08 16:20:31 +00002145 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002146 exp += 1
2147 end -= 1
Facundo Batista5dfc4802008-01-08 16:20:31 +00002148 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002149
Facundo Batista5dfc4802008-01-08 16:20:31 +00002150 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002151 """Quantize self so its exponent is the same as that of exp.
2152
2153 Similar to self._rescale(exp._exp) but with error checking.
2154 """
Facundo Batista5dfc4802008-01-08 16:20:31 +00002155 exp = _convert_other(exp, raiseit=True)
2156
2157 if context is None:
2158 context = getcontext()
2159 if rounding is None:
2160 rounding = context.rounding
2161
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002162 if self._is_special or exp._is_special:
2163 ans = self._check_nans(exp, context)
2164 if ans:
2165 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002166
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002167 if exp._isinfinity() or self._isinfinity():
2168 if exp._isinfinity() and self._isinfinity():
Facundo Batista5dfc4802008-01-08 16:20:31 +00002169 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002170 return context._raise_error(InvalidOperation,
2171 'quantize with one INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002172
Facundo Batista5dfc4802008-01-08 16:20:31 +00002173 # if we're not watching exponents, do a simple rescale
2174 if not watchexp:
2175 ans = self._rescale(exp._exp, rounding)
2176 # raise Inexact and Rounded where appropriate
2177 if ans._exp > self._exp:
2178 context._raise_error(Rounded)
2179 if ans != self:
2180 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002181 return ans
2182
Facundo Batista5dfc4802008-01-08 16:20:31 +00002183 # exp._exp should be between Etiny and Emax
2184 if not (context.Etiny() <= exp._exp <= context.Emax):
2185 return context._raise_error(InvalidOperation,
2186 'target exponent out of bounds in quantize')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002187
Facundo Batista5dfc4802008-01-08 16:20:31 +00002188 if not self:
2189 ans = _dec_from_triple(self._sign, '0', exp._exp)
2190 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002191
Facundo Batista5dfc4802008-01-08 16:20:31 +00002192 self_adjusted = self.adjusted()
2193 if self_adjusted > context.Emax:
2194 return context._raise_error(InvalidOperation,
2195 'exponent of quantize result too large for current context')
2196 if self_adjusted - exp._exp + 1 > context.prec:
2197 return context._raise_error(InvalidOperation,
2198 'quantize result has too many digits for current context')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002199
Facundo Batista5dfc4802008-01-08 16:20:31 +00002200 ans = self._rescale(exp._exp, rounding)
2201 if ans.adjusted() > context.Emax:
2202 return context._raise_error(InvalidOperation,
2203 'exponent of quantize result too large for current context')
2204 if len(ans._int) > context.prec:
2205 return context._raise_error(InvalidOperation,
2206 'quantize result has too many digits for current context')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002207
Facundo Batista5dfc4802008-01-08 16:20:31 +00002208 # raise appropriate flags
2209 if ans._exp > self._exp:
2210 context._raise_error(Rounded)
2211 if ans != self:
2212 context._raise_error(Inexact)
2213 if ans and ans.adjusted() < context.Emin:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002214 context._raise_error(Subnormal)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002215
Facundo Batista5dfc4802008-01-08 16:20:31 +00002216 # call to fix takes care of any necessary folddown
2217 ans = ans._fix(context)
2218 return ans
2219
2220 def same_quantum(self, other):
2221 """Return True if self and other have the same exponent; otherwise
2222 return False.
2223
2224 If either operand is a special value, the following rules are used:
2225 * return True if both operands are infinities
2226 * return True if both operands are NaNs
2227 * otherwise, return False.
2228 """
2229 other = _convert_other(other, raiseit=True)
2230 if self._is_special or other._is_special:
2231 return (self.is_nan() and other.is_nan() or
2232 self.is_infinite() and other.is_infinite())
2233 return self._exp == other._exp
2234
2235 def _rescale(self, exp, rounding):
2236 """Rescale self so that the exponent is exp, either by padding with zeros
2237 or by truncating digits, using the given rounding mode.
2238
2239 Specials are returned without change. This operation is
2240 quiet: it raises no flags, and uses no information from the
2241 context.
2242
2243 exp = exp to scale to (an integer)
2244 rounding = rounding mode
2245 """
2246 if self._is_special:
2247 return Decimal(self)
2248 if not self:
2249 return _dec_from_triple(self._sign, '0', exp)
2250
2251 if self._exp >= exp:
2252 # pad answer with zeros if necessary
2253 return _dec_from_triple(self._sign,
2254 self._int + '0'*(self._exp - exp), exp)
2255
2256 # too many digits; round and lose data. If self.adjusted() <
2257 # exp-1, replace self by 10**(exp-1) before rounding
2258 digits = len(self._int) + self._exp - exp
2259 if digits < 0:
2260 self = _dec_from_triple(self._sign, '1', exp-1)
2261 digits = 0
2262 this_function = getattr(self, self._pick_rounding_function[rounding])
2263 changed = this_function(digits)
2264 coeff = self._int[:digits] or '0'
2265 if changed == 1:
2266 coeff = str(int(coeff)+1)
2267 return _dec_from_triple(self._sign, coeff, exp)
2268
2269 def to_integral_exact(self, rounding=None, context=None):
2270 """Rounds to a nearby integer.
2271
2272 If no rounding mode is specified, take the rounding mode from
2273 the context. This method raises the Rounded and Inexact flags
2274 when appropriate.
2275
2276 See also: to_integral_value, which does exactly the same as
2277 this method except that it doesn't raise Inexact or Rounded.
2278 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002279 if self._is_special:
2280 ans = self._check_nans(context=context)
2281 if ans:
2282 return ans
Facundo Batista5dfc4802008-01-08 16:20:31 +00002283 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002284 if self._exp >= 0:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002285 return Decimal(self)
2286 if not self:
2287 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002288 if context is None:
2289 context = getcontext()
Facundo Batista5dfc4802008-01-08 16:20:31 +00002290 if rounding is None:
2291 rounding = context.rounding
2292 context._raise_error(Rounded)
2293 ans = self._rescale(0, rounding)
2294 if ans != self:
2295 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002296 return ans
2297
Facundo Batista5dfc4802008-01-08 16:20:31 +00002298 def to_integral_value(self, rounding=None, context=None):
2299 """Rounds to the nearest integer, without raising inexact, rounded."""
2300 if context is None:
2301 context = getcontext()
2302 if rounding is None:
2303 rounding = context.rounding
2304 if self._is_special:
2305 ans = self._check_nans(context=context)
2306 if ans:
2307 return ans
2308 return Decimal(self)
2309 if self._exp >= 0:
2310 return Decimal(self)
2311 else:
2312 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002313
Facundo Batista5dfc4802008-01-08 16:20:31 +00002314 # the method name changed, but we provide also the old one, for compatibility
2315 to_integral = to_integral_value
2316
2317 def sqrt(self, context=None):
2318 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002319 if self._is_special:
2320 ans = self._check_nans(context=context)
2321 if ans:
2322 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002323
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002324 if self._isinfinity() and self._sign == 0:
2325 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002326
2327 if not self:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002328 # exponent = self._exp // 2. sqrt(-0) = -0
2329 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2330 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002331
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002332 if context is None:
2333 context = getcontext()
2334
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002335 if self._sign == 1:
2336 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2337
Facundo Batista5dfc4802008-01-08 16:20:31 +00002338 # At this point self represents a positive number. Let p be
2339 # the desired precision and express self in the form c*100**e
2340 # with c a positive real number and e an integer, c and e
2341 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2342 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2343 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2344 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2345 # the closest integer to sqrt(c) with the even integer chosen
2346 # in the case of a tie.
2347 #
2348 # To ensure correct rounding in all cases, we use the
2349 # following trick: we compute the square root to an extra
2350 # place (precision p+1 instead of precision p), rounding down.
2351 # Then, if the result is inexact and its last digit is 0 or 5,
2352 # we increase the last digit to 1 or 6 respectively; if it's
2353 # exact we leave the last digit alone. Now the final round to
2354 # p places (or fewer in the case of underflow) will round
2355 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002356
Facundo Batista5dfc4802008-01-08 16:20:31 +00002357 # use an extra digit of precision
2358 prec = context.prec+1
2359
2360 # write argument in the form c*100**e where e = self._exp//2
2361 # is the 'ideal' exponent, to be used if the square root is
2362 # exactly representable. l is the number of 'digits' of c in
2363 # base 100, so that 100**(l-1) <= c < 100**l.
2364 op = _WorkRep(self)
2365 e = op.exp >> 1
2366 if op.exp & 1:
2367 c = op.int * 10
2368 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002369 else:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002370 c = op.int
2371 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002372
Facundo Batista5dfc4802008-01-08 16:20:31 +00002373 # rescale so that c has exactly prec base 100 'digits'
2374 shift = prec-l
2375 if shift >= 0:
2376 c *= 100**shift
2377 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002378 else:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002379 c, remainder = divmod(c, 100**-shift)
2380 exact = not remainder
2381 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002382
Facundo Batista5dfc4802008-01-08 16:20:31 +00002383 # find n = floor(sqrt(c)) using Newton's method
2384 n = 10**prec
2385 while True:
2386 q = c//n
2387 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002388 break
Facundo Batista5dfc4802008-01-08 16:20:31 +00002389 else:
2390 n = n + q >> 1
2391 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002392
Facundo Batista5dfc4802008-01-08 16:20:31 +00002393 if exact:
2394 # result is exact; rescale to use ideal exponent e
2395 if shift >= 0:
2396 # assert n % 10**shift == 0
2397 n //= 10**shift
2398 else:
2399 n *= 10**-shift
2400 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002401 else:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002402 # result is not exact; fix last digit as described above
2403 if n % 5 == 0:
2404 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002405
Facundo Batista5dfc4802008-01-08 16:20:31 +00002406 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002407
Facundo Batista5dfc4802008-01-08 16:20:31 +00002408 # round, and fit to current context
2409 context = context._shallow_copy()
2410 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002411 ans = ans._fix(context)
Facundo Batista5dfc4802008-01-08 16:20:31 +00002412 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002413
Facundo Batista5dfc4802008-01-08 16:20:31 +00002414 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002415
2416 def max(self, other, context=None):
2417 """Returns the larger value.
2418
Facundo Batista5dfc4802008-01-08 16:20:31 +00002419 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002420 NaN (and signals if one is sNaN). Also rounds.
2421 """
Facundo Batista5dfc4802008-01-08 16:20:31 +00002422 other = _convert_other(other, raiseit=True)
2423
2424 if context is None:
2425 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002426
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002427 if self._is_special or other._is_special:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002428 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002429 # number is always returned
2430 sn = self._isnan()
2431 on = other._isnan()
2432 if sn or on:
2433 if on == 1 and sn != 2:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002434 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002435 if sn == 1 and on != 2:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002436 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002437 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002438
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002439 c = self.__cmp__(other)
2440 if c == 0:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002441 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002442 # then an ordering is applied:
2443 #
Facundo Batista5dfc4802008-01-08 16:20:31 +00002444 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002445 # positive sign and min returns the operand with the negative sign
2446 #
Facundo Batista5dfc4802008-01-08 16:20:31 +00002447 # If the signs are the same then the exponent is used to select
2448 # the result. This is exactly the ordering used in compare_total.
2449 c = self.compare_total(other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002450
Facundo Batista5dfc4802008-01-08 16:20:31 +00002451 if c == -1:
2452 ans = other
2453 else:
2454 ans = self
2455
2456 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002457
2458 def min(self, other, context=None):
2459 """Returns the smaller value.
2460
Facundo Batista5dfc4802008-01-08 16:20:31 +00002461 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002462 NaN (and signals if one is sNaN). Also rounds.
2463 """
Facundo Batista5dfc4802008-01-08 16:20:31 +00002464 other = _convert_other(other, raiseit=True)
2465
2466 if context is None:
2467 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002468
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002469 if self._is_special or other._is_special:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002470 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002471 # number is always returned
2472 sn = self._isnan()
2473 on = other._isnan()
2474 if sn or on:
2475 if on == 1 and sn != 2:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002476 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002477 if sn == 1 and on != 2:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002478 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002479 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002480
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002481 c = self.__cmp__(other)
2482 if c == 0:
Facundo Batista5dfc4802008-01-08 16:20:31 +00002483 c = self.compare_total(other)
2484
2485 if c == -1:
2486 ans = self
2487 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002488 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002489
Facundo Batista5dfc4802008-01-08 16:20:31 +00002490 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002491
2492 def _isinteger(self):
2493 """Returns whether self is an integer"""
Facundo Batista5dfc4802008-01-08 16:20:31 +00002494 if self._is_special:
2495 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002496 if self._exp >= 0:
2497 return True
2498 rest = self._int[self._exp:]
Facundo Batista5dfc4802008-01-08 16:20:31 +00002499 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002500
2501 def _iseven(self):
Facundo Batista5dfc4802008-01-08 16:20:31 +00002502 """Returns True if self is even. Assumes self is an integer."""
2503 if not self or self._exp > 0:
2504 return True
2505 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002506
2507 def adjusted(self):
2508 """Return the adjusted exponent of self"""
2509 try:
2510 return self._exp + len(self._int) - 1
Facundo Batista5dfc4802008-01-08 16:20:31 +00002511 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002512 except TypeError:
2513 return 0
2514
Facundo Batista5dfc4802008-01-08 16:20:31 +00002515 def canonical(self, context=None):
2516 """Returns the same Decimal object.
2517
2518 As we do not have different encodings for the same number, the
2519 received object already is in its canonical form.
2520 """
2521 return self
2522
2523 def compare_signal(self, other, context=None):
2524 """Compares self to the other operand numerically.
2525
2526 It's pretty much like compare(), but all NaNs signal, with signaling
2527 NaNs taking precedence over quiet NaNs.
2528 """
2529 if context is None:
2530 context = getcontext()
2531
2532 self_is_nan = self._isnan()
2533 other_is_nan = other._isnan()
2534 if self_is_nan == 2:
2535 return context._raise_error(InvalidOperation, 'sNaN',
2536 self)
2537 if other_is_nan == 2:
2538 return context._raise_error(InvalidOperation, 'sNaN',
2539 other)
2540 if self_is_nan:
2541 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2542 self)
2543 if other_is_nan:
2544 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2545 other)
2546 return self.compare(other, context=context)
2547
2548 def compare_total(self, other):
2549 """Compares self to other using the abstract representations.
2550
2551 This is not like the standard compare, which use their numerical
2552 value. Note that a total ordering is defined for all possible abstract
2553 representations.
2554 """
2555 # if one is negative and the other is positive, it's easy
2556 if self._sign and not other._sign:
2557 return Dec_n1
2558 if not self._sign and other._sign:
2559 return Dec_p1
2560 sign = self._sign
2561
2562 # let's handle both NaN types
2563 self_nan = self._isnan()
2564 other_nan = other._isnan()
2565 if self_nan or other_nan:
2566 if self_nan == other_nan:
2567 if self._int < other._int:
2568 if sign:
2569 return Dec_p1
2570 else:
2571 return Dec_n1
2572 if self._int > other._int:
2573 if sign:
2574 return Dec_n1
2575 else:
2576 return Dec_p1
2577 return Dec_0
2578
2579 if sign:
2580 if self_nan == 1:
2581 return Dec_n1
2582 if other_nan == 1:
2583 return Dec_p1
2584 if self_nan == 2:
2585 return Dec_n1
2586 if other_nan == 2:
2587 return Dec_p1
2588 else:
2589 if self_nan == 1:
2590 return Dec_p1
2591 if other_nan == 1:
2592 return Dec_n1
2593 if self_nan == 2:
2594 return Dec_p1
2595 if other_nan == 2:
2596 return Dec_n1
2597
2598 if self < other:
2599 return Dec_n1
2600 if self > other:
2601 return Dec_p1
2602
2603 if self._exp < other._exp:
2604 if sign:
2605 return Dec_p1
2606 else:
2607 return Dec_n1
2608 if self._exp > other._exp:
2609 if sign:
2610 return Dec_n1
2611 else:
2612 return Dec_p1
2613 return Dec_0
2614
2615
2616 def compare_total_mag(self, other):
2617 """Compares self to other using abstract repr., ignoring sign.
2618
2619 Like compare_total, but with operand's sign ignored and assumed to be 0.
2620 """
2621 s = self.copy_abs()
2622 o = other.copy_abs()
2623 return s.compare_total(o)
2624
2625 def copy_abs(self):
2626 """Returns a copy with the sign set to 0. """
2627 return _dec_from_triple(0, self._int, self._exp, self._is_special)
2628
2629 def copy_negate(self):
2630 """Returns a copy with the sign inverted."""
2631 if self._sign:
2632 return _dec_from_triple(0, self._int, self._exp, self._is_special)
2633 else:
2634 return _dec_from_triple(1, self._int, self._exp, self._is_special)
2635
2636 def copy_sign(self, other):
2637 """Returns self with the sign of other."""
2638 return _dec_from_triple(other._sign, self._int,
2639 self._exp, self._is_special)
2640
2641 def exp(self, context=None):
2642 """Returns e ** self."""
2643
2644 if context is None:
2645 context = getcontext()
2646
2647 # exp(NaN) = NaN
2648 ans = self._check_nans(context=context)
2649 if ans:
2650 return ans
2651
2652 # exp(-Infinity) = 0
2653 if self._isinfinity() == -1:
2654 return Dec_0
2655
2656 # exp(0) = 1
2657 if not self:
2658 return Dec_p1
2659
2660 # exp(Infinity) = Infinity
2661 if self._isinfinity() == 1:
2662 return Decimal(self)
2663
2664 # the result is now guaranteed to be inexact (the true
2665 # mathematical result is transcendental). There's no need to
2666 # raise Rounded and Inexact here---they'll always be raised as
2667 # a result of the call to _fix.
2668 p = context.prec
2669 adj = self.adjusted()
2670
2671 # we only need to do any computation for quite a small range
2672 # of adjusted exponents---for example, -29 <= adj <= 10 for
2673 # the default context. For smaller exponent the result is
2674 # indistinguishable from 1 at the given precision, while for
2675 # larger exponent the result either overflows or underflows.
2676 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2677 # overflow
2678 ans = _dec_from_triple(0, '1', context.Emax+1)
2679 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2680 # underflow to 0
2681 ans = _dec_from_triple(0, '1', context.Etiny()-1)
2682 elif self._sign == 0 and adj < -p:
2683 # p+1 digits; final round will raise correct flags
2684 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
2685 elif self._sign == 1 and adj < -p-1:
2686 # p+1 digits; final round will raise correct flags
2687 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
2688 # general case
2689 else:
2690 op = _WorkRep(self)
2691 c, e = op.int, op.exp
2692 if op.sign == 1:
2693 c = -c
2694
2695 # compute correctly rounded result: increase precision by
2696 # 3 digits at a time until we get an unambiguously
2697 # roundable result
2698 extra = 3
2699 while True:
2700 coeff, exp = _dexp(c, e, p+extra)
2701 if coeff % (5*10**(len(str(coeff))-p-1)):
2702 break
2703 extra += 3
2704
2705 ans = _dec_from_triple(0, str(coeff), exp)
2706
2707 # at this stage, ans should round correctly with *any*
2708 # rounding mode, not just with ROUND_HALF_EVEN
2709 context = context._shallow_copy()
2710 rounding = context._set_rounding(ROUND_HALF_EVEN)
2711 ans = ans._fix(context)
2712 context.rounding = rounding
2713
2714 return ans
2715
2716 def is_canonical(self):
2717 """Return True if self is canonical; otherwise return False.
2718
2719 Currently, the encoding of a Decimal instance is always
2720 canonical, so this method returns True for any Decimal.
2721 """
2722 return True
2723
2724 def is_finite(self):
2725 """Return True if self is finite; otherwise return False.
2726
2727 A Decimal instance is considered finite if it is neither
2728 infinite nor a NaN.
2729 """
2730 return not self._is_special
2731
2732 def is_infinite(self):
2733 """Return True if self is infinite; otherwise return False."""
2734 return self._exp == 'F'
2735
2736 def is_nan(self):
2737 """Return True if self is a qNaN or sNaN; otherwise return False."""
2738 return self._exp in ('n', 'N')
2739
2740 def is_normal(self, context=None):
2741 """Return True if self is a normal number; otherwise return False."""
2742 if self._is_special or not self:
2743 return False
2744 if context is None:
2745 context = getcontext()
2746 return context.Emin <= self.adjusted() <= context.Emax
2747
2748 def is_qnan(self):
2749 """Return True if self is a quiet NaN; otherwise return False."""
2750 return self._exp == 'n'
2751
2752 def is_signed(self):
2753 """Return True if self is negative; otherwise return False."""
2754 return self._sign == 1
2755
2756 def is_snan(self):
2757 """Return True if self is a signaling NaN; otherwise return False."""
2758 return self._exp == 'N'
2759
2760 def is_subnormal(self, context=None):
2761 """Return True if self is subnormal; otherwise return False."""
2762 if self._is_special or not self:
2763 return False
2764 if context is None:
2765 context = getcontext()
2766 return self.adjusted() < context.Emin
2767
2768 def is_zero(self):
2769 """Return True if self is a zero; otherwise return False."""
2770 return not self._is_special and self._int == '0'
2771
2772 def _ln_exp_bound(self):
2773 """Compute a lower bound for the adjusted exponent of self.ln().
2774 In other words, compute r such that self.ln() >= 10**r. Assumes
2775 that self is finite and positive and that self != 1.
2776 """
2777
2778 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2779 adj = self._exp + len(self._int) - 1
2780 if adj >= 1:
2781 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2782 return len(str(adj*23//10)) - 1
2783 if adj <= -2:
2784 # argument <= 0.1
2785 return len(str((-1-adj)*23//10)) - 1
2786 op = _WorkRep(self)
2787 c, e = op.int, op.exp
2788 if adj == 0:
2789 # 1 < self < 10
2790 num = str(c-10**-e)
2791 den = str(c)
2792 return len(num) - len(den) - (num < den)
2793 # adj == -1, 0.1 <= self < 1
2794 return e + len(str(10**-e - c)) - 1
2795
2796
2797 def ln(self, context=None):
2798 """Returns the natural (base e) logarithm of self."""
2799
2800 if context is None:
2801 context = getcontext()
2802
2803 # ln(NaN) = NaN
2804 ans = self._check_nans(context=context)
2805 if ans:
2806 return ans
2807
2808 # ln(0.0) == -Infinity
2809 if not self:
2810 return negInf
2811
2812 # ln(Infinity) = Infinity
2813 if self._isinfinity() == 1:
2814 return Inf
2815
2816 # ln(1.0) == 0.0
2817 if self == Dec_p1:
2818 return Dec_0
2819
2820 # ln(negative) raises InvalidOperation
2821 if self._sign == 1:
2822 return context._raise_error(InvalidOperation,
2823 'ln of a negative value')
2824
2825 # result is irrational, so necessarily inexact
2826 op = _WorkRep(self)
2827 c, e = op.int, op.exp
2828 p = context.prec
2829
2830 # correctly rounded result: repeatedly increase precision by 3
2831 # until we get an unambiguously roundable result
2832 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2833 while True:
2834 coeff = _dlog(c, e, places)
2835 # assert len(str(abs(coeff)))-p >= 1
2836 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2837 break
2838 places += 3
2839 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2840
2841 context = context._shallow_copy()
2842 rounding = context._set_rounding(ROUND_HALF_EVEN)
2843 ans = ans._fix(context)
2844 context.rounding = rounding
2845 return ans
2846
2847 def _log10_exp_bound(self):
2848 """Compute a lower bound for the adjusted exponent of self.log10().
2849 In other words, find r such that self.log10() >= 10**r.
2850 Assumes that self is finite and positive and that self != 1.
2851 """
2852
2853 # For x >= 10 or x < 0.1 we only need a bound on the integer
2854 # part of log10(self), and this comes directly from the
2855 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2856 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2857 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2858
2859 adj = self._exp + len(self._int) - 1
2860 if adj >= 1:
2861 # self >= 10
2862 return len(str(adj))-1
2863 if adj <= -2:
2864 # self < 0.1
2865 return len(str(-1-adj))-1
2866 op = _WorkRep(self)
2867 c, e = op.int, op.exp
2868 if adj == 0:
2869 # 1 < self < 10
2870 num = str(c-10**-e)
2871 den = str(231*c)
2872 return len(num) - len(den) - (num < den) + 2
2873 # adj == -1, 0.1 <= self < 1
2874 num = str(10**-e-c)
2875 return len(num) + e - (num < "231") - 1
2876
2877 def log10(self, context=None):
2878 """Returns the base 10 logarithm of self."""
2879
2880 if context is None:
2881 context = getcontext()
2882
2883 # log10(NaN) = NaN
2884 ans = self._check_nans(context=context)
2885 if ans:
2886 return ans
2887
2888 # log10(0.0) == -Infinity
2889 if not self:
2890 return negInf
2891
2892 # log10(Infinity) = Infinity
2893 if self._isinfinity() == 1:
2894 return Inf
2895
2896 # log10(negative or -Infinity) raises InvalidOperation
2897 if self._sign == 1:
2898 return context._raise_error(InvalidOperation,
2899 'log10 of a negative value')
2900
2901 # log10(10**n) = n
2902 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
2903 # answer may need rounding
2904 ans = Decimal(self._exp + len(self._int) - 1)
2905 else:
2906 # result is irrational, so necessarily inexact
2907 op = _WorkRep(self)
2908 c, e = op.int, op.exp
2909 p = context.prec
2910
2911 # correctly rounded result: repeatedly increase precision
2912 # until result is unambiguously roundable
2913 places = p-self._log10_exp_bound()+2
2914 while True:
2915 coeff = _dlog10(c, e, places)
2916 # assert len(str(abs(coeff)))-p >= 1
2917 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2918 break
2919 places += 3
2920 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2921
2922 context = context._shallow_copy()
2923 rounding = context._set_rounding(ROUND_HALF_EVEN)
2924 ans = ans._fix(context)
2925 context.rounding = rounding
2926 return ans
2927
2928 def logb(self, context=None):
2929 """ Returns the exponent of the magnitude of self's MSD.
2930
2931 The result is the integer which is the exponent of the magnitude
2932 of the most significant digit of self (as though it were truncated
2933 to a single digit while maintaining the value of that digit and
2934 without limiting the resulting exponent).
2935 """
2936 # logb(NaN) = NaN
2937 ans = self._check_nans(context=context)
2938 if ans:
2939 return ans
2940
2941 if context is None:
2942 context = getcontext()
2943
2944 # logb(+/-Inf) = +Inf
2945 if self._isinfinity():
2946 return Inf
2947
2948 # logb(0) = -Inf, DivisionByZero
2949 if not self:
2950 return context._raise_error(DivisionByZero, 'logb(0)', 1)
2951
2952 # otherwise, simply return the adjusted exponent of self, as a
2953 # Decimal. Note that no attempt is made to fit the result
2954 # into the current context.
2955 return Decimal(self.adjusted())
2956
2957 def _islogical(self):
2958 """Return True if self is a logical operand.
2959
2960 For being logical, it must be a finite numbers with a sign of 0,
2961 an exponent of 0, and a coefficient whose digits must all be
2962 either 0 or 1.
2963 """
2964 if self._sign != 0 or self._exp != 0:
2965 return False
2966 for dig in self._int:
2967 if dig not in '01':
2968 return False
2969 return True
2970
2971 def _fill_logical(self, context, opa, opb):
2972 dif = context.prec - len(opa)
2973 if dif > 0:
2974 opa = '0'*dif + opa
2975 elif dif < 0:
2976 opa = opa[-context.prec:]
2977 dif = context.prec - len(opb)
2978 if dif > 0:
2979 opb = '0'*dif + opb
2980 elif dif < 0:
2981 opb = opb[-context.prec:]
2982 return opa, opb
2983
2984 def logical_and(self, other, context=None):
2985 """Applies an 'and' operation between self and other's digits."""
2986 if context is None:
2987 context = getcontext()
2988 if not self._islogical() or not other._islogical():
2989 return context._raise_error(InvalidOperation)
2990
2991 # fill to context.prec
2992 (opa, opb) = self._fill_logical(context, self._int, other._int)
2993
2994 # make the operation, and clean starting zeroes
2995 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
2996 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
2997
2998 def logical_invert(self, context=None):
2999 """Invert all its digits."""
3000 if context is None:
3001 context = getcontext()
3002 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3003 context)
3004
3005 def logical_or(self, other, context=None):
3006 """Applies an 'or' operation between self and other's digits."""
3007 if context is None:
3008 context = getcontext()
3009 if not self._islogical() or not other._islogical():
3010 return context._raise_error(InvalidOperation)
3011
3012 # fill to context.prec
3013 (opa, opb) = self._fill_logical(context, self._int, other._int)
3014
3015 # make the operation, and clean starting zeroes
3016 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3017 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3018
3019 def logical_xor(self, other, context=None):
3020 """Applies an 'xor' operation between self and other's digits."""
3021 if context is None:
3022 context = getcontext()
3023 if not self._islogical() or not other._islogical():
3024 return context._raise_error(InvalidOperation)
3025
3026 # fill to context.prec
3027 (opa, opb) = self._fill_logical(context, self._int, other._int)
3028
3029 # make the operation, and clean starting zeroes
3030 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3031 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3032
3033 def max_mag(self, other, context=None):
3034 """Compares the values numerically with their sign ignored."""
3035 other = _convert_other(other, raiseit=True)
3036
3037 if context is None:
3038 context = getcontext()
3039
3040 if self._is_special or other._is_special:
3041 # If one operand is a quiet NaN and the other is number, then the
3042 # number is always returned
3043 sn = self._isnan()
3044 on = other._isnan()
3045 if sn or on:
3046 if on == 1 and sn != 2:
3047 return self._fix_nan(context)
3048 if sn == 1 and on != 2:
3049 return other._fix_nan(context)
3050 return self._check_nans(other, context)
3051
3052 c = self.copy_abs().__cmp__(other.copy_abs())
3053 if c == 0:
3054 c = self.compare_total(other)
3055
3056 if c == -1:
3057 ans = other
3058 else:
3059 ans = self
3060
3061 return ans._fix(context)
3062
3063 def min_mag(self, other, context=None):
3064 """Compares the values numerically with their sign ignored."""
3065 other = _convert_other(other, raiseit=True)
3066
3067 if context is None:
3068 context = getcontext()
3069
3070 if self._is_special or other._is_special:
3071 # If one operand is a quiet NaN and the other is number, then the
3072 # number is always returned
3073 sn = self._isnan()
3074 on = other._isnan()
3075 if sn or on:
3076 if on == 1 and sn != 2:
3077 return self._fix_nan(context)
3078 if sn == 1 and on != 2:
3079 return other._fix_nan(context)
3080 return self._check_nans(other, context)
3081
3082 c = self.copy_abs().__cmp__(other.copy_abs())
3083 if c == 0:
3084 c = self.compare_total(other)
3085
3086 if c == -1:
3087 ans = self
3088 else:
3089 ans = other
3090
3091 return ans._fix(context)
3092
3093 def next_minus(self, context=None):
3094 """Returns the largest representable number smaller than itself."""
3095 if context is None:
3096 context = getcontext()
3097
3098 ans = self._check_nans(context=context)
3099 if ans:
3100 return ans
3101
3102 if self._isinfinity() == -1:
3103 return negInf
3104 if self._isinfinity() == 1:
3105 return _dec_from_triple(0, '9'*context.prec, context.Etop())
3106
3107 context = context.copy()
3108 context._set_rounding(ROUND_FLOOR)
3109 context._ignore_all_flags()
3110 new_self = self._fix(context)
3111 if new_self != self:
3112 return new_self
3113 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3114 context)
3115
3116 def next_plus(self, context=None):
3117 """Returns the smallest representable number larger than itself."""
3118 if context is None:
3119 context = getcontext()
3120
3121 ans = self._check_nans(context=context)
3122 if ans:
3123 return ans
3124
3125 if self._isinfinity() == 1:
3126 return Inf
3127 if self._isinfinity() == -1:
3128 return _dec_from_triple(1, '9'*context.prec, context.Etop())
3129
3130 context = context.copy()
3131 context._set_rounding(ROUND_CEILING)
3132 context._ignore_all_flags()
3133 new_self = self._fix(context)
3134 if new_self != self:
3135 return new_self
3136 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3137 context)
3138
3139 def next_toward(self, other, context=None):
3140 """Returns the number closest to self, in the direction towards other.
3141
3142 The result is the closest representable number to self
3143 (excluding self) that is in the direction towards other,
3144 unless both have the same value. If the two operands are
3145 numerically equal, then the result is a copy of self with the
3146 sign set to be the same as the sign of other.
3147 """
3148 other = _convert_other(other, raiseit=True)
3149
3150 if context is None:
3151 context = getcontext()
3152
3153 ans = self._check_nans(other, context)
3154 if ans:
3155 return ans
3156
3157 comparison = self.__cmp__(other)
3158 if comparison == 0:
3159 return self.copy_sign(other)
3160
3161 if comparison == -1:
3162 ans = self.next_plus(context)
3163 else: # comparison == 1
3164 ans = self.next_minus(context)
3165
3166 # decide which flags to raise using value of ans
3167 if ans._isinfinity():
3168 context._raise_error(Overflow,
3169 'Infinite result from next_toward',
3170 ans._sign)
3171 context._raise_error(Rounded)
3172 context._raise_error(Inexact)
3173 elif ans.adjusted() < context.Emin:
3174 context._raise_error(Underflow)
3175 context._raise_error(Subnormal)
3176 context._raise_error(Rounded)
3177 context._raise_error(Inexact)
3178 # if precision == 1 then we don't raise Clamped for a
3179 # result 0E-Etiny.
3180 if not ans:
3181 context._raise_error(Clamped)
3182
3183 return ans
3184
3185 def number_class(self, context=None):
3186 """Returns an indication of the class of self.
3187
3188 The class is one of the following strings:
3189 sNaN
3190 NaN
3191 -Infinity
3192 -Normal
3193 -Subnormal
3194 -Zero
3195 +Zero
3196 +Subnormal
3197 +Normal
3198 +Infinity
3199 """
3200 if self.is_snan():
3201 return "sNaN"
3202 if self.is_qnan():
3203 return "NaN"
3204 inf = self._isinfinity()
3205 if inf == 1:
3206 return "+Infinity"
3207 if inf == -1:
3208 return "-Infinity"
3209 if self.is_zero():
3210 if self._sign:
3211 return "-Zero"
3212 else:
3213 return "+Zero"
3214 if context is None:
3215 context = getcontext()
3216 if self.is_subnormal(context=context):
3217 if self._sign:
3218 return "-Subnormal"
3219 else:
3220 return "+Subnormal"
3221 # just a normal, regular, boring number, :)
3222 if self._sign:
3223 return "-Normal"
3224 else:
3225 return "+Normal"
3226
3227 def radix(self):
3228 """Just returns 10, as this is Decimal, :)"""
3229 return Decimal(10)
3230
3231 def rotate(self, other, context=None):
3232 """Returns a rotated copy of self, value-of-other times."""
3233 if context is None:
3234 context = getcontext()
3235
3236 ans = self._check_nans(other, context)
3237 if ans:
3238 return ans
3239
3240 if other._exp != 0:
3241 return context._raise_error(InvalidOperation)
3242 if not (-context.prec <= int(other) <= context.prec):
3243 return context._raise_error(InvalidOperation)
3244
3245 if self._isinfinity():
3246 return Decimal(self)
3247
3248 # get values, pad if necessary
3249 torot = int(other)
3250 rotdig = self._int
3251 topad = context.prec - len(rotdig)
3252 if topad:
3253 rotdig = '0'*topad + rotdig
3254
3255 # let's rotate!
3256 rotated = rotdig[torot:] + rotdig[:torot]
3257 return _dec_from_triple(self._sign,
3258 rotated.lstrip('0') or '0', self._exp)
3259
3260 def scaleb (self, other, context=None):
3261 """Returns self operand after adding the second value to its exp."""
3262 if context is None:
3263 context = getcontext()
3264
3265 ans = self._check_nans(other, context)
3266 if ans:
3267 return ans
3268
3269 if other._exp != 0:
3270 return context._raise_error(InvalidOperation)
3271 liminf = -2 * (context.Emax + context.prec)
3272 limsup = 2 * (context.Emax + context.prec)
3273 if not (liminf <= int(other) <= limsup):
3274 return context._raise_error(InvalidOperation)
3275
3276 if self._isinfinity():
3277 return Decimal(self)
3278
3279 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
3280 d = d._fix(context)
3281 return d
3282
3283 def shift(self, other, context=None):
3284 """Returns a shifted copy of self, value-of-other times."""
3285 if context is None:
3286 context = getcontext()
3287
3288 ans = self._check_nans(other, context)
3289 if ans:
3290 return ans
3291
3292 if other._exp != 0:
3293 return context._raise_error(InvalidOperation)
3294 if not (-context.prec <= int(other) <= context.prec):
3295 return context._raise_error(InvalidOperation)
3296
3297 if self._isinfinity():
3298 return Decimal(self)
3299
3300 # get values, pad if necessary
3301 torot = int(other)
3302 if not torot:
3303 return Decimal(self)
3304 rotdig = self._int
3305 topad = context.prec - len(rotdig)
3306 if topad:
3307 rotdig = '0'*topad + rotdig
3308
3309 # let's shift!
3310 if torot < 0:
3311 rotated = rotdig[:torot]
3312 else:
3313 rotated = rotdig + '0'*torot
3314 rotated = rotated[-context.prec:]
3315
3316 return _dec_from_triple(self._sign,
3317 rotated.lstrip('0') or '0', self._exp)
3318
3319 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003320 def __reduce__(self):
3321 return (self.__class__, (str(self),))
3322
3323 def __copy__(self):
3324 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003325 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003326 return self.__class__(str(self))
3327
3328 def __deepcopy__(self, memo):
3329 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003330 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003331 return self.__class__(str(self))
3332
Facundo Batista5dfc4802008-01-08 16:20:31 +00003333def _dec_from_triple(sign, coefficient, exponent, special=False):
3334 """Create a decimal instance directly, without any validation,
3335 normalization (e.g. removal of leading zeros) or argument
3336 conversion.
3337
3338 This function is for *internal use only*.
3339 """
3340
3341 self = object.__new__(Decimal)
3342 self._sign = sign
3343 self._int = coefficient
3344 self._exp = exponent
3345 self._is_special = special
3346
3347 return self
3348
3349##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003350
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003351
3352# get rounding method function:
Facundo Batista5dfc4802008-01-08 16:20:31 +00003353rounding_functions = [name for name in Decimal.__dict__.keys()
3354 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003355for name in rounding_functions:
Facundo Batista5dfc4802008-01-08 16:20:31 +00003356 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003357 globalname = name[1:].upper()
3358 val = globals()[globalname]
3359 Decimal._pick_rounding_function[val] = name
3360
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003361del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003362
Nick Coghlanc48daf52006-09-03 01:08:30 +00003363class _ContextManager(object):
3364 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003365
Nick Coghlanc48daf52006-09-03 01:08:30 +00003366 Sets a copy of the supplied context in __enter__() and restores
3367 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003368 """
3369 def __init__(self, new_context):
Nick Coghlanc48daf52006-09-03 01:08:30 +00003370 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003371 def __enter__(self):
3372 self.saved_context = getcontext()
3373 setcontext(self.new_context)
3374 return self.new_context
3375 def __exit__(self, t, v, tb):
3376 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003377
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003378class Context(object):
3379 """Contains the context for a Decimal instance.
3380
3381 Contains:
3382 prec - precision (for use in rounding, division, square roots..)
Facundo Batista5dfc4802008-01-08 16:20:31 +00003383 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003384 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003385 raised when it is caused. Otherwise, a value is
3386 substituted in.
3387 flags - When an exception is caused, flags[exception] is incremented.
3388 (Whether or not the trap_enabler is set)
3389 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003390 Emin - Minimum exponent
3391 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003392 capitals - If 1, 1*10^1 is printed as 1E+1.
3393 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003394 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003395 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003396
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003397 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003398 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003399 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003400 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003401 _ignored_flags=None):
3402 if flags is None:
3403 flags = []
3404 if _ignored_flags is None:
3405 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003406 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003407 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003408 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003409 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003410 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003411 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003412 for name, val in locals().items():
3413 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003414 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003415 else:
3416 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003417 del self.self
3418
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003419 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003420 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003421 s = []
Facundo Batista5dfc4802008-01-08 16:20:31 +00003422 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3423 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3424 % vars(self))
3425 names = [f.__name__ for f, v in self.flags.items() if v]
3426 s.append('flags=[' + ', '.join(names) + ']')
3427 names = [t.__name__ for t, v in self.traps.items() if v]
3428 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003429 return ', '.join(s) + ')'
3430
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003431 def clear_flags(self):
3432 """Reset all flags to zero"""
3433 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003434 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003435
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003436 def _shallow_copy(self):
3437 """Returns a shallow copy from self."""
Facundo Batista5dfc4802008-01-08 16:20:31 +00003438 nc = Context(self.prec, self.rounding, self.traps,
3439 self.flags, self.Emin, self.Emax,
3440 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003441 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003442
3443 def copy(self):
3444 """Returns a deep copy from self."""
Facundo Batista5dfc4802008-01-08 16:20:31 +00003445 nc = Context(self.prec, self.rounding, self.traps.copy(),
3446 self.flags.copy(), self.Emin, self.Emax,
3447 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003448 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003449 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003450
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003451 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003452 """Handles an error
3453
3454 If the flag is in _ignored_flags, returns the default response.
3455 Otherwise, it increments the flag, then, if the corresponding
3456 trap_enabler is set, it reaises the exception. Otherwise, it returns
3457 the default value after incrementing the flag.
3458 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003459 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003460 if error in self._ignored_flags:
Facundo Batista5dfc4802008-01-08 16:20:31 +00003461 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003462 return error().handle(self, *args)
3463
3464 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003465 if not self.traps[error]:
Facundo Batista5dfc4802008-01-08 16:20:31 +00003466 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003467 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003468
3469 # Errors should only be risked on copies of the context
Facundo Batista5dfc4802008-01-08 16:20:31 +00003470 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003471 raise error, explanation
3472
3473 def _ignore_all_flags(self):
3474 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003475 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003476
3477 def _ignore_flags(self, *flags):
3478 """Ignore the flags, if they are raised"""
3479 # Do not mutate-- This way, copies of a context leave the original
3480 # alone.
3481 self._ignored_flags = (self._ignored_flags + list(flags))
3482 return list(flags)
3483
3484 def _regard_flags(self, *flags):
3485 """Stop ignoring the flags, if they are raised"""
3486 if flags and isinstance(flags[0], (tuple,list)):
3487 flags = flags[0]
3488 for flag in flags:
3489 self._ignored_flags.remove(flag)
3490
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003491 def __hash__(self):
3492 """A Context cannot be hashed."""
3493 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista5dfc4802008-01-08 16:20:31 +00003494 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003495
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003496 def Etiny(self):
3497 """Returns Etiny (= Emin - prec + 1)"""
3498 return int(self.Emin - self.prec + 1)
3499
3500 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003501 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003502 return int(self.Emax - self.prec + 1)
3503
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003504 def _set_rounding(self, type):
3505 """Sets the rounding type.
3506
3507 Sets the rounding type, and returns the current (previous)
3508 rounding type. Often used like:
3509
3510 context = context.copy()
3511 # so you don't change the calling context
3512 # if an error occurs in the middle.
3513 rounding = context._set_rounding(ROUND_UP)
3514 val = self.__sub__(other, context=context)
3515 context._set_rounding(rounding)
3516
3517 This will make it round up for that operation.
3518 """
3519 rounding = self.rounding
3520 self.rounding= type
3521 return rounding
3522
Raymond Hettingerfed52962004-07-14 15:41:57 +00003523 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003524 """Creates a new Decimal instance but using self as context."""
3525 d = Decimal(num, context=self)
Facundo Batista5dfc4802008-01-08 16:20:31 +00003526 if d._isnan() and len(d._int) > self.prec - self._clamp:
3527 return self._raise_error(ConversionSyntax,
3528 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003529 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003530
Facundo Batista5dfc4802008-01-08 16:20:31 +00003531 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003532 def abs(self, a):
3533 """Returns the absolute value of the operand.
3534
3535 If the operand is negative, the result is the same as using the minus
Facundo Batista5dfc4802008-01-08 16:20:31 +00003536 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003537 the plus operation on the operand.
3538
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003539 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003540 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003541 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003542 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003543 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003544 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003545 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003546 Decimal("101.5")
3547 """
3548 return a.__abs__(context=self)
3549
3550 def add(self, a, b):
3551 """Return the sum of the two operands.
3552
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003553 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003554 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003555 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003556 Decimal("1.02E+4")
3557 """
3558 return a.__add__(b, context=self)
3559
3560 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003561 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003562
Facundo Batista5dfc4802008-01-08 16:20:31 +00003563 def canonical(self, a):
3564 """Returns the same Decimal object.
3565
3566 As we do not have different encodings for the same number, the
3567 received object already is in its canonical form.
3568
3569 >>> ExtendedContext.canonical(Decimal('2.50'))
3570 Decimal("2.50")
3571 """
3572 return a.canonical(context=self)
3573
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003574 def compare(self, a, b):
3575 """Compares values numerically.
3576
3577 If the signs of the operands differ, a value representing each operand
3578 ('-1' if the operand is less than zero, '0' if the operand is zero or
3579 negative zero, or '1' if the operand is greater than zero) is used in
3580 place of that operand for the comparison instead of the actual
3581 operand.
3582
3583 The comparison is then effected by subtracting the second operand from
3584 the first and then returning a value according to the result of the
3585 subtraction: '-1' if the result is less than zero, '0' if the result is
3586 zero or negative zero, or '1' if the result is greater than zero.
3587
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003588 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003589 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003590 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003591 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003592 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003593 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003594 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003595 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003596 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003597 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003598 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003599 Decimal("-1")
3600 """
3601 return a.compare(b, context=self)
3602
Facundo Batista5dfc4802008-01-08 16:20:31 +00003603 def compare_signal(self, a, b):
3604 """Compares the values of the two operands numerically.
3605
3606 It's pretty much like compare(), but all NaNs signal, with signaling
3607 NaNs taking precedence over quiet NaNs.
3608
3609 >>> c = ExtendedContext
3610 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3611 Decimal("-1")
3612 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3613 Decimal("0")
3614 >>> c.flags[InvalidOperation] = 0
3615 >>> print c.flags[InvalidOperation]
3616 0
3617 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3618 Decimal("NaN")
3619 >>> print c.flags[InvalidOperation]
3620 1
3621 >>> c.flags[InvalidOperation] = 0
3622 >>> print c.flags[InvalidOperation]
3623 0
3624 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3625 Decimal("NaN")
3626 >>> print c.flags[InvalidOperation]
3627 1
3628 """
3629 return a.compare_signal(b, context=self)
3630
3631 def compare_total(self, a, b):
3632 """Compares two operands using their abstract representation.
3633
3634 This is not like the standard compare, which use their numerical
3635 value. Note that a total ordering is defined for all possible abstract
3636 representations.
3637
3638 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3639 Decimal("-1")
3640 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3641 Decimal("-1")
3642 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3643 Decimal("-1")
3644 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3645 Decimal("0")
3646 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3647 Decimal("1")
3648 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3649 Decimal("-1")
3650 """
3651 return a.compare_total(b)
3652
3653 def compare_total_mag(self, a, b):
3654 """Compares two operands using their abstract representation ignoring sign.
3655
3656 Like compare_total, but with operand's sign ignored and assumed to be 0.
3657 """
3658 return a.compare_total_mag(b)
3659
3660 def copy_abs(self, a):
3661 """Returns a copy of the operand with the sign set to 0.
3662
3663 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3664 Decimal("2.1")
3665 >>> ExtendedContext.copy_abs(Decimal('-100'))
3666 Decimal("100")
3667 """
3668 return a.copy_abs()
3669
3670 def copy_decimal(self, a):
3671 """Returns a copy of the decimal objet.
3672
3673 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3674 Decimal("2.1")
3675 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3676 Decimal("-1.00")
3677 """
3678 return Decimal(a)
3679
3680 def copy_negate(self, a):
3681 """Returns a copy of the operand with the sign inverted.
3682
3683 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3684 Decimal("-101.5")
3685 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3686 Decimal("101.5")
3687 """
3688 return a.copy_negate()
3689
3690 def copy_sign(self, a, b):
3691 """Copies the second operand's sign to the first one.
3692
3693 In detail, it returns a copy of the first operand with the sign
3694 equal to the sign of the second operand.
3695
3696 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3697 Decimal("1.50")
3698 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3699 Decimal("1.50")
3700 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3701 Decimal("-1.50")
3702 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3703 Decimal("-1.50")
3704 """
3705 return a.copy_sign(b)
3706
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003707 def divide(self, a, b):
3708 """Decimal division in a specified context.
3709
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003710 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003711 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003712 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003713 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003714 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003715 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003716 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003717 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003718 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003719 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003720 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003721 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003722 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003723 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003724 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003725 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003726 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003727 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003728 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003729 Decimal("1.20E+6")
3730 """
3731 return a.__div__(b, context=self)
3732
3733 def divide_int(self, a, b):
3734 """Divides two numbers and returns the integer part of the result.
3735
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003736 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003737 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003738 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003739 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003740 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003741 Decimal("3")
3742 """
3743 return a.__floordiv__(b, context=self)
3744
3745 def divmod(self, a, b):
3746 return a.__divmod__(b, context=self)
3747
Facundo Batista5dfc4802008-01-08 16:20:31 +00003748 def exp(self, a):
3749 """Returns e ** a.
3750
3751 >>> c = ExtendedContext.copy()
3752 >>> c.Emin = -999
3753 >>> c.Emax = 999
3754 >>> c.exp(Decimal('-Infinity'))
3755 Decimal("0")
3756 >>> c.exp(Decimal('-1'))
3757 Decimal("0.367879441")
3758 >>> c.exp(Decimal('0'))
3759 Decimal("1")
3760 >>> c.exp(Decimal('1'))
3761 Decimal("2.71828183")
3762 >>> c.exp(Decimal('0.693147181'))
3763 Decimal("2.00000000")
3764 >>> c.exp(Decimal('+Infinity'))
3765 Decimal("Infinity")
3766 """
3767 return a.exp(context=self)
3768
3769 def fma(self, a, b, c):
3770 """Returns a multiplied by b, plus c.
3771
3772 The first two operands are multiplied together, using multiply,
3773 the third operand is then added to the result of that
3774 multiplication, using add, all with only one final rounding.
3775
3776 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3777 Decimal("22")
3778 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3779 Decimal("-8")
3780 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3781 Decimal("1.38435736E+12")
3782 """
3783 return a.fma(b, c, context=self)
3784
3785 def is_canonical(self, a):
3786 """Return True if the operand is canonical; otherwise return False.
3787
3788 Currently, the encoding of a Decimal instance is always
3789 canonical, so this method returns True for any Decimal.
3790
3791 >>> ExtendedContext.is_canonical(Decimal('2.50'))
3792 True
3793 """
3794 return a.is_canonical()
3795
3796 def is_finite(self, a):
3797 """Return True if the operand is finite; otherwise return False.
3798
3799 A Decimal instance is considered finite if it is neither
3800 infinite nor a NaN.
3801
3802 >>> ExtendedContext.is_finite(Decimal('2.50'))
3803 True
3804 >>> ExtendedContext.is_finite(Decimal('-0.3'))
3805 True
3806 >>> ExtendedContext.is_finite(Decimal('0'))
3807 True
3808 >>> ExtendedContext.is_finite(Decimal('Inf'))
3809 False
3810 >>> ExtendedContext.is_finite(Decimal('NaN'))
3811 False
3812 """
3813 return a.is_finite()
3814
3815 def is_infinite(self, a):
3816 """Return True if the operand is infinite; otherwise return False.
3817
3818 >>> ExtendedContext.is_infinite(Decimal('2.50'))
3819 False
3820 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
3821 True
3822 >>> ExtendedContext.is_infinite(Decimal('NaN'))
3823 False
3824 """
3825 return a.is_infinite()
3826
3827 def is_nan(self, a):
3828 """Return True if the operand is a qNaN or sNaN;
3829 otherwise return False.
3830
3831 >>> ExtendedContext.is_nan(Decimal('2.50'))
3832 False
3833 >>> ExtendedContext.is_nan(Decimal('NaN'))
3834 True
3835 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
3836 True
3837 """
3838 return a.is_nan()
3839
3840 def is_normal(self, a):
3841 """Return True if the operand is a normal number;
3842 otherwise return False.
3843
3844 >>> c = ExtendedContext.copy()
3845 >>> c.Emin = -999
3846 >>> c.Emax = 999
3847 >>> c.is_normal(Decimal('2.50'))
3848 True
3849 >>> c.is_normal(Decimal('0.1E-999'))
3850 False
3851 >>> c.is_normal(Decimal('0.00'))
3852 False
3853 >>> c.is_normal(Decimal('-Inf'))
3854 False
3855 >>> c.is_normal(Decimal('NaN'))
3856 False
3857 """
3858 return a.is_normal(context=self)
3859
3860 def is_qnan(self, a):
3861 """Return True if the operand is a quiet NaN; otherwise return False.
3862
3863 >>> ExtendedContext.is_qnan(Decimal('2.50'))
3864 False
3865 >>> ExtendedContext.is_qnan(Decimal('NaN'))
3866 True
3867 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
3868 False
3869 """
3870 return a.is_qnan()
3871
3872 def is_signed(self, a):
3873 """Return True if the operand is negative; otherwise return False.
3874
3875 >>> ExtendedContext.is_signed(Decimal('2.50'))
3876 False
3877 >>> ExtendedContext.is_signed(Decimal('-12'))
3878 True
3879 >>> ExtendedContext.is_signed(Decimal('-0'))
3880 True
3881 """
3882 return a.is_signed()
3883
3884 def is_snan(self, a):
3885 """Return True if the operand is a signaling NaN;
3886 otherwise return False.
3887
3888 >>> ExtendedContext.is_snan(Decimal('2.50'))
3889 False
3890 >>> ExtendedContext.is_snan(Decimal('NaN'))
3891 False
3892 >>> ExtendedContext.is_snan(Decimal('sNaN'))
3893 True
3894 """
3895 return a.is_snan()
3896
3897 def is_subnormal(self, a):
3898 """Return True if the operand is subnormal; otherwise return False.
3899
3900 >>> c = ExtendedContext.copy()
3901 >>> c.Emin = -999
3902 >>> c.Emax = 999
3903 >>> c.is_subnormal(Decimal('2.50'))
3904 False
3905 >>> c.is_subnormal(Decimal('0.1E-999'))
3906 True
3907 >>> c.is_subnormal(Decimal('0.00'))
3908 False
3909 >>> c.is_subnormal(Decimal('-Inf'))
3910 False
3911 >>> c.is_subnormal(Decimal('NaN'))
3912 False
3913 """
3914 return a.is_subnormal(context=self)
3915
3916 def is_zero(self, a):
3917 """Return True if the operand is a zero; otherwise return False.
3918
3919 >>> ExtendedContext.is_zero(Decimal('0'))
3920 True
3921 >>> ExtendedContext.is_zero(Decimal('2.50'))
3922 False
3923 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
3924 True
3925 """
3926 return a.is_zero()
3927
3928 def ln(self, a):
3929 """Returns the natural (base e) logarithm of the operand.
3930
3931 >>> c = ExtendedContext.copy()
3932 >>> c.Emin = -999
3933 >>> c.Emax = 999
3934 >>> c.ln(Decimal('0'))
3935 Decimal("-Infinity")
3936 >>> c.ln(Decimal('1.000'))
3937 Decimal("0")
3938 >>> c.ln(Decimal('2.71828183'))
3939 Decimal("1.00000000")
3940 >>> c.ln(Decimal('10'))
3941 Decimal("2.30258509")
3942 >>> c.ln(Decimal('+Infinity'))
3943 Decimal("Infinity")
3944 """
3945 return a.ln(context=self)
3946
3947 def log10(self, a):
3948 """Returns the base 10 logarithm of the operand.
3949
3950 >>> c = ExtendedContext.copy()
3951 >>> c.Emin = -999
3952 >>> c.Emax = 999
3953 >>> c.log10(Decimal('0'))
3954 Decimal("-Infinity")
3955 >>> c.log10(Decimal('0.001'))
3956 Decimal("-3")
3957 >>> c.log10(Decimal('1.000'))
3958 Decimal("0")
3959 >>> c.log10(Decimal('2'))
3960 Decimal("0.301029996")
3961 >>> c.log10(Decimal('10'))
3962 Decimal("1")
3963 >>> c.log10(Decimal('70'))
3964 Decimal("1.84509804")
3965 >>> c.log10(Decimal('+Infinity'))
3966 Decimal("Infinity")
3967 """
3968 return a.log10(context=self)
3969
3970 def logb(self, a):
3971 """ Returns the exponent of the magnitude of the operand's MSD.
3972
3973 The result is the integer which is the exponent of the magnitude
3974 of the most significant digit of the operand (as though the
3975 operand were truncated to a single digit while maintaining the
3976 value of that digit and without limiting the resulting exponent).
3977
3978 >>> ExtendedContext.logb(Decimal('250'))
3979 Decimal("2")
3980 >>> ExtendedContext.logb(Decimal('2.50'))
3981 Decimal("0")
3982 >>> ExtendedContext.logb(Decimal('0.03'))
3983 Decimal("-2")
3984 >>> ExtendedContext.logb(Decimal('0'))
3985 Decimal("-Infinity")
3986 """
3987 return a.logb(context=self)
3988
3989 def logical_and(self, a, b):
3990 """Applies the logical operation 'and' between each operand's digits.
3991
3992 The operands must be both logical numbers.
3993
3994 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
3995 Decimal("0")
3996 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
3997 Decimal("0")
3998 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
3999 Decimal("0")
4000 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4001 Decimal("1")
4002 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4003 Decimal("1000")
4004 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4005 Decimal("10")
4006 """
4007 return a.logical_and(b, context=self)
4008
4009 def logical_invert(self, a):
4010 """Invert all the digits in the operand.
4011
4012 The operand must be a logical number.
4013
4014 >>> ExtendedContext.logical_invert(Decimal('0'))
4015 Decimal("111111111")
4016 >>> ExtendedContext.logical_invert(Decimal('1'))
4017 Decimal("111111110")
4018 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4019 Decimal("0")
4020 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4021 Decimal("10101010")
4022 """
4023 return a.logical_invert(context=self)
4024
4025 def logical_or(self, a, b):
4026 """Applies the logical operation 'or' between each operand's digits.
4027
4028 The operands must be both logical numbers.
4029
4030 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4031 Decimal("0")
4032 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4033 Decimal("1")
4034 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4035 Decimal("1")
4036 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4037 Decimal("1")
4038 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4039 Decimal("1110")
4040 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4041 Decimal("1110")
4042 """
4043 return a.logical_or(b, context=self)
4044
4045 def logical_xor(self, a, b):
4046 """Applies the logical operation 'xor' between each operand's digits.
4047
4048 The operands must be both logical numbers.
4049
4050 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4051 Decimal("0")
4052 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4053 Decimal("1")
4054 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4055 Decimal("1")
4056 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4057 Decimal("0")
4058 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4059 Decimal("110")
4060 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4061 Decimal("1101")
4062 """
4063 return a.logical_xor(b, context=self)
4064
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004065 def max(self, a,b):
4066 """max compares two values numerically and returns the maximum.
4067
4068 If either operand is a NaN then the general rules apply.
4069 Otherwise, the operands are compared as as though by the compare
Facundo Batista5dfc4802008-01-08 16:20:31 +00004070 operation. If they are numerically equal then the left-hand operand
4071 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004072 infinity) of the two operands is chosen as the result.
4073
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004074 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004075 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004076 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004077 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004078 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004079 Decimal("1")
4080 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4081 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004082 """
4083 return a.max(b, context=self)
4084
Facundo Batista5dfc4802008-01-08 16:20:31 +00004085 def max_mag(self, a, b):
4086 """Compares the values numerically with their sign ignored."""
4087 return a.max_mag(b, context=self)
4088
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004089 def min(self, a,b):
4090 """min compares two values numerically and returns the minimum.
4091
4092 If either operand is a NaN then the general rules apply.
4093 Otherwise, the operands are compared as as though by the compare
Facundo Batista5dfc4802008-01-08 16:20:31 +00004094 operation. If they are numerically equal then the left-hand operand
4095 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004096 infinity) of the two operands is chosen as the result.
4097
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004098 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004099 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004100 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004101 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004102 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004103 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004104 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4105 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004106 """
4107 return a.min(b, context=self)
4108
Facundo Batista5dfc4802008-01-08 16:20:31 +00004109 def min_mag(self, a, b):
4110 """Compares the values numerically with their sign ignored."""
4111 return a.min_mag(b, context=self)
4112
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004113 def minus(self, a):
4114 """Minus corresponds to unary prefix minus in Python.
4115
4116 The operation is evaluated using the same rules as subtract; the
4117 operation minus(a) is calculated as subtract('0', a) where the '0'
4118 has the same exponent as the operand.
4119
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004120 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004121 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004122 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004123 Decimal("1.3")
4124 """
4125 return a.__neg__(context=self)
4126
4127 def multiply(self, a, b):
4128 """multiply multiplies two operands.
4129
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004130 If either operand is a special value then the general rules apply.
4131 Otherwise, the operands are multiplied together ('long multiplication'),
4132 resulting in a number which may be as long as the sum of the lengths
4133 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004134
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004135 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004136 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004137 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004138 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004139 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004140 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004141 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004142 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004143 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004144 Decimal("4.28135971E+11")
4145 """
4146 return a.__mul__(b, context=self)
4147
Facundo Batista5dfc4802008-01-08 16:20:31 +00004148 def next_minus(self, a):
4149 """Returns the largest representable number smaller than a.
4150
4151 >>> c = ExtendedContext.copy()
4152 >>> c.Emin = -999
4153 >>> c.Emax = 999
4154 >>> ExtendedContext.next_minus(Decimal('1'))
4155 Decimal("0.999999999")
4156 >>> c.next_minus(Decimal('1E-1007'))
4157 Decimal("0E-1007")
4158 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4159 Decimal("-1.00000004")
4160 >>> c.next_minus(Decimal('Infinity'))
4161 Decimal("9.99999999E+999")
4162 """
4163 return a.next_minus(context=self)
4164
4165 def next_plus(self, a):
4166 """Returns the smallest representable number larger than a.
4167
4168 >>> c = ExtendedContext.copy()
4169 >>> c.Emin = -999
4170 >>> c.Emax = 999
4171 >>> ExtendedContext.next_plus(Decimal('1'))
4172 Decimal("1.00000001")
4173 >>> c.next_plus(Decimal('-1E-1007'))
4174 Decimal("-0E-1007")
4175 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4176 Decimal("-1.00000002")
4177 >>> c.next_plus(Decimal('-Infinity'))
4178 Decimal("-9.99999999E+999")
4179 """
4180 return a.next_plus(context=self)
4181
4182 def next_toward(self, a, b):
4183 """Returns the number closest to a, in direction towards b.
4184
4185 The result is the closest representable number from the first
4186 operand (but not the first operand) that is in the direction
4187 towards the second operand, unless the operands have the same
4188 value.
4189
4190 >>> c = ExtendedContext.copy()
4191 >>> c.Emin = -999
4192 >>> c.Emax = 999
4193 >>> c.next_toward(Decimal('1'), Decimal('2'))
4194 Decimal("1.00000001")
4195 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4196 Decimal("-0E-1007")
4197 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4198 Decimal("-1.00000002")
4199 >>> c.next_toward(Decimal('1'), Decimal('0'))
4200 Decimal("0.999999999")
4201 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4202 Decimal("0E-1007")
4203 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4204 Decimal("-1.00000004")
4205 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4206 Decimal("-0.00")
4207 """
4208 return a.next_toward(b, context=self)
4209
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004210 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004211 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004212
4213 Essentially a plus operation with all trailing zeros removed from the
4214 result.
4215
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004216 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004217 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004218 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004219 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004220 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004221 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004222 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004223 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004224 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004225 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004226 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004227 Decimal("0")
4228 """
4229 return a.normalize(context=self)
4230
Facundo Batista5dfc4802008-01-08 16:20:31 +00004231 def number_class(self, a):
4232 """Returns an indication of the class of the operand.
4233
4234 The class is one of the following strings:
4235 -sNaN
4236 -NaN
4237 -Infinity
4238 -Normal
4239 -Subnormal
4240 -Zero
4241 +Zero
4242 +Subnormal
4243 +Normal
4244 +Infinity
4245
4246 >>> c = Context(ExtendedContext)
4247 >>> c.Emin = -999
4248 >>> c.Emax = 999
4249 >>> c.number_class(Decimal('Infinity'))
4250 '+Infinity'
4251 >>> c.number_class(Decimal('1E-10'))
4252 '+Normal'
4253 >>> c.number_class(Decimal('2.50'))
4254 '+Normal'
4255 >>> c.number_class(Decimal('0.1E-999'))
4256 '+Subnormal'
4257 >>> c.number_class(Decimal('0'))
4258 '+Zero'
4259 >>> c.number_class(Decimal('-0'))
4260 '-Zero'
4261 >>> c.number_class(Decimal('-0.1E-999'))
4262 '-Subnormal'
4263 >>> c.number_class(Decimal('-1E-10'))
4264 '-Normal'
4265 >>> c.number_class(Decimal('-2.50'))
4266 '-Normal'
4267 >>> c.number_class(Decimal('-Infinity'))
4268 '-Infinity'
4269 >>> c.number_class(Decimal('NaN'))
4270 'NaN'
4271 >>> c.number_class(Decimal('-NaN'))
4272 'NaN'
4273 >>> c.number_class(Decimal('sNaN'))
4274 'sNaN'
4275 """
4276 return a.number_class(context=self)
4277
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004278 def plus(self, a):
4279 """Plus corresponds to unary prefix plus in Python.
4280
4281 The operation is evaluated using the same rules as add; the
4282 operation plus(a) is calculated as add('0', a) where the '0'
4283 has the same exponent as the operand.
4284
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004285 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004286 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004287 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004288 Decimal("-1.3")
4289 """
4290 return a.__pos__(context=self)
4291
4292 def power(self, a, b, modulo=None):
4293 """Raises a to the power of b, to modulo if given.
4294
Facundo Batista5dfc4802008-01-08 16:20:31 +00004295 With two arguments, compute a**b. If a is negative then b
4296 must be integral. The result will be inexact unless b is
4297 integral and the result is finite and can be expressed exactly
4298 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004299
Facundo Batista5dfc4802008-01-08 16:20:31 +00004300 With three arguments, compute (a**b) % modulo. For the
4301 three argument form, the following restrictions on the
4302 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004303
Facundo Batista5dfc4802008-01-08 16:20:31 +00004304 - all three arguments must be integral
4305 - b must be nonnegative
4306 - at least one of a or b must be nonzero
4307 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004308
Facundo Batista5dfc4802008-01-08 16:20:31 +00004309 The result of pow(a, b, modulo) is identical to the result
4310 that would be obtained by computing (a**b) % modulo with
4311 unbounded precision, but is computed more efficiently. It is
4312 always exact.
4313
4314 >>> c = ExtendedContext.copy()
4315 >>> c.Emin = -999
4316 >>> c.Emax = 999
4317 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004318 Decimal("8")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004319 >>> c.power(Decimal('-2'), Decimal('3'))
4320 Decimal("-8")
4321 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004322 Decimal("0.125")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004323 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004324 Decimal("69.7575744")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004325 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4326 Decimal("2.00000000")
4327 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004328 Decimal("0")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004329 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004330 Decimal("1")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004331 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004332 Decimal("Infinity")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004333 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004334 Decimal("-0")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004335 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004336 Decimal("1")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004337 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004338 Decimal("-Infinity")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004339 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004340 Decimal("Infinity")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004341 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004342 Decimal("NaN")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004343
4344 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4345 Decimal("11")
4346 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4347 Decimal("-11")
4348 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4349 Decimal("1")
4350 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4351 Decimal("11")
4352 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4353 Decimal("11729830")
4354 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4355 Decimal("-0")
4356 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4357 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004358 """
4359 return a.__pow__(b, modulo, context=self)
4360
4361 def quantize(self, a, b):
Facundo Batista5dfc4802008-01-08 16:20:31 +00004362 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004363
4364 The coefficient of the result is derived from that of the left-hand
Facundo Batista5dfc4802008-01-08 16:20:31 +00004365 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004366 exponent is being increased), multiplied by a positive power of ten (if
4367 the exponent is being decreased), or is unchanged (if the exponent is
4368 already equal to that of the right-hand operand).
4369
4370 Unlike other operations, if the length of the coefficient after the
4371 quantize operation would be greater than precision then an Invalid
Facundo Batista5dfc4802008-01-08 16:20:31 +00004372 operation condition is raised. This guarantees that, unless there is
4373 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004374 equal to that of the right-hand operand.
4375
4376 Also unlike other operations, quantize will never raise Underflow, even
4377 if the result is subnormal and inexact.
4378
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004379 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004380 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004381 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004382 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004383 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004384 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004385 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004386 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004387 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004388 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004389 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004390 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004391 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004392 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004393 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004394 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004395 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004396 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004397 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004399 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004400 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004401 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004402 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004403 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004404 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004405 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004406 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004407 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408 Decimal("2E+2")
4409 """
4410 return a.quantize(b, context=self)
4411
Facundo Batista5dfc4802008-01-08 16:20:31 +00004412 def radix(self):
4413 """Just returns 10, as this is Decimal, :)
4414
4415 >>> ExtendedContext.radix()
4416 Decimal("10")
4417 """
4418 return Decimal(10)
4419
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004420 def remainder(self, a, b):
4421 """Returns the remainder from integer division.
4422
4423 The result is the residue of the dividend after the operation of
Facundo Batista5dfc4802008-01-08 16:20:31 +00004424 calculating integer division as described for divide-integer, rounded
4425 to precision digits if necessary. The sign of the result, if
4426 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004427
4428 This operation will fail under the same conditions as integer division
4429 (that is, if integer division on the same two operands would fail, the
4430 remainder cannot be calculated).
4431
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004432 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004433 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004434 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004435 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004436 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004437 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004438 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004439 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004440 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004441 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004442 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004443 Decimal("1.0")
4444 """
4445 return a.__mod__(b, context=self)
4446
4447 def remainder_near(self, a, b):
4448 """Returns to be "a - b * n", where n is the integer nearest the exact
4449 value of "x / b" (if two integers are equally near then the even one
Facundo Batista5dfc4802008-01-08 16:20:31 +00004450 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004451 sign of a.
4452
4453 This operation will fail under the same conditions as integer division
4454 (that is, if integer division on the same two operands would fail, the
4455 remainder cannot be calculated).
4456
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004457 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004458 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004459 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004460 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004461 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004462 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004463 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004464 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004465 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004466 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004467 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004468 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004469 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004470 Decimal("-0.3")
4471 """
4472 return a.remainder_near(b, context=self)
4473
Facundo Batista5dfc4802008-01-08 16:20:31 +00004474 def rotate(self, a, b):
4475 """Returns a rotated copy of a, b times.
4476
4477 The coefficient of the result is a rotated copy of the digits in
4478 the coefficient of the first operand. The number of places of
4479 rotation is taken from the absolute value of the second operand,
4480 with the rotation being to the left if the second operand is
4481 positive or to the right otherwise.
4482
4483 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4484 Decimal("400000003")
4485 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4486 Decimal("12")
4487 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4488 Decimal("891234567")
4489 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4490 Decimal("123456789")
4491 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4492 Decimal("345678912")
4493 """
4494 return a.rotate(b, context=self)
4495
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004496 def same_quantum(self, a, b):
4497 """Returns True if the two operands have the same exponent.
4498
4499 The result is never affected by either the sign or the coefficient of
4500 either operand.
4501
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004502 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004503 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004504 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004505 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004506 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004507 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004508 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004509 True
4510 """
4511 return a.same_quantum(b)
4512
Facundo Batista5dfc4802008-01-08 16:20:31 +00004513 def scaleb (self, a, b):
4514 """Returns the first operand after adding the second value its exp.
4515
4516 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4517 Decimal("0.0750")
4518 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4519 Decimal("7.50")
4520 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4521 Decimal("7.50E+3")
4522 """
4523 return a.scaleb (b, context=self)
4524
4525 def shift(self, a, b):
4526 """Returns a shifted copy of a, b times.
4527
4528 The coefficient of the result is a shifted copy of the digits
4529 in the coefficient of the first operand. The number of places
4530 to shift is taken from the absolute value of the second operand,
4531 with the shift being to the left if the second operand is
4532 positive or to the right otherwise. Digits shifted into the
4533 coefficient are zeros.
4534
4535 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4536 Decimal("400000000")
4537 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4538 Decimal("0")
4539 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4540 Decimal("1234567")
4541 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4542 Decimal("123456789")
4543 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4544 Decimal("345678900")
4545 """
4546 return a.shift(b, context=self)
4547
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004548 def sqrt(self, a):
Facundo Batista5dfc4802008-01-08 16:20:31 +00004549 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004550
4551 If the result must be inexact, it is rounded using the round-half-even
4552 algorithm.
4553
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004554 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004555 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004556 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004557 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004558 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004559 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004560 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004561 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004562 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004563 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004564 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004565 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004566 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004567 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004568 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004569 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004570 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004571 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004572 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004573 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004574 """
4575 return a.sqrt(context=self)
4576
4577 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004578 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004579
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004580 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004581 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004582 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004583 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004584 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004585 Decimal("-0.77")
4586 """
4587 return a.__sub__(b, context=self)
4588
4589 def to_eng_string(self, a):
4590 """Converts a number to a string, using scientific notation.
4591
4592 The operation is not affected by the context.
4593 """
4594 return a.to_eng_string(context=self)
4595
4596 def to_sci_string(self, a):
4597 """Converts a number to a string, using scientific notation.
4598
4599 The operation is not affected by the context.
4600 """
4601 return a.__str__(context=self)
4602
Facundo Batista5dfc4802008-01-08 16:20:31 +00004603 def to_integral_exact(self, a):
4604 """Rounds to an integer.
4605
4606 When the operand has a negative exponent, the result is the same
4607 as using the quantize() operation using the given operand as the
4608 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4609 of the operand as the precision setting; Inexact and Rounded flags
4610 are allowed in this operation. The rounding mode is taken from the
4611 context.
4612
4613 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4614 Decimal("2")
4615 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4616 Decimal("100")
4617 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4618 Decimal("100")
4619 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4620 Decimal("102")
4621 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4622 Decimal("-102")
4623 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4624 Decimal("1.0E+6")
4625 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4626 Decimal("7.89E+77")
4627 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4628 Decimal("-Infinity")
4629 """
4630 return a.to_integral_exact(context=self)
4631
4632 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004633 """Rounds to an integer.
4634
4635 When the operand has a negative exponent, the result is the same
4636 as using the quantize() operation using the given operand as the
4637 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4638 of the operand as the precision setting, except that no flags will
Facundo Batista5dfc4802008-01-08 16:20:31 +00004639 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004640
Facundo Batista5dfc4802008-01-08 16:20:31 +00004641 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004642 Decimal("2")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004643 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004644 Decimal("100")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004645 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004646 Decimal("100")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004647 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648 Decimal("102")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004649 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004650 Decimal("-102")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004651 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004652 Decimal("1.0E+6")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004653 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004654 Decimal("7.89E+77")
Facundo Batista5dfc4802008-01-08 16:20:31 +00004655 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004656 Decimal("-Infinity")
4657 """
Facundo Batista5dfc4802008-01-08 16:20:31 +00004658 return a.to_integral_value(context=self)
4659
4660 # the method name changed, but we provide also the old one, for compatibility
4661 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004662
4663class _WorkRep(object):
4664 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004665 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004666 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 # exp: None, int, or string
4668
4669 def __init__(self, value=None):
4670 if value is None:
4671 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004672 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004673 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004674 elif isinstance(value, Decimal):
4675 self.sign = value._sign
Facundo Batista5dfc4802008-01-08 16:20:31 +00004676 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004677 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004678 else:
4679 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004680 self.sign = value[0]
4681 self.int = value[1]
4682 self.exp = value[2]
4683
4684 def __repr__(self):
4685 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4686
4687 __str__ = __repr__
4688
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004689
4690
Facundo Batista5dfc4802008-01-08 16:20:31 +00004691def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004692 """Normalizes op1, op2 to have the same exp and length of coefficient.
4693
4694 Done during addition.
4695 """
Facundo Batista5dfc4802008-01-08 16:20:31 +00004696 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004697 tmp = op2
4698 other = op1
4699 else:
4700 tmp = op1
4701 other = op2
4702
Facundo Batista5dfc4802008-01-08 16:20:31 +00004703 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4704 # Then adding 10**exp to tmp has the same effect (after rounding)
4705 # as adding any positive quantity smaller than 10**exp; similarly
4706 # for subtraction. So if other is smaller than 10**exp we replace
4707 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4708 tmp_len = len(str(tmp.int))
4709 other_len = len(str(other.int))
4710 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4711 if other_len + other.exp - 1 < exp:
4712 other.int = 1
4713 other.exp = exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004714
Facundo Batista5dfc4802008-01-08 16:20:31 +00004715 tmp.int *= 10 ** (tmp.exp - other.exp)
4716 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004717 return op1, op2
4718
Facundo Batista5dfc4802008-01-08 16:20:31 +00004719##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004720
Facundo Batista5dfc4802008-01-08 16:20:31 +00004721# This function from Tim Peters was taken from here:
4722# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4723# The correction being in the function definition is for speed, and
4724# the whole function is not resolved with math.log because of avoiding
4725# the use of floats.
4726def _nbits(n, correction = {
4727 '0': 4, '1': 3, '2': 2, '3': 2,
4728 '4': 1, '5': 1, '6': 1, '7': 1,
4729 '8': 0, '9': 0, 'a': 0, 'b': 0,
4730 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4731 """Number of bits in binary representation of the positive integer n,
4732 or 0 if n == 0.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004733 """
Facundo Batista5dfc4802008-01-08 16:20:31 +00004734 if n < 0:
4735 raise ValueError("The argument to _nbits should be nonnegative.")
4736 hex_n = "%x" % n
4737 return 4*len(hex_n) - correction[hex_n[0]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004738
Facundo Batista5dfc4802008-01-08 16:20:31 +00004739def _sqrt_nearest(n, a):
4740 """Closest integer to the square root of the positive integer n. a is
4741 an initial approximation to the square root. Any positive integer
4742 will do for a, but the closer a is to the square root of n the
4743 faster convergence will be.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004744
Facundo Batista5dfc4802008-01-08 16:20:31 +00004745 """
4746 if n <= 0 or a <= 0:
4747 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004748
Facundo Batista5dfc4802008-01-08 16:20:31 +00004749 b=0
4750 while a != b:
4751 b, a = a, a--n//a>>1
4752 return a
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004753
Facundo Batista5dfc4802008-01-08 16:20:31 +00004754def _rshift_nearest(x, shift):
4755 """Given an integer x and a nonnegative integer shift, return closest
4756 integer to x / 2**shift; use round-to-even in case of a tie.
4757
4758 """
4759 b, q = 1L << shift, x >> shift
4760 return q + (2*(x & (b-1)) + (q&1) > b)
4761
4762def _div_nearest(a, b):
4763 """Closest integer to a/b, a and b positive integers; rounds to even
4764 in the case of a tie.
4765
4766 """
4767 q, r = divmod(a, b)
4768 return q + (2*r + (q&1) > b)
4769
4770def _ilog(x, M, L = 8):
4771 """Integer approximation to M*log(x/M), with absolute error boundable
4772 in terms only of x/M.
4773
4774 Given positive integers x and M, return an integer approximation to
4775 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4776 between the approximation and the exact result is at most 22. For
4777 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4778 both cases these are upper bounds on the error; it will usually be
4779 much smaller."""
4780
4781 # The basic algorithm is the following: let log1p be the function
4782 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4783 # the reduction
4784 #
4785 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4786 #
4787 # repeatedly until the argument to log1p is small (< 2**-L in
4788 # absolute value). For small y we can use the Taylor series
4789 # expansion
4790 #
4791 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4792 #
4793 # truncating at T such that y**T is small enough. The whole
4794 # computation is carried out in a form of fixed-point arithmetic,
4795 # with a real number z being represented by an integer
4796 # approximation to z*M. To avoid loss of precision, the y below
4797 # is actually an integer approximation to 2**R*y*M, where R is the
4798 # number of reductions performed so far.
4799
4800 y = x-M
4801 # argument reduction; R = number of reductions performed
4802 R = 0
4803 while (R <= L and long(abs(y)) << L-R >= M or
4804 R > L and abs(y) >> R-L >= M):
4805 y = _div_nearest(long(M*y) << 1,
4806 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4807 R += 1
4808
4809 # Taylor series with T terms
4810 T = -int(-10*len(str(M))//(3*L))
4811 yshift = _rshift_nearest(y, R)
4812 w = _div_nearest(M, T)
4813 for k in xrange(T-1, 0, -1):
4814 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4815
4816 return _div_nearest(w*y, M)
4817
4818def _dlog10(c, e, p):
4819 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4820 approximation to 10**p * log10(c*10**e), with an absolute error of
4821 at most 1. Assumes that c*10**e is not exactly 1."""
4822
4823 # increase precision by 2; compensate for this by dividing
4824 # final result by 100
4825 p += 2
4826
4827 # write c*10**e as d*10**f with either:
4828 # f >= 0 and 1 <= d <= 10, or
4829 # f <= 0 and 0.1 <= d <= 1.
4830 # Thus for c*10**e close to 1, f = 0
4831 l = len(str(c))
4832 f = e+l - (e+l >= 1)
4833
4834 if p > 0:
4835 M = 10**p
4836 k = e+p-f
4837 if k >= 0:
4838 c *= 10**k
4839 else:
4840 c = _div_nearest(c, 10**-k)
4841
4842 log_d = _ilog(c, M) # error < 5 + 22 = 27
4843 log_10 = _log10_digits(p) # error < 1
4844 log_d = _div_nearest(log_d*M, log_10)
4845 log_tenpower = f*M # exact
4846 else:
4847 log_d = 0 # error < 2.31
4848 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4849
4850 return _div_nearest(log_tenpower+log_d, 100)
4851
4852def _dlog(c, e, p):
4853 """Given integers c, e and p with c > 0, compute an integer
4854 approximation to 10**p * log(c*10**e), with an absolute error of
4855 at most 1. Assumes that c*10**e is not exactly 1."""
4856
4857 # Increase precision by 2. The precision increase is compensated
4858 # for at the end with a division by 100.
4859 p += 2
4860
4861 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4862 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4863 # as 10**p * log(d) + 10**p*f * log(10).
4864 l = len(str(c))
4865 f = e+l - (e+l >= 1)
4866
4867 # compute approximation to 10**p*log(d), with error < 27
4868 if p > 0:
4869 k = e+p-f
4870 if k >= 0:
4871 c *= 10**k
4872 else:
4873 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4874
4875 # _ilog magnifies existing error in c by a factor of at most 10
4876 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4877 else:
4878 # p <= 0: just approximate the whole thing by 0; error < 2.31
4879 log_d = 0
4880
4881 # compute approximation to f*10**p*log(10), with error < 11.
4882 if f:
4883 extra = len(str(abs(f)))-1
4884 if p + extra >= 0:
4885 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4886 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4887 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
4888 else:
4889 f_log_ten = 0
4890 else:
4891 f_log_ten = 0
4892
4893 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
4894 return _div_nearest(f_log_ten + log_d, 100)
4895
4896class _Log10Memoize(object):
4897 """Class to compute, store, and allow retrieval of, digits of the
4898 constant log(10) = 2.302585.... This constant is needed by
4899 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4900 def __init__(self):
4901 self.digits = "23025850929940456840179914546843642076011014886"
4902
4903 def getdigits(self, p):
4904 """Given an integer p >= 0, return floor(10**p)*log(10).
4905
4906 For example, self.getdigits(3) returns 2302.
4907 """
4908 # digits are stored as a string, for quick conversion to
4909 # integer in the case that we've already computed enough
4910 # digits; the stored digits should always be correct
4911 # (truncated, not rounded to nearest).
4912 if p < 0:
4913 raise ValueError("p should be nonnegative")
4914
4915 if p >= len(self.digits):
4916 # compute p+3, p+6, p+9, ... digits; continue until at
4917 # least one of the extra digits is nonzero
4918 extra = 3
4919 while True:
4920 # compute p+extra digits, correct to within 1ulp
4921 M = 10**(p+extra+2)
4922 digits = str(_div_nearest(_ilog(10*M, M), 100))
4923 if digits[-extra:] != '0'*extra:
4924 break
4925 extra += 3
4926 # keep all reliable digits so far; remove trailing zeros
4927 # and next nonzero digit
4928 self.digits = digits.rstrip('0')[:-1]
4929 return int(self.digits[:p+1])
4930
4931_log10_digits = _Log10Memoize().getdigits
4932
4933def _iexp(x, M, L=8):
4934 """Given integers x and M, M > 0, such that x/M is small in absolute
4935 value, compute an integer approximation to M*exp(x/M). For 0 <=
4936 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4937 is usually much smaller)."""
4938
4939 # Algorithm: to compute exp(z) for a real number z, first divide z
4940 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4941 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4942 # series
4943 #
4944 # expm1(x) = x + x**2/2! + x**3/3! + ...
4945 #
4946 # Now use the identity
4947 #
4948 # expm1(2x) = expm1(x)*(expm1(x)+2)
4949 #
4950 # R times to compute the sequence expm1(z/2**R),
4951 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4952
4953 # Find R such that x/2**R/M <= 2**-L
4954 R = _nbits((long(x)<<L)//M)
4955
4956 # Taylor series. (2**L)**T > M
4957 T = -int(-10*len(str(M))//(3*L))
4958 y = _div_nearest(x, T)
4959 Mshift = long(M)<<R
4960 for i in xrange(T-1, 0, -1):
4961 y = _div_nearest(x*(Mshift + y), Mshift * i)
4962
4963 # Expansion
4964 for k in xrange(R-1, -1, -1):
4965 Mshift = long(M)<<(k+2)
4966 y = _div_nearest(y*(y+Mshift), Mshift)
4967
4968 return M+y
4969
4970def _dexp(c, e, p):
4971 """Compute an approximation to exp(c*10**e), with p decimal places of
4972 precision.
4973
4974 Returns integers d, f such that:
4975
4976 10**(p-1) <= d <= 10**p, and
4977 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
4978
4979 In other words, d*10**f is an approximation to exp(c*10**e) with p
4980 digits of precision, and with an error in d of at most 1. This is
4981 almost, but not quite, the same as the error being < 1ulp: when d
4982 = 10**(p-1) the error could be up to 10 ulp."""
4983
4984 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
4985 p += 2
4986
4987 # compute log(10) with extra precision = adjusted exponent of c*10**e
4988 extra = max(0, e + len(str(c)) - 1)
4989 q = p + extra
4990
4991 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
4992 # rounding down
4993 shift = e+q
4994 if shift >= 0:
4995 cshift = c*10**shift
4996 else:
4997 cshift = c//10**-shift
4998 quot, rem = divmod(cshift, _log10_digits(q))
4999
5000 # reduce remainder back to original precision
5001 rem = _div_nearest(rem, 10**extra)
5002
5003 # error in result of _iexp < 120; error after division < 0.62
5004 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5005
5006def _dpower(xc, xe, yc, ye, p):
5007 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5008 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5009
5010 10**(p-1) <= c <= 10**p, and
5011 (c-1)*10**e < x**y < (c+1)*10**e
5012
5013 in other words, c*10**e is an approximation to x**y with p digits
5014 of precision, and with an error in c of at most 1. (This is
5015 almost, but not quite, the same as the error being < 1ulp: when c
5016 == 10**(p-1) we can only guarantee error < 10ulp.)
5017
5018 We assume that: x is positive and not equal to 1, and y is nonzero.
5019 """
5020
5021 # Find b such that 10**(b-1) <= |y| <= 10**b
5022 b = len(str(abs(yc))) + ye
5023
5024 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5025 lxc = _dlog(xc, xe, p+b+1)
5026
5027 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5028 shift = ye-b
5029 if shift >= 0:
5030 pc = lxc*yc*10**shift
5031 else:
5032 pc = _div_nearest(lxc*yc, 10**-shift)
5033
5034 if pc == 0:
5035 # we prefer a result that isn't exactly 1; this makes it
5036 # easier to compute a correctly rounded result in __pow__
5037 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5038 coeff, exp = 10**(p-1)+1, 1-p
5039 else:
5040 coeff, exp = 10**p-1, -p
5041 else:
5042 coeff, exp = _dexp(pc, -(p+1), p+1)
5043 coeff = _div_nearest(coeff, 10)
5044 exp += 1
5045
5046 return coeff, exp
5047
5048def _log10_lb(c, correction = {
5049 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5050 '6': 23, '7': 16, '8': 10, '9': 5}):
5051 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5052 if c <= 0:
5053 raise ValueError("The argument to _log10_lb should be nonnegative.")
5054 str_c = str(c)
5055 return 100*len(str_c) - correction[str_c[0]]
5056
5057##### Helper Functions ####################################################
5058
5059def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005060 """Convert other to Decimal.
5061
5062 Verifies that it's ok to use in an implicit construction.
5063 """
5064 if isinstance(other, Decimal):
5065 return other
5066 if isinstance(other, (int, long)):
5067 return Decimal(other)
Facundo Batista5dfc4802008-01-08 16:20:31 +00005068 if raiseit:
5069 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005070 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005071
Facundo Batista5dfc4802008-01-08 16:20:31 +00005072##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005073
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005074# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005075# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005076
5077DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005078 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005079 traps=[DivisionByZero, Overflow, InvalidOperation],
5080 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005081 Emax=999999999,
5082 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005083 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005084)
5085
5086# Pre-made alternate contexts offered by the specification
5087# Don't change these; the user should be able to select these
5088# contexts and be able to reproduce results from other implementations
5089# of the spec.
5090
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005091BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005092 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005093 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5094 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005095)
5096
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005097ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005098 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005099 traps=[],
5100 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005101)
5102
5103
Facundo Batista5dfc4802008-01-08 16:20:31 +00005104##### crud for parsing strings #############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005105import re
5106
Facundo Batista5dfc4802008-01-08 16:20:31 +00005107# Regular expression used for parsing numeric strings. Additional
5108# comments:
5109#
5110# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5111# whitespace. But note that the specification disallows whitespace in
5112# a numeric string.
5113#
5114# 2. For finite numbers (not infinities and NaNs) the body of the
5115# number between the optional sign and the optional exponent must have
5116# at least one decimal digit, possibly after the decimal point. The
5117# lookahead expression '(?=\d|\.\d)' checks this.
5118#
5119# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5120# other meaning for \d than the numbers [0-9].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005121
Facundo Batista5dfc4802008-01-08 16:20:31 +00005122import re
5123_parser = re.compile(r""" # A numeric string consists of:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005124# \s*
Facundo Batista5dfc4802008-01-08 16:20:31 +00005125 (?P<sign>[-+])? # an optional sign, followed by either...
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005126 (
Facundo Batista5dfc4802008-01-08 16:20:31 +00005127 (?=\d|\.\d) # ...a number (with at least one digit)
5128 (?P<int>\d*) # consisting of a (possibly empty) integer part
5129 (\.(?P<frac>\d*))? # followed by an optional fractional part
5130 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005131 |
Facundo Batista5dfc4802008-01-08 16:20:31 +00005132 Inf(inity)? # ...an infinity, or...
5133 |
5134 (?P<signal>s)? # ...an (optionally signaling)
5135 NaN # NaN
5136 (?P<diag>\d*) # with (possibly empty) diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005137 )
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005138# \s*
5139 $
Facundo Batista5dfc4802008-01-08 16:20:31 +00005140""", re.VERBOSE | re.IGNORECASE).match
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005141
Facundo Batista5dfc4802008-01-08 16:20:31 +00005142_all_zeros = re.compile('0*$').match
5143_exact_half = re.compile('50*$').match
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005144del re
5145
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005146
Facundo Batista5dfc4802008-01-08 16:20:31 +00005147##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005148
Facundo Batista5dfc4802008-01-08 16:20:31 +00005149# Reusable defaults
5150Inf = Decimal('Inf')
5151negInf = Decimal('-Inf')
5152NaN = Decimal('NaN')
5153Dec_0 = Decimal(0)
5154Dec_p1 = Decimal(1)
5155Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005156
Facundo Batista5dfc4802008-01-08 16:20:31 +00005157# Infsign[sign] is infinity w/ that sign
5158Infsign = (Inf, negInf)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005159
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005160
5161
5162if __name__ == '__main__':
5163 import doctest, sys
5164 doctest.testmod(sys.modules[__name__])