blob: 882c3a24c68ab33752396cb505752832040fe248 [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 Batista59c58842007-04-10 12:58:45 +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 Batista353750c2007-09-13 18:13:15 +0000131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000132
133 # Functions for manipulating contexts
Nick Coghlan8b6999b2006-08-31 12:00:43 +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 Batista59c58842007-04-10 12:58:45 +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 Batista353750c2007-09-13 18:13:15 +0000147ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000148
Facundo Batista59c58842007-04-10 12:58:45 +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 Batista59c58842007-04-10 12:58:45 +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
186
187class InvalidOperation(DecimalException):
188 """An invalid operation was performed.
189
190 Various bad things cause this:
191
192 Something creates a signaling NaN
193 -INF + INF
Facundo Batista59c58842007-04-10 12:58:45 +0000194 0 * (+-)INF
195 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000196 x % 0
197 (+-)INF % x
198 x._rescale( non-integer )
199 sqrt(-x) , x > 0
200 0 ** 0
201 x ** (non-integer)
202 x ** (+-)INF
203 An operand is invalid
Facundo Batista353750c2007-09-13 18:13:15 +0000204
205 The result of the operation after these is a quiet positive NaN,
206 except when the cause is a signaling NaN, in which case the result is
207 also a quiet NaN, but with the original sign, and an optional
208 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000209 """
210 def handle(self, context, *args):
211 if args:
Facundo Batista59c58842007-04-10 12:58:45 +0000212 if args[0] == 1: # sNaN, must drop 's' but keep diagnostics
Facundo Batista72bc54f2007-11-23 17:59:00 +0000213 ans = _dec_from_triple(args[1]._sign, args[1]._int, 'n', True)
Facundo Batista353750c2007-09-13 18:13:15 +0000214 return ans._fix_nan(context)
215 elif args[0] == 2:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000216 return _dec_from_triple(args[1], args[2], 'n', True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000217 return NaN
218
Facundo Batista353750c2007-09-13 18:13:15 +0000219
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000220class ConversionSyntax(InvalidOperation):
221 """Trying to convert badly formed string.
222
223 This occurs and signals invalid-operation if an string is being
224 converted to a number and it does not conform to the numeric string
Facundo Batista59c58842007-04-10 12:58:45 +0000225 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000226 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000227 def handle(self, context, *args):
Facundo Batista353750c2007-09-13 18:13:15 +0000228 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000229
230class DivisionByZero(DecimalException, ZeroDivisionError):
231 """Division by 0.
232
233 This occurs and signals division-by-zero if division of a finite number
234 by zero was attempted (during a divide-integer or divide operation, or a
235 power operation with negative right-hand operand), and the dividend was
236 not zero.
237
238 The result of the operation is [sign,inf], where sign is the exclusive
239 or of the signs of the operands for divide, or is 1 for an odd power of
240 -0, for power.
241 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000242
Facundo Batistacce8df22007-09-18 16:53:18 +0000243 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000244 return Infsign[sign]
245
246class DivisionImpossible(InvalidOperation):
247 """Cannot perform the division adequately.
248
249 This occurs and signals invalid-operation if the integer result of a
250 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000251 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000252 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000253
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000254 def handle(self, context, *args):
Facundo Batistacce8df22007-09-18 16:53:18 +0000255 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000256
257class DivisionUndefined(InvalidOperation, ZeroDivisionError):
258 """Undefined result of division.
259
260 This occurs and signals invalid-operation if division by zero was
261 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000262 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000263 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000264
Facundo Batistacce8df22007-09-18 16:53:18 +0000265 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000266 return NaN
267
268class Inexact(DecimalException):
269 """Had to round, losing information.
270
271 This occurs and signals inexact whenever the result of an operation is
272 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000273 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000274 result in all cases is unchanged.
275
276 The inexact signal may be tested (or trapped) to determine if a given
277 operation (or sequence of operations) was inexact.
278 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000279 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000280
281class InvalidContext(InvalidOperation):
282 """Invalid context. Unknown rounding, for example.
283
284 This occurs and signals invalid-operation if an invalid context was
Facundo Batista59c58842007-04-10 12:58:45 +0000285 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000286 on creation and either the precision exceeds the capability of the
287 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista59c58842007-04-10 12:58:45 +0000288 was specified. These aspects of the context need only be checked when
289 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000290 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000291
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000292 def handle(self, context, *args):
293 return NaN
294
295class Rounded(DecimalException):
296 """Number got rounded (not necessarily changed during rounding).
297
298 This occurs and signals rounded whenever the result of an operation is
299 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista59c58842007-04-10 12:58:45 +0000300 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000301 result in all cases is unchanged.
302
303 The rounded signal may be tested (or trapped) to determine if a given
304 operation (or sequence of operations) caused a loss of precision.
305 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000306 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000307
308class Subnormal(DecimalException):
309 """Exponent < Emin before rounding.
310
311 This occurs and signals subnormal whenever the result of a conversion or
312 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000313 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000314
315 The subnormal signal may be tested (or trapped) to determine if a given
316 or operation (or sequence of operations) yielded a subnormal result.
317 """
318 pass
319
320class Overflow(Inexact, Rounded):
321 """Numerical overflow.
322
323 This occurs and signals overflow if the adjusted exponent of a result
324 (from a conversion or from an operation that is not an attempt to divide
325 by zero), after rounding, would be greater than the largest value that
326 can be handled by the implementation (the value Emax).
327
328 The result depends on the rounding mode:
329
330 For round-half-up and round-half-even (and for round-half-down and
331 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000332 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000333 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000334 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000335 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000336 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000338 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339 will also be raised.
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000340 """
341
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000342 def handle(self, context, sign, *args):
343 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000344 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000345 return Infsign[sign]
346 if sign == 0:
347 if context.rounding == ROUND_CEILING:
348 return Infsign[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000349 return _dec_from_triple(sign, '9'*context.prec,
350 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000351 if sign == 1:
352 if context.rounding == ROUND_FLOOR:
353 return Infsign[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000354 return _dec_from_triple(sign, '9'*context.prec,
355 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000356
357
358class Underflow(Inexact, Rounded, Subnormal):
359 """Numerical underflow with result rounded to 0.
360
361 This occurs and signals underflow if a result is inexact and the
362 adjusted exponent of the result would be smaller (more negative) than
363 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000364 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000365
366 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000367 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000368 in 0 with the sign of the intermediate result and an exponent of Etiny.
369
370 In all cases, Inexact, Rounded, and Subnormal will also be raised.
371 """
372
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000373# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000374_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000375 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000376
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000377# Map conditions (per the spec) to signals
378_condition_map = {ConversionSyntax:InvalidOperation,
379 DivisionImpossible:InvalidOperation,
380 DivisionUndefined:InvalidOperation,
381 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000382
Facundo Batista59c58842007-04-10 12:58:45 +0000383##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000384
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000385# The getcontext() and setcontext() function manage access to a thread-local
386# current context. Py2.4 offers direct support for thread locals. If that
387# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000388# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000389# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000390
391try:
392 import threading
393except ImportError:
394 # Python was compiled without threads; create a mock object instead
395 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000396 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000397 def local(self, sys=sys):
398 return sys.modules[__name__]
399 threading = MockThreading()
400 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000401
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000402try:
403 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000404
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000405except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000406
Facundo Batista59c58842007-04-10 12:58:45 +0000407 # To fix reloading, force it to create a new context
408 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000409 if hasattr(threading.currentThread(), '__decimal_context__'):
410 del threading.currentThread().__decimal_context__
411
412 def setcontext(context):
413 """Set this thread's context to context."""
414 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000415 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000416 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000417 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000418
419 def getcontext():
420 """Returns this thread's context.
421
422 If this thread does not yet have a context, returns
423 a new context and sets this thread's context.
424 New contexts are copies of DefaultContext.
425 """
426 try:
427 return threading.currentThread().__decimal_context__
428 except AttributeError:
429 context = Context()
430 threading.currentThread().__decimal_context__ = context
431 return context
432
433else:
434
435 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000436 if hasattr(local, '__decimal_context__'):
437 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000438
439 def getcontext(_local=local):
440 """Returns this thread's context.
441
442 If this thread does not yet have a context, returns
443 a new context and sets this thread's context.
444 New contexts are copies of DefaultContext.
445 """
446 try:
447 return _local.__decimal_context__
448 except AttributeError:
449 context = Context()
450 _local.__decimal_context__ = context
451 return context
452
453 def setcontext(context, _local=local):
454 """Set this thread's context to context."""
455 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000456 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000457 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000458 _local.__decimal_context__ = context
459
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000460 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000461
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000462def localcontext(ctx=None):
463 """Return a context manager for a copy of the supplied context
464
465 Uses a copy of the current context if no context is specified
466 The returned context manager creates a local decimal context
467 in a with statement:
468 def sin(x):
469 with localcontext() as ctx:
470 ctx.prec += 2
471 # Rest of sin calculation algorithm
472 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000473 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000474
475 def sin(x):
476 with localcontext(ExtendedContext):
477 # Rest of sin calculation algorithm
478 # uses the Extended Context from the
479 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000480 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000481
482 """
Neal Norwitz681d8672006-09-02 18:51:34 +0000483 # The string below can't be included in the docstring until Python 2.6
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000484 # as the doctest module doesn't understand __future__ statements
485 """
486 >>> from __future__ import with_statement
487 >>> print getcontext().prec
488 28
489 >>> with localcontext():
490 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000491 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000492 ... print ctx.prec
493 ...
494 30
495 >>> with localcontext(ExtendedContext):
496 ... print getcontext().prec
497 ...
498 9
499 >>> print getcontext().prec
500 28
501 """
Nick Coghlanced12182006-09-02 03:54:17 +0000502 if ctx is None: ctx = getcontext()
503 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000504
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000505
Facundo Batista59c58842007-04-10 12:58:45 +0000506##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000507
508class Decimal(object):
509 """Floating point class for decimal arithmetic."""
510
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000511 __slots__ = ('_exp','_int','_sign', '_is_special')
512 # Generally, the value of the Decimal instance is given by
513 # (-1)**_sign * _int * 10**_exp
514 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000515
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000516 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000517 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000518 """Create a decimal point instance.
519
520 >>> Decimal('3.14') # string input
521 Decimal("3.14")
Facundo Batista59c58842007-04-10 12:58:45 +0000522 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000523 Decimal("3.14")
524 >>> Decimal(314) # int or long
525 Decimal("314")
526 >>> Decimal(Decimal(314)) # another decimal instance
527 Decimal("314")
528 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529
Facundo Batista72bc54f2007-11-23 17:59:00 +0000530 # Note that the coefficient, self._int, is actually stored as
531 # a string rather than as a tuple of digits. This speeds up
532 # the "digits to integer" and "integer to digits" conversions
533 # that are used in almost every arithmetic operation on
534 # Decimals. This is an internal detail: the as_tuple function
535 # and the Decimal constructor still deal with tuples of
536 # digits.
537
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000538 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000539
Facundo Batista0d157a02007-11-30 17:15:25 +0000540 # From a string
541 # REs insist on real strings, so we can too.
542 if isinstance(value, basestring):
543 m = _parser(value)
544 if m is None:
545 if context is None:
546 context = getcontext()
547 return context._raise_error(ConversionSyntax,
548 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000549
Facundo Batista0d157a02007-11-30 17:15:25 +0000550 if m.group('sign') == "-":
551 self._sign = 1
552 else:
553 self._sign = 0
554 intpart = m.group('int')
555 if intpart is not None:
556 # finite number
557 fracpart = m.group('frac')
558 exp = int(m.group('exp') or '0')
559 if fracpart is not None:
560 self._int = (intpart+fracpart).lstrip('0') or '0'
561 self._exp = exp - len(fracpart)
562 else:
563 self._int = intpart.lstrip('0') or '0'
564 self._exp = exp
565 self._is_special = False
566 else:
567 diag = m.group('diag')
568 if diag is not None:
569 # NaN
570 self._int = diag.lstrip('0')
571 if m.group('signal'):
572 self._exp = 'N'
573 else:
574 self._exp = 'n'
575 else:
576 # infinity
577 self._int = '0'
578 self._exp = 'F'
579 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580 return self
581
582 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000583 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000584 if value >= 0:
585 self._sign = 0
586 else:
587 self._sign = 1
588 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000589 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000590 self._is_special = False
591 return self
592
593 # From another decimal
594 if isinstance(value, Decimal):
595 self._exp = value._exp
596 self._sign = value._sign
597 self._int = value._int
598 self._is_special = value._is_special
599 return self
600
601 # From an internal working value
602 if isinstance(value, _WorkRep):
603 self._sign = value.sign
604 self._int = str(value.int)
605 self._exp = int(value.exp)
606 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000607 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000608
609 # tuple/list conversion (possibly from as_tuple())
610 if isinstance(value, (list,tuple)):
611 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000612 raise ValueError('Invalid tuple size in creation of Decimal '
613 'from list or tuple. The list or tuple '
614 'should have exactly three elements.')
615 # process sign. The isinstance test rejects floats
616 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
617 raise ValueError("Invalid sign. The first value in the tuple "
618 "should be an integer; either 0 for a "
619 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000620 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000621 if value[2] == 'F':
622 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000623 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000625 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000626 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000627 # process and validate the digits in value[1]
628 digits = []
629 for digit in value[1]:
630 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
631 # skip leading zeros
632 if digits or digit != 0:
633 digits.append(digit)
634 else:
635 raise ValueError("The second value in the tuple must "
636 "be composed of integers in the range "
637 "0 through 9.")
638 if value[2] in ('n', 'N'):
639 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000640 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000641 self._exp = value[2]
642 self._is_special = True
643 elif isinstance(value[2], (int, long)):
644 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000645 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000646 self._exp = value[2]
647 self._is_special = False
648 else:
649 raise ValueError("The third value in the tuple must "
650 "be an integer, or one of the "
651 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000652 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000653
Raymond Hettingerbf440692004-07-10 14:14:37 +0000654 if isinstance(value, float):
655 raise TypeError("Cannot convert float to Decimal. " +
656 "First convert the float to a string")
657
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000658 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000659
660 def _isnan(self):
661 """Returns whether the number is not actually one.
662
663 0 if a number
Facundo Batista353750c2007-09-13 18:13:15 +0000664 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000665 2 if sNaN
666 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000667 if self._is_special:
668 exp = self._exp
669 if exp == 'n':
670 return 1
671 elif exp == 'N':
672 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000673 return 0
674
675 def _isinfinity(self):
676 """Returns whether the number is infinite
677
678 0 if finite or not a number
679 1 if +INF
680 -1 if -INF
681 """
682 if self._exp == 'F':
683 if self._sign:
684 return -1
685 return 1
686 return 0
687
Facundo Batista353750c2007-09-13 18:13:15 +0000688 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000689 """Returns whether the number is not actually one.
690
691 if self, other are sNaN, signal
692 if self, other are NaN return nan
693 return 0
694
695 Done before operations.
696 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000697
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000698 self_is_nan = self._isnan()
699 if other is None:
700 other_is_nan = False
701 else:
702 other_is_nan = other._isnan()
703
704 if self_is_nan or other_is_nan:
705 if context is None:
706 context = getcontext()
707
708 if self_is_nan == 2:
709 return context._raise_error(InvalidOperation, 'sNaN',
710 1, self)
711 if other_is_nan == 2:
712 return context._raise_error(InvalidOperation, 'sNaN',
713 1, other)
714 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000715 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000716
Facundo Batista353750c2007-09-13 18:13:15 +0000717 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000718 return 0
719
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000720 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000721 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000722
Facundo Batista1a191df2007-10-02 17:01:24 +0000723 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000724 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000725 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000726
Facundo Batista353750c2007-09-13 18:13:15 +0000727 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000728 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000729 if other is NotImplemented:
Facundo Batista353750c2007-09-13 18:13:15 +0000730 # Never return NotImplemented
731 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000732
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000733 if self._is_special or other._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +0000734 # check for nans, without raising on a signaling nan
735 if self._isnan() or other._isnan():
Facundo Batista59c58842007-04-10 12:58:45 +0000736 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000737
738 # INF = INF
739 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000740
Facundo Batista353750c2007-09-13 18:13:15 +0000741 # check for zeros; note that cmp(0, -0) should return 0
742 if not self:
743 if not other:
744 return 0
745 else:
746 return -((-1)**other._sign)
747 if not other:
748 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000749
Facundo Batista59c58842007-04-10 12:58:45 +0000750 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000751 if other._sign < self._sign:
752 return -1
753 if self._sign < other._sign:
754 return 1
755
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000756 self_adjusted = self.adjusted()
757 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000758 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000759 self_padded = self._int + '0'*(self._exp - other._exp)
760 other_padded = other._int + '0'*(other._exp - self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +0000761 return cmp(self_padded, other_padded) * (-1)**self._sign
762 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000763 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000764 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000765 return -((-1)**self._sign)
766
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000767 def __eq__(self, other):
768 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000769 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000770 return self.__cmp__(other) == 0
771
772 def __ne__(self, other):
773 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000774 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000775 return self.__cmp__(other) != 0
776
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000777 def compare(self, other, context=None):
778 """Compares one to another.
779
780 -1 => a < b
781 0 => a = b
782 1 => a > b
783 NaN => one is NaN
784 Like __cmp__, but returns Decimal instances.
785 """
Facundo Batista353750c2007-09-13 18:13:15 +0000786 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000787
Facundo Batista59c58842007-04-10 12:58:45 +0000788 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000789 if (self._is_special or other and other._is_special):
790 ans = self._check_nans(other, context)
791 if ans:
792 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000793
Facundo Batista353750c2007-09-13 18:13:15 +0000794 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000795
796 def __hash__(self):
797 """x.__hash__() <==> hash(x)"""
798 # Decimal integers must hash the same as the ints
799 # Non-integer decimals are normalized and hashed as strings
Georg Brandl1fb9f522006-05-11 19:57:09 +0000800 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000801 if self._is_special:
802 if self._isnan():
803 raise TypeError('Cannot hash a NaN value.')
804 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000805 if not self:
806 return 0
807 if self._isinteger():
808 op = _WorkRep(self.to_integral_value())
809 # to make computation feasible for Decimals with large
810 # exponent, we use the fact that hash(n) == hash(m) for
811 # any two nonzero integers n and m such that (i) n and m
812 # have the same sign, and (ii) n is congruent to m modulo
813 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
814 # hash((-1)**s*c*pow(10, e, 2**64-1).
815 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000816 return hash(str(self.normalize()))
817
818 def as_tuple(self):
819 """Represents the number as a triple tuple.
820
821 To show the internals exactly as they are.
822 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000823 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000824
825 def __repr__(self):
826 """Represents the number as an instance of Decimal."""
827 # Invariant: eval(repr(d)) == d
828 return 'Decimal("%s")' % str(self)
829
Facundo Batista353750c2007-09-13 18:13:15 +0000830 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000831 """Return string representation of the number in scientific notation.
832
833 Captures all of the information in the underlying representation.
834 """
835
Facundo Batista62edb712007-12-03 16:29:52 +0000836 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000837 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000838 if self._exp == 'F':
839 return sign + 'Infinity'
840 elif self._exp == 'n':
841 return sign + 'NaN' + self._int
842 else: # self._exp == 'N'
843 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000844
Facundo Batista62edb712007-12-03 16:29:52 +0000845 # number of digits of self._int to left of decimal point
846 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000847
Facundo Batista62edb712007-12-03 16:29:52 +0000848 # dotplace is number of digits of self._int to the left of the
849 # decimal point in the mantissa of the output string (that is,
850 # after adjusting the exponent)
851 if self._exp <= 0 and leftdigits > -6:
852 # no exponent required
853 dotplace = leftdigits
854 elif not eng:
855 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000856 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000857 elif self._int == '0':
858 # engineering notation, zero
859 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000860 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000861 # engineering notation, nonzero
862 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000863
Facundo Batista62edb712007-12-03 16:29:52 +0000864 if dotplace <= 0:
865 intpart = '0'
866 fracpart = '.' + '0'*(-dotplace) + self._int
867 elif dotplace >= len(self._int):
868 intpart = self._int+'0'*(dotplace-len(self._int))
869 fracpart = ''
870 else:
871 intpart = self._int[:dotplace]
872 fracpart = '.' + self._int[dotplace:]
873 if leftdigits == dotplace:
874 exp = ''
875 else:
876 if context is None:
877 context = getcontext()
878 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
879
880 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000881
882 def to_eng_string(self, context=None):
883 """Convert to engineering-type string.
884
885 Engineering notation has an exponent which is a multiple of 3, so there
886 are up to 3 digits left of the decimal place.
887
888 Same rules for when in exponential and when as a value as in __str__.
889 """
Facundo Batista353750c2007-09-13 18:13:15 +0000890 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000891
892 def __neg__(self, context=None):
893 """Returns a copy with the sign switched.
894
895 Rounds, if it has reason.
896 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000897 if self._is_special:
898 ans = self._check_nans(context=context)
899 if ans:
900 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000901
902 if not self:
903 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000904 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000905 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000906 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000907
908 if context is None:
909 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +0000910 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000911
912 def __pos__(self, context=None):
913 """Returns a copy, unless it is a sNaN.
914
915 Rounds the number (if more then precision digits)
916 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000917 if self._is_special:
918 ans = self._check_nans(context=context)
919 if ans:
920 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000921
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000922 if not self:
923 # + (-0) = 0
Facundo Batista353750c2007-09-13 18:13:15 +0000924 ans = self.copy_sign(Dec_0)
925 else:
926 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000927
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000928 if context is None:
929 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +0000930 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000931
Facundo Batistae64acfa2007-12-17 14:18:42 +0000932 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000933 """Returns the absolute value of self.
934
Facundo Batistae64acfa2007-12-17 14:18:42 +0000935 If the keyword argument 'round' is false, do not round. The
936 expression self.__abs__(round=False) is equivalent to
937 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000938 """
Facundo Batistae64acfa2007-12-17 14:18:42 +0000939 if not round:
940 return self.copy_abs()
941
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000942 if self._is_special:
943 ans = self._check_nans(context=context)
944 if ans:
945 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000946
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000947 if self._sign:
948 ans = self.__neg__(context=context)
949 else:
950 ans = self.__pos__(context=context)
951
952 return ans
953
954 def __add__(self, other, context=None):
955 """Returns self + other.
956
957 -INF + INF (or the reverse) cause InvalidOperation errors.
958 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000959 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000960 if other is NotImplemented:
961 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000962
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000963 if context is None:
964 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000965
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000966 if self._is_special or other._is_special:
967 ans = self._check_nans(other, context)
968 if ans:
969 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000970
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000971 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000972 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000973 if self._sign != other._sign and other._isinfinity():
974 return context._raise_error(InvalidOperation, '-INF + INF')
975 return Decimal(self)
976 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000977 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000978
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000979 exp = min(self._exp, other._exp)
980 negativezero = 0
981 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +0000982 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000983 negativezero = 1
984
985 if not self and not other:
986 sign = min(self._sign, other._sign)
987 if negativezero:
988 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +0000989 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +0000990 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +0000991 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000992 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +0000993 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +0000994 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +0000995 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000996 return ans
997 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +0000998 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +0000999 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001000 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001001 return ans
1002
1003 op1 = _WorkRep(self)
1004 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001005 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001006
1007 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001008 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001010 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001011 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001012 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001013 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001014 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001015 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001016 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001017 if op1.sign == 1:
1018 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001019 op1.sign, op2.sign = op2.sign, op1.sign
1020 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001021 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001022 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001023 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001024 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001025 op1.sign, op2.sign = (0, 0)
1026 else:
1027 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001028 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001029
Raymond Hettinger17931de2004-10-27 06:21:46 +00001030 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001031 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001032 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001033 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034
1035 result.exp = op1.exp
1036 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001037 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001038 return ans
1039
1040 __radd__ = __add__
1041
1042 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001043 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001044 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001045 if other is NotImplemented:
1046 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001048 if self._is_special or other._is_special:
1049 ans = self._check_nans(other, context=context)
1050 if ans:
1051 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001052
Facundo Batista353750c2007-09-13 18:13:15 +00001053 # self - other is computed as self + other.copy_negate()
1054 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055
1056 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001057 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001058 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001059 if other is NotImplemented:
1060 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001061
Facundo Batista353750c2007-09-13 18:13:15 +00001062 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001063
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064 def __mul__(self, other, context=None):
1065 """Return self * other.
1066
1067 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1068 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001069 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001070 if other is NotImplemented:
1071 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001072
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073 if context is None:
1074 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001075
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001076 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001078 if self._is_special or other._is_special:
1079 ans = self._check_nans(other, context)
1080 if ans:
1081 return ans
1082
1083 if self._isinfinity():
1084 if not other:
1085 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1086 return Infsign[resultsign]
1087
1088 if other._isinfinity():
1089 if not self:
1090 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1091 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092
1093 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094
1095 # Special case for multiplying by zero
1096 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001097 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001098 # Fixing in case the exponent is out of bounds
1099 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100 return ans
1101
1102 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001103 if self._int == '1':
1104 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001105 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001106 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001107 if other._int == '1':
1108 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001109 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001110 return ans
1111
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001112 op1 = _WorkRep(self)
1113 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001114
Facundo Batista72bc54f2007-11-23 17:59:00 +00001115 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001116 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001117
1118 return ans
1119 __rmul__ = __mul__
1120
1121 def __div__(self, other, context=None):
1122 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001123 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001124 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001125 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001126
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001127 if context is None:
1128 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001130 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001131
1132 if self._is_special or other._is_special:
1133 ans = self._check_nans(other, context)
1134 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001135 return ans
1136
1137 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001139
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001141 return Infsign[sign]
1142
1143 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001144 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001145 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001146
1147 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001148 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001149 if not self:
1150 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001151 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001152
Facundo Batistacce8df22007-09-18 16:53:18 +00001153 if not self:
1154 exp = self._exp - other._exp
1155 coeff = 0
1156 else:
1157 # OK, so neither = 0, INF or NaN
1158 shift = len(other._int) - len(self._int) + context.prec + 1
1159 exp = self._exp - other._exp - shift
1160 op1 = _WorkRep(self)
1161 op2 = _WorkRep(other)
1162 if shift >= 0:
1163 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1164 else:
1165 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1166 if remainder:
1167 # result is not exact; adjust to ensure correct rounding
1168 if coeff % 5 == 0:
1169 coeff += 1
1170 else:
1171 # result is exact; get as close to ideal exponent as possible
1172 ideal_exp = self._exp - other._exp
1173 while exp < ideal_exp and coeff % 10 == 0:
1174 coeff //= 10
1175 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176
Facundo Batista72bc54f2007-11-23 17:59:00 +00001177 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001178 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001179
Facundo Batistacce8df22007-09-18 16:53:18 +00001180 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001181
Facundo Batistacce8df22007-09-18 16:53:18 +00001182 def _divide(self, other, context):
1183 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184
Facundo Batistacce8df22007-09-18 16:53:18 +00001185 Assumes that neither self nor other is a NaN, that self is not
1186 infinite and that other is nonzero.
1187 """
1188 sign = self._sign ^ other._sign
1189 if other._isinfinity():
1190 ideal_exp = self._exp
1191 else:
1192 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001193
Facundo Batistacce8df22007-09-18 16:53:18 +00001194 expdiff = self.adjusted() - other.adjusted()
1195 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001196 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001197 self._rescale(ideal_exp, context.rounding))
1198 if expdiff <= context.prec:
1199 op1 = _WorkRep(self)
1200 op2 = _WorkRep(other)
1201 if op1.exp >= op2.exp:
1202 op1.int *= 10**(op1.exp - op2.exp)
1203 else:
1204 op2.int *= 10**(op2.exp - op1.exp)
1205 q, r = divmod(op1.int, op2.int)
1206 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001207 return (_dec_from_triple(sign, str(q), 0),
1208 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001209
Facundo Batistacce8df22007-09-18 16:53:18 +00001210 # Here the quotient is too large to be representable
1211 ans = context._raise_error(DivisionImpossible,
1212 'quotient too large in //, % or divmod')
1213 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001214
1215 def __rdiv__(self, other, context=None):
1216 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001217 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001218 if other is NotImplemented:
1219 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220 return other.__div__(self, context=context)
1221 __rtruediv__ = __rdiv__
1222
1223 def __divmod__(self, other, context=None):
1224 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001225 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001226 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001227 other = _convert_other(other)
1228 if other is NotImplemented:
1229 return other
1230
1231 if context is None:
1232 context = getcontext()
1233
1234 ans = self._check_nans(other, context)
1235 if ans:
1236 return (ans, ans)
1237
1238 sign = self._sign ^ other._sign
1239 if self._isinfinity():
1240 if other._isinfinity():
1241 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1242 return ans, ans
1243 else:
1244 return (Infsign[sign],
1245 context._raise_error(InvalidOperation, 'INF % x'))
1246
1247 if not other:
1248 if not self:
1249 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1250 return ans, ans
1251 else:
1252 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1253 context._raise_error(InvalidOperation, 'x % 0'))
1254
1255 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001256 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001257 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001258
1259 def __rdivmod__(self, other, context=None):
1260 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001261 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001262 if other is NotImplemented:
1263 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001264 return other.__divmod__(self, context=context)
1265
1266 def __mod__(self, other, context=None):
1267 """
1268 self % other
1269 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001270 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001271 if other is NotImplemented:
1272 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273
Facundo Batistacce8df22007-09-18 16:53:18 +00001274 if context is None:
1275 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276
Facundo Batistacce8df22007-09-18 16:53:18 +00001277 ans = self._check_nans(other, context)
1278 if ans:
1279 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001280
Facundo Batistacce8df22007-09-18 16:53:18 +00001281 if self._isinfinity():
1282 return context._raise_error(InvalidOperation, 'INF % x')
1283 elif not other:
1284 if self:
1285 return context._raise_error(InvalidOperation, 'x % 0')
1286 else:
1287 return context._raise_error(DivisionUndefined, '0 % 0')
1288
1289 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001290 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001291 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001292
1293 def __rmod__(self, other, context=None):
1294 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001295 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001296 if other is NotImplemented:
1297 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001298 return other.__mod__(self, context=context)
1299
1300 def remainder_near(self, other, context=None):
1301 """
1302 Remainder nearest to 0- abs(remainder-near) <= other/2
1303 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001304 if context is None:
1305 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001306
Facundo Batista353750c2007-09-13 18:13:15 +00001307 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001308
Facundo Batista353750c2007-09-13 18:13:15 +00001309 ans = self._check_nans(other, context)
1310 if ans:
1311 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312
Facundo Batista353750c2007-09-13 18:13:15 +00001313 # self == +/-infinity -> InvalidOperation
1314 if self._isinfinity():
1315 return context._raise_error(InvalidOperation,
1316 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001317
Facundo Batista353750c2007-09-13 18:13:15 +00001318 # other == 0 -> either InvalidOperation or DivisionUndefined
1319 if not other:
1320 if self:
1321 return context._raise_error(InvalidOperation,
1322 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001323 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001324 return context._raise_error(DivisionUndefined,
1325 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001326
Facundo Batista353750c2007-09-13 18:13:15 +00001327 # other = +/-infinity -> remainder = self
1328 if other._isinfinity():
1329 ans = Decimal(self)
1330 return ans._fix(context)
1331
1332 # self = 0 -> remainder = self, with ideal exponent
1333 ideal_exponent = min(self._exp, other._exp)
1334 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001335 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001336 return ans._fix(context)
1337
1338 # catch most cases of large or small quotient
1339 expdiff = self.adjusted() - other.adjusted()
1340 if expdiff >= context.prec + 1:
1341 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001342 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001343 if expdiff <= -2:
1344 # expdiff <= -2 => abs(self/other) < 0.1
1345 ans = self._rescale(ideal_exponent, context.rounding)
1346 return ans._fix(context)
1347
1348 # adjust both arguments to have the same exponent, then divide
1349 op1 = _WorkRep(self)
1350 op2 = _WorkRep(other)
1351 if op1.exp >= op2.exp:
1352 op1.int *= 10**(op1.exp - op2.exp)
1353 else:
1354 op2.int *= 10**(op2.exp - op1.exp)
1355 q, r = divmod(op1.int, op2.int)
1356 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1357 # 10**ideal_exponent. Apply correction to ensure that
1358 # abs(remainder) <= abs(other)/2
1359 if 2*r + (q&1) > op2.int:
1360 r -= op2.int
1361 q += 1
1362
1363 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001364 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001365
1366 # result has same sign as self unless r is negative
1367 sign = self._sign
1368 if r < 0:
1369 sign = 1-sign
1370 r = -r
1371
Facundo Batista72bc54f2007-11-23 17:59:00 +00001372 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001373 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001374
1375 def __floordiv__(self, other, context=None):
1376 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001377 other = _convert_other(other)
1378 if other is NotImplemented:
1379 return other
1380
1381 if context is None:
1382 context = getcontext()
1383
1384 ans = self._check_nans(other, context)
1385 if ans:
1386 return ans
1387
1388 if self._isinfinity():
1389 if other._isinfinity():
1390 return context._raise_error(InvalidOperation, 'INF // INF')
1391 else:
1392 return Infsign[self._sign ^ other._sign]
1393
1394 if not other:
1395 if self:
1396 return context._raise_error(DivisionByZero, 'x // 0',
1397 self._sign ^ other._sign)
1398 else:
1399 return context._raise_error(DivisionUndefined, '0 // 0')
1400
1401 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001402
1403 def __rfloordiv__(self, other, context=None):
1404 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001405 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001406 if other is NotImplemented:
1407 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001408 return other.__floordiv__(self, context=context)
1409
1410 def __float__(self):
1411 """Float representation."""
1412 return float(str(self))
1413
1414 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001415 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001416 if self._is_special:
1417 if self._isnan():
1418 context = getcontext()
1419 return context._raise_error(InvalidContext)
1420 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001421 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001422 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001423 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001424 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001425 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001426 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001427
1428 def __long__(self):
1429 """Converts to a long.
1430
1431 Equivalent to long(int(self))
1432 """
1433 return long(self.__int__())
1434
Facundo Batista353750c2007-09-13 18:13:15 +00001435 def _fix_nan(self, context):
1436 """Decapitate the payload of a NaN to fit the context"""
1437 payload = self._int
1438
1439 # maximum length of payload is precision if _clamp=0,
1440 # precision-1 if _clamp=1.
1441 max_payload_len = context.prec - context._clamp
1442 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001443 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1444 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001445 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001446
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001447 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001448 """Round if it is necessary to keep self within prec precision.
1449
1450 Rounds and fixes the exponent. Does not raise on a sNaN.
1451
1452 Arguments:
1453 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001454 context - context used.
1455 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001456
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001457 if context is None:
1458 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001459
Facundo Batista353750c2007-09-13 18:13:15 +00001460 if self._is_special:
1461 if self._isnan():
1462 # decapitate payload if necessary
1463 return self._fix_nan(context)
1464 else:
1465 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001466 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001467
Facundo Batista353750c2007-09-13 18:13:15 +00001468 # if self is zero then exponent should be between Etiny and
1469 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1470 Etiny = context.Etiny()
1471 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001472 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001473 exp_max = [context.Emax, Etop][context._clamp]
1474 new_exp = min(max(self._exp, Etiny), exp_max)
1475 if new_exp != self._exp:
1476 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001477 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001478 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001479 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001480
1481 # exp_min is the smallest allowable exponent of the result,
1482 # equal to max(self.adjusted()-context.prec+1, Etiny)
1483 exp_min = len(self._int) + self._exp - context.prec
1484 if exp_min > Etop:
1485 # overflow: exp_min > Etop iff self.adjusted() > Emax
1486 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001487 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001488 return context._raise_error(Overflow, 'above Emax', self._sign)
1489 self_is_subnormal = exp_min < Etiny
1490 if self_is_subnormal:
1491 context._raise_error(Subnormal)
1492 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001493
Facundo Batista353750c2007-09-13 18:13:15 +00001494 # round if self has too many digits
1495 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001496 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001497 digits = len(self._int) + self._exp - exp_min
1498 if digits < 0:
1499 self = _dec_from_triple(self._sign, '1', exp_min-1)
1500 digits = 0
1501 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1502 changed = this_function(digits)
1503 coeff = self._int[:digits] or '0'
1504 if changed == 1:
1505 coeff = str(int(coeff)+1)
1506 ans = _dec_from_triple(self._sign, coeff, exp_min)
1507
1508 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001509 context._raise_error(Inexact)
1510 if self_is_subnormal:
1511 context._raise_error(Underflow)
1512 if not ans:
1513 # raise Clamped on underflow to 0
1514 context._raise_error(Clamped)
1515 elif len(ans._int) == context.prec+1:
1516 # we get here only if rescaling rounds the
1517 # cofficient up to exactly 10**context.prec
1518 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001519 ans = _dec_from_triple(ans._sign,
1520 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001521 else:
1522 # Inexact and Rounded have already been raised
1523 ans = context._raise_error(Overflow, 'above Emax',
1524 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001525 return ans
1526
Facundo Batista353750c2007-09-13 18:13:15 +00001527 # fold down if _clamp == 1 and self has too few digits
1528 if context._clamp == 1 and self._exp > Etop:
1529 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001530 self_padded = self._int + '0'*(self._exp - Etop)
1531 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001532
Facundo Batista353750c2007-09-13 18:13:15 +00001533 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001534 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001535
1536 _pick_rounding_function = {}
1537
Facundo Batista353750c2007-09-13 18:13:15 +00001538 # for each of the rounding functions below:
1539 # self is a finite, nonzero Decimal
1540 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001541 #
1542 # each function returns either -1, 0, or 1, as follows:
1543 # 1 indicates that self should be rounded up (away from zero)
1544 # 0 indicates that self should be truncated, and that all the
1545 # digits to be truncated are zeros (so the value is unchanged)
1546 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001547
1548 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001549 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001550 if _all_zeros(self._int, prec):
1551 return 0
1552 else:
1553 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001554
Facundo Batista353750c2007-09-13 18:13:15 +00001555 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001556 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001557 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001558
Facundo Batista353750c2007-09-13 18:13:15 +00001559 def _round_half_up(self, prec):
1560 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001561 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001562 return 1
1563 elif _all_zeros(self._int, prec):
1564 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001565 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001566 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001567
1568 def _round_half_down(self, prec):
1569 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001570 if _exact_half(self._int, prec):
1571 return -1
1572 else:
1573 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001574
1575 def _round_half_even(self, prec):
1576 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001577 if _exact_half(self._int, prec) and \
1578 (prec == 0 or self._int[prec-1] in '02468'):
1579 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001580 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001581 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001582
1583 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001584 """Rounds up (not away from 0 if negative.)"""
1585 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001586 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001587 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001588 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001589
Facundo Batista353750c2007-09-13 18:13:15 +00001590 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001591 """Rounds down (not towards 0 if negative)"""
1592 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001593 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001594 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001595 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001596
Facundo Batista353750c2007-09-13 18:13:15 +00001597 def _round_05up(self, prec):
1598 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001599 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001600 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001601 else:
1602 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001603
Facundo Batista353750c2007-09-13 18:13:15 +00001604 def fma(self, other, third, context=None):
1605 """Fused multiply-add.
1606
1607 Returns self*other+third with no rounding of the intermediate
1608 product self*other.
1609
1610 self and other are multiplied together, with no rounding of
1611 the result. The third operand is then added to the result,
1612 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001613 """
Facundo Batista353750c2007-09-13 18:13:15 +00001614
1615 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001616
1617 # compute product; raise InvalidOperation if either operand is
1618 # a signaling NaN or if the product is zero times infinity.
1619 if self._is_special or other._is_special:
1620 if context is None:
1621 context = getcontext()
1622 if self._exp == 'N':
1623 return context._raise_error(InvalidOperation, 'sNaN',
1624 1, self)
1625 if other._exp == 'N':
1626 return context._raise_error(InvalidOperation, 'sNaN',
1627 1, other)
1628 if self._exp == 'n':
1629 product = self
1630 elif other._exp == 'n':
1631 product = other
1632 elif self._exp == 'F':
1633 if not other:
1634 return context._raise_error(InvalidOperation,
1635 'INF * 0 in fma')
1636 product = Infsign[self._sign ^ other._sign]
1637 elif other._exp == 'F':
1638 if not self:
1639 return context._raise_error(InvalidOperation,
1640 '0 * INF in fma')
1641 product = Infsign[self._sign ^ other._sign]
1642 else:
1643 product = _dec_from_triple(self._sign ^ other._sign,
1644 str(int(self._int) * int(other._int)),
1645 self._exp + other._exp)
1646
Facundo Batista353750c2007-09-13 18:13:15 +00001647 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001648 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001649
Facundo Batista353750c2007-09-13 18:13:15 +00001650 def _power_modulo(self, other, modulo, context=None):
1651 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001652
Facundo Batista353750c2007-09-13 18:13:15 +00001653 # if can't convert other and modulo to Decimal, raise
1654 # TypeError; there's no point returning NotImplemented (no
1655 # equivalent of __rpow__ for three argument pow)
1656 other = _convert_other(other, raiseit=True)
1657 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001658
Facundo Batista353750c2007-09-13 18:13:15 +00001659 if context is None:
1660 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001661
Facundo Batista353750c2007-09-13 18:13:15 +00001662 # deal with NaNs: if there are any sNaNs then first one wins,
1663 # (i.e. behaviour for NaNs is identical to that of fma)
1664 self_is_nan = self._isnan()
1665 other_is_nan = other._isnan()
1666 modulo_is_nan = modulo._isnan()
1667 if self_is_nan or other_is_nan or modulo_is_nan:
1668 if self_is_nan == 2:
1669 return context._raise_error(InvalidOperation, 'sNaN',
1670 1, self)
1671 if other_is_nan == 2:
1672 return context._raise_error(InvalidOperation, 'sNaN',
1673 1, other)
1674 if modulo_is_nan == 2:
1675 return context._raise_error(InvalidOperation, 'sNaN',
1676 1, modulo)
1677 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001678 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001679 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001680 return other._fix_nan(context)
1681 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001682
Facundo Batista353750c2007-09-13 18:13:15 +00001683 # check inputs: we apply same restrictions as Python's pow()
1684 if not (self._isinteger() and
1685 other._isinteger() and
1686 modulo._isinteger()):
1687 return context._raise_error(InvalidOperation,
1688 'pow() 3rd argument not allowed '
1689 'unless all arguments are integers')
1690 if other < 0:
1691 return context._raise_error(InvalidOperation,
1692 'pow() 2nd argument cannot be '
1693 'negative when 3rd argument specified')
1694 if not modulo:
1695 return context._raise_error(InvalidOperation,
1696 'pow() 3rd argument cannot be 0')
1697
1698 # additional restriction for decimal: the modulus must be less
1699 # than 10**prec in absolute value
1700 if modulo.adjusted() >= context.prec:
1701 return context._raise_error(InvalidOperation,
1702 'insufficient precision: pow() 3rd '
1703 'argument must not have more than '
1704 'precision digits')
1705
1706 # define 0**0 == NaN, for consistency with two-argument pow
1707 # (even though it hurts!)
1708 if not other and not self:
1709 return context._raise_error(InvalidOperation,
1710 'at least one of pow() 1st argument '
1711 'and 2nd argument must be nonzero ;'
1712 '0**0 is not defined')
1713
1714 # compute sign of result
1715 if other._iseven():
1716 sign = 0
1717 else:
1718 sign = self._sign
1719
1720 # convert modulo to a Python integer, and self and other to
1721 # Decimal integers (i.e. force their exponents to be >= 0)
1722 modulo = abs(int(modulo))
1723 base = _WorkRep(self.to_integral_value())
1724 exponent = _WorkRep(other.to_integral_value())
1725
1726 # compute result using integer pow()
1727 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1728 for i in xrange(exponent.exp):
1729 base = pow(base, 10, modulo)
1730 base = pow(base, exponent.int, modulo)
1731
Facundo Batista72bc54f2007-11-23 17:59:00 +00001732 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001733
1734 def _power_exact(self, other, p):
1735 """Attempt to compute self**other exactly.
1736
1737 Given Decimals self and other and an integer p, attempt to
1738 compute an exact result for the power self**other, with p
1739 digits of precision. Return None if self**other is not
1740 exactly representable in p digits.
1741
1742 Assumes that elimination of special cases has already been
1743 performed: self and other must both be nonspecial; self must
1744 be positive and not numerically equal to 1; other must be
1745 nonzero. For efficiency, other._exp should not be too large,
1746 so that 10**abs(other._exp) is a feasible calculation."""
1747
1748 # In the comments below, we write x for the value of self and
1749 # y for the value of other. Write x = xc*10**xe and y =
1750 # yc*10**ye.
1751
1752 # The main purpose of this method is to identify the *failure*
1753 # of x**y to be exactly representable with as little effort as
1754 # possible. So we look for cheap and easy tests that
1755 # eliminate the possibility of x**y being exact. Only if all
1756 # these tests are passed do we go on to actually compute x**y.
1757
1758 # Here's the main idea. First normalize both x and y. We
1759 # express y as a rational m/n, with m and n relatively prime
1760 # and n>0. Then for x**y to be exactly representable (at
1761 # *any* precision), xc must be the nth power of a positive
1762 # integer and xe must be divisible by n. If m is negative
1763 # then additionally xc must be a power of either 2 or 5, hence
1764 # a power of 2**n or 5**n.
1765 #
1766 # There's a limit to how small |y| can be: if y=m/n as above
1767 # then:
1768 #
1769 # (1) if xc != 1 then for the result to be representable we
1770 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1771 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1772 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1773 # representable.
1774 #
1775 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1776 # |y| < 1/|xe| then the result is not representable.
1777 #
1778 # Note that since x is not equal to 1, at least one of (1) and
1779 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1780 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1781 #
1782 # There's also a limit to how large y can be, at least if it's
1783 # positive: the normalized result will have coefficient xc**y,
1784 # so if it's representable then xc**y < 10**p, and y <
1785 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1786 # not exactly representable.
1787
1788 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1789 # so |y| < 1/xe and the result is not representable.
1790 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1791 # < 1/nbits(xc).
1792
1793 x = _WorkRep(self)
1794 xc, xe = x.int, x.exp
1795 while xc % 10 == 0:
1796 xc //= 10
1797 xe += 1
1798
1799 y = _WorkRep(other)
1800 yc, ye = y.int, y.exp
1801 while yc % 10 == 0:
1802 yc //= 10
1803 ye += 1
1804
1805 # case where xc == 1: result is 10**(xe*y), with xe*y
1806 # required to be an integer
1807 if xc == 1:
1808 if ye >= 0:
1809 exponent = xe*yc*10**ye
1810 else:
1811 exponent, remainder = divmod(xe*yc, 10**-ye)
1812 if remainder:
1813 return None
1814 if y.sign == 1:
1815 exponent = -exponent
1816 # if other is a nonnegative integer, use ideal exponent
1817 if other._isinteger() and other._sign == 0:
1818 ideal_exponent = self._exp*int(other)
1819 zeros = min(exponent-ideal_exponent, p-1)
1820 else:
1821 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001822 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001823
1824 # case where y is negative: xc must be either a power
1825 # of 2 or a power of 5.
1826 if y.sign == 1:
1827 last_digit = xc % 10
1828 if last_digit in (2,4,6,8):
1829 # quick test for power of 2
1830 if xc & -xc != xc:
1831 return None
1832 # now xc is a power of 2; e is its exponent
1833 e = _nbits(xc)-1
1834 # find e*y and xe*y; both must be integers
1835 if ye >= 0:
1836 y_as_int = yc*10**ye
1837 e = e*y_as_int
1838 xe = xe*y_as_int
1839 else:
1840 ten_pow = 10**-ye
1841 e, remainder = divmod(e*yc, ten_pow)
1842 if remainder:
1843 return None
1844 xe, remainder = divmod(xe*yc, ten_pow)
1845 if remainder:
1846 return None
1847
1848 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1849 return None
1850 xc = 5**e
1851
1852 elif last_digit == 5:
1853 # e >= log_5(xc) if xc is a power of 5; we have
1854 # equality all the way up to xc=5**2658
1855 e = _nbits(xc)*28//65
1856 xc, remainder = divmod(5**e, xc)
1857 if remainder:
1858 return None
1859 while xc % 5 == 0:
1860 xc //= 5
1861 e -= 1
1862 if ye >= 0:
1863 y_as_integer = yc*10**ye
1864 e = e*y_as_integer
1865 xe = xe*y_as_integer
1866 else:
1867 ten_pow = 10**-ye
1868 e, remainder = divmod(e*yc, ten_pow)
1869 if remainder:
1870 return None
1871 xe, remainder = divmod(xe*yc, ten_pow)
1872 if remainder:
1873 return None
1874 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1875 return None
1876 xc = 2**e
1877 else:
1878 return None
1879
1880 if xc >= 10**p:
1881 return None
1882 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001883 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001884
1885 # now y is positive; find m and n such that y = m/n
1886 if ye >= 0:
1887 m, n = yc*10**ye, 1
1888 else:
1889 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1890 return None
1891 xc_bits = _nbits(xc)
1892 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1893 return None
1894 m, n = yc, 10**(-ye)
1895 while m % 2 == n % 2 == 0:
1896 m //= 2
1897 n //= 2
1898 while m % 5 == n % 5 == 0:
1899 m //= 5
1900 n //= 5
1901
1902 # compute nth root of xc*10**xe
1903 if n > 1:
1904 # if 1 < xc < 2**n then xc isn't an nth power
1905 if xc != 1 and xc_bits <= n:
1906 return None
1907
1908 xe, rem = divmod(xe, n)
1909 if rem != 0:
1910 return None
1911
1912 # compute nth root of xc using Newton's method
1913 a = 1L << -(-_nbits(xc)//n) # initial estimate
1914 while True:
1915 q, r = divmod(xc, a**(n-1))
1916 if a <= q:
1917 break
1918 else:
1919 a = (a*(n-1) + q)//n
1920 if not (a == q and r == 0):
1921 return None
1922 xc = a
1923
1924 # now xc*10**xe is the nth root of the original xc*10**xe
1925 # compute mth power of xc*10**xe
1926
1927 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1928 # 10**p and the result is not representable.
1929 if xc > 1 and m > p*100//_log10_lb(xc):
1930 return None
1931 xc = xc**m
1932 xe *= m
1933 if xc > 10**p:
1934 return None
1935
1936 # by this point the result *is* exactly representable
1937 # adjust the exponent to get as close as possible to the ideal
1938 # exponent, if necessary
1939 str_xc = str(xc)
1940 if other._isinteger() and other._sign == 0:
1941 ideal_exponent = self._exp*int(other)
1942 zeros = min(xe-ideal_exponent, p-len(str_xc))
1943 else:
1944 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001945 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001946
1947 def __pow__(self, other, modulo=None, context=None):
1948 """Return self ** other [ % modulo].
1949
1950 With two arguments, compute self**other.
1951
1952 With three arguments, compute (self**other) % modulo. For the
1953 three argument form, the following restrictions on the
1954 arguments hold:
1955
1956 - all three arguments must be integral
1957 - other must be nonnegative
1958 - either self or other (or both) must be nonzero
1959 - modulo must be nonzero and must have at most p digits,
1960 where p is the context precision.
1961
1962 If any of these restrictions is violated the InvalidOperation
1963 flag is raised.
1964
1965 The result of pow(self, other, modulo) is identical to the
1966 result that would be obtained by computing (self**other) %
1967 modulo with unbounded precision, but is computed more
1968 efficiently. It is always exact.
1969 """
1970
1971 if modulo is not None:
1972 return self._power_modulo(other, modulo, context)
1973
1974 other = _convert_other(other)
1975 if other is NotImplemented:
1976 return other
1977
1978 if context is None:
1979 context = getcontext()
1980
1981 # either argument is a NaN => result is NaN
1982 ans = self._check_nans(other, context)
1983 if ans:
1984 return ans
1985
1986 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1987 if not other:
1988 if not self:
1989 return context._raise_error(InvalidOperation, '0 ** 0')
1990 else:
1991 return Dec_p1
1992
1993 # result has sign 1 iff self._sign is 1 and other is an odd integer
1994 result_sign = 0
1995 if self._sign == 1:
1996 if other._isinteger():
1997 if not other._iseven():
1998 result_sign = 1
1999 else:
2000 # -ve**noninteger = NaN
2001 # (-0)**noninteger = 0**noninteger
2002 if self:
2003 return context._raise_error(InvalidOperation,
2004 'x ** y with x negative and y not an integer')
2005 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002006 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002007
2008 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2009 if not self:
2010 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002011 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002012 else:
2013 return Infsign[result_sign]
2014
2015 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002016 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002017 if other._sign == 0:
2018 return Infsign[result_sign]
2019 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002020 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002021
Facundo Batista353750c2007-09-13 18:13:15 +00002022 # 1**other = 1, but the choice of exponent and the flags
2023 # depend on the exponent of self, and on whether other is a
2024 # positive integer, a negative integer, or neither
2025 if self == Dec_p1:
2026 if other._isinteger():
2027 # exp = max(self._exp*max(int(other), 0),
2028 # 1-context.prec) but evaluating int(other) directly
2029 # is dangerous until we know other is small (other
2030 # could be 1e999999999)
2031 if other._sign == 1:
2032 multiplier = 0
2033 elif other > context.prec:
2034 multiplier = context.prec
2035 else:
2036 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002037
Facundo Batista353750c2007-09-13 18:13:15 +00002038 exp = self._exp * multiplier
2039 if exp < 1-context.prec:
2040 exp = 1-context.prec
2041 context._raise_error(Rounded)
2042 else:
2043 context._raise_error(Inexact)
2044 context._raise_error(Rounded)
2045 exp = 1-context.prec
2046
Facundo Batista72bc54f2007-11-23 17:59:00 +00002047 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002048
2049 # compute adjusted exponent of self
2050 self_adj = self.adjusted()
2051
2052 # self ** infinity is infinity if self > 1, 0 if self < 1
2053 # self ** -infinity is infinity if self < 1, 0 if self > 1
2054 if other._isinfinity():
2055 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002056 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002057 else:
2058 return Infsign[result_sign]
2059
2060 # from here on, the result always goes through the call
2061 # to _fix at the end of this function.
2062 ans = None
2063
2064 # crude test to catch cases of extreme overflow/underflow. If
2065 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2066 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2067 # self**other >= 10**(Emax+1), so overflow occurs. The test
2068 # for underflow is similar.
2069 bound = self._log10_exp_bound() + other.adjusted()
2070 if (self_adj >= 0) == (other._sign == 0):
2071 # self > 1 and other +ve, or self < 1 and other -ve
2072 # possibility of overflow
2073 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002074 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002075 else:
2076 # self > 1 and other -ve, or self < 1 and other +ve
2077 # possibility of underflow to 0
2078 Etiny = context.Etiny()
2079 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002080 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002081
2082 # try for an exact result with precision +1
2083 if ans is None:
2084 ans = self._power_exact(other, context.prec + 1)
2085 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002086 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002087
2088 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2089 if ans is None:
2090 p = context.prec
2091 x = _WorkRep(self)
2092 xc, xe = x.int, x.exp
2093 y = _WorkRep(other)
2094 yc, ye = y.int, y.exp
2095 if y.sign == 1:
2096 yc = -yc
2097
2098 # compute correctly rounded result: start with precision +3,
2099 # then increase precision until result is unambiguously roundable
2100 extra = 3
2101 while True:
2102 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2103 if coeff % (5*10**(len(str(coeff))-p-1)):
2104 break
2105 extra += 3
2106
Facundo Batista72bc54f2007-11-23 17:59:00 +00002107 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002108
2109 # the specification says that for non-integer other we need to
2110 # raise Inexact, even when the result is actually exact. In
2111 # the same way, we need to raise Underflow here if the result
2112 # is subnormal. (The call to _fix will take care of raising
2113 # Rounded and Subnormal, as usual.)
2114 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002115 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002116 # pad with zeros up to length context.prec+1 if necessary
2117 if len(ans._int) <= context.prec:
2118 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002119 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2120 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002121 if ans.adjusted() < context.Emin:
2122 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002123
Facundo Batista353750c2007-09-13 18:13:15 +00002124 # unlike exp, ln and log10, the power function respects the
2125 # rounding mode; no need to use ROUND_HALF_EVEN here
2126 ans = ans._fix(context)
2127 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002128
2129 def __rpow__(self, other, context=None):
2130 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002131 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002132 if other is NotImplemented:
2133 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002134 return other.__pow__(self, context=context)
2135
2136 def normalize(self, context=None):
2137 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002138
Facundo Batista353750c2007-09-13 18:13:15 +00002139 if context is None:
2140 context = getcontext()
2141
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002142 if self._is_special:
2143 ans = self._check_nans(context=context)
2144 if ans:
2145 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002146
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002147 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002148 if dup._isinfinity():
2149 return dup
2150
2151 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002152 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002153 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002154 end = len(dup._int)
2155 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002156 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002157 exp += 1
2158 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002159 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002160
Facundo Batistabd2fe832007-09-13 18:42:09 +00002161 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002162 """Quantize self so its exponent is the same as that of exp.
2163
2164 Similar to self._rescale(exp._exp) but with error checking.
2165 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002166 exp = _convert_other(exp, raiseit=True)
2167
Facundo Batista353750c2007-09-13 18:13:15 +00002168 if context is None:
2169 context = getcontext()
2170 if rounding is None:
2171 rounding = context.rounding
2172
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002173 if self._is_special or exp._is_special:
2174 ans = self._check_nans(exp, context)
2175 if ans:
2176 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002177
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002178 if exp._isinfinity() or self._isinfinity():
2179 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002180 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002181 return context._raise_error(InvalidOperation,
2182 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002183
Facundo Batistabd2fe832007-09-13 18:42:09 +00002184 # if we're not watching exponents, do a simple rescale
2185 if not watchexp:
2186 ans = self._rescale(exp._exp, rounding)
2187 # raise Inexact and Rounded where appropriate
2188 if ans._exp > self._exp:
2189 context._raise_error(Rounded)
2190 if ans != self:
2191 context._raise_error(Inexact)
2192 return ans
2193
Facundo Batista353750c2007-09-13 18:13:15 +00002194 # exp._exp should be between Etiny and Emax
2195 if not (context.Etiny() <= exp._exp <= context.Emax):
2196 return context._raise_error(InvalidOperation,
2197 'target exponent out of bounds in quantize')
2198
2199 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002200 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002201 return ans._fix(context)
2202
2203 self_adjusted = self.adjusted()
2204 if self_adjusted > context.Emax:
2205 return context._raise_error(InvalidOperation,
2206 'exponent of quantize result too large for current context')
2207 if self_adjusted - exp._exp + 1 > context.prec:
2208 return context._raise_error(InvalidOperation,
2209 'quantize result has too many digits for current context')
2210
2211 ans = self._rescale(exp._exp, rounding)
2212 if ans.adjusted() > context.Emax:
2213 return context._raise_error(InvalidOperation,
2214 'exponent of quantize result too large for current context')
2215 if len(ans._int) > context.prec:
2216 return context._raise_error(InvalidOperation,
2217 'quantize result has too many digits for current context')
2218
2219 # raise appropriate flags
2220 if ans._exp > self._exp:
2221 context._raise_error(Rounded)
2222 if ans != self:
2223 context._raise_error(Inexact)
2224 if ans and ans.adjusted() < context.Emin:
2225 context._raise_error(Subnormal)
2226
2227 # call to fix takes care of any necessary folddown
2228 ans = ans._fix(context)
2229 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002230
2231 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002232 """Return True if self and other have the same exponent; otherwise
2233 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002234
Facundo Batista1a191df2007-10-02 17:01:24 +00002235 If either operand is a special value, the following rules are used:
2236 * return True if both operands are infinities
2237 * return True if both operands are NaNs
2238 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002239 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002240 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002241 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002242 return (self.is_nan() and other.is_nan() or
2243 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002244 return self._exp == other._exp
2245
Facundo Batista353750c2007-09-13 18:13:15 +00002246 def _rescale(self, exp, rounding):
2247 """Rescale self so that the exponent is exp, either by padding with zeros
2248 or by truncating digits, using the given rounding mode.
2249
2250 Specials are returned without change. This operation is
2251 quiet: it raises no flags, and uses no information from the
2252 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002253
2254 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002255 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002256 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002257 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002258 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002259 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002260 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002261
Facundo Batista353750c2007-09-13 18:13:15 +00002262 if self._exp >= exp:
2263 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002264 return _dec_from_triple(self._sign,
2265 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002266
Facundo Batista353750c2007-09-13 18:13:15 +00002267 # too many digits; round and lose data. If self.adjusted() <
2268 # exp-1, replace self by 10**(exp-1) before rounding
2269 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002270 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002271 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002272 digits = 0
2273 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002274 changed = this_function(digits)
2275 coeff = self._int[:digits] or '0'
2276 if changed == 1:
2277 coeff = str(int(coeff)+1)
2278 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002279
Facundo Batista353750c2007-09-13 18:13:15 +00002280 def to_integral_exact(self, rounding=None, context=None):
2281 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002282
Facundo Batista353750c2007-09-13 18:13:15 +00002283 If no rounding mode is specified, take the rounding mode from
2284 the context. This method raises the Rounded and Inexact flags
2285 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002286
Facundo Batista353750c2007-09-13 18:13:15 +00002287 See also: to_integral_value, which does exactly the same as
2288 this method except that it doesn't raise Inexact or Rounded.
2289 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002290 if self._is_special:
2291 ans = self._check_nans(context=context)
2292 if ans:
2293 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002294 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002295 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002296 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002297 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002298 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002299 if context is None:
2300 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002301 if rounding is None:
2302 rounding = context.rounding
2303 context._raise_error(Rounded)
2304 ans = self._rescale(0, rounding)
2305 if ans != self:
2306 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002307 return ans
2308
Facundo Batista353750c2007-09-13 18:13:15 +00002309 def to_integral_value(self, rounding=None, context=None):
2310 """Rounds to the nearest integer, without raising inexact, rounded."""
2311 if context is None:
2312 context = getcontext()
2313 if rounding is None:
2314 rounding = context.rounding
2315 if self._is_special:
2316 ans = self._check_nans(context=context)
2317 if ans:
2318 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002319 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002320 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002321 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002322 else:
2323 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002324
Facundo Batista353750c2007-09-13 18:13:15 +00002325 # the method name changed, but we provide also the old one, for compatibility
2326 to_integral = to_integral_value
2327
2328 def sqrt(self, context=None):
2329 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002330 if self._is_special:
2331 ans = self._check_nans(context=context)
2332 if ans:
2333 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002334
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002335 if self._isinfinity() and self._sign == 0:
2336 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002337
2338 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002339 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002340 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002341 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002342
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002343 if context is None:
2344 context = getcontext()
2345
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002346 if self._sign == 1:
2347 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2348
Facundo Batista353750c2007-09-13 18:13:15 +00002349 # At this point self represents a positive number. Let p be
2350 # the desired precision and express self in the form c*100**e
2351 # with c a positive real number and e an integer, c and e
2352 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2353 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2354 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2355 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2356 # the closest integer to sqrt(c) with the even integer chosen
2357 # in the case of a tie.
2358 #
2359 # To ensure correct rounding in all cases, we use the
2360 # following trick: we compute the square root to an extra
2361 # place (precision p+1 instead of precision p), rounding down.
2362 # Then, if the result is inexact and its last digit is 0 or 5,
2363 # we increase the last digit to 1 or 6 respectively; if it's
2364 # exact we leave the last digit alone. Now the final round to
2365 # p places (or fewer in the case of underflow) will round
2366 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002367
Facundo Batista353750c2007-09-13 18:13:15 +00002368 # use an extra digit of precision
2369 prec = context.prec+1
2370
2371 # write argument in the form c*100**e where e = self._exp//2
2372 # is the 'ideal' exponent, to be used if the square root is
2373 # exactly representable. l is the number of 'digits' of c in
2374 # base 100, so that 100**(l-1) <= c < 100**l.
2375 op = _WorkRep(self)
2376 e = op.exp >> 1
2377 if op.exp & 1:
2378 c = op.int * 10
2379 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002380 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002381 c = op.int
2382 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002383
Facundo Batista353750c2007-09-13 18:13:15 +00002384 # rescale so that c has exactly prec base 100 'digits'
2385 shift = prec-l
2386 if shift >= 0:
2387 c *= 100**shift
2388 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002389 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002390 c, remainder = divmod(c, 100**-shift)
2391 exact = not remainder
2392 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002393
Facundo Batista353750c2007-09-13 18:13:15 +00002394 # find n = floor(sqrt(c)) using Newton's method
2395 n = 10**prec
2396 while True:
2397 q = c//n
2398 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002399 break
Facundo Batista353750c2007-09-13 18:13:15 +00002400 else:
2401 n = n + q >> 1
2402 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002403
Facundo Batista353750c2007-09-13 18:13:15 +00002404 if exact:
2405 # result is exact; rescale to use ideal exponent e
2406 if shift >= 0:
2407 # assert n % 10**shift == 0
2408 n //= 10**shift
2409 else:
2410 n *= 10**-shift
2411 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002412 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002413 # result is not exact; fix last digit as described above
2414 if n % 5 == 0:
2415 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002416
Facundo Batista72bc54f2007-11-23 17:59:00 +00002417 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002418
Facundo Batista353750c2007-09-13 18:13:15 +00002419 # round, and fit to current context
2420 context = context._shallow_copy()
2421 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002422 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002423 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002424
Facundo Batista353750c2007-09-13 18:13:15 +00002425 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002426
2427 def max(self, other, context=None):
2428 """Returns the larger value.
2429
Facundo Batista353750c2007-09-13 18:13:15 +00002430 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002431 NaN (and signals if one is sNaN). Also rounds.
2432 """
Facundo Batista353750c2007-09-13 18:13:15 +00002433 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002434
Facundo Batista6c398da2007-09-17 17:30:13 +00002435 if context is None:
2436 context = getcontext()
2437
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002438 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002439 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002440 # number is always returned
2441 sn = self._isnan()
2442 on = other._isnan()
2443 if sn or on:
2444 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002445 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002446 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002447 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002448 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002449
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002450 c = self.__cmp__(other)
2451 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002452 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002453 # then an ordering is applied:
2454 #
Facundo Batista59c58842007-04-10 12:58:45 +00002455 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002456 # positive sign and min returns the operand with the negative sign
2457 #
Facundo Batista59c58842007-04-10 12:58:45 +00002458 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002459 # the result. This is exactly the ordering used in compare_total.
2460 c = self.compare_total(other)
2461
2462 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002463 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002464 else:
2465 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002466
Facundo Batistae64acfa2007-12-17 14:18:42 +00002467 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002468
2469 def min(self, other, context=None):
2470 """Returns the smaller value.
2471
Facundo Batista59c58842007-04-10 12:58:45 +00002472 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002473 NaN (and signals if one is sNaN). Also rounds.
2474 """
Facundo Batista353750c2007-09-13 18:13:15 +00002475 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002476
Facundo Batista6c398da2007-09-17 17:30:13 +00002477 if context is None:
2478 context = getcontext()
2479
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002480 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002481 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002482 # number is always returned
2483 sn = self._isnan()
2484 on = other._isnan()
2485 if sn or on:
2486 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002487 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002488 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002489 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002490 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002491
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002492 c = self.__cmp__(other)
2493 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002494 c = self.compare_total(other)
2495
2496 if c == -1:
2497 ans = self
2498 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002499 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002500
Facundo Batistae64acfa2007-12-17 14:18:42 +00002501 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002502
2503 def _isinteger(self):
2504 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002505 if self._is_special:
2506 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002507 if self._exp >= 0:
2508 return True
2509 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002510 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002511
2512 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002513 """Returns True if self is even. Assumes self is an integer."""
2514 if not self or self._exp > 0:
2515 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002516 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002517
2518 def adjusted(self):
2519 """Return the adjusted exponent of self"""
2520 try:
2521 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002522 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002523 except TypeError:
2524 return 0
2525
Facundo Batista353750c2007-09-13 18:13:15 +00002526 def canonical(self, context=None):
2527 """Returns the same Decimal object.
2528
2529 As we do not have different encodings for the same number, the
2530 received object already is in its canonical form.
2531 """
2532 return self
2533
2534 def compare_signal(self, other, context=None):
2535 """Compares self to the other operand numerically.
2536
2537 It's pretty much like compare(), but all NaNs signal, with signaling
2538 NaNs taking precedence over quiet NaNs.
2539 """
2540 if context is None:
2541 context = getcontext()
2542
2543 self_is_nan = self._isnan()
2544 other_is_nan = other._isnan()
2545 if self_is_nan == 2:
2546 return context._raise_error(InvalidOperation, 'sNaN',
2547 1, self)
2548 if other_is_nan == 2:
2549 return context._raise_error(InvalidOperation, 'sNaN',
2550 1, other)
2551 if self_is_nan:
2552 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2553 1, self)
2554 if other_is_nan:
2555 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2556 1, other)
2557 return self.compare(other, context=context)
2558
2559 def compare_total(self, other):
2560 """Compares self to other using the abstract representations.
2561
2562 This is not like the standard compare, which use their numerical
2563 value. Note that a total ordering is defined for all possible abstract
2564 representations.
2565 """
2566 # if one is negative and the other is positive, it's easy
2567 if self._sign and not other._sign:
2568 return Dec_n1
2569 if not self._sign and other._sign:
2570 return Dec_p1
2571 sign = self._sign
2572
2573 # let's handle both NaN types
2574 self_nan = self._isnan()
2575 other_nan = other._isnan()
2576 if self_nan or other_nan:
2577 if self_nan == other_nan:
2578 if self._int < other._int:
2579 if sign:
2580 return Dec_p1
2581 else:
2582 return Dec_n1
2583 if self._int > other._int:
2584 if sign:
2585 return Dec_n1
2586 else:
2587 return Dec_p1
2588 return Dec_0
2589
2590 if sign:
2591 if self_nan == 1:
2592 return Dec_n1
2593 if other_nan == 1:
2594 return Dec_p1
2595 if self_nan == 2:
2596 return Dec_n1
2597 if other_nan == 2:
2598 return Dec_p1
2599 else:
2600 if self_nan == 1:
2601 return Dec_p1
2602 if other_nan == 1:
2603 return Dec_n1
2604 if self_nan == 2:
2605 return Dec_p1
2606 if other_nan == 2:
2607 return Dec_n1
2608
2609 if self < other:
2610 return Dec_n1
2611 if self > other:
2612 return Dec_p1
2613
2614 if self._exp < other._exp:
2615 if sign:
2616 return Dec_p1
2617 else:
2618 return Dec_n1
2619 if self._exp > other._exp:
2620 if sign:
2621 return Dec_n1
2622 else:
2623 return Dec_p1
2624 return Dec_0
2625
2626
2627 def compare_total_mag(self, other):
2628 """Compares self to other using abstract repr., ignoring sign.
2629
2630 Like compare_total, but with operand's sign ignored and assumed to be 0.
2631 """
2632 s = self.copy_abs()
2633 o = other.copy_abs()
2634 return s.compare_total(o)
2635
2636 def copy_abs(self):
2637 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002638 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002639
2640 def copy_negate(self):
2641 """Returns a copy with the sign inverted."""
2642 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002643 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002644 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002645 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002646
2647 def copy_sign(self, other):
2648 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002649 return _dec_from_triple(other._sign, self._int,
2650 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002651
2652 def exp(self, context=None):
2653 """Returns e ** self."""
2654
2655 if context is None:
2656 context = getcontext()
2657
2658 # exp(NaN) = NaN
2659 ans = self._check_nans(context=context)
2660 if ans:
2661 return ans
2662
2663 # exp(-Infinity) = 0
2664 if self._isinfinity() == -1:
2665 return Dec_0
2666
2667 # exp(0) = 1
2668 if not self:
2669 return Dec_p1
2670
2671 # exp(Infinity) = Infinity
2672 if self._isinfinity() == 1:
2673 return Decimal(self)
2674
2675 # the result is now guaranteed to be inexact (the true
2676 # mathematical result is transcendental). There's no need to
2677 # raise Rounded and Inexact here---they'll always be raised as
2678 # a result of the call to _fix.
2679 p = context.prec
2680 adj = self.adjusted()
2681
2682 # we only need to do any computation for quite a small range
2683 # of adjusted exponents---for example, -29 <= adj <= 10 for
2684 # the default context. For smaller exponent the result is
2685 # indistinguishable from 1 at the given precision, while for
2686 # larger exponent the result either overflows or underflows.
2687 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2688 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002689 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002690 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2691 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002692 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002693 elif self._sign == 0 and adj < -p:
2694 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002695 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002696 elif self._sign == 1 and adj < -p-1:
2697 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002698 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002699 # general case
2700 else:
2701 op = _WorkRep(self)
2702 c, e = op.int, op.exp
2703 if op.sign == 1:
2704 c = -c
2705
2706 # compute correctly rounded result: increase precision by
2707 # 3 digits at a time until we get an unambiguously
2708 # roundable result
2709 extra = 3
2710 while True:
2711 coeff, exp = _dexp(c, e, p+extra)
2712 if coeff % (5*10**(len(str(coeff))-p-1)):
2713 break
2714 extra += 3
2715
Facundo Batista72bc54f2007-11-23 17:59:00 +00002716 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002717
2718 # at this stage, ans should round correctly with *any*
2719 # rounding mode, not just with ROUND_HALF_EVEN
2720 context = context._shallow_copy()
2721 rounding = context._set_rounding(ROUND_HALF_EVEN)
2722 ans = ans._fix(context)
2723 context.rounding = rounding
2724
2725 return ans
2726
2727 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002728 """Return True if self is canonical; otherwise return False.
2729
2730 Currently, the encoding of a Decimal instance is always
2731 canonical, so this method returns True for any Decimal.
2732 """
2733 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002734
2735 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002736 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002737
Facundo Batista1a191df2007-10-02 17:01:24 +00002738 A Decimal instance is considered finite if it is neither
2739 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002740 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002741 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002742
2743 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002744 """Return True if self is infinite; otherwise return False."""
2745 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002746
2747 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002748 """Return True if self is a qNaN or sNaN; otherwise return False."""
2749 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002750
2751 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002752 """Return True if self is a normal number; otherwise return False."""
2753 if self._is_special or not self:
2754 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002755 if context is None:
2756 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002757 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002758
2759 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002760 """Return True if self is a quiet NaN; otherwise return False."""
2761 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002762
2763 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002764 """Return True if self is negative; otherwise return False."""
2765 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002766
2767 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002768 """Return True if self is a signaling NaN; otherwise return False."""
2769 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002770
2771 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002772 """Return True if self is subnormal; otherwise return False."""
2773 if self._is_special or not self:
2774 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002775 if context is None:
2776 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002777 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002778
2779 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002780 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002781 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002782
2783 def _ln_exp_bound(self):
2784 """Compute a lower bound for the adjusted exponent of self.ln().
2785 In other words, compute r such that self.ln() >= 10**r. Assumes
2786 that self is finite and positive and that self != 1.
2787 """
2788
2789 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2790 adj = self._exp + len(self._int) - 1
2791 if adj >= 1:
2792 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2793 return len(str(adj*23//10)) - 1
2794 if adj <= -2:
2795 # argument <= 0.1
2796 return len(str((-1-adj)*23//10)) - 1
2797 op = _WorkRep(self)
2798 c, e = op.int, op.exp
2799 if adj == 0:
2800 # 1 < self < 10
2801 num = str(c-10**-e)
2802 den = str(c)
2803 return len(num) - len(den) - (num < den)
2804 # adj == -1, 0.1 <= self < 1
2805 return e + len(str(10**-e - c)) - 1
2806
2807
2808 def ln(self, context=None):
2809 """Returns the natural (base e) logarithm of self."""
2810
2811 if context is None:
2812 context = getcontext()
2813
2814 # ln(NaN) = NaN
2815 ans = self._check_nans(context=context)
2816 if ans:
2817 return ans
2818
2819 # ln(0.0) == -Infinity
2820 if not self:
2821 return negInf
2822
2823 # ln(Infinity) = Infinity
2824 if self._isinfinity() == 1:
2825 return Inf
2826
2827 # ln(1.0) == 0.0
2828 if self == Dec_p1:
2829 return Dec_0
2830
2831 # ln(negative) raises InvalidOperation
2832 if self._sign == 1:
2833 return context._raise_error(InvalidOperation,
2834 'ln of a negative value')
2835
2836 # result is irrational, so necessarily inexact
2837 op = _WorkRep(self)
2838 c, e = op.int, op.exp
2839 p = context.prec
2840
2841 # correctly rounded result: repeatedly increase precision by 3
2842 # until we get an unambiguously roundable result
2843 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2844 while True:
2845 coeff = _dlog(c, e, places)
2846 # assert len(str(abs(coeff)))-p >= 1
2847 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2848 break
2849 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002850 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002851
2852 context = context._shallow_copy()
2853 rounding = context._set_rounding(ROUND_HALF_EVEN)
2854 ans = ans._fix(context)
2855 context.rounding = rounding
2856 return ans
2857
2858 def _log10_exp_bound(self):
2859 """Compute a lower bound for the adjusted exponent of self.log10().
2860 In other words, find r such that self.log10() >= 10**r.
2861 Assumes that self is finite and positive and that self != 1.
2862 """
2863
2864 # For x >= 10 or x < 0.1 we only need a bound on the integer
2865 # part of log10(self), and this comes directly from the
2866 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2867 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2868 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2869
2870 adj = self._exp + len(self._int) - 1
2871 if adj >= 1:
2872 # self >= 10
2873 return len(str(adj))-1
2874 if adj <= -2:
2875 # self < 0.1
2876 return len(str(-1-adj))-1
2877 op = _WorkRep(self)
2878 c, e = op.int, op.exp
2879 if adj == 0:
2880 # 1 < self < 10
2881 num = str(c-10**-e)
2882 den = str(231*c)
2883 return len(num) - len(den) - (num < den) + 2
2884 # adj == -1, 0.1 <= self < 1
2885 num = str(10**-e-c)
2886 return len(num) + e - (num < "231") - 1
2887
2888 def log10(self, context=None):
2889 """Returns the base 10 logarithm of self."""
2890
2891 if context is None:
2892 context = getcontext()
2893
2894 # log10(NaN) = NaN
2895 ans = self._check_nans(context=context)
2896 if ans:
2897 return ans
2898
2899 # log10(0.0) == -Infinity
2900 if not self:
2901 return negInf
2902
2903 # log10(Infinity) = Infinity
2904 if self._isinfinity() == 1:
2905 return Inf
2906
2907 # log10(negative or -Infinity) raises InvalidOperation
2908 if self._sign == 1:
2909 return context._raise_error(InvalidOperation,
2910 'log10 of a negative value')
2911
2912 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00002913 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00002914 # answer may need rounding
2915 ans = Decimal(self._exp + len(self._int) - 1)
2916 else:
2917 # result is irrational, so necessarily inexact
2918 op = _WorkRep(self)
2919 c, e = op.int, op.exp
2920 p = context.prec
2921
2922 # correctly rounded result: repeatedly increase precision
2923 # until result is unambiguously roundable
2924 places = p-self._log10_exp_bound()+2
2925 while True:
2926 coeff = _dlog10(c, e, places)
2927 # assert len(str(abs(coeff)))-p >= 1
2928 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2929 break
2930 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002931 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002932
2933 context = context._shallow_copy()
2934 rounding = context._set_rounding(ROUND_HALF_EVEN)
2935 ans = ans._fix(context)
2936 context.rounding = rounding
2937 return ans
2938
2939 def logb(self, context=None):
2940 """ Returns the exponent of the magnitude of self's MSD.
2941
2942 The result is the integer which is the exponent of the magnitude
2943 of the most significant digit of self (as though it were truncated
2944 to a single digit while maintaining the value of that digit and
2945 without limiting the resulting exponent).
2946 """
2947 # logb(NaN) = NaN
2948 ans = self._check_nans(context=context)
2949 if ans:
2950 return ans
2951
2952 if context is None:
2953 context = getcontext()
2954
2955 # logb(+/-Inf) = +Inf
2956 if self._isinfinity():
2957 return Inf
2958
2959 # logb(0) = -Inf, DivisionByZero
2960 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00002961 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00002962
2963 # otherwise, simply return the adjusted exponent of self, as a
2964 # Decimal. Note that no attempt is made to fit the result
2965 # into the current context.
2966 return Decimal(self.adjusted())
2967
2968 def _islogical(self):
2969 """Return True if self is a logical operand.
2970
2971 For being logical, it must be a finite numbers with a sign of 0,
2972 an exponent of 0, and a coefficient whose digits must all be
2973 either 0 or 1.
2974 """
2975 if self._sign != 0 or self._exp != 0:
2976 return False
2977 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002978 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00002979 return False
2980 return True
2981
2982 def _fill_logical(self, context, opa, opb):
2983 dif = context.prec - len(opa)
2984 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002985 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00002986 elif dif < 0:
2987 opa = opa[-context.prec:]
2988 dif = context.prec - len(opb)
2989 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002990 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00002991 elif dif < 0:
2992 opb = opb[-context.prec:]
2993 return opa, opb
2994
2995 def logical_and(self, other, context=None):
2996 """Applies an 'and' operation between self and other's digits."""
2997 if context is None:
2998 context = getcontext()
2999 if not self._islogical() or not other._islogical():
3000 return context._raise_error(InvalidOperation)
3001
3002 # fill to context.prec
3003 (opa, opb) = self._fill_logical(context, self._int, other._int)
3004
3005 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003006 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3007 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003008
3009 def logical_invert(self, context=None):
3010 """Invert all its digits."""
3011 if context is None:
3012 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003013 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3014 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003015
3016 def logical_or(self, other, context=None):
3017 """Applies an 'or' operation between self and other's digits."""
3018 if context is None:
3019 context = getcontext()
3020 if not self._islogical() or not other._islogical():
3021 return context._raise_error(InvalidOperation)
3022
3023 # fill to context.prec
3024 (opa, opb) = self._fill_logical(context, self._int, other._int)
3025
3026 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003027 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3028 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003029
3030 def logical_xor(self, other, context=None):
3031 """Applies an 'xor' operation between self and other's digits."""
3032 if context is None:
3033 context = getcontext()
3034 if not self._islogical() or not other._islogical():
3035 return context._raise_error(InvalidOperation)
3036
3037 # fill to context.prec
3038 (opa, opb) = self._fill_logical(context, self._int, other._int)
3039
3040 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003041 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3042 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003043
3044 def max_mag(self, other, context=None):
3045 """Compares the values numerically with their sign ignored."""
3046 other = _convert_other(other, raiseit=True)
3047
Facundo Batista6c398da2007-09-17 17:30:13 +00003048 if context is None:
3049 context = getcontext()
3050
Facundo Batista353750c2007-09-13 18:13:15 +00003051 if self._is_special or other._is_special:
3052 # If one operand is a quiet NaN and the other is number, then the
3053 # number is always returned
3054 sn = self._isnan()
3055 on = other._isnan()
3056 if sn or on:
3057 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003058 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003059 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003060 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003061 return self._check_nans(other, context)
3062
3063 c = self.copy_abs().__cmp__(other.copy_abs())
3064 if c == 0:
3065 c = self.compare_total(other)
3066
3067 if c == -1:
3068 ans = other
3069 else:
3070 ans = self
3071
Facundo Batistae64acfa2007-12-17 14:18:42 +00003072 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003073
3074 def min_mag(self, other, context=None):
3075 """Compares the values numerically with their sign ignored."""
3076 other = _convert_other(other, raiseit=True)
3077
Facundo Batista6c398da2007-09-17 17:30:13 +00003078 if context is None:
3079 context = getcontext()
3080
Facundo Batista353750c2007-09-13 18:13:15 +00003081 if self._is_special or other._is_special:
3082 # If one operand is a quiet NaN and the other is number, then the
3083 # number is always returned
3084 sn = self._isnan()
3085 on = other._isnan()
3086 if sn or on:
3087 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003088 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003089 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003090 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003091 return self._check_nans(other, context)
3092
3093 c = self.copy_abs().__cmp__(other.copy_abs())
3094 if c == 0:
3095 c = self.compare_total(other)
3096
3097 if c == -1:
3098 ans = self
3099 else:
3100 ans = other
3101
Facundo Batistae64acfa2007-12-17 14:18:42 +00003102 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003103
3104 def next_minus(self, context=None):
3105 """Returns the largest representable number smaller than itself."""
3106 if context is None:
3107 context = getcontext()
3108
3109 ans = self._check_nans(context=context)
3110 if ans:
3111 return ans
3112
3113 if self._isinfinity() == -1:
3114 return negInf
3115 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003116 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003117
3118 context = context.copy()
3119 context._set_rounding(ROUND_FLOOR)
3120 context._ignore_all_flags()
3121 new_self = self._fix(context)
3122 if new_self != self:
3123 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003124 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3125 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003126
3127 def next_plus(self, context=None):
3128 """Returns the smallest representable number larger than itself."""
3129 if context is None:
3130 context = getcontext()
3131
3132 ans = self._check_nans(context=context)
3133 if ans:
3134 return ans
3135
3136 if self._isinfinity() == 1:
3137 return Inf
3138 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003139 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003140
3141 context = context.copy()
3142 context._set_rounding(ROUND_CEILING)
3143 context._ignore_all_flags()
3144 new_self = self._fix(context)
3145 if new_self != self:
3146 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003147 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3148 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003149
3150 def next_toward(self, other, context=None):
3151 """Returns the number closest to self, in the direction towards other.
3152
3153 The result is the closest representable number to self
3154 (excluding self) that is in the direction towards other,
3155 unless both have the same value. If the two operands are
3156 numerically equal, then the result is a copy of self with the
3157 sign set to be the same as the sign of other.
3158 """
3159 other = _convert_other(other, raiseit=True)
3160
3161 if context is None:
3162 context = getcontext()
3163
3164 ans = self._check_nans(other, context)
3165 if ans:
3166 return ans
3167
3168 comparison = self.__cmp__(other)
3169 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003170 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003171
3172 if comparison == -1:
3173 ans = self.next_plus(context)
3174 else: # comparison == 1
3175 ans = self.next_minus(context)
3176
3177 # decide which flags to raise using value of ans
3178 if ans._isinfinity():
3179 context._raise_error(Overflow,
3180 'Infinite result from next_toward',
3181 ans._sign)
3182 context._raise_error(Rounded)
3183 context._raise_error(Inexact)
3184 elif ans.adjusted() < context.Emin:
3185 context._raise_error(Underflow)
3186 context._raise_error(Subnormal)
3187 context._raise_error(Rounded)
3188 context._raise_error(Inexact)
3189 # if precision == 1 then we don't raise Clamped for a
3190 # result 0E-Etiny.
3191 if not ans:
3192 context._raise_error(Clamped)
3193
3194 return ans
3195
3196 def number_class(self, context=None):
3197 """Returns an indication of the class of self.
3198
3199 The class is one of the following strings:
3200 -sNaN
3201 -NaN
3202 -Infinity
3203 -Normal
3204 -Subnormal
3205 -Zero
3206 +Zero
3207 +Subnormal
3208 +Normal
3209 +Infinity
3210 """
3211 if self.is_snan():
3212 return "sNaN"
3213 if self.is_qnan():
3214 return "NaN"
3215 inf = self._isinfinity()
3216 if inf == 1:
3217 return "+Infinity"
3218 if inf == -1:
3219 return "-Infinity"
3220 if self.is_zero():
3221 if self._sign:
3222 return "-Zero"
3223 else:
3224 return "+Zero"
3225 if context is None:
3226 context = getcontext()
3227 if self.is_subnormal(context=context):
3228 if self._sign:
3229 return "-Subnormal"
3230 else:
3231 return "+Subnormal"
3232 # just a normal, regular, boring number, :)
3233 if self._sign:
3234 return "-Normal"
3235 else:
3236 return "+Normal"
3237
3238 def radix(self):
3239 """Just returns 10, as this is Decimal, :)"""
3240 return Decimal(10)
3241
3242 def rotate(self, other, context=None):
3243 """Returns a rotated copy of self, value-of-other times."""
3244 if context is None:
3245 context = getcontext()
3246
3247 ans = self._check_nans(other, context)
3248 if ans:
3249 return ans
3250
3251 if other._exp != 0:
3252 return context._raise_error(InvalidOperation)
3253 if not (-context.prec <= int(other) <= context.prec):
3254 return context._raise_error(InvalidOperation)
3255
3256 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003257 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003258
3259 # get values, pad if necessary
3260 torot = int(other)
3261 rotdig = self._int
3262 topad = context.prec - len(rotdig)
3263 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003264 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003265
3266 # let's rotate!
3267 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003268 return _dec_from_triple(self._sign,
3269 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003270
3271 def scaleb (self, other, context=None):
3272 """Returns self operand after adding the second value to its exp."""
3273 if context is None:
3274 context = getcontext()
3275
3276 ans = self._check_nans(other, context)
3277 if ans:
3278 return ans
3279
3280 if other._exp != 0:
3281 return context._raise_error(InvalidOperation)
3282 liminf = -2 * (context.Emax + context.prec)
3283 limsup = 2 * (context.Emax + context.prec)
3284 if not (liminf <= int(other) <= limsup):
3285 return context._raise_error(InvalidOperation)
3286
3287 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003288 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003289
Facundo Batista72bc54f2007-11-23 17:59:00 +00003290 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003291 d = d._fix(context)
3292 return d
3293
3294 def shift(self, other, context=None):
3295 """Returns a shifted copy of self, value-of-other times."""
3296 if context is None:
3297 context = getcontext()
3298
3299 ans = self._check_nans(other, context)
3300 if ans:
3301 return ans
3302
3303 if other._exp != 0:
3304 return context._raise_error(InvalidOperation)
3305 if not (-context.prec <= int(other) <= context.prec):
3306 return context._raise_error(InvalidOperation)
3307
3308 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003309 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003310
3311 # get values, pad if necessary
3312 torot = int(other)
3313 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003314 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003315 rotdig = self._int
3316 topad = context.prec - len(rotdig)
3317 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003318 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003319
3320 # let's shift!
3321 if torot < 0:
3322 rotated = rotdig[:torot]
3323 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003324 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003325 rotated = rotated[-context.prec:]
3326
Facundo Batista72bc54f2007-11-23 17:59:00 +00003327 return _dec_from_triple(self._sign,
3328 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003329
Facundo Batista59c58842007-04-10 12:58:45 +00003330 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003331 def __reduce__(self):
3332 return (self.__class__, (str(self),))
3333
3334 def __copy__(self):
3335 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003336 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003337 return self.__class__(str(self))
3338
3339 def __deepcopy__(self, memo):
3340 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003341 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003342 return self.__class__(str(self))
3343
Facundo Batista72bc54f2007-11-23 17:59:00 +00003344def _dec_from_triple(sign, coefficient, exponent, special=False):
3345 """Create a decimal instance directly, without any validation,
3346 normalization (e.g. removal of leading zeros) or argument
3347 conversion.
3348
3349 This function is for *internal use only*.
3350 """
3351
3352 self = object.__new__(Decimal)
3353 self._sign = sign
3354 self._int = coefficient
3355 self._exp = exponent
3356 self._is_special = special
3357
3358 return self
3359
Facundo Batista59c58842007-04-10 12:58:45 +00003360##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003361
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003362
3363# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003364rounding_functions = [name for name in Decimal.__dict__.keys()
3365 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003366for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003367 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003368 globalname = name[1:].upper()
3369 val = globals()[globalname]
3370 Decimal._pick_rounding_function[val] = name
3371
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003372del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003373
Nick Coghlanced12182006-09-02 03:54:17 +00003374class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003375 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003376
Nick Coghlanced12182006-09-02 03:54:17 +00003377 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003378 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003379 """
3380 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003381 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003382 def __enter__(self):
3383 self.saved_context = getcontext()
3384 setcontext(self.new_context)
3385 return self.new_context
3386 def __exit__(self, t, v, tb):
3387 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003388
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003389class Context(object):
3390 """Contains the context for a Decimal instance.
3391
3392 Contains:
3393 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003394 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003395 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003396 raised when it is caused. Otherwise, a value is
3397 substituted in.
3398 flags - When an exception is caused, flags[exception] is incremented.
3399 (Whether or not the trap_enabler is set)
3400 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003401 Emin - Minimum exponent
3402 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003403 capitals - If 1, 1*10^1 is printed as 1E+1.
3404 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003405 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003406 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003407
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003408 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003409 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003410 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003411 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003412 _ignored_flags=None):
3413 if flags is None:
3414 flags = []
3415 if _ignored_flags is None:
3416 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003417 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003418 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003419 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003420 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003421 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003422 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003423 for name, val in locals().items():
3424 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003425 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003426 else:
3427 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003428 del self.self
3429
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003430 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003431 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003432 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003433 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3434 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3435 % vars(self))
3436 names = [f.__name__ for f, v in self.flags.items() if v]
3437 s.append('flags=[' + ', '.join(names) + ']')
3438 names = [t.__name__ for t, v in self.traps.items() if v]
3439 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003440 return ', '.join(s) + ')'
3441
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003442 def clear_flags(self):
3443 """Reset all flags to zero"""
3444 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003445 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003446
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003447 def _shallow_copy(self):
3448 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003449 nc = Context(self.prec, self.rounding, self.traps,
3450 self.flags, self.Emin, self.Emax,
3451 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003452 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003453
3454 def copy(self):
3455 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003456 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003457 self.flags.copy(), self.Emin, self.Emax,
3458 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003459 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003460 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003461
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003462 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003463 """Handles an error
3464
3465 If the flag is in _ignored_flags, returns the default response.
3466 Otherwise, it increments the flag, then, if the corresponding
3467 trap_enabler is set, it reaises the exception. Otherwise, it returns
3468 the default value after incrementing the flag.
3469 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003470 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003471 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003472 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003473 return error().handle(self, *args)
3474
3475 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003476 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003477 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003478 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003479
3480 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003481 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003482 raise error, explanation
3483
3484 def _ignore_all_flags(self):
3485 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003486 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003487
3488 def _ignore_flags(self, *flags):
3489 """Ignore the flags, if they are raised"""
3490 # Do not mutate-- This way, copies of a context leave the original
3491 # alone.
3492 self._ignored_flags = (self._ignored_flags + list(flags))
3493 return list(flags)
3494
3495 def _regard_flags(self, *flags):
3496 """Stop ignoring the flags, if they are raised"""
3497 if flags and isinstance(flags[0], (tuple,list)):
3498 flags = flags[0]
3499 for flag in flags:
3500 self._ignored_flags.remove(flag)
3501
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003502 def __hash__(self):
3503 """A Context cannot be hashed."""
3504 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003505 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003506
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003507 def Etiny(self):
3508 """Returns Etiny (= Emin - prec + 1)"""
3509 return int(self.Emin - self.prec + 1)
3510
3511 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003512 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003513 return int(self.Emax - self.prec + 1)
3514
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003515 def _set_rounding(self, type):
3516 """Sets the rounding type.
3517
3518 Sets the rounding type, and returns the current (previous)
3519 rounding type. Often used like:
3520
3521 context = context.copy()
3522 # so you don't change the calling context
3523 # if an error occurs in the middle.
3524 rounding = context._set_rounding(ROUND_UP)
3525 val = self.__sub__(other, context=context)
3526 context._set_rounding(rounding)
3527
3528 This will make it round up for that operation.
3529 """
3530 rounding = self.rounding
3531 self.rounding= type
3532 return rounding
3533
Raymond Hettingerfed52962004-07-14 15:41:57 +00003534 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003535 """Creates a new Decimal instance but using self as context."""
3536 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003537 if d._isnan() and len(d._int) > self.prec - self._clamp:
3538 return self._raise_error(ConversionSyntax,
3539 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003540 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003541
Facundo Batista59c58842007-04-10 12:58:45 +00003542 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003543 def abs(self, a):
3544 """Returns the absolute value of the operand.
3545
3546 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003547 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003548 the plus operation on the operand.
3549
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003550 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003551 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003552 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003553 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003554 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003555 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003556 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003557 Decimal("101.5")
3558 """
3559 return a.__abs__(context=self)
3560
3561 def add(self, a, b):
3562 """Return the sum of the two operands.
3563
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003564 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003565 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003566 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003567 Decimal("1.02E+4")
3568 """
3569 return a.__add__(b, context=self)
3570
3571 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003572 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003573
Facundo Batista353750c2007-09-13 18:13:15 +00003574 def canonical(self, a):
3575 """Returns the same Decimal object.
3576
3577 As we do not have different encodings for the same number, the
3578 received object already is in its canonical form.
3579
3580 >>> ExtendedContext.canonical(Decimal('2.50'))
3581 Decimal("2.50")
3582 """
3583 return a.canonical(context=self)
3584
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003585 def compare(self, a, b):
3586 """Compares values numerically.
3587
3588 If the signs of the operands differ, a value representing each operand
3589 ('-1' if the operand is less than zero, '0' if the operand is zero or
3590 negative zero, or '1' if the operand is greater than zero) is used in
3591 place of that operand for the comparison instead of the actual
3592 operand.
3593
3594 The comparison is then effected by subtracting the second operand from
3595 the first and then returning a value according to the result of the
3596 subtraction: '-1' if the result is less than zero, '0' if the result is
3597 zero or negative zero, or '1' if the result is greater than zero.
3598
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003599 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003600 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003601 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003602 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003603 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003604 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003605 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003606 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003607 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003608 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003609 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003610 Decimal("-1")
3611 """
3612 return a.compare(b, context=self)
3613
Facundo Batista353750c2007-09-13 18:13:15 +00003614 def compare_signal(self, a, b):
3615 """Compares the values of the two operands numerically.
3616
3617 It's pretty much like compare(), but all NaNs signal, with signaling
3618 NaNs taking precedence over quiet NaNs.
3619
3620 >>> c = ExtendedContext
3621 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3622 Decimal("-1")
3623 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3624 Decimal("0")
3625 >>> c.flags[InvalidOperation] = 0
3626 >>> print c.flags[InvalidOperation]
3627 0
3628 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3629 Decimal("NaN")
3630 >>> print c.flags[InvalidOperation]
3631 1
3632 >>> c.flags[InvalidOperation] = 0
3633 >>> print c.flags[InvalidOperation]
3634 0
3635 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3636 Decimal("NaN")
3637 >>> print c.flags[InvalidOperation]
3638 1
3639 """
3640 return a.compare_signal(b, context=self)
3641
3642 def compare_total(self, a, b):
3643 """Compares two operands using their abstract representation.
3644
3645 This is not like the standard compare, which use their numerical
3646 value. Note that a total ordering is defined for all possible abstract
3647 representations.
3648
3649 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3650 Decimal("-1")
3651 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3652 Decimal("-1")
3653 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3654 Decimal("-1")
3655 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3656 Decimal("0")
3657 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3658 Decimal("1")
3659 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3660 Decimal("-1")
3661 """
3662 return a.compare_total(b)
3663
3664 def compare_total_mag(self, a, b):
3665 """Compares two operands using their abstract representation ignoring sign.
3666
3667 Like compare_total, but with operand's sign ignored and assumed to be 0.
3668 """
3669 return a.compare_total_mag(b)
3670
3671 def copy_abs(self, a):
3672 """Returns a copy of the operand with the sign set to 0.
3673
3674 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3675 Decimal("2.1")
3676 >>> ExtendedContext.copy_abs(Decimal('-100'))
3677 Decimal("100")
3678 """
3679 return a.copy_abs()
3680
3681 def copy_decimal(self, a):
3682 """Returns a copy of the decimal objet.
3683
3684 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3685 Decimal("2.1")
3686 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3687 Decimal("-1.00")
3688 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003689 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003690
3691 def copy_negate(self, a):
3692 """Returns a copy of the operand with the sign inverted.
3693
3694 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3695 Decimal("-101.5")
3696 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3697 Decimal("101.5")
3698 """
3699 return a.copy_negate()
3700
3701 def copy_sign(self, a, b):
3702 """Copies the second operand's sign to the first one.
3703
3704 In detail, it returns a copy of the first operand with the sign
3705 equal to the sign of the second operand.
3706
3707 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3708 Decimal("1.50")
3709 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3710 Decimal("1.50")
3711 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3712 Decimal("-1.50")
3713 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3714 Decimal("-1.50")
3715 """
3716 return a.copy_sign(b)
3717
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003718 def divide(self, a, b):
3719 """Decimal division in a specified context.
3720
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003721 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003722 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003723 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003724 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003725 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003726 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003727 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003728 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003729 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003730 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003731 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003732 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003733 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003734 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003735 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003736 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003737 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003738 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003739 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003740 Decimal("1.20E+6")
3741 """
3742 return a.__div__(b, context=self)
3743
3744 def divide_int(self, a, b):
3745 """Divides two numbers and returns the integer part of the result.
3746
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003747 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003748 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003749 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003750 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003751 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003752 Decimal("3")
3753 """
3754 return a.__floordiv__(b, context=self)
3755
3756 def divmod(self, a, b):
3757 return a.__divmod__(b, context=self)
3758
Facundo Batista353750c2007-09-13 18:13:15 +00003759 def exp(self, a):
3760 """Returns e ** a.
3761
3762 >>> c = ExtendedContext.copy()
3763 >>> c.Emin = -999
3764 >>> c.Emax = 999
3765 >>> c.exp(Decimal('-Infinity'))
3766 Decimal("0")
3767 >>> c.exp(Decimal('-1'))
3768 Decimal("0.367879441")
3769 >>> c.exp(Decimal('0'))
3770 Decimal("1")
3771 >>> c.exp(Decimal('1'))
3772 Decimal("2.71828183")
3773 >>> c.exp(Decimal('0.693147181'))
3774 Decimal("2.00000000")
3775 >>> c.exp(Decimal('+Infinity'))
3776 Decimal("Infinity")
3777 """
3778 return a.exp(context=self)
3779
3780 def fma(self, a, b, c):
3781 """Returns a multiplied by b, plus c.
3782
3783 The first two operands are multiplied together, using multiply,
3784 the third operand is then added to the result of that
3785 multiplication, using add, all with only one final rounding.
3786
3787 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3788 Decimal("22")
3789 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3790 Decimal("-8")
3791 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3792 Decimal("1.38435736E+12")
3793 """
3794 return a.fma(b, c, context=self)
3795
3796 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003797 """Return True if the operand is canonical; otherwise return False.
3798
3799 Currently, the encoding of a Decimal instance is always
3800 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003801
3802 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003803 True
Facundo Batista353750c2007-09-13 18:13:15 +00003804 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003805 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003806
3807 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003808 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003809
Facundo Batista1a191df2007-10-02 17:01:24 +00003810 A Decimal instance is considered finite if it is neither
3811 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003812
3813 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003814 True
Facundo Batista353750c2007-09-13 18:13:15 +00003815 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003816 True
Facundo Batista353750c2007-09-13 18:13:15 +00003817 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003818 True
Facundo Batista353750c2007-09-13 18:13:15 +00003819 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003820 False
Facundo Batista353750c2007-09-13 18:13:15 +00003821 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003822 False
Facundo Batista353750c2007-09-13 18:13:15 +00003823 """
3824 return a.is_finite()
3825
3826 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003827 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003828
3829 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003830 False
Facundo Batista353750c2007-09-13 18:13:15 +00003831 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003832 True
Facundo Batista353750c2007-09-13 18:13:15 +00003833 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003834 False
Facundo Batista353750c2007-09-13 18:13:15 +00003835 """
3836 return a.is_infinite()
3837
3838 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003839 """Return True if the operand is a qNaN or sNaN;
3840 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003841
3842 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003843 False
Facundo Batista353750c2007-09-13 18:13:15 +00003844 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003845 True
Facundo Batista353750c2007-09-13 18:13:15 +00003846 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003847 True
Facundo Batista353750c2007-09-13 18:13:15 +00003848 """
3849 return a.is_nan()
3850
3851 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003852 """Return True if the operand is a normal number;
3853 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003854
3855 >>> c = ExtendedContext.copy()
3856 >>> c.Emin = -999
3857 >>> c.Emax = 999
3858 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003859 True
Facundo Batista353750c2007-09-13 18:13:15 +00003860 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003861 False
Facundo Batista353750c2007-09-13 18:13:15 +00003862 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003863 False
Facundo Batista353750c2007-09-13 18:13:15 +00003864 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003865 False
Facundo Batista353750c2007-09-13 18:13:15 +00003866 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003867 False
Facundo Batista353750c2007-09-13 18:13:15 +00003868 """
3869 return a.is_normal(context=self)
3870
3871 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003872 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003873
3874 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003875 False
Facundo Batista353750c2007-09-13 18:13:15 +00003876 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003877 True
Facundo Batista353750c2007-09-13 18:13:15 +00003878 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003879 False
Facundo Batista353750c2007-09-13 18:13:15 +00003880 """
3881 return a.is_qnan()
3882
3883 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003884 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003885
3886 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003887 False
Facundo Batista353750c2007-09-13 18:13:15 +00003888 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003889 True
Facundo Batista353750c2007-09-13 18:13:15 +00003890 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003891 True
Facundo Batista353750c2007-09-13 18:13:15 +00003892 """
3893 return a.is_signed()
3894
3895 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003896 """Return True if the operand is a signaling NaN;
3897 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003898
3899 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003900 False
Facundo Batista353750c2007-09-13 18:13:15 +00003901 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003902 False
Facundo Batista353750c2007-09-13 18:13:15 +00003903 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003904 True
Facundo Batista353750c2007-09-13 18:13:15 +00003905 """
3906 return a.is_snan()
3907
3908 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003909 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003910
3911 >>> c = ExtendedContext.copy()
3912 >>> c.Emin = -999
3913 >>> c.Emax = 999
3914 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003915 False
Facundo Batista353750c2007-09-13 18:13:15 +00003916 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003917 True
Facundo Batista353750c2007-09-13 18:13:15 +00003918 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003919 False
Facundo Batista353750c2007-09-13 18:13:15 +00003920 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003921 False
Facundo Batista353750c2007-09-13 18:13:15 +00003922 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003923 False
Facundo Batista353750c2007-09-13 18:13:15 +00003924 """
3925 return a.is_subnormal(context=self)
3926
3927 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003928 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003929
3930 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003931 True
Facundo Batista353750c2007-09-13 18:13:15 +00003932 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003933 False
Facundo Batista353750c2007-09-13 18:13:15 +00003934 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003935 True
Facundo Batista353750c2007-09-13 18:13:15 +00003936 """
3937 return a.is_zero()
3938
3939 def ln(self, a):
3940 """Returns the natural (base e) logarithm of the operand.
3941
3942 >>> c = ExtendedContext.copy()
3943 >>> c.Emin = -999
3944 >>> c.Emax = 999
3945 >>> c.ln(Decimal('0'))
3946 Decimal("-Infinity")
3947 >>> c.ln(Decimal('1.000'))
3948 Decimal("0")
3949 >>> c.ln(Decimal('2.71828183'))
3950 Decimal("1.00000000")
3951 >>> c.ln(Decimal('10'))
3952 Decimal("2.30258509")
3953 >>> c.ln(Decimal('+Infinity'))
3954 Decimal("Infinity")
3955 """
3956 return a.ln(context=self)
3957
3958 def log10(self, a):
3959 """Returns the base 10 logarithm of the operand.
3960
3961 >>> c = ExtendedContext.copy()
3962 >>> c.Emin = -999
3963 >>> c.Emax = 999
3964 >>> c.log10(Decimal('0'))
3965 Decimal("-Infinity")
3966 >>> c.log10(Decimal('0.001'))
3967 Decimal("-3")
3968 >>> c.log10(Decimal('1.000'))
3969 Decimal("0")
3970 >>> c.log10(Decimal('2'))
3971 Decimal("0.301029996")
3972 >>> c.log10(Decimal('10'))
3973 Decimal("1")
3974 >>> c.log10(Decimal('70'))
3975 Decimal("1.84509804")
3976 >>> c.log10(Decimal('+Infinity'))
3977 Decimal("Infinity")
3978 """
3979 return a.log10(context=self)
3980
3981 def logb(self, a):
3982 """ Returns the exponent of the magnitude of the operand's MSD.
3983
3984 The result is the integer which is the exponent of the magnitude
3985 of the most significant digit of the operand (as though the
3986 operand were truncated to a single digit while maintaining the
3987 value of that digit and without limiting the resulting exponent).
3988
3989 >>> ExtendedContext.logb(Decimal('250'))
3990 Decimal("2")
3991 >>> ExtendedContext.logb(Decimal('2.50'))
3992 Decimal("0")
3993 >>> ExtendedContext.logb(Decimal('0.03'))
3994 Decimal("-2")
3995 >>> ExtendedContext.logb(Decimal('0'))
3996 Decimal("-Infinity")
3997 """
3998 return a.logb(context=self)
3999
4000 def logical_and(self, a, b):
4001 """Applies the logical operation 'and' between each operand's digits.
4002
4003 The operands must be both logical numbers.
4004
4005 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4006 Decimal("0")
4007 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4008 Decimal("0")
4009 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4010 Decimal("0")
4011 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4012 Decimal("1")
4013 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4014 Decimal("1000")
4015 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4016 Decimal("10")
4017 """
4018 return a.logical_and(b, context=self)
4019
4020 def logical_invert(self, a):
4021 """Invert all the digits in the operand.
4022
4023 The operand must be a logical number.
4024
4025 >>> ExtendedContext.logical_invert(Decimal('0'))
4026 Decimal("111111111")
4027 >>> ExtendedContext.logical_invert(Decimal('1'))
4028 Decimal("111111110")
4029 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4030 Decimal("0")
4031 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4032 Decimal("10101010")
4033 """
4034 return a.logical_invert(context=self)
4035
4036 def logical_or(self, a, b):
4037 """Applies the logical operation 'or' between each operand's digits.
4038
4039 The operands must be both logical numbers.
4040
4041 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4042 Decimal("0")
4043 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4044 Decimal("1")
4045 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4046 Decimal("1")
4047 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4048 Decimal("1")
4049 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4050 Decimal("1110")
4051 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4052 Decimal("1110")
4053 """
4054 return a.logical_or(b, context=self)
4055
4056 def logical_xor(self, a, b):
4057 """Applies the logical operation 'xor' between each operand's digits.
4058
4059 The operands must be both logical numbers.
4060
4061 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4062 Decimal("0")
4063 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4064 Decimal("1")
4065 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4066 Decimal("1")
4067 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4068 Decimal("0")
4069 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4070 Decimal("110")
4071 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4072 Decimal("1101")
4073 """
4074 return a.logical_xor(b, context=self)
4075
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004076 def max(self, a,b):
4077 """max compares two values numerically and returns the maximum.
4078
4079 If either operand is a NaN then the general rules apply.
4080 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004081 operation. If they are numerically equal then the left-hand operand
4082 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004083 infinity) of the two operands is chosen as the result.
4084
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004085 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004086 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004087 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004088 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004089 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004090 Decimal("1")
4091 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4092 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004093 """
4094 return a.max(b, context=self)
4095
Facundo Batista353750c2007-09-13 18:13:15 +00004096 def max_mag(self, a, b):
4097 """Compares the values numerically with their sign ignored."""
4098 return a.max_mag(b, context=self)
4099
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004100 def min(self, a,b):
4101 """min compares two values numerically and returns the minimum.
4102
4103 If either operand is a NaN then the general rules apply.
4104 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004105 operation. If they are numerically equal then the left-hand operand
4106 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004107 infinity) of the two operands is chosen as the result.
4108
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004109 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004110 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004111 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004112 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004113 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004114 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004115 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4116 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004117 """
4118 return a.min(b, context=self)
4119
Facundo Batista353750c2007-09-13 18:13:15 +00004120 def min_mag(self, a, b):
4121 """Compares the values numerically with their sign ignored."""
4122 return a.min_mag(b, context=self)
4123
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004124 def minus(self, a):
4125 """Minus corresponds to unary prefix minus in Python.
4126
4127 The operation is evaluated using the same rules as subtract; the
4128 operation minus(a) is calculated as subtract('0', a) where the '0'
4129 has the same exponent as the operand.
4130
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004131 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004132 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004133 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004134 Decimal("1.3")
4135 """
4136 return a.__neg__(context=self)
4137
4138 def multiply(self, a, b):
4139 """multiply multiplies two operands.
4140
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004141 If either operand is a special value then the general rules apply.
4142 Otherwise, the operands are multiplied together ('long multiplication'),
4143 resulting in a number which may be as long as the sum of the lengths
4144 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004145
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004146 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004147 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004148 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004149 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004150 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004151 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004152 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004153 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004154 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004155 Decimal("4.28135971E+11")
4156 """
4157 return a.__mul__(b, context=self)
4158
Facundo Batista353750c2007-09-13 18:13:15 +00004159 def next_minus(self, a):
4160 """Returns the largest representable number smaller than a.
4161
4162 >>> c = ExtendedContext.copy()
4163 >>> c.Emin = -999
4164 >>> c.Emax = 999
4165 >>> ExtendedContext.next_minus(Decimal('1'))
4166 Decimal("0.999999999")
4167 >>> c.next_minus(Decimal('1E-1007'))
4168 Decimal("0E-1007")
4169 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4170 Decimal("-1.00000004")
4171 >>> c.next_minus(Decimal('Infinity'))
4172 Decimal("9.99999999E+999")
4173 """
4174 return a.next_minus(context=self)
4175
4176 def next_plus(self, a):
4177 """Returns the smallest representable number larger than a.
4178
4179 >>> c = ExtendedContext.copy()
4180 >>> c.Emin = -999
4181 >>> c.Emax = 999
4182 >>> ExtendedContext.next_plus(Decimal('1'))
4183 Decimal("1.00000001")
4184 >>> c.next_plus(Decimal('-1E-1007'))
4185 Decimal("-0E-1007")
4186 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4187 Decimal("-1.00000002")
4188 >>> c.next_plus(Decimal('-Infinity'))
4189 Decimal("-9.99999999E+999")
4190 """
4191 return a.next_plus(context=self)
4192
4193 def next_toward(self, a, b):
4194 """Returns the number closest to a, in direction towards b.
4195
4196 The result is the closest representable number from the first
4197 operand (but not the first operand) that is in the direction
4198 towards the second operand, unless the operands have the same
4199 value.
4200
4201 >>> c = ExtendedContext.copy()
4202 >>> c.Emin = -999
4203 >>> c.Emax = 999
4204 >>> c.next_toward(Decimal('1'), Decimal('2'))
4205 Decimal("1.00000001")
4206 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4207 Decimal("-0E-1007")
4208 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4209 Decimal("-1.00000002")
4210 >>> c.next_toward(Decimal('1'), Decimal('0'))
4211 Decimal("0.999999999")
4212 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4213 Decimal("0E-1007")
4214 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4215 Decimal("-1.00000004")
4216 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4217 Decimal("-0.00")
4218 """
4219 return a.next_toward(b, context=self)
4220
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004221 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004222 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004223
4224 Essentially a plus operation with all trailing zeros removed from the
4225 result.
4226
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004227 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004228 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004229 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004230 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004231 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004232 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004233 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004234 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004235 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004236 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004237 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004238 Decimal("0")
4239 """
4240 return a.normalize(context=self)
4241
Facundo Batista353750c2007-09-13 18:13:15 +00004242 def number_class(self, a):
4243 """Returns an indication of the class of the operand.
4244
4245 The class is one of the following strings:
4246 -sNaN
4247 -NaN
4248 -Infinity
4249 -Normal
4250 -Subnormal
4251 -Zero
4252 +Zero
4253 +Subnormal
4254 +Normal
4255 +Infinity
4256
4257 >>> c = Context(ExtendedContext)
4258 >>> c.Emin = -999
4259 >>> c.Emax = 999
4260 >>> c.number_class(Decimal('Infinity'))
4261 '+Infinity'
4262 >>> c.number_class(Decimal('1E-10'))
4263 '+Normal'
4264 >>> c.number_class(Decimal('2.50'))
4265 '+Normal'
4266 >>> c.number_class(Decimal('0.1E-999'))
4267 '+Subnormal'
4268 >>> c.number_class(Decimal('0'))
4269 '+Zero'
4270 >>> c.number_class(Decimal('-0'))
4271 '-Zero'
4272 >>> c.number_class(Decimal('-0.1E-999'))
4273 '-Subnormal'
4274 >>> c.number_class(Decimal('-1E-10'))
4275 '-Normal'
4276 >>> c.number_class(Decimal('-2.50'))
4277 '-Normal'
4278 >>> c.number_class(Decimal('-Infinity'))
4279 '-Infinity'
4280 >>> c.number_class(Decimal('NaN'))
4281 'NaN'
4282 >>> c.number_class(Decimal('-NaN'))
4283 'NaN'
4284 >>> c.number_class(Decimal('sNaN'))
4285 'sNaN'
4286 """
4287 return a.number_class(context=self)
4288
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004289 def plus(self, a):
4290 """Plus corresponds to unary prefix plus in Python.
4291
4292 The operation is evaluated using the same rules as add; the
4293 operation plus(a) is calculated as add('0', a) where the '0'
4294 has the same exponent as the operand.
4295
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004296 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004297 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004298 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004299 Decimal("-1.3")
4300 """
4301 return a.__pos__(context=self)
4302
4303 def power(self, a, b, modulo=None):
4304 """Raises a to the power of b, to modulo if given.
4305
Facundo Batista353750c2007-09-13 18:13:15 +00004306 With two arguments, compute a**b. If a is negative then b
4307 must be integral. The result will be inexact unless b is
4308 integral and the result is finite and can be expressed exactly
4309 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004310
Facundo Batista353750c2007-09-13 18:13:15 +00004311 With three arguments, compute (a**b) % modulo. For the
4312 three argument form, the following restrictions on the
4313 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004314
Facundo Batista353750c2007-09-13 18:13:15 +00004315 - all three arguments must be integral
4316 - b must be nonnegative
4317 - at least one of a or b must be nonzero
4318 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004319
Facundo Batista353750c2007-09-13 18:13:15 +00004320 The result of pow(a, b, modulo) is identical to the result
4321 that would be obtained by computing (a**b) % modulo with
4322 unbounded precision, but is computed more efficiently. It is
4323 always exact.
4324
4325 >>> c = ExtendedContext.copy()
4326 >>> c.Emin = -999
4327 >>> c.Emax = 999
4328 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004329 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004330 >>> c.power(Decimal('-2'), Decimal('3'))
4331 Decimal("-8")
4332 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004333 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004334 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004335 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004336 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4337 Decimal("2.00000000")
4338 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004339 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004340 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004341 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004342 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004343 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004344 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004345 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004346 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004347 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004348 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004349 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004350 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004351 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004352 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004353 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004354
4355 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4356 Decimal("11")
4357 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4358 Decimal("-11")
4359 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4360 Decimal("1")
4361 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4362 Decimal("11")
4363 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4364 Decimal("11729830")
4365 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4366 Decimal("-0")
4367 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4368 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004369 """
4370 return a.__pow__(b, modulo, context=self)
4371
4372 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004373 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004374
4375 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004376 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004377 exponent is being increased), multiplied by a positive power of ten (if
4378 the exponent is being decreased), or is unchanged (if the exponent is
4379 already equal to that of the right-hand operand).
4380
4381 Unlike other operations, if the length of the coefficient after the
4382 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004383 operation condition is raised. This guarantees that, unless there is
4384 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004385 equal to that of the right-hand operand.
4386
4387 Also unlike other operations, quantize will never raise Underflow, even
4388 if the result is subnormal and inexact.
4389
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004390 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004391 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004392 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004393 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004394 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004395 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004396 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004397 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004398 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004399 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004400 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004401 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004402 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004403 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004404 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004405 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004406 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004407 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004408 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004409 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004410 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004412 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004413 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004414 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004415 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004416 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004417 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004418 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004419 Decimal("2E+2")
4420 """
4421 return a.quantize(b, context=self)
4422
Facundo Batista353750c2007-09-13 18:13:15 +00004423 def radix(self):
4424 """Just returns 10, as this is Decimal, :)
4425
4426 >>> ExtendedContext.radix()
4427 Decimal("10")
4428 """
4429 return Decimal(10)
4430
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004431 def remainder(self, a, b):
4432 """Returns the remainder from integer division.
4433
4434 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004435 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004436 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004437 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004438
4439 This operation will fail under the same conditions as integer division
4440 (that is, if integer division on the same two operands would fail, the
4441 remainder cannot be calculated).
4442
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004443 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004444 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004445 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004446 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004447 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004448 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004449 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004450 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004451 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004452 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004453 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004454 Decimal("1.0")
4455 """
4456 return a.__mod__(b, context=self)
4457
4458 def remainder_near(self, a, b):
4459 """Returns to be "a - b * n", where n is the integer nearest the exact
4460 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004461 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004462 sign of a.
4463
4464 This operation will fail under the same conditions as integer division
4465 (that is, if integer division on the same two operands would fail, the
4466 remainder cannot be calculated).
4467
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004468 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004469 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004470 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004471 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004472 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004473 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004474 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004475 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004476 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004477 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004478 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004479 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004480 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004481 Decimal("-0.3")
4482 """
4483 return a.remainder_near(b, context=self)
4484
Facundo Batista353750c2007-09-13 18:13:15 +00004485 def rotate(self, a, b):
4486 """Returns a rotated copy of a, b times.
4487
4488 The coefficient of the result is a rotated copy of the digits in
4489 the coefficient of the first operand. The number of places of
4490 rotation is taken from the absolute value of the second operand,
4491 with the rotation being to the left if the second operand is
4492 positive or to the right otherwise.
4493
4494 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4495 Decimal("400000003")
4496 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4497 Decimal("12")
4498 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4499 Decimal("891234567")
4500 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4501 Decimal("123456789")
4502 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4503 Decimal("345678912")
4504 """
4505 return a.rotate(b, context=self)
4506
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004507 def same_quantum(self, a, b):
4508 """Returns True if the two operands have the same exponent.
4509
4510 The result is never affected by either the sign or the coefficient of
4511 either operand.
4512
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004513 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004514 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004515 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004516 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004517 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004518 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004519 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004520 True
4521 """
4522 return a.same_quantum(b)
4523
Facundo Batista353750c2007-09-13 18:13:15 +00004524 def scaleb (self, a, b):
4525 """Returns the first operand after adding the second value its exp.
4526
4527 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4528 Decimal("0.0750")
4529 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4530 Decimal("7.50")
4531 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4532 Decimal("7.50E+3")
4533 """
4534 return a.scaleb (b, context=self)
4535
4536 def shift(self, a, b):
4537 """Returns a shifted copy of a, b times.
4538
4539 The coefficient of the result is a shifted copy of the digits
4540 in the coefficient of the first operand. The number of places
4541 to shift is taken from the absolute value of the second operand,
4542 with the shift being to the left if the second operand is
4543 positive or to the right otherwise. Digits shifted into the
4544 coefficient are zeros.
4545
4546 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4547 Decimal("400000000")
4548 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4549 Decimal("0")
4550 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4551 Decimal("1234567")
4552 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4553 Decimal("123456789")
4554 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4555 Decimal("345678900")
4556 """
4557 return a.shift(b, context=self)
4558
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004559 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004560 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004561
4562 If the result must be inexact, it is rounded using the round-half-even
4563 algorithm.
4564
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004565 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004566 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004567 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004568 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004569 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004570 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004571 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004572 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004573 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004574 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004575 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004576 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004577 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004578 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004579 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004580 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004581 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004582 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004583 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004584 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004585 """
4586 return a.sqrt(context=self)
4587
4588 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004589 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004590
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004591 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004592 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004593 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004594 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004595 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004596 Decimal("-0.77")
4597 """
4598 return a.__sub__(b, context=self)
4599
4600 def to_eng_string(self, a):
4601 """Converts a number to a string, using scientific notation.
4602
4603 The operation is not affected by the context.
4604 """
4605 return a.to_eng_string(context=self)
4606
4607 def to_sci_string(self, a):
4608 """Converts a number to a string, using scientific notation.
4609
4610 The operation is not affected by the context.
4611 """
4612 return a.__str__(context=self)
4613
Facundo Batista353750c2007-09-13 18:13:15 +00004614 def to_integral_exact(self, a):
4615 """Rounds to an integer.
4616
4617 When the operand has a negative exponent, the result is the same
4618 as using the quantize() operation using the given operand as the
4619 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4620 of the operand as the precision setting; Inexact and Rounded flags
4621 are allowed in this operation. The rounding mode is taken from the
4622 context.
4623
4624 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4625 Decimal("2")
4626 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4627 Decimal("100")
4628 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4629 Decimal("100")
4630 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4631 Decimal("102")
4632 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4633 Decimal("-102")
4634 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4635 Decimal("1.0E+6")
4636 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4637 Decimal("7.89E+77")
4638 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4639 Decimal("-Infinity")
4640 """
4641 return a.to_integral_exact(context=self)
4642
4643 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004644 """Rounds to an integer.
4645
4646 When the operand has a negative exponent, the result is the same
4647 as using the quantize() operation using the given operand as the
4648 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4649 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004650 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004651
Facundo Batista353750c2007-09-13 18:13:15 +00004652 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004653 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004654 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004656 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004657 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004658 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004659 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004660 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004661 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004662 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004663 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004664 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004665 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004666 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 Decimal("-Infinity")
4668 """
Facundo Batista353750c2007-09-13 18:13:15 +00004669 return a.to_integral_value(context=self)
4670
4671 # the method name changed, but we provide also the old one, for compatibility
4672 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004673
4674class _WorkRep(object):
4675 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004676 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004677 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004678 # exp: None, int, or string
4679
4680 def __init__(self, value=None):
4681 if value is None:
4682 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004683 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004684 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004685 elif isinstance(value, Decimal):
4686 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004687 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004688 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004689 else:
4690 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004691 self.sign = value[0]
4692 self.int = value[1]
4693 self.exp = value[2]
4694
4695 def __repr__(self):
4696 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4697
4698 __str__ = __repr__
4699
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004700
4701
Facundo Batistae64acfa2007-12-17 14:18:42 +00004702def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004703 """Normalizes op1, op2 to have the same exp and length of coefficient.
4704
4705 Done during addition.
4706 """
Facundo Batista353750c2007-09-13 18:13:15 +00004707 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004708 tmp = op2
4709 other = op1
4710 else:
4711 tmp = op1
4712 other = op2
4713
Facundo Batista353750c2007-09-13 18:13:15 +00004714 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4715 # Then adding 10**exp to tmp has the same effect (after rounding)
4716 # as adding any positive quantity smaller than 10**exp; similarly
4717 # for subtraction. So if other is smaller than 10**exp we replace
4718 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004719 tmp_len = len(str(tmp.int))
4720 other_len = len(str(other.int))
4721 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4722 if other_len + other.exp - 1 < exp:
4723 other.int = 1
4724 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004725
Facundo Batista353750c2007-09-13 18:13:15 +00004726 tmp.int *= 10 ** (tmp.exp - other.exp)
4727 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004728 return op1, op2
4729
Facundo Batista353750c2007-09-13 18:13:15 +00004730##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4731
4732# This function from Tim Peters was taken from here:
4733# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4734# The correction being in the function definition is for speed, and
4735# the whole function is not resolved with math.log because of avoiding
4736# the use of floats.
4737def _nbits(n, correction = {
4738 '0': 4, '1': 3, '2': 2, '3': 2,
4739 '4': 1, '5': 1, '6': 1, '7': 1,
4740 '8': 0, '9': 0, 'a': 0, 'b': 0,
4741 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4742 """Number of bits in binary representation of the positive integer n,
4743 or 0 if n == 0.
4744 """
4745 if n < 0:
4746 raise ValueError("The argument to _nbits should be nonnegative.")
4747 hex_n = "%x" % n
4748 return 4*len(hex_n) - correction[hex_n[0]]
4749
4750def _sqrt_nearest(n, a):
4751 """Closest integer to the square root of the positive integer n. a is
4752 an initial approximation to the square root. Any positive integer
4753 will do for a, but the closer a is to the square root of n the
4754 faster convergence will be.
4755
4756 """
4757 if n <= 0 or a <= 0:
4758 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4759
4760 b=0
4761 while a != b:
4762 b, a = a, a--n//a>>1
4763 return a
4764
4765def _rshift_nearest(x, shift):
4766 """Given an integer x and a nonnegative integer shift, return closest
4767 integer to x / 2**shift; use round-to-even in case of a tie.
4768
4769 """
4770 b, q = 1L << shift, x >> shift
4771 return q + (2*(x & (b-1)) + (q&1) > b)
4772
4773def _div_nearest(a, b):
4774 """Closest integer to a/b, a and b positive integers; rounds to even
4775 in the case of a tie.
4776
4777 """
4778 q, r = divmod(a, b)
4779 return q + (2*r + (q&1) > b)
4780
4781def _ilog(x, M, L = 8):
4782 """Integer approximation to M*log(x/M), with absolute error boundable
4783 in terms only of x/M.
4784
4785 Given positive integers x and M, return an integer approximation to
4786 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4787 between the approximation and the exact result is at most 22. For
4788 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4789 both cases these are upper bounds on the error; it will usually be
4790 much smaller."""
4791
4792 # The basic algorithm is the following: let log1p be the function
4793 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4794 # the reduction
4795 #
4796 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4797 #
4798 # repeatedly until the argument to log1p is small (< 2**-L in
4799 # absolute value). For small y we can use the Taylor series
4800 # expansion
4801 #
4802 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4803 #
4804 # truncating at T such that y**T is small enough. The whole
4805 # computation is carried out in a form of fixed-point arithmetic,
4806 # with a real number z being represented by an integer
4807 # approximation to z*M. To avoid loss of precision, the y below
4808 # is actually an integer approximation to 2**R*y*M, where R is the
4809 # number of reductions performed so far.
4810
4811 y = x-M
4812 # argument reduction; R = number of reductions performed
4813 R = 0
4814 while (R <= L and long(abs(y)) << L-R >= M or
4815 R > L and abs(y) >> R-L >= M):
4816 y = _div_nearest(long(M*y) << 1,
4817 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4818 R += 1
4819
4820 # Taylor series with T terms
4821 T = -int(-10*len(str(M))//(3*L))
4822 yshift = _rshift_nearest(y, R)
4823 w = _div_nearest(M, T)
4824 for k in xrange(T-1, 0, -1):
4825 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4826
4827 return _div_nearest(w*y, M)
4828
4829def _dlog10(c, e, p):
4830 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4831 approximation to 10**p * log10(c*10**e), with an absolute error of
4832 at most 1. Assumes that c*10**e is not exactly 1."""
4833
4834 # increase precision by 2; compensate for this by dividing
4835 # final result by 100
4836 p += 2
4837
4838 # write c*10**e as d*10**f with either:
4839 # f >= 0 and 1 <= d <= 10, or
4840 # f <= 0 and 0.1 <= d <= 1.
4841 # Thus for c*10**e close to 1, f = 0
4842 l = len(str(c))
4843 f = e+l - (e+l >= 1)
4844
4845 if p > 0:
4846 M = 10**p
4847 k = e+p-f
4848 if k >= 0:
4849 c *= 10**k
4850 else:
4851 c = _div_nearest(c, 10**-k)
4852
4853 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004854 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004855 log_d = _div_nearest(log_d*M, log_10)
4856 log_tenpower = f*M # exact
4857 else:
4858 log_d = 0 # error < 2.31
4859 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4860
4861 return _div_nearest(log_tenpower+log_d, 100)
4862
4863def _dlog(c, e, p):
4864 """Given integers c, e and p with c > 0, compute an integer
4865 approximation to 10**p * log(c*10**e), with an absolute error of
4866 at most 1. Assumes that c*10**e is not exactly 1."""
4867
4868 # Increase precision by 2. The precision increase is compensated
4869 # for at the end with a division by 100.
4870 p += 2
4871
4872 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4873 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4874 # as 10**p * log(d) + 10**p*f * log(10).
4875 l = len(str(c))
4876 f = e+l - (e+l >= 1)
4877
4878 # compute approximation to 10**p*log(d), with error < 27
4879 if p > 0:
4880 k = e+p-f
4881 if k >= 0:
4882 c *= 10**k
4883 else:
4884 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4885
4886 # _ilog magnifies existing error in c by a factor of at most 10
4887 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4888 else:
4889 # p <= 0: just approximate the whole thing by 0; error < 2.31
4890 log_d = 0
4891
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004892 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004893 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004894 extra = len(str(abs(f)))-1
4895 if p + extra >= 0:
4896 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4897 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4898 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004899 else:
4900 f_log_ten = 0
4901 else:
4902 f_log_ten = 0
4903
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004904 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004905 return _div_nearest(f_log_ten + log_d, 100)
4906
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004907class _Log10Memoize(object):
4908 """Class to compute, store, and allow retrieval of, digits of the
4909 constant log(10) = 2.302585.... This constant is needed by
4910 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4911 def __init__(self):
4912 self.digits = "23025850929940456840179914546843642076011014886"
4913
4914 def getdigits(self, p):
4915 """Given an integer p >= 0, return floor(10**p)*log(10).
4916
4917 For example, self.getdigits(3) returns 2302.
4918 """
4919 # digits are stored as a string, for quick conversion to
4920 # integer in the case that we've already computed enough
4921 # digits; the stored digits should always be correct
4922 # (truncated, not rounded to nearest).
4923 if p < 0:
4924 raise ValueError("p should be nonnegative")
4925
4926 if p >= len(self.digits):
4927 # compute p+3, p+6, p+9, ... digits; continue until at
4928 # least one of the extra digits is nonzero
4929 extra = 3
4930 while True:
4931 # compute p+extra digits, correct to within 1ulp
4932 M = 10**(p+extra+2)
4933 digits = str(_div_nearest(_ilog(10*M, M), 100))
4934 if digits[-extra:] != '0'*extra:
4935 break
4936 extra += 3
4937 # keep all reliable digits so far; remove trailing zeros
4938 # and next nonzero digit
4939 self.digits = digits.rstrip('0')[:-1]
4940 return int(self.digits[:p+1])
4941
4942_log10_digits = _Log10Memoize().getdigits
4943
Facundo Batista353750c2007-09-13 18:13:15 +00004944def _iexp(x, M, L=8):
4945 """Given integers x and M, M > 0, such that x/M is small in absolute
4946 value, compute an integer approximation to M*exp(x/M). For 0 <=
4947 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4948 is usually much smaller)."""
4949
4950 # Algorithm: to compute exp(z) for a real number z, first divide z
4951 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4952 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4953 # series
4954 #
4955 # expm1(x) = x + x**2/2! + x**3/3! + ...
4956 #
4957 # Now use the identity
4958 #
4959 # expm1(2x) = expm1(x)*(expm1(x)+2)
4960 #
4961 # R times to compute the sequence expm1(z/2**R),
4962 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4963
4964 # Find R such that x/2**R/M <= 2**-L
4965 R = _nbits((long(x)<<L)//M)
4966
4967 # Taylor series. (2**L)**T > M
4968 T = -int(-10*len(str(M))//(3*L))
4969 y = _div_nearest(x, T)
4970 Mshift = long(M)<<R
4971 for i in xrange(T-1, 0, -1):
4972 y = _div_nearest(x*(Mshift + y), Mshift * i)
4973
4974 # Expansion
4975 for k in xrange(R-1, -1, -1):
4976 Mshift = long(M)<<(k+2)
4977 y = _div_nearest(y*(y+Mshift), Mshift)
4978
4979 return M+y
4980
4981def _dexp(c, e, p):
4982 """Compute an approximation to exp(c*10**e), with p decimal places of
4983 precision.
4984
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004985 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00004986
4987 10**(p-1) <= d <= 10**p, and
4988 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
4989
4990 In other words, d*10**f is an approximation to exp(c*10**e) with p
4991 digits of precision, and with an error in d of at most 1. This is
4992 almost, but not quite, the same as the error being < 1ulp: when d
4993 = 10**(p-1) the error could be up to 10 ulp."""
4994
4995 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
4996 p += 2
4997
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004998 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00004999 extra = max(0, e + len(str(c)) - 1)
5000 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005001
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005002 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005003 # rounding down
5004 shift = e+q
5005 if shift >= 0:
5006 cshift = c*10**shift
5007 else:
5008 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005009 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005010
5011 # reduce remainder back to original precision
5012 rem = _div_nearest(rem, 10**extra)
5013
5014 # error in result of _iexp < 120; error after division < 0.62
5015 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5016
5017def _dpower(xc, xe, yc, ye, p):
5018 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5019 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5020
5021 10**(p-1) <= c <= 10**p, and
5022 (c-1)*10**e < x**y < (c+1)*10**e
5023
5024 in other words, c*10**e is an approximation to x**y with p digits
5025 of precision, and with an error in c of at most 1. (This is
5026 almost, but not quite, the same as the error being < 1ulp: when c
5027 == 10**(p-1) we can only guarantee error < 10ulp.)
5028
5029 We assume that: x is positive and not equal to 1, and y is nonzero.
5030 """
5031
5032 # Find b such that 10**(b-1) <= |y| <= 10**b
5033 b = len(str(abs(yc))) + ye
5034
5035 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5036 lxc = _dlog(xc, xe, p+b+1)
5037
5038 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5039 shift = ye-b
5040 if shift >= 0:
5041 pc = lxc*yc*10**shift
5042 else:
5043 pc = _div_nearest(lxc*yc, 10**-shift)
5044
5045 if pc == 0:
5046 # we prefer a result that isn't exactly 1; this makes it
5047 # easier to compute a correctly rounded result in __pow__
5048 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5049 coeff, exp = 10**(p-1)+1, 1-p
5050 else:
5051 coeff, exp = 10**p-1, -p
5052 else:
5053 coeff, exp = _dexp(pc, -(p+1), p+1)
5054 coeff = _div_nearest(coeff, 10)
5055 exp += 1
5056
5057 return coeff, exp
5058
5059def _log10_lb(c, correction = {
5060 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5061 '6': 23, '7': 16, '8': 10, '9': 5}):
5062 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5063 if c <= 0:
5064 raise ValueError("The argument to _log10_lb should be nonnegative.")
5065 str_c = str(c)
5066 return 100*len(str_c) - correction[str_c[0]]
5067
Facundo Batista59c58842007-04-10 12:58:45 +00005068##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005069
Facundo Batista353750c2007-09-13 18:13:15 +00005070def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005071 """Convert other to Decimal.
5072
5073 Verifies that it's ok to use in an implicit construction.
5074 """
5075 if isinstance(other, Decimal):
5076 return other
5077 if isinstance(other, (int, long)):
5078 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005079 if raiseit:
5080 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005081 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005082
Facundo Batista59c58842007-04-10 12:58:45 +00005083##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005084
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005085# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005086# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005087
5088DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005089 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005090 traps=[DivisionByZero, Overflow, InvalidOperation],
5091 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005092 Emax=999999999,
5093 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005094 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005095)
5096
5097# Pre-made alternate contexts offered by the specification
5098# Don't change these; the user should be able to select these
5099# contexts and be able to reproduce results from other implementations
5100# of the spec.
5101
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005102BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005103 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005104 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5105 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005106)
5107
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005108ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005109 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005110 traps=[],
5111 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005112)
5113
5114
Facundo Batista72bc54f2007-11-23 17:59:00 +00005115##### crud for parsing strings #############################################
5116import re
5117
5118# Regular expression used for parsing numeric strings. Additional
5119# comments:
5120#
5121# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5122# whitespace. But note that the specification disallows whitespace in
5123# a numeric string.
5124#
5125# 2. For finite numbers (not infinities and NaNs) the body of the
5126# number between the optional sign and the optional exponent must have
5127# at least one decimal digit, possibly after the decimal point. The
5128# lookahead expression '(?=\d|\.\d)' checks this.
5129#
5130# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5131# other meaning for \d than the numbers [0-9].
5132
5133import re
5134_parser = re.compile(r""" # A numeric string consists of:
5135# \s*
5136 (?P<sign>[-+])? # an optional sign, followed by either...
5137 (
5138 (?=\d|\.\d) # ...a number (with at least one digit)
5139 (?P<int>\d*) # consisting of a (possibly empty) integer part
5140 (\.(?P<frac>\d*))? # followed by an optional fractional part
5141 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5142 |
5143 Inf(inity)? # ...an infinity, or...
5144 |
5145 (?P<signal>s)? # ...an (optionally signaling)
5146 NaN # NaN
5147 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5148 )
5149# \s*
5150 $
5151""", re.VERBOSE | re.IGNORECASE).match
5152
Facundo Batista2ec74152007-12-03 17:55:00 +00005153_all_zeros = re.compile('0*$').match
5154_exact_half = re.compile('50*$').match
Facundo Batista72bc54f2007-11-23 17:59:00 +00005155del re
5156
5157
Facundo Batista59c58842007-04-10 12:58:45 +00005158##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005159
Facundo Batista59c58842007-04-10 12:58:45 +00005160# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005161Inf = Decimal('Inf')
5162negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005163NaN = Decimal('NaN')
5164Dec_0 = Decimal(0)
5165Dec_p1 = Decimal(1)
5166Dec_n1 = Decimal(-1)
5167Dec_p2 = Decimal(2)
5168Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005169
Facundo Batista59c58842007-04-10 12:58:45 +00005170# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005171Infsign = (Inf, negInf)
5172
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005173
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005174
5175if __name__ == '__main__':
5176 import doctest, sys
5177 doctest.testmod(sys.modules[__name__])