blob: ee65b12ed8d4f88ded5614a00c2f80972daf1ffb [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# Rounding decision (not part of the public API)
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000150NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY
151ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000152
Facundo Batista59c58842007-04-10 12:58:45 +0000153# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
155class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000156 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000157
158 Used exceptions derive from this.
159 If an exception derives from another exception besides this (such as
160 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
161 called if the others are present. This isn't actually used for
162 anything, though.
163
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000164 handle -- Called when context._raise_error is called and the
165 trap_enabler is set. First argument is self, second is the
166 context. More arguments can be given, those being after
167 the explanation in _raise_error (For example,
168 context._raise_error(NewError, '(-x)!', self._sign) would
169 call NewError().handle(context, self._sign).)
170
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000171 To define a new exception, it should be sufficient to have it derive
172 from DecimalException.
173 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000174 def handle(self, context, *args):
175 pass
176
177
178class Clamped(DecimalException):
179 """Exponent of a 0 changed to fit bounds.
180
181 This occurs and signals clamped if the exponent of a result has been
182 altered in order to fit the constraints of a specific concrete
Facundo Batista59c58842007-04-10 12:58:45 +0000183 representation. This may occur when the exponent of a zero result would
184 be outside the bounds of a representation, or when a large normal
185 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000186 this latter case, the exponent is reduced to fit and the corresponding
187 number of zero digits are appended to the coefficient ("fold-down").
188 """
189
190
191class InvalidOperation(DecimalException):
192 """An invalid operation was performed.
193
194 Various bad things cause this:
195
196 Something creates a signaling NaN
197 -INF + INF
Facundo Batista59c58842007-04-10 12:58:45 +0000198 0 * (+-)INF
199 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000200 x % 0
201 (+-)INF % x
202 x._rescale( non-integer )
203 sqrt(-x) , x > 0
204 0 ** 0
205 x ** (non-integer)
206 x ** (+-)INF
207 An operand is invalid
Facundo Batista353750c2007-09-13 18:13:15 +0000208
209 The result of the operation after these is a quiet positive NaN,
210 except when the cause is a signaling NaN, in which case the result is
211 also a quiet NaN, but with the original sign, and an optional
212 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000213 """
214 def handle(self, context, *args):
215 if args:
Facundo Batista59c58842007-04-10 12:58:45 +0000216 if args[0] == 1: # sNaN, must drop 's' but keep diagnostics
Facundo Batista72bc54f2007-11-23 17:59:00 +0000217 ans = _dec_from_triple(args[1]._sign, args[1]._int, 'n', True)
Facundo Batista353750c2007-09-13 18:13:15 +0000218 return ans._fix_nan(context)
219 elif args[0] == 2:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000220 return _dec_from_triple(args[1], args[2], 'n', True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221 return NaN
222
Facundo Batista353750c2007-09-13 18:13:15 +0000223
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224class ConversionSyntax(InvalidOperation):
225 """Trying to convert badly formed string.
226
227 This occurs and signals invalid-operation if an string is being
228 converted to a number and it does not conform to the numeric string
Facundo Batista59c58842007-04-10 12:58:45 +0000229 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000231 def handle(self, context, *args):
Facundo Batista353750c2007-09-13 18:13:15 +0000232 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000233
234class DivisionByZero(DecimalException, ZeroDivisionError):
235 """Division by 0.
236
237 This occurs and signals division-by-zero if division of a finite number
238 by zero was attempted (during a divide-integer or divide operation, or a
239 power operation with negative right-hand operand), and the dividend was
240 not zero.
241
242 The result of the operation is [sign,inf], where sign is the exclusive
243 or of the signs of the operands for divide, or is 1 for an odd power of
244 -0, for power.
245 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000246
Facundo Batistacce8df22007-09-18 16:53:18 +0000247 def handle(self, context, sign, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000248 return Infsign[sign]
249
250class DivisionImpossible(InvalidOperation):
251 """Cannot perform the division adequately.
252
253 This occurs and signals invalid-operation if the integer result of a
254 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000255 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000256 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000257
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000258 def handle(self, context, *args):
Facundo Batistacce8df22007-09-18 16:53:18 +0000259 return NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000260
261class DivisionUndefined(InvalidOperation, ZeroDivisionError):
262 """Undefined result of division.
263
264 This occurs and signals invalid-operation if division by zero was
265 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000266 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000267 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000268
Facundo Batistacce8df22007-09-18 16:53:18 +0000269 def handle(self, context, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000270 return NaN
271
272class Inexact(DecimalException):
273 """Had to round, losing information.
274
275 This occurs and signals inexact whenever the result of an operation is
276 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000277 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000278 result in all cases is unchanged.
279
280 The inexact signal may be tested (or trapped) to determine if a given
281 operation (or sequence of operations) was inexact.
282 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000283 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000284
285class InvalidContext(InvalidOperation):
286 """Invalid context. Unknown rounding, for example.
287
288 This occurs and signals invalid-operation if an invalid context was
Facundo Batista59c58842007-04-10 12:58:45 +0000289 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000290 on creation and either the precision exceeds the capability of the
291 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista59c58842007-04-10 12:58:45 +0000292 was specified. These aspects of the context need only be checked when
293 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000294 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000295
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000296 def handle(self, context, *args):
297 return NaN
298
299class Rounded(DecimalException):
300 """Number got rounded (not necessarily changed during rounding).
301
302 This occurs and signals rounded whenever the result of an operation is
303 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista59c58842007-04-10 12:58:45 +0000304 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000305 result in all cases is unchanged.
306
307 The rounded signal may be tested (or trapped) to determine if a given
308 operation (or sequence of operations) caused a loss of precision.
309 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000310 pass
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000311
312class Subnormal(DecimalException):
313 """Exponent < Emin before rounding.
314
315 This occurs and signals subnormal whenever the result of a conversion or
316 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000317 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000318
319 The subnormal signal may be tested (or trapped) to determine if a given
320 or operation (or sequence of operations) yielded a subnormal result.
321 """
322 pass
323
324class Overflow(Inexact, Rounded):
325 """Numerical overflow.
326
327 This occurs and signals overflow if the adjusted exponent of a result
328 (from a conversion or from an operation that is not an attempt to divide
329 by zero), after rounding, would be greater than the largest value that
330 can be handled by the implementation (the value Emax).
331
332 The result depends on the rounding mode:
333
334 For round-half-up and round-half-even (and for round-half-down and
335 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000336 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000338 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000340 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000342 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000343 will also be raised.
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000344 """
345
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000346 def handle(self, context, sign, *args):
347 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000348 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349 return Infsign[sign]
350 if sign == 0:
351 if context.rounding == ROUND_CEILING:
352 return Infsign[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000353 return _dec_from_triple(sign, '9'*context.prec,
354 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000355 if sign == 1:
356 if context.rounding == ROUND_FLOOR:
357 return Infsign[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000358 return _dec_from_triple(sign, '9'*context.prec,
359 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000360
361
362class Underflow(Inexact, Rounded, Subnormal):
363 """Numerical underflow with result rounded to 0.
364
365 This occurs and signals underflow if a result is inexact and the
366 adjusted exponent of the result would be smaller (more negative) than
367 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000368 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000369
370 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000371 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000372 in 0 with the sign of the intermediate result and an exponent of Etiny.
373
374 In all cases, Inexact, Rounded, and Subnormal will also be raised.
375 """
376
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000377# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000378_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000379 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000380
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000381# Map conditions (per the spec) to signals
382_condition_map = {ConversionSyntax:InvalidOperation,
383 DivisionImpossible:InvalidOperation,
384 DivisionUndefined:InvalidOperation,
385 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000386
Facundo Batista59c58842007-04-10 12:58:45 +0000387##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000388
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000389# The getcontext() and setcontext() function manage access to a thread-local
390# current context. Py2.4 offers direct support for thread locals. If that
391# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000392# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000393# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000394
395try:
396 import threading
397except ImportError:
398 # Python was compiled without threads; create a mock object instead
399 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000400 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000401 def local(self, sys=sys):
402 return sys.modules[__name__]
403 threading = MockThreading()
404 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000406try:
407 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000408
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000409except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000410
Facundo Batista59c58842007-04-10 12:58:45 +0000411 # To fix reloading, force it to create a new context
412 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000413 if hasattr(threading.currentThread(), '__decimal_context__'):
414 del threading.currentThread().__decimal_context__
415
416 def setcontext(context):
417 """Set this thread's context to context."""
418 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000419 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000420 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000421 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000422
423 def getcontext():
424 """Returns this thread's context.
425
426 If this thread does not yet have a context, returns
427 a new context and sets this thread's context.
428 New contexts are copies of DefaultContext.
429 """
430 try:
431 return threading.currentThread().__decimal_context__
432 except AttributeError:
433 context = Context()
434 threading.currentThread().__decimal_context__ = context
435 return context
436
437else:
438
439 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000440 if hasattr(local, '__decimal_context__'):
441 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000442
443 def getcontext(_local=local):
444 """Returns this thread's context.
445
446 If this thread does not yet have a context, returns
447 a new context and sets this thread's context.
448 New contexts are copies of DefaultContext.
449 """
450 try:
451 return _local.__decimal_context__
452 except AttributeError:
453 context = Context()
454 _local.__decimal_context__ = context
455 return context
456
457 def setcontext(context, _local=local):
458 """Set this thread's context to context."""
459 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000460 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000461 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000462 _local.__decimal_context__ = context
463
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000464 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000465
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000466def localcontext(ctx=None):
467 """Return a context manager for a copy of the supplied context
468
469 Uses a copy of the current context if no context is specified
470 The returned context manager creates a local decimal context
471 in a with statement:
472 def sin(x):
473 with localcontext() as ctx:
474 ctx.prec += 2
475 # Rest of sin calculation algorithm
476 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000477 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000478
479 def sin(x):
480 with localcontext(ExtendedContext):
481 # Rest of sin calculation algorithm
482 # uses the Extended Context from the
483 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000484 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000485
486 """
Neal Norwitz681d8672006-09-02 18:51:34 +0000487 # The string below can't be included in the docstring until Python 2.6
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000488 # as the doctest module doesn't understand __future__ statements
489 """
490 >>> from __future__ import with_statement
491 >>> print getcontext().prec
492 28
493 >>> with localcontext():
494 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000495 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000496 ... print ctx.prec
497 ...
498 30
499 >>> with localcontext(ExtendedContext):
500 ... print getcontext().prec
501 ...
502 9
503 >>> print getcontext().prec
504 28
505 """
Nick Coghlanced12182006-09-02 03:54:17 +0000506 if ctx is None: ctx = getcontext()
507 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000508
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000509
Facundo Batista59c58842007-04-10 12:58:45 +0000510##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000511
512class Decimal(object):
513 """Floating point class for decimal arithmetic."""
514
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000515 __slots__ = ('_exp','_int','_sign', '_is_special')
516 # Generally, the value of the Decimal instance is given by
517 # (-1)**_sign * _int * 10**_exp
518 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000519
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000520 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000521 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 """Create a decimal point instance.
523
524 >>> Decimal('3.14') # string input
525 Decimal("3.14")
Facundo Batista59c58842007-04-10 12:58:45 +0000526 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000527 Decimal("3.14")
528 >>> Decimal(314) # int or long
529 Decimal("314")
530 >>> Decimal(Decimal(314)) # another decimal instance
531 Decimal("314")
532 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000533
Facundo Batista72bc54f2007-11-23 17:59:00 +0000534 # Note that the coefficient, self._int, is actually stored as
535 # a string rather than as a tuple of digits. This speeds up
536 # the "digits to integer" and "integer to digits" conversions
537 # that are used in almost every arithmetic operation on
538 # Decimals. This is an internal detail: the as_tuple function
539 # and the Decimal constructor still deal with tuples of
540 # digits.
541
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000542 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000543
Facundo Batista0d157a02007-11-30 17:15:25 +0000544 # From a string
545 # REs insist on real strings, so we can too.
546 if isinstance(value, basestring):
547 m = _parser(value)
548 if m is None:
549 if context is None:
550 context = getcontext()
551 return context._raise_error(ConversionSyntax,
552 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000553
Facundo Batista0d157a02007-11-30 17:15:25 +0000554 if m.group('sign') == "-":
555 self._sign = 1
556 else:
557 self._sign = 0
558 intpart = m.group('int')
559 if intpart is not None:
560 # finite number
561 fracpart = m.group('frac')
562 exp = int(m.group('exp') or '0')
563 if fracpart is not None:
564 self._int = (intpart+fracpart).lstrip('0') or '0'
565 self._exp = exp - len(fracpart)
566 else:
567 self._int = intpart.lstrip('0') or '0'
568 self._exp = exp
569 self._is_special = False
570 else:
571 diag = m.group('diag')
572 if diag is not None:
573 # NaN
574 self._int = diag.lstrip('0')
575 if m.group('signal'):
576 self._exp = 'N'
577 else:
578 self._exp = 'n'
579 else:
580 # infinity
581 self._int = '0'
582 self._exp = 'F'
583 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000584 return self
585
586 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000587 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000588 if value >= 0:
589 self._sign = 0
590 else:
591 self._sign = 1
592 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000593 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000594 self._is_special = False
595 return self
596
597 # From another decimal
598 if isinstance(value, Decimal):
599 self._exp = value._exp
600 self._sign = value._sign
601 self._int = value._int
602 self._is_special = value._is_special
603 return self
604
605 # From an internal working value
606 if isinstance(value, _WorkRep):
607 self._sign = value.sign
608 self._int = str(value.int)
609 self._exp = int(value.exp)
610 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000611 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000612
613 # tuple/list conversion (possibly from as_tuple())
614 if isinstance(value, (list,tuple)):
615 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000616 raise ValueError('Invalid tuple size in creation of Decimal '
617 'from list or tuple. The list or tuple '
618 'should have exactly three elements.')
619 # process sign. The isinstance test rejects floats
620 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
621 raise ValueError("Invalid sign. The first value in the tuple "
622 "should be an integer; either 0 for a "
623 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000625 if value[2] == 'F':
626 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000627 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000628 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000629 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000630 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000631 # process and validate the digits in value[1]
632 digits = []
633 for digit in value[1]:
634 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
635 # skip leading zeros
636 if digits or digit != 0:
637 digits.append(digit)
638 else:
639 raise ValueError("The second value in the tuple must "
640 "be composed of integers in the range "
641 "0 through 9.")
642 if value[2] in ('n', 'N'):
643 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000644 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000645 self._exp = value[2]
646 self._is_special = True
647 elif isinstance(value[2], (int, long)):
648 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000649 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000650 self._exp = value[2]
651 self._is_special = False
652 else:
653 raise ValueError("The third value in the tuple must "
654 "be an integer, or one of the "
655 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000656 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000657
Raymond Hettingerbf440692004-07-10 14:14:37 +0000658 if isinstance(value, float):
659 raise TypeError("Cannot convert float to Decimal. " +
660 "First convert the float to a string")
661
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000662 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000663
664 def _isnan(self):
665 """Returns whether the number is not actually one.
666
667 0 if a number
Facundo Batista353750c2007-09-13 18:13:15 +0000668 1 if NaN (it could be a normal quiet NaN or a phantom one)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000669 2 if sNaN
670 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000671 if self._is_special:
672 exp = self._exp
673 if exp == 'n':
674 return 1
675 elif exp == 'N':
676 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000677 return 0
678
679 def _isinfinity(self):
680 """Returns whether the number is infinite
681
682 0 if finite or not a number
683 1 if +INF
684 -1 if -INF
685 """
686 if self._exp == 'F':
687 if self._sign:
688 return -1
689 return 1
690 return 0
691
Facundo Batista353750c2007-09-13 18:13:15 +0000692 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000693 """Returns whether the number is not actually one.
694
695 if self, other are sNaN, signal
696 if self, other are NaN return nan
697 return 0
698
699 Done before operations.
700 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000701
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000702 self_is_nan = self._isnan()
703 if other is None:
704 other_is_nan = False
705 else:
706 other_is_nan = other._isnan()
707
708 if self_is_nan or other_is_nan:
709 if context is None:
710 context = getcontext()
711
712 if self_is_nan == 2:
713 return context._raise_error(InvalidOperation, 'sNaN',
714 1, self)
715 if other_is_nan == 2:
716 return context._raise_error(InvalidOperation, 'sNaN',
717 1, other)
718 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000719 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000720
Facundo Batista353750c2007-09-13 18:13:15 +0000721 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000722 return 0
723
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000724 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000725 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000726
Facundo Batista1a191df2007-10-02 17:01:24 +0000727 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000728 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000729 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000730
Facundo Batista353750c2007-09-13 18:13:15 +0000731 def __cmp__(self, other):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000732 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000733 if other is NotImplemented:
Facundo Batista353750c2007-09-13 18:13:15 +0000734 # Never return NotImplemented
735 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000736
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000737 if self._is_special or other._is_special:
Facundo Batista353750c2007-09-13 18:13:15 +0000738 # check for nans, without raising on a signaling nan
739 if self._isnan() or other._isnan():
Facundo Batista59c58842007-04-10 12:58:45 +0000740 return 1 # Comparison involving NaN's always reports self > other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000741
742 # INF = INF
743 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000744
Facundo Batista353750c2007-09-13 18:13:15 +0000745 # check for zeros; note that cmp(0, -0) should return 0
746 if not self:
747 if not other:
748 return 0
749 else:
750 return -((-1)**other._sign)
751 if not other:
752 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000753
Facundo Batista59c58842007-04-10 12:58:45 +0000754 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000755 if other._sign < self._sign:
756 return -1
757 if self._sign < other._sign:
758 return 1
759
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000760 self_adjusted = self.adjusted()
761 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000762 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000763 self_padded = self._int + '0'*(self._exp - other._exp)
764 other_padded = other._int + '0'*(other._exp - self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +0000765 return cmp(self_padded, other_padded) * (-1)**self._sign
766 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000767 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000768 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000769 return -((-1)**self._sign)
770
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000771 def __eq__(self, other):
772 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000773 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000774 return self.__cmp__(other) == 0
775
776 def __ne__(self, other):
777 if not isinstance(other, (Decimal, int, long)):
Raymond Hettinger267b8682005-03-27 10:47:39 +0000778 return NotImplemented
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000779 return self.__cmp__(other) != 0
780
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000781 def compare(self, other, context=None):
782 """Compares one to another.
783
784 -1 => a < b
785 0 => a = b
786 1 => a > b
787 NaN => one is NaN
788 Like __cmp__, but returns Decimal instances.
789 """
Facundo Batista353750c2007-09-13 18:13:15 +0000790 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000791
Facundo Batista59c58842007-04-10 12:58:45 +0000792 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000793 if (self._is_special or other and other._is_special):
794 ans = self._check_nans(other, context)
795 if ans:
796 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000797
Facundo Batista353750c2007-09-13 18:13:15 +0000798 return Decimal(self.__cmp__(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000799
800 def __hash__(self):
801 """x.__hash__() <==> hash(x)"""
802 # Decimal integers must hash the same as the ints
803 # Non-integer decimals are normalized and hashed as strings
Georg Brandl1fb9f522006-05-11 19:57:09 +0000804 # Normalization assures that hash(100E-1) == hash(10)
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000805 if self._is_special:
806 if self._isnan():
807 raise TypeError('Cannot hash a NaN value.')
808 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000809 if not self:
810 return 0
811 if self._isinteger():
812 op = _WorkRep(self.to_integral_value())
813 # to make computation feasible for Decimals with large
814 # exponent, we use the fact that hash(n) == hash(m) for
815 # any two nonzero integers n and m such that (i) n and m
816 # have the same sign, and (ii) n is congruent to m modulo
817 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
818 # hash((-1)**s*c*pow(10, e, 2**64-1).
819 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000820 return hash(str(self.normalize()))
821
822 def as_tuple(self):
823 """Represents the number as a triple tuple.
824
825 To show the internals exactly as they are.
826 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000827 return (self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000828
829 def __repr__(self):
830 """Represents the number as an instance of Decimal."""
831 # Invariant: eval(repr(d)) == d
832 return 'Decimal("%s")' % str(self)
833
Facundo Batista353750c2007-09-13 18:13:15 +0000834 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000835 """Return string representation of the number in scientific notation.
836
837 Captures all of the information in the underlying representation.
838 """
839
Facundo Batista62edb712007-12-03 16:29:52 +0000840 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000841 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000842 if self._exp == 'F':
843 return sign + 'Infinity'
844 elif self._exp == 'n':
845 return sign + 'NaN' + self._int
846 else: # self._exp == 'N'
847 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000848
Facundo Batista62edb712007-12-03 16:29:52 +0000849 # number of digits of self._int to left of decimal point
850 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000851
Facundo Batista62edb712007-12-03 16:29:52 +0000852 # dotplace is number of digits of self._int to the left of the
853 # decimal point in the mantissa of the output string (that is,
854 # after adjusting the exponent)
855 if self._exp <= 0 and leftdigits > -6:
856 # no exponent required
857 dotplace = leftdigits
858 elif not eng:
859 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000860 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000861 elif self._int == '0':
862 # engineering notation, zero
863 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000864 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000865 # engineering notation, nonzero
866 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000867
Facundo Batista62edb712007-12-03 16:29:52 +0000868 if dotplace <= 0:
869 intpart = '0'
870 fracpart = '.' + '0'*(-dotplace) + self._int
871 elif dotplace >= len(self._int):
872 intpart = self._int+'0'*(dotplace-len(self._int))
873 fracpart = ''
874 else:
875 intpart = self._int[:dotplace]
876 fracpart = '.' + self._int[dotplace:]
877 if leftdigits == dotplace:
878 exp = ''
879 else:
880 if context is None:
881 context = getcontext()
882 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
883
884 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000885
886 def to_eng_string(self, context=None):
887 """Convert to engineering-type string.
888
889 Engineering notation has an exponent which is a multiple of 3, so there
890 are up to 3 digits left of the decimal place.
891
892 Same rules for when in exponential and when as a value as in __str__.
893 """
Facundo Batista353750c2007-09-13 18:13:15 +0000894 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000895
896 def __neg__(self, context=None):
897 """Returns a copy with the sign switched.
898
899 Rounds, if it has reason.
900 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000901 if self._is_special:
902 ans = self._check_nans(context=context)
903 if ans:
904 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000905
906 if not self:
907 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000908 ans = self.copy_sign(Dec_0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000909 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000910 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000911
912 if context is None:
913 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000914 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000915 return ans._fix(context)
916 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000917
918 def __pos__(self, context=None):
919 """Returns a copy, unless it is a sNaN.
920
921 Rounds the number (if more then precision digits)
922 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000923 if self._is_special:
924 ans = self._check_nans(context=context)
925 if ans:
926 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000927
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000928 if not self:
929 # + (-0) = 0
Facundo Batista353750c2007-09-13 18:13:15 +0000930 ans = self.copy_sign(Dec_0)
931 else:
932 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000933
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000934 if context is None:
935 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000936 if context._rounding_decision == ALWAYS_ROUND:
Facundo Batista353750c2007-09-13 18:13:15 +0000937 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000938 return ans
939
940 def __abs__(self, round=1, context=None):
941 """Returns the absolute value of self.
942
943 If the second argument is 0, do not round.
944 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000945 if self._is_special:
946 ans = self._check_nans(context=context)
947 if ans:
948 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000949
950 if not round:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000951 if context is None:
952 context = getcontext()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000953 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000954 context._set_rounding_decision(NEVER_ROUND)
955
956 if self._sign:
957 ans = self.__neg__(context=context)
958 else:
959 ans = self.__pos__(context=context)
960
961 return ans
962
963 def __add__(self, other, context=None):
964 """Returns self + other.
965
966 -INF + INF (or the reverse) cause InvalidOperation errors.
967 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000968 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +0000969 if other is NotImplemented:
970 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000971
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000972 if context is None:
973 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000974
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000975 if self._is_special or other._is_special:
976 ans = self._check_nans(other, context)
977 if ans:
978 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000979
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000980 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000981 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000982 if self._sign != other._sign and other._isinfinity():
983 return context._raise_error(InvalidOperation, '-INF + INF')
984 return Decimal(self)
985 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +0000986 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000987
988 shouldround = context._rounding_decision == ALWAYS_ROUND
989
990 exp = min(self._exp, other._exp)
991 negativezero = 0
992 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +0000993 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000994 negativezero = 1
995
996 if not self and not other:
997 sign = min(self._sign, other._sign)
998 if negativezero:
999 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001000 ans = _dec_from_triple(sign, '0', exp)
Facundo Batista353750c2007-09-13 18:13:15 +00001001 if shouldround:
1002 ans = ans._fix(context)
1003 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001004 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001005 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001006 ans = other._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001007 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001008 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009 return ans
1010 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001011 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001012 ans = self._rescale(exp, context.rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001013 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001014 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001015 return ans
1016
1017 op1 = _WorkRep(self)
1018 op2 = _WorkRep(other)
1019 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1020
1021 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001024 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001025 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batista353750c2007-09-13 18:13:15 +00001026 if shouldround:
1027 ans = ans._fix(context)
1028 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001029 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001031 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001032 if op1.sign == 1:
1033 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034 op1.sign, op2.sign = op2.sign, op1.sign
1035 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001036 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001037 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001038 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001039 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001040 op1.sign, op2.sign = (0, 0)
1041 else:
1042 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001043 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001044
Raymond Hettinger17931de2004-10-27 06:21:46 +00001045 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001046 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001048 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001049
1050 result.exp = op1.exp
1051 ans = Decimal(result)
1052 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001053 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001054 return ans
1055
1056 __radd__ = __add__
1057
1058 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001059 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001060 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001061 if other is NotImplemented:
1062 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001063
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001064 if self._is_special or other._is_special:
1065 ans = self._check_nans(other, context=context)
1066 if ans:
1067 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068
Facundo Batista353750c2007-09-13 18:13:15 +00001069 # self - other is computed as self + other.copy_negate()
1070 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071
1072 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001073 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001074 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001075 if other is NotImplemented:
1076 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077
Facundo Batista353750c2007-09-13 18:13:15 +00001078 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001079
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001080 def __mul__(self, other, context=None):
1081 """Return self * other.
1082
1083 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1084 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001085 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001086 if other is NotImplemented:
1087 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001088
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001089 if context is None:
1090 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001091
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001092 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001093
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001094 if self._is_special or other._is_special:
1095 ans = self._check_nans(other, context)
1096 if ans:
1097 return ans
1098
1099 if self._isinfinity():
1100 if not other:
1101 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1102 return Infsign[resultsign]
1103
1104 if other._isinfinity():
1105 if not self:
1106 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1107 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001108
1109 resultexp = self._exp + other._exp
1110 shouldround = context._rounding_decision == ALWAYS_ROUND
1111
1112 # Special case for multiplying by zero
1113 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001114 ans = _dec_from_triple(resultsign, '0', resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001115 if shouldround:
Facundo Batista59c58842007-04-10 12:58:45 +00001116 # Fixing in case the exponent is out of bounds
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001117 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001118 return ans
1119
1120 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001121 if self._int == '1':
1122 ans = _dec_from_triple(resultsign, other._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001123 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001124 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001125 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001126 if other._int == '1':
1127 ans = _dec_from_triple(resultsign, self._int, resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001129 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001130 return ans
1131
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001132 op1 = _WorkRep(self)
1133 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001134
Facundo Batista72bc54f2007-11-23 17:59:00 +00001135 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001136 if shouldround:
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001137 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138
1139 return ans
1140 __rmul__ = __mul__
1141
1142 def __div__(self, other, context=None):
1143 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001144 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001145 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001146 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001147
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148 if context is None:
1149 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001150
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001151 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001152
1153 if self._is_special or other._is_special:
1154 ans = self._check_nans(other, context)
1155 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001156 return ans
1157
1158 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001159 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001160
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001162 return Infsign[sign]
1163
1164 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001165 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001166 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001167
1168 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001169 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001170 if not self:
1171 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001172 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173
Facundo Batistacce8df22007-09-18 16:53:18 +00001174 if not self:
1175 exp = self._exp - other._exp
1176 coeff = 0
1177 else:
1178 # OK, so neither = 0, INF or NaN
1179 shift = len(other._int) - len(self._int) + context.prec + 1
1180 exp = self._exp - other._exp - shift
1181 op1 = _WorkRep(self)
1182 op2 = _WorkRep(other)
1183 if shift >= 0:
1184 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1185 else:
1186 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1187 if remainder:
1188 # result is not exact; adjust to ensure correct rounding
1189 if coeff % 5 == 0:
1190 coeff += 1
1191 else:
1192 # result is exact; get as close to ideal exponent as possible
1193 ideal_exp = self._exp - other._exp
1194 while exp < ideal_exp and coeff % 10 == 0:
1195 coeff //= 10
1196 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001197
Facundo Batista72bc54f2007-11-23 17:59:00 +00001198 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001199 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200
Facundo Batistacce8df22007-09-18 16:53:18 +00001201 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202
Facundo Batistacce8df22007-09-18 16:53:18 +00001203 def _divide(self, other, context):
1204 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001205
Facundo Batistacce8df22007-09-18 16:53:18 +00001206 Assumes that neither self nor other is a NaN, that self is not
1207 infinite and that other is nonzero.
1208 """
1209 sign = self._sign ^ other._sign
1210 if other._isinfinity():
1211 ideal_exp = self._exp
1212 else:
1213 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001214
Facundo Batistacce8df22007-09-18 16:53:18 +00001215 expdiff = self.adjusted() - other.adjusted()
1216 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001217 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001218 self._rescale(ideal_exp, context.rounding))
1219 if expdiff <= context.prec:
1220 op1 = _WorkRep(self)
1221 op2 = _WorkRep(other)
1222 if op1.exp >= op2.exp:
1223 op1.int *= 10**(op1.exp - op2.exp)
1224 else:
1225 op2.int *= 10**(op2.exp - op1.exp)
1226 q, r = divmod(op1.int, op2.int)
1227 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001228 return (_dec_from_triple(sign, str(q), 0),
1229 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001230
Facundo Batistacce8df22007-09-18 16:53:18 +00001231 # Here the quotient is too large to be representable
1232 ans = context._raise_error(DivisionImpossible,
1233 'quotient too large in //, % or divmod')
1234 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001235
1236 def __rdiv__(self, other, context=None):
1237 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001238 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001239 if other is NotImplemented:
1240 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001241 return other.__div__(self, context=context)
1242 __rtruediv__ = __rdiv__
1243
1244 def __divmod__(self, other, context=None):
1245 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001246 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001247 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001248 other = _convert_other(other)
1249 if other is NotImplemented:
1250 return other
1251
1252 if context is None:
1253 context = getcontext()
1254
1255 ans = self._check_nans(other, context)
1256 if ans:
1257 return (ans, ans)
1258
1259 sign = self._sign ^ other._sign
1260 if self._isinfinity():
1261 if other._isinfinity():
1262 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1263 return ans, ans
1264 else:
1265 return (Infsign[sign],
1266 context._raise_error(InvalidOperation, 'INF % x'))
1267
1268 if not other:
1269 if not self:
1270 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1271 return ans, ans
1272 else:
1273 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1274 context._raise_error(InvalidOperation, 'x % 0'))
1275
1276 quotient, remainder = self._divide(other, context)
1277 if context._rounding_decision == ALWAYS_ROUND:
1278 remainder = remainder._fix(context)
1279 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001280
1281 def __rdivmod__(self, other, context=None):
1282 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001283 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001284 if other is NotImplemented:
1285 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001286 return other.__divmod__(self, context=context)
1287
1288 def __mod__(self, other, context=None):
1289 """
1290 self % other
1291 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001292 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001293 if other is NotImplemented:
1294 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001295
Facundo Batistacce8df22007-09-18 16:53:18 +00001296 if context is None:
1297 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001298
Facundo Batistacce8df22007-09-18 16:53:18 +00001299 ans = self._check_nans(other, context)
1300 if ans:
1301 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001302
Facundo Batistacce8df22007-09-18 16:53:18 +00001303 if self._isinfinity():
1304 return context._raise_error(InvalidOperation, 'INF % x')
1305 elif not other:
1306 if self:
1307 return context._raise_error(InvalidOperation, 'x % 0')
1308 else:
1309 return context._raise_error(DivisionUndefined, '0 % 0')
1310
1311 remainder = self._divide(other, context)[1]
1312 if context._rounding_decision == ALWAYS_ROUND:
1313 remainder = remainder._fix(context)
1314 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001315
1316 def __rmod__(self, other, context=None):
1317 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001318 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001319 if other is NotImplemented:
1320 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001321 return other.__mod__(self, context=context)
1322
1323 def remainder_near(self, other, context=None):
1324 """
1325 Remainder nearest to 0- abs(remainder-near) <= other/2
1326 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001327 if context is None:
1328 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001329
Facundo Batista353750c2007-09-13 18:13:15 +00001330 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001331
Facundo Batista353750c2007-09-13 18:13:15 +00001332 ans = self._check_nans(other, context)
1333 if ans:
1334 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001335
Facundo Batista353750c2007-09-13 18:13:15 +00001336 # self == +/-infinity -> InvalidOperation
1337 if self._isinfinity():
1338 return context._raise_error(InvalidOperation,
1339 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001340
Facundo Batista353750c2007-09-13 18:13:15 +00001341 # other == 0 -> either InvalidOperation or DivisionUndefined
1342 if not other:
1343 if self:
1344 return context._raise_error(InvalidOperation,
1345 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001346 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001347 return context._raise_error(DivisionUndefined,
1348 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001349
Facundo Batista353750c2007-09-13 18:13:15 +00001350 # other = +/-infinity -> remainder = self
1351 if other._isinfinity():
1352 ans = Decimal(self)
1353 return ans._fix(context)
1354
1355 # self = 0 -> remainder = self, with ideal exponent
1356 ideal_exponent = min(self._exp, other._exp)
1357 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001358 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001359 return ans._fix(context)
1360
1361 # catch most cases of large or small quotient
1362 expdiff = self.adjusted() - other.adjusted()
1363 if expdiff >= context.prec + 1:
1364 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001365 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001366 if expdiff <= -2:
1367 # expdiff <= -2 => abs(self/other) < 0.1
1368 ans = self._rescale(ideal_exponent, context.rounding)
1369 return ans._fix(context)
1370
1371 # adjust both arguments to have the same exponent, then divide
1372 op1 = _WorkRep(self)
1373 op2 = _WorkRep(other)
1374 if op1.exp >= op2.exp:
1375 op1.int *= 10**(op1.exp - op2.exp)
1376 else:
1377 op2.int *= 10**(op2.exp - op1.exp)
1378 q, r = divmod(op1.int, op2.int)
1379 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1380 # 10**ideal_exponent. Apply correction to ensure that
1381 # abs(remainder) <= abs(other)/2
1382 if 2*r + (q&1) > op2.int:
1383 r -= op2.int
1384 q += 1
1385
1386 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001387 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001388
1389 # result has same sign as self unless r is negative
1390 sign = self._sign
1391 if r < 0:
1392 sign = 1-sign
1393 r = -r
1394
Facundo Batista72bc54f2007-11-23 17:59:00 +00001395 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001396 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001397
1398 def __floordiv__(self, other, context=None):
1399 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001400 other = _convert_other(other)
1401 if other is NotImplemented:
1402 return other
1403
1404 if context is None:
1405 context = getcontext()
1406
1407 ans = self._check_nans(other, context)
1408 if ans:
1409 return ans
1410
1411 if self._isinfinity():
1412 if other._isinfinity():
1413 return context._raise_error(InvalidOperation, 'INF // INF')
1414 else:
1415 return Infsign[self._sign ^ other._sign]
1416
1417 if not other:
1418 if self:
1419 return context._raise_error(DivisionByZero, 'x // 0',
1420 self._sign ^ other._sign)
1421 else:
1422 return context._raise_error(DivisionUndefined, '0 // 0')
1423
1424 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001425
1426 def __rfloordiv__(self, other, context=None):
1427 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001428 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001429 if other is NotImplemented:
1430 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001431 return other.__floordiv__(self, context=context)
1432
1433 def __float__(self):
1434 """Float representation."""
1435 return float(str(self))
1436
1437 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001438 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001439 if self._is_special:
1440 if self._isnan():
1441 context = getcontext()
1442 return context._raise_error(InvalidContext)
1443 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001444 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001445 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001446 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001447 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001448 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001449 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001450
1451 def __long__(self):
1452 """Converts to a long.
1453
1454 Equivalent to long(int(self))
1455 """
1456 return long(self.__int__())
1457
Facundo Batista353750c2007-09-13 18:13:15 +00001458 def _fix_nan(self, context):
1459 """Decapitate the payload of a NaN to fit the context"""
1460 payload = self._int
1461
1462 # maximum length of payload is precision if _clamp=0,
1463 # precision-1 if _clamp=1.
1464 max_payload_len = context.prec - context._clamp
1465 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001466 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1467 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001468 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001469
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001470 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001471 """Round if it is necessary to keep self within prec precision.
1472
1473 Rounds and fixes the exponent. Does not raise on a sNaN.
1474
1475 Arguments:
1476 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001477 context - context used.
1478 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001479
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001480 if context is None:
1481 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001482
Facundo Batista353750c2007-09-13 18:13:15 +00001483 if self._is_special:
1484 if self._isnan():
1485 # decapitate payload if necessary
1486 return self._fix_nan(context)
1487 else:
1488 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001489 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001490
Facundo Batista353750c2007-09-13 18:13:15 +00001491 # if self is zero then exponent should be between Etiny and
1492 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1493 Etiny = context.Etiny()
1494 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001495 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001496 exp_max = [context.Emax, Etop][context._clamp]
1497 new_exp = min(max(self._exp, Etiny), exp_max)
1498 if new_exp != self._exp:
1499 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001500 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001501 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001502 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001503
1504 # exp_min is the smallest allowable exponent of the result,
1505 # equal to max(self.adjusted()-context.prec+1, Etiny)
1506 exp_min = len(self._int) + self._exp - context.prec
1507 if exp_min > Etop:
1508 # overflow: exp_min > Etop iff self.adjusted() > Emax
1509 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001510 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001511 return context._raise_error(Overflow, 'above Emax', self._sign)
1512 self_is_subnormal = exp_min < Etiny
1513 if self_is_subnormal:
1514 context._raise_error(Subnormal)
1515 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001516
Facundo Batista353750c2007-09-13 18:13:15 +00001517 # round if self has too many digits
1518 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001519 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001520 digits = len(self._int) + self._exp - exp_min
1521 if digits < 0:
1522 self = _dec_from_triple(self._sign, '1', exp_min-1)
1523 digits = 0
1524 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1525 changed = this_function(digits)
1526 coeff = self._int[:digits] or '0'
1527 if changed == 1:
1528 coeff = str(int(coeff)+1)
1529 ans = _dec_from_triple(self._sign, coeff, exp_min)
1530
1531 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001532 context._raise_error(Inexact)
1533 if self_is_subnormal:
1534 context._raise_error(Underflow)
1535 if not ans:
1536 # raise Clamped on underflow to 0
1537 context._raise_error(Clamped)
1538 elif len(ans._int) == context.prec+1:
1539 # we get here only if rescaling rounds the
1540 # cofficient up to exactly 10**context.prec
1541 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001542 ans = _dec_from_triple(ans._sign,
1543 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001544 else:
1545 # Inexact and Rounded have already been raised
1546 ans = context._raise_error(Overflow, 'above Emax',
1547 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001548 return ans
1549
Facundo Batista353750c2007-09-13 18:13:15 +00001550 # fold down if _clamp == 1 and self has too few digits
1551 if context._clamp == 1 and self._exp > Etop:
1552 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001553 self_padded = self._int + '0'*(self._exp - Etop)
1554 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001555
Facundo Batista353750c2007-09-13 18:13:15 +00001556 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001557 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001558
1559 _pick_rounding_function = {}
1560
Facundo Batista353750c2007-09-13 18:13:15 +00001561 # for each of the rounding functions below:
1562 # self is a finite, nonzero Decimal
1563 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001564 #
1565 # each function returns either -1, 0, or 1, as follows:
1566 # 1 indicates that self should be rounded up (away from zero)
1567 # 0 indicates that self should be truncated, and that all the
1568 # digits to be truncated are zeros (so the value is unchanged)
1569 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001570
1571 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001572 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001573 if _all_zeros(self._int, prec):
1574 return 0
1575 else:
1576 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001577
Facundo Batista353750c2007-09-13 18:13:15 +00001578 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001579 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001580 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001581
Facundo Batista353750c2007-09-13 18:13:15 +00001582 def _round_half_up(self, prec):
1583 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001584 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001585 return 1
1586 elif _all_zeros(self._int, prec):
1587 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001588 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001589 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001590
1591 def _round_half_down(self, prec):
1592 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001593 if _exact_half(self._int, prec):
1594 return -1
1595 else:
1596 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001597
1598 def _round_half_even(self, prec):
1599 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001600 if _exact_half(self._int, prec) and \
1601 (prec == 0 or self._int[prec-1] in '02468'):
1602 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001603 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001604 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001605
1606 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001607 """Rounds up (not away from 0 if negative.)"""
1608 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001609 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001610 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001611 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001612
Facundo Batista353750c2007-09-13 18:13:15 +00001613 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001614 """Rounds down (not towards 0 if negative)"""
1615 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001616 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001617 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001618 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001619
Facundo Batista353750c2007-09-13 18:13:15 +00001620 def _round_05up(self, prec):
1621 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001622 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001623 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001624 else:
1625 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001626
Facundo Batista353750c2007-09-13 18:13:15 +00001627 def fma(self, other, third, context=None):
1628 """Fused multiply-add.
1629
1630 Returns self*other+third with no rounding of the intermediate
1631 product self*other.
1632
1633 self and other are multiplied together, with no rounding of
1634 the result. The third operand is then added to the result,
1635 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001636 """
Facundo Batista353750c2007-09-13 18:13:15 +00001637
1638 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001639
1640 # compute product; raise InvalidOperation if either operand is
1641 # a signaling NaN or if the product is zero times infinity.
1642 if self._is_special or other._is_special:
1643 if context is None:
1644 context = getcontext()
1645 if self._exp == 'N':
1646 return context._raise_error(InvalidOperation, 'sNaN',
1647 1, self)
1648 if other._exp == 'N':
1649 return context._raise_error(InvalidOperation, 'sNaN',
1650 1, other)
1651 if self._exp == 'n':
1652 product = self
1653 elif other._exp == 'n':
1654 product = other
1655 elif self._exp == 'F':
1656 if not other:
1657 return context._raise_error(InvalidOperation,
1658 'INF * 0 in fma')
1659 product = Infsign[self._sign ^ other._sign]
1660 elif other._exp == 'F':
1661 if not self:
1662 return context._raise_error(InvalidOperation,
1663 '0 * INF in fma')
1664 product = Infsign[self._sign ^ other._sign]
1665 else:
1666 product = _dec_from_triple(self._sign ^ other._sign,
1667 str(int(self._int) * int(other._int)),
1668 self._exp + other._exp)
1669
Facundo Batista353750c2007-09-13 18:13:15 +00001670 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001671 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001672
Facundo Batista353750c2007-09-13 18:13:15 +00001673 def _power_modulo(self, other, modulo, context=None):
1674 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001675
Facundo Batista353750c2007-09-13 18:13:15 +00001676 # if can't convert other and modulo to Decimal, raise
1677 # TypeError; there's no point returning NotImplemented (no
1678 # equivalent of __rpow__ for three argument pow)
1679 other = _convert_other(other, raiseit=True)
1680 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001681
Facundo Batista353750c2007-09-13 18:13:15 +00001682 if context is None:
1683 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001684
Facundo Batista353750c2007-09-13 18:13:15 +00001685 # deal with NaNs: if there are any sNaNs then first one wins,
1686 # (i.e. behaviour for NaNs is identical to that of fma)
1687 self_is_nan = self._isnan()
1688 other_is_nan = other._isnan()
1689 modulo_is_nan = modulo._isnan()
1690 if self_is_nan or other_is_nan or modulo_is_nan:
1691 if self_is_nan == 2:
1692 return context._raise_error(InvalidOperation, 'sNaN',
1693 1, self)
1694 if other_is_nan == 2:
1695 return context._raise_error(InvalidOperation, 'sNaN',
1696 1, other)
1697 if modulo_is_nan == 2:
1698 return context._raise_error(InvalidOperation, 'sNaN',
1699 1, modulo)
1700 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001701 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001702 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001703 return other._fix_nan(context)
1704 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001705
Facundo Batista353750c2007-09-13 18:13:15 +00001706 # check inputs: we apply same restrictions as Python's pow()
1707 if not (self._isinteger() and
1708 other._isinteger() and
1709 modulo._isinteger()):
1710 return context._raise_error(InvalidOperation,
1711 'pow() 3rd argument not allowed '
1712 'unless all arguments are integers')
1713 if other < 0:
1714 return context._raise_error(InvalidOperation,
1715 'pow() 2nd argument cannot be '
1716 'negative when 3rd argument specified')
1717 if not modulo:
1718 return context._raise_error(InvalidOperation,
1719 'pow() 3rd argument cannot be 0')
1720
1721 # additional restriction for decimal: the modulus must be less
1722 # than 10**prec in absolute value
1723 if modulo.adjusted() >= context.prec:
1724 return context._raise_error(InvalidOperation,
1725 'insufficient precision: pow() 3rd '
1726 'argument must not have more than '
1727 'precision digits')
1728
1729 # define 0**0 == NaN, for consistency with two-argument pow
1730 # (even though it hurts!)
1731 if not other and not self:
1732 return context._raise_error(InvalidOperation,
1733 'at least one of pow() 1st argument '
1734 'and 2nd argument must be nonzero ;'
1735 '0**0 is not defined')
1736
1737 # compute sign of result
1738 if other._iseven():
1739 sign = 0
1740 else:
1741 sign = self._sign
1742
1743 # convert modulo to a Python integer, and self and other to
1744 # Decimal integers (i.e. force their exponents to be >= 0)
1745 modulo = abs(int(modulo))
1746 base = _WorkRep(self.to_integral_value())
1747 exponent = _WorkRep(other.to_integral_value())
1748
1749 # compute result using integer pow()
1750 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1751 for i in xrange(exponent.exp):
1752 base = pow(base, 10, modulo)
1753 base = pow(base, exponent.int, modulo)
1754
Facundo Batista72bc54f2007-11-23 17:59:00 +00001755 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001756
1757 def _power_exact(self, other, p):
1758 """Attempt to compute self**other exactly.
1759
1760 Given Decimals self and other and an integer p, attempt to
1761 compute an exact result for the power self**other, with p
1762 digits of precision. Return None if self**other is not
1763 exactly representable in p digits.
1764
1765 Assumes that elimination of special cases has already been
1766 performed: self and other must both be nonspecial; self must
1767 be positive and not numerically equal to 1; other must be
1768 nonzero. For efficiency, other._exp should not be too large,
1769 so that 10**abs(other._exp) is a feasible calculation."""
1770
1771 # In the comments below, we write x for the value of self and
1772 # y for the value of other. Write x = xc*10**xe and y =
1773 # yc*10**ye.
1774
1775 # The main purpose of this method is to identify the *failure*
1776 # of x**y to be exactly representable with as little effort as
1777 # possible. So we look for cheap and easy tests that
1778 # eliminate the possibility of x**y being exact. Only if all
1779 # these tests are passed do we go on to actually compute x**y.
1780
1781 # Here's the main idea. First normalize both x and y. We
1782 # express y as a rational m/n, with m and n relatively prime
1783 # and n>0. Then for x**y to be exactly representable (at
1784 # *any* precision), xc must be the nth power of a positive
1785 # integer and xe must be divisible by n. If m is negative
1786 # then additionally xc must be a power of either 2 or 5, hence
1787 # a power of 2**n or 5**n.
1788 #
1789 # There's a limit to how small |y| can be: if y=m/n as above
1790 # then:
1791 #
1792 # (1) if xc != 1 then for the result to be representable we
1793 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1794 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1795 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1796 # representable.
1797 #
1798 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1799 # |y| < 1/|xe| then the result is not representable.
1800 #
1801 # Note that since x is not equal to 1, at least one of (1) and
1802 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1803 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1804 #
1805 # There's also a limit to how large y can be, at least if it's
1806 # positive: the normalized result will have coefficient xc**y,
1807 # so if it's representable then xc**y < 10**p, and y <
1808 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1809 # not exactly representable.
1810
1811 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1812 # so |y| < 1/xe and the result is not representable.
1813 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1814 # < 1/nbits(xc).
1815
1816 x = _WorkRep(self)
1817 xc, xe = x.int, x.exp
1818 while xc % 10 == 0:
1819 xc //= 10
1820 xe += 1
1821
1822 y = _WorkRep(other)
1823 yc, ye = y.int, y.exp
1824 while yc % 10 == 0:
1825 yc //= 10
1826 ye += 1
1827
1828 # case where xc == 1: result is 10**(xe*y), with xe*y
1829 # required to be an integer
1830 if xc == 1:
1831 if ye >= 0:
1832 exponent = xe*yc*10**ye
1833 else:
1834 exponent, remainder = divmod(xe*yc, 10**-ye)
1835 if remainder:
1836 return None
1837 if y.sign == 1:
1838 exponent = -exponent
1839 # if other is a nonnegative integer, use ideal exponent
1840 if other._isinteger() and other._sign == 0:
1841 ideal_exponent = self._exp*int(other)
1842 zeros = min(exponent-ideal_exponent, p-1)
1843 else:
1844 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001845 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001846
1847 # case where y is negative: xc must be either a power
1848 # of 2 or a power of 5.
1849 if y.sign == 1:
1850 last_digit = xc % 10
1851 if last_digit in (2,4,6,8):
1852 # quick test for power of 2
1853 if xc & -xc != xc:
1854 return None
1855 # now xc is a power of 2; e is its exponent
1856 e = _nbits(xc)-1
1857 # find e*y and xe*y; both must be integers
1858 if ye >= 0:
1859 y_as_int = yc*10**ye
1860 e = e*y_as_int
1861 xe = xe*y_as_int
1862 else:
1863 ten_pow = 10**-ye
1864 e, remainder = divmod(e*yc, ten_pow)
1865 if remainder:
1866 return None
1867 xe, remainder = divmod(xe*yc, ten_pow)
1868 if remainder:
1869 return None
1870
1871 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1872 return None
1873 xc = 5**e
1874
1875 elif last_digit == 5:
1876 # e >= log_5(xc) if xc is a power of 5; we have
1877 # equality all the way up to xc=5**2658
1878 e = _nbits(xc)*28//65
1879 xc, remainder = divmod(5**e, xc)
1880 if remainder:
1881 return None
1882 while xc % 5 == 0:
1883 xc //= 5
1884 e -= 1
1885 if ye >= 0:
1886 y_as_integer = yc*10**ye
1887 e = e*y_as_integer
1888 xe = xe*y_as_integer
1889 else:
1890 ten_pow = 10**-ye
1891 e, remainder = divmod(e*yc, ten_pow)
1892 if remainder:
1893 return None
1894 xe, remainder = divmod(xe*yc, ten_pow)
1895 if remainder:
1896 return None
1897 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1898 return None
1899 xc = 2**e
1900 else:
1901 return None
1902
1903 if xc >= 10**p:
1904 return None
1905 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001906 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001907
1908 # now y is positive; find m and n such that y = m/n
1909 if ye >= 0:
1910 m, n = yc*10**ye, 1
1911 else:
1912 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1913 return None
1914 xc_bits = _nbits(xc)
1915 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1916 return None
1917 m, n = yc, 10**(-ye)
1918 while m % 2 == n % 2 == 0:
1919 m //= 2
1920 n //= 2
1921 while m % 5 == n % 5 == 0:
1922 m //= 5
1923 n //= 5
1924
1925 # compute nth root of xc*10**xe
1926 if n > 1:
1927 # if 1 < xc < 2**n then xc isn't an nth power
1928 if xc != 1 and xc_bits <= n:
1929 return None
1930
1931 xe, rem = divmod(xe, n)
1932 if rem != 0:
1933 return None
1934
1935 # compute nth root of xc using Newton's method
1936 a = 1L << -(-_nbits(xc)//n) # initial estimate
1937 while True:
1938 q, r = divmod(xc, a**(n-1))
1939 if a <= q:
1940 break
1941 else:
1942 a = (a*(n-1) + q)//n
1943 if not (a == q and r == 0):
1944 return None
1945 xc = a
1946
1947 # now xc*10**xe is the nth root of the original xc*10**xe
1948 # compute mth power of xc*10**xe
1949
1950 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1951 # 10**p and the result is not representable.
1952 if xc > 1 and m > p*100//_log10_lb(xc):
1953 return None
1954 xc = xc**m
1955 xe *= m
1956 if xc > 10**p:
1957 return None
1958
1959 # by this point the result *is* exactly representable
1960 # adjust the exponent to get as close as possible to the ideal
1961 # exponent, if necessary
1962 str_xc = str(xc)
1963 if other._isinteger() and other._sign == 0:
1964 ideal_exponent = self._exp*int(other)
1965 zeros = min(xe-ideal_exponent, p-len(str_xc))
1966 else:
1967 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001968 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001969
1970 def __pow__(self, other, modulo=None, context=None):
1971 """Return self ** other [ % modulo].
1972
1973 With two arguments, compute self**other.
1974
1975 With three arguments, compute (self**other) % modulo. For the
1976 three argument form, the following restrictions on the
1977 arguments hold:
1978
1979 - all three arguments must be integral
1980 - other must be nonnegative
1981 - either self or other (or both) must be nonzero
1982 - modulo must be nonzero and must have at most p digits,
1983 where p is the context precision.
1984
1985 If any of these restrictions is violated the InvalidOperation
1986 flag is raised.
1987
1988 The result of pow(self, other, modulo) is identical to the
1989 result that would be obtained by computing (self**other) %
1990 modulo with unbounded precision, but is computed more
1991 efficiently. It is always exact.
1992 """
1993
1994 if modulo is not None:
1995 return self._power_modulo(other, modulo, context)
1996
1997 other = _convert_other(other)
1998 if other is NotImplemented:
1999 return other
2000
2001 if context is None:
2002 context = getcontext()
2003
2004 # either argument is a NaN => result is NaN
2005 ans = self._check_nans(other, context)
2006 if ans:
2007 return ans
2008
2009 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2010 if not other:
2011 if not self:
2012 return context._raise_error(InvalidOperation, '0 ** 0')
2013 else:
2014 return Dec_p1
2015
2016 # result has sign 1 iff self._sign is 1 and other is an odd integer
2017 result_sign = 0
2018 if self._sign == 1:
2019 if other._isinteger():
2020 if not other._iseven():
2021 result_sign = 1
2022 else:
2023 # -ve**noninteger = NaN
2024 # (-0)**noninteger = 0**noninteger
2025 if self:
2026 return context._raise_error(InvalidOperation,
2027 'x ** y with x negative and y not an integer')
2028 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002029 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002030
2031 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2032 if not self:
2033 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002034 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002035 else:
2036 return Infsign[result_sign]
2037
2038 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002039 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002040 if other._sign == 0:
2041 return Infsign[result_sign]
2042 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002043 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002044
Facundo Batista353750c2007-09-13 18:13:15 +00002045 # 1**other = 1, but the choice of exponent and the flags
2046 # depend on the exponent of self, and on whether other is a
2047 # positive integer, a negative integer, or neither
2048 if self == Dec_p1:
2049 if other._isinteger():
2050 # exp = max(self._exp*max(int(other), 0),
2051 # 1-context.prec) but evaluating int(other) directly
2052 # is dangerous until we know other is small (other
2053 # could be 1e999999999)
2054 if other._sign == 1:
2055 multiplier = 0
2056 elif other > context.prec:
2057 multiplier = context.prec
2058 else:
2059 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002060
Facundo Batista353750c2007-09-13 18:13:15 +00002061 exp = self._exp * multiplier
2062 if exp < 1-context.prec:
2063 exp = 1-context.prec
2064 context._raise_error(Rounded)
2065 else:
2066 context._raise_error(Inexact)
2067 context._raise_error(Rounded)
2068 exp = 1-context.prec
2069
Facundo Batista72bc54f2007-11-23 17:59:00 +00002070 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002071
2072 # compute adjusted exponent of self
2073 self_adj = self.adjusted()
2074
2075 # self ** infinity is infinity if self > 1, 0 if self < 1
2076 # self ** -infinity is infinity if self < 1, 0 if self > 1
2077 if other._isinfinity():
2078 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002079 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002080 else:
2081 return Infsign[result_sign]
2082
2083 # from here on, the result always goes through the call
2084 # to _fix at the end of this function.
2085 ans = None
2086
2087 # crude test to catch cases of extreme overflow/underflow. If
2088 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2089 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2090 # self**other >= 10**(Emax+1), so overflow occurs. The test
2091 # for underflow is similar.
2092 bound = self._log10_exp_bound() + other.adjusted()
2093 if (self_adj >= 0) == (other._sign == 0):
2094 # self > 1 and other +ve, or self < 1 and other -ve
2095 # possibility of overflow
2096 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002097 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002098 else:
2099 # self > 1 and other -ve, or self < 1 and other +ve
2100 # possibility of underflow to 0
2101 Etiny = context.Etiny()
2102 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002103 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002104
2105 # try for an exact result with precision +1
2106 if ans is None:
2107 ans = self._power_exact(other, context.prec + 1)
2108 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002109 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002110
2111 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2112 if ans is None:
2113 p = context.prec
2114 x = _WorkRep(self)
2115 xc, xe = x.int, x.exp
2116 y = _WorkRep(other)
2117 yc, ye = y.int, y.exp
2118 if y.sign == 1:
2119 yc = -yc
2120
2121 # compute correctly rounded result: start with precision +3,
2122 # then increase precision until result is unambiguously roundable
2123 extra = 3
2124 while True:
2125 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2126 if coeff % (5*10**(len(str(coeff))-p-1)):
2127 break
2128 extra += 3
2129
Facundo Batista72bc54f2007-11-23 17:59:00 +00002130 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002131
2132 # the specification says that for non-integer other we need to
2133 # raise Inexact, even when the result is actually exact. In
2134 # the same way, we need to raise Underflow here if the result
2135 # is subnormal. (The call to _fix will take care of raising
2136 # Rounded and Subnormal, as usual.)
2137 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002138 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002139 # pad with zeros up to length context.prec+1 if necessary
2140 if len(ans._int) <= context.prec:
2141 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002142 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2143 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002144 if ans.adjusted() < context.Emin:
2145 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002146
Facundo Batista353750c2007-09-13 18:13:15 +00002147 # unlike exp, ln and log10, the power function respects the
2148 # rounding mode; no need to use ROUND_HALF_EVEN here
2149 ans = ans._fix(context)
2150 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002151
2152 def __rpow__(self, other, context=None):
2153 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002154 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002155 if other is NotImplemented:
2156 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002157 return other.__pow__(self, context=context)
2158
2159 def normalize(self, context=None):
2160 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002161
Facundo Batista353750c2007-09-13 18:13:15 +00002162 if context is None:
2163 context = getcontext()
2164
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002165 if self._is_special:
2166 ans = self._check_nans(context=context)
2167 if ans:
2168 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002169
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002170 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002171 if dup._isinfinity():
2172 return dup
2173
2174 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002175 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002176 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002177 end = len(dup._int)
2178 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002179 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002180 exp += 1
2181 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002182 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002183
Facundo Batistabd2fe832007-09-13 18:42:09 +00002184 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002185 """Quantize self so its exponent is the same as that of exp.
2186
2187 Similar to self._rescale(exp._exp) but with error checking.
2188 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002189 exp = _convert_other(exp, raiseit=True)
2190
Facundo Batista353750c2007-09-13 18:13:15 +00002191 if context is None:
2192 context = getcontext()
2193 if rounding is None:
2194 rounding = context.rounding
2195
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002196 if self._is_special or exp._is_special:
2197 ans = self._check_nans(exp, context)
2198 if ans:
2199 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002200
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002201 if exp._isinfinity() or self._isinfinity():
2202 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002203 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002204 return context._raise_error(InvalidOperation,
2205 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002206
Facundo Batistabd2fe832007-09-13 18:42:09 +00002207 # if we're not watching exponents, do a simple rescale
2208 if not watchexp:
2209 ans = self._rescale(exp._exp, rounding)
2210 # raise Inexact and Rounded where appropriate
2211 if ans._exp > self._exp:
2212 context._raise_error(Rounded)
2213 if ans != self:
2214 context._raise_error(Inexact)
2215 return ans
2216
Facundo Batista353750c2007-09-13 18:13:15 +00002217 # exp._exp should be between Etiny and Emax
2218 if not (context.Etiny() <= exp._exp <= context.Emax):
2219 return context._raise_error(InvalidOperation,
2220 'target exponent out of bounds in quantize')
2221
2222 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002223 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002224 return ans._fix(context)
2225
2226 self_adjusted = self.adjusted()
2227 if self_adjusted > context.Emax:
2228 return context._raise_error(InvalidOperation,
2229 'exponent of quantize result too large for current context')
2230 if self_adjusted - exp._exp + 1 > context.prec:
2231 return context._raise_error(InvalidOperation,
2232 'quantize result has too many digits for current context')
2233
2234 ans = self._rescale(exp._exp, rounding)
2235 if ans.adjusted() > context.Emax:
2236 return context._raise_error(InvalidOperation,
2237 'exponent of quantize result too large for current context')
2238 if len(ans._int) > context.prec:
2239 return context._raise_error(InvalidOperation,
2240 'quantize result has too many digits for current context')
2241
2242 # raise appropriate flags
2243 if ans._exp > self._exp:
2244 context._raise_error(Rounded)
2245 if ans != self:
2246 context._raise_error(Inexact)
2247 if ans and ans.adjusted() < context.Emin:
2248 context._raise_error(Subnormal)
2249
2250 # call to fix takes care of any necessary folddown
2251 ans = ans._fix(context)
2252 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002253
2254 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002255 """Return True if self and other have the same exponent; otherwise
2256 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002257
Facundo Batista1a191df2007-10-02 17:01:24 +00002258 If either operand is a special value, the following rules are used:
2259 * return True if both operands are infinities
2260 * return True if both operands are NaNs
2261 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002262 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002263 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002264 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002265 return (self.is_nan() and other.is_nan() or
2266 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002267 return self._exp == other._exp
2268
Facundo Batista353750c2007-09-13 18:13:15 +00002269 def _rescale(self, exp, rounding):
2270 """Rescale self so that the exponent is exp, either by padding with zeros
2271 or by truncating digits, using the given rounding mode.
2272
2273 Specials are returned without change. This operation is
2274 quiet: it raises no flags, and uses no information from the
2275 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002276
2277 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002278 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002279 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002280 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002281 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002282 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002283 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002284
Facundo Batista353750c2007-09-13 18:13:15 +00002285 if self._exp >= exp:
2286 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002287 return _dec_from_triple(self._sign,
2288 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002289
Facundo Batista353750c2007-09-13 18:13:15 +00002290 # too many digits; round and lose data. If self.adjusted() <
2291 # exp-1, replace self by 10**(exp-1) before rounding
2292 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002293 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002294 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002295 digits = 0
2296 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002297 changed = this_function(digits)
2298 coeff = self._int[:digits] or '0'
2299 if changed == 1:
2300 coeff = str(int(coeff)+1)
2301 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002302
Facundo Batista353750c2007-09-13 18:13:15 +00002303 def to_integral_exact(self, rounding=None, context=None):
2304 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002305
Facundo Batista353750c2007-09-13 18:13:15 +00002306 If no rounding mode is specified, take the rounding mode from
2307 the context. This method raises the Rounded and Inexact flags
2308 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002309
Facundo Batista353750c2007-09-13 18:13:15 +00002310 See also: to_integral_value, which does exactly the same as
2311 this method except that it doesn't raise Inexact or Rounded.
2312 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002313 if self._is_special:
2314 ans = self._check_nans(context=context)
2315 if ans:
2316 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002317 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002318 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002319 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002320 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002321 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002322 if context is None:
2323 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002324 if rounding is None:
2325 rounding = context.rounding
2326 context._raise_error(Rounded)
2327 ans = self._rescale(0, rounding)
2328 if ans != self:
2329 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002330 return ans
2331
Facundo Batista353750c2007-09-13 18:13:15 +00002332 def to_integral_value(self, rounding=None, context=None):
2333 """Rounds to the nearest integer, without raising inexact, rounded."""
2334 if context is None:
2335 context = getcontext()
2336 if rounding is None:
2337 rounding = context.rounding
2338 if self._is_special:
2339 ans = self._check_nans(context=context)
2340 if ans:
2341 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002342 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002343 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002344 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002345 else:
2346 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002347
Facundo Batista353750c2007-09-13 18:13:15 +00002348 # the method name changed, but we provide also the old one, for compatibility
2349 to_integral = to_integral_value
2350
2351 def sqrt(self, context=None):
2352 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002353 if self._is_special:
2354 ans = self._check_nans(context=context)
2355 if ans:
2356 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002357
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002358 if self._isinfinity() and self._sign == 0:
2359 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002360
2361 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002362 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002363 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002364 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002365
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002366 if context is None:
2367 context = getcontext()
2368
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002369 if self._sign == 1:
2370 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2371
Facundo Batista353750c2007-09-13 18:13:15 +00002372 # At this point self represents a positive number. Let p be
2373 # the desired precision and express self in the form c*100**e
2374 # with c a positive real number and e an integer, c and e
2375 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2376 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2377 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2378 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2379 # the closest integer to sqrt(c) with the even integer chosen
2380 # in the case of a tie.
2381 #
2382 # To ensure correct rounding in all cases, we use the
2383 # following trick: we compute the square root to an extra
2384 # place (precision p+1 instead of precision p), rounding down.
2385 # Then, if the result is inexact and its last digit is 0 or 5,
2386 # we increase the last digit to 1 or 6 respectively; if it's
2387 # exact we leave the last digit alone. Now the final round to
2388 # p places (or fewer in the case of underflow) will round
2389 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002390
Facundo Batista353750c2007-09-13 18:13:15 +00002391 # use an extra digit of precision
2392 prec = context.prec+1
2393
2394 # write argument in the form c*100**e where e = self._exp//2
2395 # is the 'ideal' exponent, to be used if the square root is
2396 # exactly representable. l is the number of 'digits' of c in
2397 # base 100, so that 100**(l-1) <= c < 100**l.
2398 op = _WorkRep(self)
2399 e = op.exp >> 1
2400 if op.exp & 1:
2401 c = op.int * 10
2402 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002403 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002404 c = op.int
2405 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002406
Facundo Batista353750c2007-09-13 18:13:15 +00002407 # rescale so that c has exactly prec base 100 'digits'
2408 shift = prec-l
2409 if shift >= 0:
2410 c *= 100**shift
2411 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002412 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002413 c, remainder = divmod(c, 100**-shift)
2414 exact = not remainder
2415 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002416
Facundo Batista353750c2007-09-13 18:13:15 +00002417 # find n = floor(sqrt(c)) using Newton's method
2418 n = 10**prec
2419 while True:
2420 q = c//n
2421 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002422 break
Facundo Batista353750c2007-09-13 18:13:15 +00002423 else:
2424 n = n + q >> 1
2425 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002426
Facundo Batista353750c2007-09-13 18:13:15 +00002427 if exact:
2428 # result is exact; rescale to use ideal exponent e
2429 if shift >= 0:
2430 # assert n % 10**shift == 0
2431 n //= 10**shift
2432 else:
2433 n *= 10**-shift
2434 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002435 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002436 # result is not exact; fix last digit as described above
2437 if n % 5 == 0:
2438 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002439
Facundo Batista72bc54f2007-11-23 17:59:00 +00002440 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002441
Facundo Batista353750c2007-09-13 18:13:15 +00002442 # round, and fit to current context
2443 context = context._shallow_copy()
2444 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002445 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002446 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002447
Facundo Batista353750c2007-09-13 18:13:15 +00002448 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002449
2450 def max(self, other, context=None):
2451 """Returns the larger value.
2452
Facundo Batista353750c2007-09-13 18:13:15 +00002453 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002454 NaN (and signals if one is sNaN). Also rounds.
2455 """
Facundo Batista353750c2007-09-13 18:13:15 +00002456 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002457
Facundo Batista6c398da2007-09-17 17:30:13 +00002458 if context is None:
2459 context = getcontext()
2460
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002461 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002462 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002463 # number is always returned
2464 sn = self._isnan()
2465 on = other._isnan()
2466 if sn or on:
2467 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002468 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002469 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002470 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002471 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002472
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002473 c = self.__cmp__(other)
2474 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002475 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002476 # then an ordering is applied:
2477 #
Facundo Batista59c58842007-04-10 12:58:45 +00002478 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002479 # positive sign and min returns the operand with the negative sign
2480 #
Facundo Batista59c58842007-04-10 12:58:45 +00002481 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002482 # the result. This is exactly the ordering used in compare_total.
2483 c = self.compare_total(other)
2484
2485 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002486 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002487 else:
2488 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002489
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002490 if context._rounding_decision == ALWAYS_ROUND:
2491 return ans._fix(context)
2492 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002493
2494 def min(self, other, context=None):
2495 """Returns the smaller value.
2496
Facundo Batista59c58842007-04-10 12:58:45 +00002497 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002498 NaN (and signals if one is sNaN). Also rounds.
2499 """
Facundo Batista353750c2007-09-13 18:13:15 +00002500 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002501
Facundo Batista6c398da2007-09-17 17:30:13 +00002502 if context is None:
2503 context = getcontext()
2504
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002505 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002506 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002507 # number is always returned
2508 sn = self._isnan()
2509 on = other._isnan()
2510 if sn or on:
2511 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002512 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002513 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002514 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002515 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002517 c = self.__cmp__(other)
2518 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002519 c = self.compare_total(other)
2520
2521 if c == -1:
2522 ans = self
2523 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002524 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002525
Raymond Hettinger76e60d62004-10-20 06:58:28 +00002526 if context._rounding_decision == ALWAYS_ROUND:
2527 return ans._fix(context)
2528 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002529
2530 def _isinteger(self):
2531 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002532 if self._is_special:
2533 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002534 if self._exp >= 0:
2535 return True
2536 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002537 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002538
2539 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002540 """Returns True if self is even. Assumes self is an integer."""
2541 if not self or self._exp > 0:
2542 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002543 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002544
2545 def adjusted(self):
2546 """Return the adjusted exponent of self"""
2547 try:
2548 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002549 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002550 except TypeError:
2551 return 0
2552
Facundo Batista353750c2007-09-13 18:13:15 +00002553 def canonical(self, context=None):
2554 """Returns the same Decimal object.
2555
2556 As we do not have different encodings for the same number, the
2557 received object already is in its canonical form.
2558 """
2559 return self
2560
2561 def compare_signal(self, other, context=None):
2562 """Compares self to the other operand numerically.
2563
2564 It's pretty much like compare(), but all NaNs signal, with signaling
2565 NaNs taking precedence over quiet NaNs.
2566 """
2567 if context is None:
2568 context = getcontext()
2569
2570 self_is_nan = self._isnan()
2571 other_is_nan = other._isnan()
2572 if self_is_nan == 2:
2573 return context._raise_error(InvalidOperation, 'sNaN',
2574 1, self)
2575 if other_is_nan == 2:
2576 return context._raise_error(InvalidOperation, 'sNaN',
2577 1, other)
2578 if self_is_nan:
2579 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2580 1, self)
2581 if other_is_nan:
2582 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2583 1, other)
2584 return self.compare(other, context=context)
2585
2586 def compare_total(self, other):
2587 """Compares self to other using the abstract representations.
2588
2589 This is not like the standard compare, which use their numerical
2590 value. Note that a total ordering is defined for all possible abstract
2591 representations.
2592 """
2593 # if one is negative and the other is positive, it's easy
2594 if self._sign and not other._sign:
2595 return Dec_n1
2596 if not self._sign and other._sign:
2597 return Dec_p1
2598 sign = self._sign
2599
2600 # let's handle both NaN types
2601 self_nan = self._isnan()
2602 other_nan = other._isnan()
2603 if self_nan or other_nan:
2604 if self_nan == other_nan:
2605 if self._int < other._int:
2606 if sign:
2607 return Dec_p1
2608 else:
2609 return Dec_n1
2610 if self._int > other._int:
2611 if sign:
2612 return Dec_n1
2613 else:
2614 return Dec_p1
2615 return Dec_0
2616
2617 if sign:
2618 if self_nan == 1:
2619 return Dec_n1
2620 if other_nan == 1:
2621 return Dec_p1
2622 if self_nan == 2:
2623 return Dec_n1
2624 if other_nan == 2:
2625 return Dec_p1
2626 else:
2627 if self_nan == 1:
2628 return Dec_p1
2629 if other_nan == 1:
2630 return Dec_n1
2631 if self_nan == 2:
2632 return Dec_p1
2633 if other_nan == 2:
2634 return Dec_n1
2635
2636 if self < other:
2637 return Dec_n1
2638 if self > other:
2639 return Dec_p1
2640
2641 if self._exp < other._exp:
2642 if sign:
2643 return Dec_p1
2644 else:
2645 return Dec_n1
2646 if self._exp > other._exp:
2647 if sign:
2648 return Dec_n1
2649 else:
2650 return Dec_p1
2651 return Dec_0
2652
2653
2654 def compare_total_mag(self, other):
2655 """Compares self to other using abstract repr., ignoring sign.
2656
2657 Like compare_total, but with operand's sign ignored and assumed to be 0.
2658 """
2659 s = self.copy_abs()
2660 o = other.copy_abs()
2661 return s.compare_total(o)
2662
2663 def copy_abs(self):
2664 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002665 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002666
2667 def copy_negate(self):
2668 """Returns a copy with the sign inverted."""
2669 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002670 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002671 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002672 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002673
2674 def copy_sign(self, other):
2675 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002676 return _dec_from_triple(other._sign, self._int,
2677 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002678
2679 def exp(self, context=None):
2680 """Returns e ** self."""
2681
2682 if context is None:
2683 context = getcontext()
2684
2685 # exp(NaN) = NaN
2686 ans = self._check_nans(context=context)
2687 if ans:
2688 return ans
2689
2690 # exp(-Infinity) = 0
2691 if self._isinfinity() == -1:
2692 return Dec_0
2693
2694 # exp(0) = 1
2695 if not self:
2696 return Dec_p1
2697
2698 # exp(Infinity) = Infinity
2699 if self._isinfinity() == 1:
2700 return Decimal(self)
2701
2702 # the result is now guaranteed to be inexact (the true
2703 # mathematical result is transcendental). There's no need to
2704 # raise Rounded and Inexact here---they'll always be raised as
2705 # a result of the call to _fix.
2706 p = context.prec
2707 adj = self.adjusted()
2708
2709 # we only need to do any computation for quite a small range
2710 # of adjusted exponents---for example, -29 <= adj <= 10 for
2711 # the default context. For smaller exponent the result is
2712 # indistinguishable from 1 at the given precision, while for
2713 # larger exponent the result either overflows or underflows.
2714 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2715 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002716 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002717 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2718 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002719 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002720 elif self._sign == 0 and adj < -p:
2721 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002722 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002723 elif self._sign == 1 and adj < -p-1:
2724 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002725 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002726 # general case
2727 else:
2728 op = _WorkRep(self)
2729 c, e = op.int, op.exp
2730 if op.sign == 1:
2731 c = -c
2732
2733 # compute correctly rounded result: increase precision by
2734 # 3 digits at a time until we get an unambiguously
2735 # roundable result
2736 extra = 3
2737 while True:
2738 coeff, exp = _dexp(c, e, p+extra)
2739 if coeff % (5*10**(len(str(coeff))-p-1)):
2740 break
2741 extra += 3
2742
Facundo Batista72bc54f2007-11-23 17:59:00 +00002743 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002744
2745 # at this stage, ans should round correctly with *any*
2746 # rounding mode, not just with ROUND_HALF_EVEN
2747 context = context._shallow_copy()
2748 rounding = context._set_rounding(ROUND_HALF_EVEN)
2749 ans = ans._fix(context)
2750 context.rounding = rounding
2751
2752 return ans
2753
2754 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002755 """Return True if self is canonical; otherwise return False.
2756
2757 Currently, the encoding of a Decimal instance is always
2758 canonical, so this method returns True for any Decimal.
2759 """
2760 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002761
2762 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002763 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002764
Facundo Batista1a191df2007-10-02 17:01:24 +00002765 A Decimal instance is considered finite if it is neither
2766 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002767 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002768 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002769
2770 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002771 """Return True if self is infinite; otherwise return False."""
2772 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002773
2774 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002775 """Return True if self is a qNaN or sNaN; otherwise return False."""
2776 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002777
2778 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002779 """Return True if self is a normal number; otherwise return False."""
2780 if self._is_special or not self:
2781 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002782 if context is None:
2783 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002784 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002785
2786 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002787 """Return True if self is a quiet NaN; otherwise return False."""
2788 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002789
2790 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002791 """Return True if self is negative; otherwise return False."""
2792 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002793
2794 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002795 """Return True if self is a signaling NaN; otherwise return False."""
2796 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002797
2798 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002799 """Return True if self is subnormal; otherwise return False."""
2800 if self._is_special or not self:
2801 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002802 if context is None:
2803 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002804 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002805
2806 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002807 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002808 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002809
2810 def _ln_exp_bound(self):
2811 """Compute a lower bound for the adjusted exponent of self.ln().
2812 In other words, compute r such that self.ln() >= 10**r. Assumes
2813 that self is finite and positive and that self != 1.
2814 """
2815
2816 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2817 adj = self._exp + len(self._int) - 1
2818 if adj >= 1:
2819 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2820 return len(str(adj*23//10)) - 1
2821 if adj <= -2:
2822 # argument <= 0.1
2823 return len(str((-1-adj)*23//10)) - 1
2824 op = _WorkRep(self)
2825 c, e = op.int, op.exp
2826 if adj == 0:
2827 # 1 < self < 10
2828 num = str(c-10**-e)
2829 den = str(c)
2830 return len(num) - len(den) - (num < den)
2831 # adj == -1, 0.1 <= self < 1
2832 return e + len(str(10**-e - c)) - 1
2833
2834
2835 def ln(self, context=None):
2836 """Returns the natural (base e) logarithm of self."""
2837
2838 if context is None:
2839 context = getcontext()
2840
2841 # ln(NaN) = NaN
2842 ans = self._check_nans(context=context)
2843 if ans:
2844 return ans
2845
2846 # ln(0.0) == -Infinity
2847 if not self:
2848 return negInf
2849
2850 # ln(Infinity) = Infinity
2851 if self._isinfinity() == 1:
2852 return Inf
2853
2854 # ln(1.0) == 0.0
2855 if self == Dec_p1:
2856 return Dec_0
2857
2858 # ln(negative) raises InvalidOperation
2859 if self._sign == 1:
2860 return context._raise_error(InvalidOperation,
2861 'ln of a negative value')
2862
2863 # result is irrational, so necessarily inexact
2864 op = _WorkRep(self)
2865 c, e = op.int, op.exp
2866 p = context.prec
2867
2868 # correctly rounded result: repeatedly increase precision by 3
2869 # until we get an unambiguously roundable result
2870 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2871 while True:
2872 coeff = _dlog(c, e, places)
2873 # assert len(str(abs(coeff)))-p >= 1
2874 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2875 break
2876 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002877 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002878
2879 context = context._shallow_copy()
2880 rounding = context._set_rounding(ROUND_HALF_EVEN)
2881 ans = ans._fix(context)
2882 context.rounding = rounding
2883 return ans
2884
2885 def _log10_exp_bound(self):
2886 """Compute a lower bound for the adjusted exponent of self.log10().
2887 In other words, find r such that self.log10() >= 10**r.
2888 Assumes that self is finite and positive and that self != 1.
2889 """
2890
2891 # For x >= 10 or x < 0.1 we only need a bound on the integer
2892 # part of log10(self), and this comes directly from the
2893 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2894 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2895 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2896
2897 adj = self._exp + len(self._int) - 1
2898 if adj >= 1:
2899 # self >= 10
2900 return len(str(adj))-1
2901 if adj <= -2:
2902 # self < 0.1
2903 return len(str(-1-adj))-1
2904 op = _WorkRep(self)
2905 c, e = op.int, op.exp
2906 if adj == 0:
2907 # 1 < self < 10
2908 num = str(c-10**-e)
2909 den = str(231*c)
2910 return len(num) - len(den) - (num < den) + 2
2911 # adj == -1, 0.1 <= self < 1
2912 num = str(10**-e-c)
2913 return len(num) + e - (num < "231") - 1
2914
2915 def log10(self, context=None):
2916 """Returns the base 10 logarithm of self."""
2917
2918 if context is None:
2919 context = getcontext()
2920
2921 # log10(NaN) = NaN
2922 ans = self._check_nans(context=context)
2923 if ans:
2924 return ans
2925
2926 # log10(0.0) == -Infinity
2927 if not self:
2928 return negInf
2929
2930 # log10(Infinity) = Infinity
2931 if self._isinfinity() == 1:
2932 return Inf
2933
2934 # log10(negative or -Infinity) raises InvalidOperation
2935 if self._sign == 1:
2936 return context._raise_error(InvalidOperation,
2937 'log10 of a negative value')
2938
2939 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00002940 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00002941 # answer may need rounding
2942 ans = Decimal(self._exp + len(self._int) - 1)
2943 else:
2944 # result is irrational, so necessarily inexact
2945 op = _WorkRep(self)
2946 c, e = op.int, op.exp
2947 p = context.prec
2948
2949 # correctly rounded result: repeatedly increase precision
2950 # until result is unambiguously roundable
2951 places = p-self._log10_exp_bound()+2
2952 while True:
2953 coeff = _dlog10(c, e, places)
2954 # assert len(str(abs(coeff)))-p >= 1
2955 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2956 break
2957 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002958 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002959
2960 context = context._shallow_copy()
2961 rounding = context._set_rounding(ROUND_HALF_EVEN)
2962 ans = ans._fix(context)
2963 context.rounding = rounding
2964 return ans
2965
2966 def logb(self, context=None):
2967 """ Returns the exponent of the magnitude of self's MSD.
2968
2969 The result is the integer which is the exponent of the magnitude
2970 of the most significant digit of self (as though it were truncated
2971 to a single digit while maintaining the value of that digit and
2972 without limiting the resulting exponent).
2973 """
2974 # logb(NaN) = NaN
2975 ans = self._check_nans(context=context)
2976 if ans:
2977 return ans
2978
2979 if context is None:
2980 context = getcontext()
2981
2982 # logb(+/-Inf) = +Inf
2983 if self._isinfinity():
2984 return Inf
2985
2986 # logb(0) = -Inf, DivisionByZero
2987 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00002988 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00002989
2990 # otherwise, simply return the adjusted exponent of self, as a
2991 # Decimal. Note that no attempt is made to fit the result
2992 # into the current context.
2993 return Decimal(self.adjusted())
2994
2995 def _islogical(self):
2996 """Return True if self is a logical operand.
2997
2998 For being logical, it must be a finite numbers with a sign of 0,
2999 an exponent of 0, and a coefficient whose digits must all be
3000 either 0 or 1.
3001 """
3002 if self._sign != 0 or self._exp != 0:
3003 return False
3004 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003005 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003006 return False
3007 return True
3008
3009 def _fill_logical(self, context, opa, opb):
3010 dif = context.prec - len(opa)
3011 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003012 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003013 elif dif < 0:
3014 opa = opa[-context.prec:]
3015 dif = context.prec - len(opb)
3016 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003017 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003018 elif dif < 0:
3019 opb = opb[-context.prec:]
3020 return opa, opb
3021
3022 def logical_and(self, other, context=None):
3023 """Applies an 'and' operation between self and other's digits."""
3024 if context is None:
3025 context = getcontext()
3026 if not self._islogical() or not other._islogical():
3027 return context._raise_error(InvalidOperation)
3028
3029 # fill to context.prec
3030 (opa, opb) = self._fill_logical(context, self._int, other._int)
3031
3032 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003033 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3034 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003035
3036 def logical_invert(self, context=None):
3037 """Invert all its digits."""
3038 if context is None:
3039 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003040 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3041 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003042
3043 def logical_or(self, other, context=None):
3044 """Applies an 'or' operation between self and other's digits."""
3045 if context is None:
3046 context = getcontext()
3047 if not self._islogical() or not other._islogical():
3048 return context._raise_error(InvalidOperation)
3049
3050 # fill to context.prec
3051 (opa, opb) = self._fill_logical(context, self._int, other._int)
3052
3053 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003054 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3055 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003056
3057 def logical_xor(self, other, context=None):
3058 """Applies an 'xor' operation between self and other's digits."""
3059 if context is None:
3060 context = getcontext()
3061 if not self._islogical() or not other._islogical():
3062 return context._raise_error(InvalidOperation)
3063
3064 # fill to context.prec
3065 (opa, opb) = self._fill_logical(context, self._int, other._int)
3066
3067 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003068 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3069 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003070
3071 def max_mag(self, other, context=None):
3072 """Compares the values numerically with their sign ignored."""
3073 other = _convert_other(other, raiseit=True)
3074
Facundo Batista6c398da2007-09-17 17:30:13 +00003075 if context is None:
3076 context = getcontext()
3077
Facundo Batista353750c2007-09-13 18:13:15 +00003078 if self._is_special or other._is_special:
3079 # If one operand is a quiet NaN and the other is number, then the
3080 # number is always returned
3081 sn = self._isnan()
3082 on = other._isnan()
3083 if sn or on:
3084 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003085 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003086 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003087 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003088 return self._check_nans(other, context)
3089
3090 c = self.copy_abs().__cmp__(other.copy_abs())
3091 if c == 0:
3092 c = self.compare_total(other)
3093
3094 if c == -1:
3095 ans = other
3096 else:
3097 ans = self
3098
Facundo Batista353750c2007-09-13 18:13:15 +00003099 if context._rounding_decision == ALWAYS_ROUND:
3100 return ans._fix(context)
3101 return ans
3102
3103 def min_mag(self, other, context=None):
3104 """Compares the values numerically with their sign ignored."""
3105 other = _convert_other(other, raiseit=True)
3106
Facundo Batista6c398da2007-09-17 17:30:13 +00003107 if context is None:
3108 context = getcontext()
3109
Facundo Batista353750c2007-09-13 18:13:15 +00003110 if self._is_special or other._is_special:
3111 # If one operand is a quiet NaN and the other is number, then the
3112 # number is always returned
3113 sn = self._isnan()
3114 on = other._isnan()
3115 if sn or on:
3116 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003117 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003118 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003119 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003120 return self._check_nans(other, context)
3121
3122 c = self.copy_abs().__cmp__(other.copy_abs())
3123 if c == 0:
3124 c = self.compare_total(other)
3125
3126 if c == -1:
3127 ans = self
3128 else:
3129 ans = other
3130
Facundo Batista353750c2007-09-13 18:13:15 +00003131 if context._rounding_decision == ALWAYS_ROUND:
3132 return ans._fix(context)
3133 return ans
3134
3135 def next_minus(self, context=None):
3136 """Returns the largest representable number smaller than itself."""
3137 if context is None:
3138 context = getcontext()
3139
3140 ans = self._check_nans(context=context)
3141 if ans:
3142 return ans
3143
3144 if self._isinfinity() == -1:
3145 return negInf
3146 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003147 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003148
3149 context = context.copy()
3150 context._set_rounding(ROUND_FLOOR)
3151 context._ignore_all_flags()
3152 new_self = self._fix(context)
3153 if new_self != self:
3154 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003155 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3156 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003157
3158 def next_plus(self, context=None):
3159 """Returns the smallest representable number larger than itself."""
3160 if context is None:
3161 context = getcontext()
3162
3163 ans = self._check_nans(context=context)
3164 if ans:
3165 return ans
3166
3167 if self._isinfinity() == 1:
3168 return Inf
3169 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003170 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003171
3172 context = context.copy()
3173 context._set_rounding(ROUND_CEILING)
3174 context._ignore_all_flags()
3175 new_self = self._fix(context)
3176 if new_self != self:
3177 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003178 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3179 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003180
3181 def next_toward(self, other, context=None):
3182 """Returns the number closest to self, in the direction towards other.
3183
3184 The result is the closest representable number to self
3185 (excluding self) that is in the direction towards other,
3186 unless both have the same value. If the two operands are
3187 numerically equal, then the result is a copy of self with the
3188 sign set to be the same as the sign of other.
3189 """
3190 other = _convert_other(other, raiseit=True)
3191
3192 if context is None:
3193 context = getcontext()
3194
3195 ans = self._check_nans(other, context)
3196 if ans:
3197 return ans
3198
3199 comparison = self.__cmp__(other)
3200 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003201 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003202
3203 if comparison == -1:
3204 ans = self.next_plus(context)
3205 else: # comparison == 1
3206 ans = self.next_minus(context)
3207
3208 # decide which flags to raise using value of ans
3209 if ans._isinfinity():
3210 context._raise_error(Overflow,
3211 'Infinite result from next_toward',
3212 ans._sign)
3213 context._raise_error(Rounded)
3214 context._raise_error(Inexact)
3215 elif ans.adjusted() < context.Emin:
3216 context._raise_error(Underflow)
3217 context._raise_error(Subnormal)
3218 context._raise_error(Rounded)
3219 context._raise_error(Inexact)
3220 # if precision == 1 then we don't raise Clamped for a
3221 # result 0E-Etiny.
3222 if not ans:
3223 context._raise_error(Clamped)
3224
3225 return ans
3226
3227 def number_class(self, context=None):
3228 """Returns an indication of the class of self.
3229
3230 The class is one of the following strings:
3231 -sNaN
3232 -NaN
3233 -Infinity
3234 -Normal
3235 -Subnormal
3236 -Zero
3237 +Zero
3238 +Subnormal
3239 +Normal
3240 +Infinity
3241 """
3242 if self.is_snan():
3243 return "sNaN"
3244 if self.is_qnan():
3245 return "NaN"
3246 inf = self._isinfinity()
3247 if inf == 1:
3248 return "+Infinity"
3249 if inf == -1:
3250 return "-Infinity"
3251 if self.is_zero():
3252 if self._sign:
3253 return "-Zero"
3254 else:
3255 return "+Zero"
3256 if context is None:
3257 context = getcontext()
3258 if self.is_subnormal(context=context):
3259 if self._sign:
3260 return "-Subnormal"
3261 else:
3262 return "+Subnormal"
3263 # just a normal, regular, boring number, :)
3264 if self._sign:
3265 return "-Normal"
3266 else:
3267 return "+Normal"
3268
3269 def radix(self):
3270 """Just returns 10, as this is Decimal, :)"""
3271 return Decimal(10)
3272
3273 def rotate(self, other, context=None):
3274 """Returns a rotated copy of self, value-of-other times."""
3275 if context is None:
3276 context = getcontext()
3277
3278 ans = self._check_nans(other, context)
3279 if ans:
3280 return ans
3281
3282 if other._exp != 0:
3283 return context._raise_error(InvalidOperation)
3284 if not (-context.prec <= int(other) <= context.prec):
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
3290 # get values, pad if necessary
3291 torot = int(other)
3292 rotdig = self._int
3293 topad = context.prec - len(rotdig)
3294 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003295 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003296
3297 # let's rotate!
3298 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003299 return _dec_from_triple(self._sign,
3300 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003301
3302 def scaleb (self, other, context=None):
3303 """Returns self operand after adding the second value to its exp."""
3304 if context is None:
3305 context = getcontext()
3306
3307 ans = self._check_nans(other, context)
3308 if ans:
3309 return ans
3310
3311 if other._exp != 0:
3312 return context._raise_error(InvalidOperation)
3313 liminf = -2 * (context.Emax + context.prec)
3314 limsup = 2 * (context.Emax + context.prec)
3315 if not (liminf <= int(other) <= limsup):
3316 return context._raise_error(InvalidOperation)
3317
3318 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003319 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003320
Facundo Batista72bc54f2007-11-23 17:59:00 +00003321 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003322 d = d._fix(context)
3323 return d
3324
3325 def shift(self, other, context=None):
3326 """Returns a shifted copy of self, value-of-other times."""
3327 if context is None:
3328 context = getcontext()
3329
3330 ans = self._check_nans(other, context)
3331 if ans:
3332 return ans
3333
3334 if other._exp != 0:
3335 return context._raise_error(InvalidOperation)
3336 if not (-context.prec <= int(other) <= context.prec):
3337 return context._raise_error(InvalidOperation)
3338
3339 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003340 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003341
3342 # get values, pad if necessary
3343 torot = int(other)
3344 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003345 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003346 rotdig = self._int
3347 topad = context.prec - len(rotdig)
3348 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003349 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003350
3351 # let's shift!
3352 if torot < 0:
3353 rotated = rotdig[:torot]
3354 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003355 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003356 rotated = rotated[-context.prec:]
3357
Facundo Batista72bc54f2007-11-23 17:59:00 +00003358 return _dec_from_triple(self._sign,
3359 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003360
Facundo Batista59c58842007-04-10 12:58:45 +00003361 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003362 def __reduce__(self):
3363 return (self.__class__, (str(self),))
3364
3365 def __copy__(self):
3366 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003367 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003368 return self.__class__(str(self))
3369
3370 def __deepcopy__(self, memo):
3371 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003372 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003373 return self.__class__(str(self))
3374
Facundo Batista72bc54f2007-11-23 17:59:00 +00003375def _dec_from_triple(sign, coefficient, exponent, special=False):
3376 """Create a decimal instance directly, without any validation,
3377 normalization (e.g. removal of leading zeros) or argument
3378 conversion.
3379
3380 This function is for *internal use only*.
3381 """
3382
3383 self = object.__new__(Decimal)
3384 self._sign = sign
3385 self._int = coefficient
3386 self._exp = exponent
3387 self._is_special = special
3388
3389 return self
3390
Facundo Batista59c58842007-04-10 12:58:45 +00003391##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003392
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003393
3394# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003395rounding_functions = [name for name in Decimal.__dict__.keys()
3396 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003397for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003398 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003399 globalname = name[1:].upper()
3400 val = globals()[globalname]
3401 Decimal._pick_rounding_function[val] = name
3402
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003403del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003404
Nick Coghlanced12182006-09-02 03:54:17 +00003405class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003406 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003407
Nick Coghlanced12182006-09-02 03:54:17 +00003408 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003409 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003410 """
3411 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003412 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003413 def __enter__(self):
3414 self.saved_context = getcontext()
3415 setcontext(self.new_context)
3416 return self.new_context
3417 def __exit__(self, t, v, tb):
3418 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003419
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003420class Context(object):
3421 """Contains the context for a Decimal instance.
3422
3423 Contains:
3424 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003425 rounding - rounding type (how you round)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003426 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
Raymond Hettingerbf440692004-07-10 14:14:37 +00003427 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003428 raised when it is caused. Otherwise, a value is
3429 substituted in.
3430 flags - When an exception is caused, flags[exception] is incremented.
3431 (Whether or not the trap_enabler is set)
3432 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003433 Emin - Minimum exponent
3434 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003435 capitals - If 1, 1*10^1 is printed as 1E+1.
3436 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003437 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003438 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003439
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003440 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003441 traps=None, flags=None,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003442 _rounding_decision=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003443 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003444 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003445 _ignored_flags=None):
3446 if flags is None:
3447 flags = []
3448 if _ignored_flags is None:
3449 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003450 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003451 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003452 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003453 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003454 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003455 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003456 for name, val in locals().items():
3457 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003458 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003459 else:
3460 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003461 del self.self
3462
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003463 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003464 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003465 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003466 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3467 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3468 % vars(self))
3469 names = [f.__name__ for f, v in self.flags.items() if v]
3470 s.append('flags=[' + ', '.join(names) + ']')
3471 names = [t.__name__ for t, v in self.traps.items() if v]
3472 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003473 return ', '.join(s) + ')'
3474
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003475 def clear_flags(self):
3476 """Reset all flags to zero"""
3477 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003478 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003479
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003480 def _shallow_copy(self):
3481 """Returns a shallow copy from self."""
Raymond Hettingerbf440692004-07-10 14:14:37 +00003482 nc = Context(self.prec, self.rounding, self.traps, self.flags,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003483 self._rounding_decision, self.Emin, self.Emax,
3484 self.capitals, self._clamp, self._ignored_flags)
3485 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003486
3487 def copy(self):
3488 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003489 nc = Context(self.prec, self.rounding, self.traps.copy(),
3490 self.flags.copy(), self._rounding_decision, self.Emin,
3491 self.Emax, self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003492 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003493 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003494
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003495 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003496 """Handles an error
3497
3498 If the flag is in _ignored_flags, returns the default response.
3499 Otherwise, it increments the flag, then, if the corresponding
3500 trap_enabler is set, it reaises the exception. Otherwise, it returns
3501 the default value after incrementing the flag.
3502 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003503 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003504 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003505 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003506 return error().handle(self, *args)
3507
3508 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003509 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003510 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003511 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003512
3513 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003514 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003515 raise error, explanation
3516
3517 def _ignore_all_flags(self):
3518 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003519 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003520
3521 def _ignore_flags(self, *flags):
3522 """Ignore the flags, if they are raised"""
3523 # Do not mutate-- This way, copies of a context leave the original
3524 # alone.
3525 self._ignored_flags = (self._ignored_flags + list(flags))
3526 return list(flags)
3527
3528 def _regard_flags(self, *flags):
3529 """Stop ignoring the flags, if they are raised"""
3530 if flags and isinstance(flags[0], (tuple,list)):
3531 flags = flags[0]
3532 for flag in flags:
3533 self._ignored_flags.remove(flag)
3534
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003535 def __hash__(self):
3536 """A Context cannot be hashed."""
3537 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003538 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003539
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003540 def Etiny(self):
3541 """Returns Etiny (= Emin - prec + 1)"""
3542 return int(self.Emin - self.prec + 1)
3543
3544 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003545 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003546 return int(self.Emax - self.prec + 1)
3547
3548 def _set_rounding_decision(self, type):
3549 """Sets the rounding decision.
3550
3551 Sets the rounding decision, and returns the current (previous)
3552 rounding decision. Often used like:
3553
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003554 context = context._shallow_copy()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003555 # That so you don't change the calling context
3556 # if an error occurs in the middle (say DivisionImpossible is raised).
3557
3558 rounding = context._set_rounding_decision(NEVER_ROUND)
3559 instance = instance / Decimal(2)
3560 context._set_rounding_decision(rounding)
3561
3562 This will make it not round for that operation.
3563 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003564
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003565 rounding = self._rounding_decision
3566 self._rounding_decision = type
3567 return rounding
3568
3569 def _set_rounding(self, type):
3570 """Sets the rounding type.
3571
3572 Sets the rounding type, and returns the current (previous)
3573 rounding type. Often used like:
3574
3575 context = context.copy()
3576 # so you don't change the calling context
3577 # if an error occurs in the middle.
3578 rounding = context._set_rounding(ROUND_UP)
3579 val = self.__sub__(other, context=context)
3580 context._set_rounding(rounding)
3581
3582 This will make it round up for that operation.
3583 """
3584 rounding = self.rounding
3585 self.rounding= type
3586 return rounding
3587
Raymond Hettingerfed52962004-07-14 15:41:57 +00003588 def create_decimal(self, num='0'):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003589 """Creates a new Decimal instance but using self as context."""
3590 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003591 if d._isnan() and len(d._int) > self.prec - self._clamp:
3592 return self._raise_error(ConversionSyntax,
3593 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003594 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003595
Facundo Batista59c58842007-04-10 12:58:45 +00003596 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003597 def abs(self, a):
3598 """Returns the absolute value of the operand.
3599
3600 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003601 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003602 the plus operation on the operand.
3603
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003604 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003605 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003606 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003607 Decimal("100")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003608 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003609 Decimal("101.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003610 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003611 Decimal("101.5")
3612 """
3613 return a.__abs__(context=self)
3614
3615 def add(self, a, b):
3616 """Return the sum of the two operands.
3617
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003618 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003619 Decimal("19.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003620 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003621 Decimal("1.02E+4")
3622 """
3623 return a.__add__(b, context=self)
3624
3625 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003626 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003627
Facundo Batista353750c2007-09-13 18:13:15 +00003628 def canonical(self, a):
3629 """Returns the same Decimal object.
3630
3631 As we do not have different encodings for the same number, the
3632 received object already is in its canonical form.
3633
3634 >>> ExtendedContext.canonical(Decimal('2.50'))
3635 Decimal("2.50")
3636 """
3637 return a.canonical(context=self)
3638
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003639 def compare(self, a, b):
3640 """Compares values numerically.
3641
3642 If the signs of the operands differ, a value representing each operand
3643 ('-1' if the operand is less than zero, '0' if the operand is zero or
3644 negative zero, or '1' if the operand is greater than zero) is used in
3645 place of that operand for the comparison instead of the actual
3646 operand.
3647
3648 The comparison is then effected by subtracting the second operand from
3649 the first and then returning a value according to the result of the
3650 subtraction: '-1' if the result is less than zero, '0' if the result is
3651 zero or negative zero, or '1' if the result is greater than zero.
3652
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003653 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003654 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003655 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003656 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003657 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003658 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003659 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003660 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003661 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003662 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003663 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003664 Decimal("-1")
3665 """
3666 return a.compare(b, context=self)
3667
Facundo Batista353750c2007-09-13 18:13:15 +00003668 def compare_signal(self, a, b):
3669 """Compares the values of the two operands numerically.
3670
3671 It's pretty much like compare(), but all NaNs signal, with signaling
3672 NaNs taking precedence over quiet NaNs.
3673
3674 >>> c = ExtendedContext
3675 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3676 Decimal("-1")
3677 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3678 Decimal("0")
3679 >>> c.flags[InvalidOperation] = 0
3680 >>> print c.flags[InvalidOperation]
3681 0
3682 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3683 Decimal("NaN")
3684 >>> print c.flags[InvalidOperation]
3685 1
3686 >>> c.flags[InvalidOperation] = 0
3687 >>> print c.flags[InvalidOperation]
3688 0
3689 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3690 Decimal("NaN")
3691 >>> print c.flags[InvalidOperation]
3692 1
3693 """
3694 return a.compare_signal(b, context=self)
3695
3696 def compare_total(self, a, b):
3697 """Compares two operands using their abstract representation.
3698
3699 This is not like the standard compare, which use their numerical
3700 value. Note that a total ordering is defined for all possible abstract
3701 representations.
3702
3703 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3704 Decimal("-1")
3705 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3706 Decimal("-1")
3707 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3708 Decimal("-1")
3709 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3710 Decimal("0")
3711 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3712 Decimal("1")
3713 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3714 Decimal("-1")
3715 """
3716 return a.compare_total(b)
3717
3718 def compare_total_mag(self, a, b):
3719 """Compares two operands using their abstract representation ignoring sign.
3720
3721 Like compare_total, but with operand's sign ignored and assumed to be 0.
3722 """
3723 return a.compare_total_mag(b)
3724
3725 def copy_abs(self, a):
3726 """Returns a copy of the operand with the sign set to 0.
3727
3728 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3729 Decimal("2.1")
3730 >>> ExtendedContext.copy_abs(Decimal('-100'))
3731 Decimal("100")
3732 """
3733 return a.copy_abs()
3734
3735 def copy_decimal(self, a):
3736 """Returns a copy of the decimal objet.
3737
3738 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3739 Decimal("2.1")
3740 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3741 Decimal("-1.00")
3742 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003743 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003744
3745 def copy_negate(self, a):
3746 """Returns a copy of the operand with the sign inverted.
3747
3748 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3749 Decimal("-101.5")
3750 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3751 Decimal("101.5")
3752 """
3753 return a.copy_negate()
3754
3755 def copy_sign(self, a, b):
3756 """Copies the second operand's sign to the first one.
3757
3758 In detail, it returns a copy of the first operand with the sign
3759 equal to the sign of the second operand.
3760
3761 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3762 Decimal("1.50")
3763 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3764 Decimal("1.50")
3765 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3766 Decimal("-1.50")
3767 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3768 Decimal("-1.50")
3769 """
3770 return a.copy_sign(b)
3771
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003772 def divide(self, a, b):
3773 """Decimal division in a specified context.
3774
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003775 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003776 Decimal("0.333333333")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003777 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003778 Decimal("0.666666667")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003779 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003780 Decimal("2.5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003781 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003782 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003783 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003784 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003785 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003786 Decimal("4.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003787 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003788 Decimal("1.20")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003789 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003790 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003791 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003792 Decimal("1000")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003793 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003794 Decimal("1.20E+6")
3795 """
3796 return a.__div__(b, context=self)
3797
3798 def divide_int(self, a, b):
3799 """Divides two numbers and returns the integer part of the result.
3800
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003801 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003802 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003803 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003804 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003805 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003806 Decimal("3")
3807 """
3808 return a.__floordiv__(b, context=self)
3809
3810 def divmod(self, a, b):
3811 return a.__divmod__(b, context=self)
3812
Facundo Batista353750c2007-09-13 18:13:15 +00003813 def exp(self, a):
3814 """Returns e ** a.
3815
3816 >>> c = ExtendedContext.copy()
3817 >>> c.Emin = -999
3818 >>> c.Emax = 999
3819 >>> c.exp(Decimal('-Infinity'))
3820 Decimal("0")
3821 >>> c.exp(Decimal('-1'))
3822 Decimal("0.367879441")
3823 >>> c.exp(Decimal('0'))
3824 Decimal("1")
3825 >>> c.exp(Decimal('1'))
3826 Decimal("2.71828183")
3827 >>> c.exp(Decimal('0.693147181'))
3828 Decimal("2.00000000")
3829 >>> c.exp(Decimal('+Infinity'))
3830 Decimal("Infinity")
3831 """
3832 return a.exp(context=self)
3833
3834 def fma(self, a, b, c):
3835 """Returns a multiplied by b, plus c.
3836
3837 The first two operands are multiplied together, using multiply,
3838 the third operand is then added to the result of that
3839 multiplication, using add, all with only one final rounding.
3840
3841 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3842 Decimal("22")
3843 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3844 Decimal("-8")
3845 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3846 Decimal("1.38435736E+12")
3847 """
3848 return a.fma(b, c, context=self)
3849
3850 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003851 """Return True if the operand is canonical; otherwise return False.
3852
3853 Currently, the encoding of a Decimal instance is always
3854 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00003855
3856 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003857 True
Facundo Batista353750c2007-09-13 18:13:15 +00003858 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003859 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00003860
3861 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003862 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003863
Facundo Batista1a191df2007-10-02 17:01:24 +00003864 A Decimal instance is considered finite if it is neither
3865 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003866
3867 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003868 True
Facundo Batista353750c2007-09-13 18:13:15 +00003869 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003870 True
Facundo Batista353750c2007-09-13 18:13:15 +00003871 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003872 True
Facundo Batista353750c2007-09-13 18:13:15 +00003873 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003874 False
Facundo Batista353750c2007-09-13 18:13:15 +00003875 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003876 False
Facundo Batista353750c2007-09-13 18:13:15 +00003877 """
3878 return a.is_finite()
3879
3880 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003881 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003882
3883 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003884 False
Facundo Batista353750c2007-09-13 18:13:15 +00003885 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003886 True
Facundo Batista353750c2007-09-13 18:13:15 +00003887 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003888 False
Facundo Batista353750c2007-09-13 18:13:15 +00003889 """
3890 return a.is_infinite()
3891
3892 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003893 """Return True if the operand is a qNaN or sNaN;
3894 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003895
3896 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003897 False
Facundo Batista353750c2007-09-13 18:13:15 +00003898 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003899 True
Facundo Batista353750c2007-09-13 18:13:15 +00003900 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003901 True
Facundo Batista353750c2007-09-13 18:13:15 +00003902 """
3903 return a.is_nan()
3904
3905 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003906 """Return True if the operand is a normal number;
3907 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003908
3909 >>> c = ExtendedContext.copy()
3910 >>> c.Emin = -999
3911 >>> c.Emax = 999
3912 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003913 True
Facundo Batista353750c2007-09-13 18:13:15 +00003914 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003915 False
Facundo Batista353750c2007-09-13 18:13:15 +00003916 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003917 False
Facundo Batista353750c2007-09-13 18:13:15 +00003918 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003919 False
Facundo Batista353750c2007-09-13 18:13:15 +00003920 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003921 False
Facundo Batista353750c2007-09-13 18:13:15 +00003922 """
3923 return a.is_normal(context=self)
3924
3925 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003926 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003927
3928 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003929 False
Facundo Batista353750c2007-09-13 18:13:15 +00003930 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003931 True
Facundo Batista353750c2007-09-13 18:13:15 +00003932 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003933 False
Facundo Batista353750c2007-09-13 18:13:15 +00003934 """
3935 return a.is_qnan()
3936
3937 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003938 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003939
3940 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003941 False
Facundo Batista353750c2007-09-13 18:13:15 +00003942 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003943 True
Facundo Batista353750c2007-09-13 18:13:15 +00003944 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003945 True
Facundo Batista353750c2007-09-13 18:13:15 +00003946 """
3947 return a.is_signed()
3948
3949 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003950 """Return True if the operand is a signaling NaN;
3951 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003952
3953 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003954 False
Facundo Batista353750c2007-09-13 18:13:15 +00003955 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003956 False
Facundo Batista353750c2007-09-13 18:13:15 +00003957 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003958 True
Facundo Batista353750c2007-09-13 18:13:15 +00003959 """
3960 return a.is_snan()
3961
3962 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003963 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003964
3965 >>> c = ExtendedContext.copy()
3966 >>> c.Emin = -999
3967 >>> c.Emax = 999
3968 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003969 False
Facundo Batista353750c2007-09-13 18:13:15 +00003970 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003971 True
Facundo Batista353750c2007-09-13 18:13:15 +00003972 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003973 False
Facundo Batista353750c2007-09-13 18:13:15 +00003974 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003975 False
Facundo Batista353750c2007-09-13 18:13:15 +00003976 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003977 False
Facundo Batista353750c2007-09-13 18:13:15 +00003978 """
3979 return a.is_subnormal(context=self)
3980
3981 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00003982 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003983
3984 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003985 True
Facundo Batista353750c2007-09-13 18:13:15 +00003986 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003987 False
Facundo Batista353750c2007-09-13 18:13:15 +00003988 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00003989 True
Facundo Batista353750c2007-09-13 18:13:15 +00003990 """
3991 return a.is_zero()
3992
3993 def ln(self, a):
3994 """Returns the natural (base e) logarithm of the operand.
3995
3996 >>> c = ExtendedContext.copy()
3997 >>> c.Emin = -999
3998 >>> c.Emax = 999
3999 >>> c.ln(Decimal('0'))
4000 Decimal("-Infinity")
4001 >>> c.ln(Decimal('1.000'))
4002 Decimal("0")
4003 >>> c.ln(Decimal('2.71828183'))
4004 Decimal("1.00000000")
4005 >>> c.ln(Decimal('10'))
4006 Decimal("2.30258509")
4007 >>> c.ln(Decimal('+Infinity'))
4008 Decimal("Infinity")
4009 """
4010 return a.ln(context=self)
4011
4012 def log10(self, a):
4013 """Returns the base 10 logarithm of the operand.
4014
4015 >>> c = ExtendedContext.copy()
4016 >>> c.Emin = -999
4017 >>> c.Emax = 999
4018 >>> c.log10(Decimal('0'))
4019 Decimal("-Infinity")
4020 >>> c.log10(Decimal('0.001'))
4021 Decimal("-3")
4022 >>> c.log10(Decimal('1.000'))
4023 Decimal("0")
4024 >>> c.log10(Decimal('2'))
4025 Decimal("0.301029996")
4026 >>> c.log10(Decimal('10'))
4027 Decimal("1")
4028 >>> c.log10(Decimal('70'))
4029 Decimal("1.84509804")
4030 >>> c.log10(Decimal('+Infinity'))
4031 Decimal("Infinity")
4032 """
4033 return a.log10(context=self)
4034
4035 def logb(self, a):
4036 """ Returns the exponent of the magnitude of the operand's MSD.
4037
4038 The result is the integer which is the exponent of the magnitude
4039 of the most significant digit of the operand (as though the
4040 operand were truncated to a single digit while maintaining the
4041 value of that digit and without limiting the resulting exponent).
4042
4043 >>> ExtendedContext.logb(Decimal('250'))
4044 Decimal("2")
4045 >>> ExtendedContext.logb(Decimal('2.50'))
4046 Decimal("0")
4047 >>> ExtendedContext.logb(Decimal('0.03'))
4048 Decimal("-2")
4049 >>> ExtendedContext.logb(Decimal('0'))
4050 Decimal("-Infinity")
4051 """
4052 return a.logb(context=self)
4053
4054 def logical_and(self, a, b):
4055 """Applies the logical operation 'and' between each operand's digits.
4056
4057 The operands must be both logical numbers.
4058
4059 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4060 Decimal("0")
4061 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4062 Decimal("0")
4063 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4064 Decimal("0")
4065 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4066 Decimal("1")
4067 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4068 Decimal("1000")
4069 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4070 Decimal("10")
4071 """
4072 return a.logical_and(b, context=self)
4073
4074 def logical_invert(self, a):
4075 """Invert all the digits in the operand.
4076
4077 The operand must be a logical number.
4078
4079 >>> ExtendedContext.logical_invert(Decimal('0'))
4080 Decimal("111111111")
4081 >>> ExtendedContext.logical_invert(Decimal('1'))
4082 Decimal("111111110")
4083 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4084 Decimal("0")
4085 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4086 Decimal("10101010")
4087 """
4088 return a.logical_invert(context=self)
4089
4090 def logical_or(self, a, b):
4091 """Applies the logical operation 'or' between each operand's digits.
4092
4093 The operands must be both logical numbers.
4094
4095 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4096 Decimal("0")
4097 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4098 Decimal("1")
4099 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4100 Decimal("1")
4101 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4102 Decimal("1")
4103 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4104 Decimal("1110")
4105 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4106 Decimal("1110")
4107 """
4108 return a.logical_or(b, context=self)
4109
4110 def logical_xor(self, a, b):
4111 """Applies the logical operation 'xor' between each operand's digits.
4112
4113 The operands must be both logical numbers.
4114
4115 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4116 Decimal("0")
4117 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4118 Decimal("1")
4119 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4120 Decimal("1")
4121 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4122 Decimal("0")
4123 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4124 Decimal("110")
4125 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4126 Decimal("1101")
4127 """
4128 return a.logical_xor(b, context=self)
4129
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004130 def max(self, a,b):
4131 """max compares two values numerically and returns the maximum.
4132
4133 If either operand is a NaN then the general rules apply.
4134 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004135 operation. If they are numerically equal then the left-hand operand
4136 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004137 infinity) of the two operands is chosen as the result.
4138
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004139 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004140 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004141 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004142 Decimal("3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004143 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004144 Decimal("1")
4145 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4146 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004147 """
4148 return a.max(b, context=self)
4149
Facundo Batista353750c2007-09-13 18:13:15 +00004150 def max_mag(self, a, b):
4151 """Compares the values numerically with their sign ignored."""
4152 return a.max_mag(b, context=self)
4153
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004154 def min(self, a,b):
4155 """min compares two values numerically and returns the minimum.
4156
4157 If either operand is a NaN then the general rules apply.
4158 Otherwise, the operands are compared as as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004159 operation. If they are numerically equal then the left-hand operand
4160 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004161 infinity) of the two operands is chosen as the result.
4162
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004163 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004164 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004165 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004166 Decimal("-10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004167 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004168 Decimal("1.0")
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004169 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4170 Decimal("7")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004171 """
4172 return a.min(b, context=self)
4173
Facundo Batista353750c2007-09-13 18:13:15 +00004174 def min_mag(self, a, b):
4175 """Compares the values numerically with their sign ignored."""
4176 return a.min_mag(b, context=self)
4177
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004178 def minus(self, a):
4179 """Minus corresponds to unary prefix minus in Python.
4180
4181 The operation is evaluated using the same rules as subtract; the
4182 operation minus(a) is calculated as subtract('0', a) where the '0'
4183 has the same exponent as the operand.
4184
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004185 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004186 Decimal("-1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004187 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004188 Decimal("1.3")
4189 """
4190 return a.__neg__(context=self)
4191
4192 def multiply(self, a, b):
4193 """multiply multiplies two operands.
4194
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004195 If either operand is a special value then the general rules apply.
4196 Otherwise, the operands are multiplied together ('long multiplication'),
4197 resulting in a number which may be as long as the sum of the lengths
4198 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004199
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004200 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004201 Decimal("3.60")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004202 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004203 Decimal("21")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004204 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004205 Decimal("0.72")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004206 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004207 Decimal("-0.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004208 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004209 Decimal("4.28135971E+11")
4210 """
4211 return a.__mul__(b, context=self)
4212
Facundo Batista353750c2007-09-13 18:13:15 +00004213 def next_minus(self, a):
4214 """Returns the largest representable number smaller than a.
4215
4216 >>> c = ExtendedContext.copy()
4217 >>> c.Emin = -999
4218 >>> c.Emax = 999
4219 >>> ExtendedContext.next_minus(Decimal('1'))
4220 Decimal("0.999999999")
4221 >>> c.next_minus(Decimal('1E-1007'))
4222 Decimal("0E-1007")
4223 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4224 Decimal("-1.00000004")
4225 >>> c.next_minus(Decimal('Infinity'))
4226 Decimal("9.99999999E+999")
4227 """
4228 return a.next_minus(context=self)
4229
4230 def next_plus(self, a):
4231 """Returns the smallest representable number larger than a.
4232
4233 >>> c = ExtendedContext.copy()
4234 >>> c.Emin = -999
4235 >>> c.Emax = 999
4236 >>> ExtendedContext.next_plus(Decimal('1'))
4237 Decimal("1.00000001")
4238 >>> c.next_plus(Decimal('-1E-1007'))
4239 Decimal("-0E-1007")
4240 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4241 Decimal("-1.00000002")
4242 >>> c.next_plus(Decimal('-Infinity'))
4243 Decimal("-9.99999999E+999")
4244 """
4245 return a.next_plus(context=self)
4246
4247 def next_toward(self, a, b):
4248 """Returns the number closest to a, in direction towards b.
4249
4250 The result is the closest representable number from the first
4251 operand (but not the first operand) that is in the direction
4252 towards the second operand, unless the operands have the same
4253 value.
4254
4255 >>> c = ExtendedContext.copy()
4256 >>> c.Emin = -999
4257 >>> c.Emax = 999
4258 >>> c.next_toward(Decimal('1'), Decimal('2'))
4259 Decimal("1.00000001")
4260 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4261 Decimal("-0E-1007")
4262 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4263 Decimal("-1.00000002")
4264 >>> c.next_toward(Decimal('1'), Decimal('0'))
4265 Decimal("0.999999999")
4266 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4267 Decimal("0E-1007")
4268 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4269 Decimal("-1.00000004")
4270 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4271 Decimal("-0.00")
4272 """
4273 return a.next_toward(b, context=self)
4274
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004275 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004276 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004277
4278 Essentially a plus operation with all trailing zeros removed from the
4279 result.
4280
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004281 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004282 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004283 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004284 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004285 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004286 Decimal("1.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004287 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004288 Decimal("-1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004289 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004290 Decimal("1.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004291 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004292 Decimal("0")
4293 """
4294 return a.normalize(context=self)
4295
Facundo Batista353750c2007-09-13 18:13:15 +00004296 def number_class(self, a):
4297 """Returns an indication of the class of the operand.
4298
4299 The class is one of the following strings:
4300 -sNaN
4301 -NaN
4302 -Infinity
4303 -Normal
4304 -Subnormal
4305 -Zero
4306 +Zero
4307 +Subnormal
4308 +Normal
4309 +Infinity
4310
4311 >>> c = Context(ExtendedContext)
4312 >>> c.Emin = -999
4313 >>> c.Emax = 999
4314 >>> c.number_class(Decimal('Infinity'))
4315 '+Infinity'
4316 >>> c.number_class(Decimal('1E-10'))
4317 '+Normal'
4318 >>> c.number_class(Decimal('2.50'))
4319 '+Normal'
4320 >>> c.number_class(Decimal('0.1E-999'))
4321 '+Subnormal'
4322 >>> c.number_class(Decimal('0'))
4323 '+Zero'
4324 >>> c.number_class(Decimal('-0'))
4325 '-Zero'
4326 >>> c.number_class(Decimal('-0.1E-999'))
4327 '-Subnormal'
4328 >>> c.number_class(Decimal('-1E-10'))
4329 '-Normal'
4330 >>> c.number_class(Decimal('-2.50'))
4331 '-Normal'
4332 >>> c.number_class(Decimal('-Infinity'))
4333 '-Infinity'
4334 >>> c.number_class(Decimal('NaN'))
4335 'NaN'
4336 >>> c.number_class(Decimal('-NaN'))
4337 'NaN'
4338 >>> c.number_class(Decimal('sNaN'))
4339 'sNaN'
4340 """
4341 return a.number_class(context=self)
4342
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004343 def plus(self, a):
4344 """Plus corresponds to unary prefix plus in Python.
4345
4346 The operation is evaluated using the same rules as add; the
4347 operation plus(a) is calculated as add('0', a) where the '0'
4348 has the same exponent as the operand.
4349
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004350 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004351 Decimal("1.3")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004352 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004353 Decimal("-1.3")
4354 """
4355 return a.__pos__(context=self)
4356
4357 def power(self, a, b, modulo=None):
4358 """Raises a to the power of b, to modulo if given.
4359
Facundo Batista353750c2007-09-13 18:13:15 +00004360 With two arguments, compute a**b. If a is negative then b
4361 must be integral. The result will be inexact unless b is
4362 integral and the result is finite and can be expressed exactly
4363 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004364
Facundo Batista353750c2007-09-13 18:13:15 +00004365 With three arguments, compute (a**b) % modulo. For the
4366 three argument form, the following restrictions on the
4367 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004368
Facundo Batista353750c2007-09-13 18:13:15 +00004369 - all three arguments must be integral
4370 - b must be nonnegative
4371 - at least one of a or b must be nonzero
4372 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004373
Facundo Batista353750c2007-09-13 18:13:15 +00004374 The result of pow(a, b, modulo) is identical to the result
4375 that would be obtained by computing (a**b) % modulo with
4376 unbounded precision, but is computed more efficiently. It is
4377 always exact.
4378
4379 >>> c = ExtendedContext.copy()
4380 >>> c.Emin = -999
4381 >>> c.Emax = 999
4382 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004383 Decimal("8")
Facundo Batista353750c2007-09-13 18:13:15 +00004384 >>> c.power(Decimal('-2'), Decimal('3'))
4385 Decimal("-8")
4386 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004387 Decimal("0.125")
Facundo Batista353750c2007-09-13 18:13:15 +00004388 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004389 Decimal("69.7575744")
Facundo Batista353750c2007-09-13 18:13:15 +00004390 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4391 Decimal("2.00000000")
4392 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004393 Decimal("0")
Facundo Batista353750c2007-09-13 18:13:15 +00004394 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004395 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004396 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004397 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004398 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004399 Decimal("-0")
Facundo Batista353750c2007-09-13 18:13:15 +00004400 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004401 Decimal("1")
Facundo Batista353750c2007-09-13 18:13:15 +00004402 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004403 Decimal("-Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004404 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004405 Decimal("Infinity")
Facundo Batista353750c2007-09-13 18:13:15 +00004406 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004407 Decimal("NaN")
Facundo Batista353750c2007-09-13 18:13:15 +00004408
4409 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4410 Decimal("11")
4411 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4412 Decimal("-11")
4413 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4414 Decimal("1")
4415 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4416 Decimal("11")
4417 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4418 Decimal("11729830")
4419 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4420 Decimal("-0")
4421 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4422 Decimal("1")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004423 """
4424 return a.__pow__(b, modulo, context=self)
4425
4426 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004427 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004428
4429 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004430 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004431 exponent is being increased), multiplied by a positive power of ten (if
4432 the exponent is being decreased), or is unchanged (if the exponent is
4433 already equal to that of the right-hand operand).
4434
4435 Unlike other operations, if the length of the coefficient after the
4436 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004437 operation condition is raised. This guarantees that, unless there is
4438 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004439 equal to that of the right-hand operand.
4440
4441 Also unlike other operations, quantize will never raise Underflow, even
4442 if the result is subnormal and inexact.
4443
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004444 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004445 Decimal("2.170")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004446 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004447 Decimal("2.17")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004448 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004449 Decimal("2.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004450 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004451 Decimal("2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004452 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004453 Decimal("0E+1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004454 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004455 Decimal("-Infinity")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004456 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004457 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004458 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004459 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004460 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004461 Decimal("-0E+5")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004462 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004463 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004464 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004465 Decimal("NaN")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004466 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004467 Decimal("217.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004468 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004469 Decimal("217")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004470 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004471 Decimal("2.2E+2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004472 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004473 Decimal("2E+2")
4474 """
4475 return a.quantize(b, context=self)
4476
Facundo Batista353750c2007-09-13 18:13:15 +00004477 def radix(self):
4478 """Just returns 10, as this is Decimal, :)
4479
4480 >>> ExtendedContext.radix()
4481 Decimal("10")
4482 """
4483 return Decimal(10)
4484
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004485 def remainder(self, a, b):
4486 """Returns the remainder from integer division.
4487
4488 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004489 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004490 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004491 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004492
4493 This operation will fail under the same conditions as integer division
4494 (that is, if integer division on the same two operands would fail, the
4495 remainder cannot be calculated).
4496
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004497 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004498 Decimal("2.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004499 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004500 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004501 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004502 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004503 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004504 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004505 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004506 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004507 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004508 Decimal("1.0")
4509 """
4510 return a.__mod__(b, context=self)
4511
4512 def remainder_near(self, a, b):
4513 """Returns to be "a - b * n", where n is the integer nearest the exact
4514 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004515 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004516 sign of a.
4517
4518 This operation will fail under the same conditions as integer division
4519 (that is, if integer division on the same two operands would fail, the
4520 remainder cannot be calculated).
4521
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004522 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004523 Decimal("-0.9")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004524 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004525 Decimal("-2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004526 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004527 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004528 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004529 Decimal("-1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004530 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004531 Decimal("0.2")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004532 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004533 Decimal("0.1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004534 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004535 Decimal("-0.3")
4536 """
4537 return a.remainder_near(b, context=self)
4538
Facundo Batista353750c2007-09-13 18:13:15 +00004539 def rotate(self, a, b):
4540 """Returns a rotated copy of a, b times.
4541
4542 The coefficient of the result is a rotated copy of the digits in
4543 the coefficient of the first operand. The number of places of
4544 rotation is taken from the absolute value of the second operand,
4545 with the rotation being to the left if the second operand is
4546 positive or to the right otherwise.
4547
4548 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4549 Decimal("400000003")
4550 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4551 Decimal("12")
4552 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4553 Decimal("891234567")
4554 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4555 Decimal("123456789")
4556 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4557 Decimal("345678912")
4558 """
4559 return a.rotate(b, context=self)
4560
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004561 def same_quantum(self, a, b):
4562 """Returns True if the two operands have the same exponent.
4563
4564 The result is never affected by either the sign or the coefficient of
4565 either operand.
4566
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004567 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004568 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004569 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004570 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004571 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004572 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004573 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004574 True
4575 """
4576 return a.same_quantum(b)
4577
Facundo Batista353750c2007-09-13 18:13:15 +00004578 def scaleb (self, a, b):
4579 """Returns the first operand after adding the second value its exp.
4580
4581 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4582 Decimal("0.0750")
4583 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4584 Decimal("7.50")
4585 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4586 Decimal("7.50E+3")
4587 """
4588 return a.scaleb (b, context=self)
4589
4590 def shift(self, a, b):
4591 """Returns a shifted copy of a, b times.
4592
4593 The coefficient of the result is a shifted copy of the digits
4594 in the coefficient of the first operand. The number of places
4595 to shift is taken from the absolute value of the second operand,
4596 with the shift being to the left if the second operand is
4597 positive or to the right otherwise. Digits shifted into the
4598 coefficient are zeros.
4599
4600 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4601 Decimal("400000000")
4602 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4603 Decimal("0")
4604 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4605 Decimal("1234567")
4606 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4607 Decimal("123456789")
4608 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4609 Decimal("345678900")
4610 """
4611 return a.shift(b, context=self)
4612
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004613 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004614 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004615
4616 If the result must be inexact, it is rounded using the round-half-even
4617 algorithm.
4618
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004619 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004620 Decimal("0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004621 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004622 Decimal("-0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004623 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004624 Decimal("0.624499800")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004625 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004626 Decimal("10")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004627 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004628 Decimal("1")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004629 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004630 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004631 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004632 Decimal("1.0")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004633 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004634 Decimal("2.64575131")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004635 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004636 Decimal("3.16227766")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004637 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004638 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004639 """
4640 return a.sqrt(context=self)
4641
4642 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004643 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004644
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004645 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004646 Decimal("0.23")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004647 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648 Decimal("0.00")
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004649 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004650 Decimal("-0.77")
4651 """
4652 return a.__sub__(b, context=self)
4653
4654 def to_eng_string(self, a):
4655 """Converts a number to a string, using scientific notation.
4656
4657 The operation is not affected by the context.
4658 """
4659 return a.to_eng_string(context=self)
4660
4661 def to_sci_string(self, a):
4662 """Converts a number to a string, using scientific notation.
4663
4664 The operation is not affected by the context.
4665 """
4666 return a.__str__(context=self)
4667
Facundo Batista353750c2007-09-13 18:13:15 +00004668 def to_integral_exact(self, a):
4669 """Rounds to an integer.
4670
4671 When the operand has a negative exponent, the result is the same
4672 as using the quantize() operation using the given operand as the
4673 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4674 of the operand as the precision setting; Inexact and Rounded flags
4675 are allowed in this operation. The rounding mode is taken from the
4676 context.
4677
4678 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4679 Decimal("2")
4680 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4681 Decimal("100")
4682 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4683 Decimal("100")
4684 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4685 Decimal("102")
4686 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4687 Decimal("-102")
4688 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4689 Decimal("1.0E+6")
4690 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4691 Decimal("7.89E+77")
4692 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4693 Decimal("-Infinity")
4694 """
4695 return a.to_integral_exact(context=self)
4696
4697 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004698 """Rounds to an integer.
4699
4700 When the operand has a negative exponent, the result is the same
4701 as using the quantize() operation using the given operand as the
4702 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4703 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004704 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004705
Facundo Batista353750c2007-09-13 18:13:15 +00004706 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004707 Decimal("2")
Facundo Batista353750c2007-09-13 18:13:15 +00004708 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004709 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004710 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004711 Decimal("100")
Facundo Batista353750c2007-09-13 18:13:15 +00004712 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004713 Decimal("102")
Facundo Batista353750c2007-09-13 18:13:15 +00004714 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004715 Decimal("-102")
Facundo Batista353750c2007-09-13 18:13:15 +00004716 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004717 Decimal("1.0E+6")
Facundo Batista353750c2007-09-13 18:13:15 +00004718 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004719 Decimal("7.89E+77")
Facundo Batista353750c2007-09-13 18:13:15 +00004720 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004721 Decimal("-Infinity")
4722 """
Facundo Batista353750c2007-09-13 18:13:15 +00004723 return a.to_integral_value(context=self)
4724
4725 # the method name changed, but we provide also the old one, for compatibility
4726 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004727
4728class _WorkRep(object):
4729 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004730 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004731 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004732 # exp: None, int, or string
4733
4734 def __init__(self, value=None):
4735 if value is None:
4736 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004737 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004738 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004739 elif isinstance(value, Decimal):
4740 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004741 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004742 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004743 else:
4744 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004745 self.sign = value[0]
4746 self.int = value[1]
4747 self.exp = value[2]
4748
4749 def __repr__(self):
4750 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4751
4752 __str__ = __repr__
4753
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004754
4755
4756def _normalize(op1, op2, shouldround = 0, prec = 0):
4757 """Normalizes op1, op2 to have the same exp and length of coefficient.
4758
4759 Done during addition.
4760 """
Facundo Batista353750c2007-09-13 18:13:15 +00004761 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004762 tmp = op2
4763 other = op1
4764 else:
4765 tmp = op1
4766 other = op2
4767
Facundo Batista353750c2007-09-13 18:13:15 +00004768 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4769 # Then adding 10**exp to tmp has the same effect (after rounding)
4770 # as adding any positive quantity smaller than 10**exp; similarly
4771 # for subtraction. So if other is smaller than 10**exp we replace
4772 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4773 if shouldround:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004774 tmp_len = len(str(tmp.int))
4775 other_len = len(str(other.int))
Facundo Batista353750c2007-09-13 18:13:15 +00004776 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4777 if other_len + other.exp - 1 < exp:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004778 other.int = 1
Facundo Batista353750c2007-09-13 18:13:15 +00004779 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004780
Facundo Batista353750c2007-09-13 18:13:15 +00004781 tmp.int *= 10 ** (tmp.exp - other.exp)
4782 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004783 return op1, op2
4784
Facundo Batista353750c2007-09-13 18:13:15 +00004785##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4786
4787# This function from Tim Peters was taken from here:
4788# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4789# The correction being in the function definition is for speed, and
4790# the whole function is not resolved with math.log because of avoiding
4791# the use of floats.
4792def _nbits(n, correction = {
4793 '0': 4, '1': 3, '2': 2, '3': 2,
4794 '4': 1, '5': 1, '6': 1, '7': 1,
4795 '8': 0, '9': 0, 'a': 0, 'b': 0,
4796 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4797 """Number of bits in binary representation of the positive integer n,
4798 or 0 if n == 0.
4799 """
4800 if n < 0:
4801 raise ValueError("The argument to _nbits should be nonnegative.")
4802 hex_n = "%x" % n
4803 return 4*len(hex_n) - correction[hex_n[0]]
4804
4805def _sqrt_nearest(n, a):
4806 """Closest integer to the square root of the positive integer n. a is
4807 an initial approximation to the square root. Any positive integer
4808 will do for a, but the closer a is to the square root of n the
4809 faster convergence will be.
4810
4811 """
4812 if n <= 0 or a <= 0:
4813 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4814
4815 b=0
4816 while a != b:
4817 b, a = a, a--n//a>>1
4818 return a
4819
4820def _rshift_nearest(x, shift):
4821 """Given an integer x and a nonnegative integer shift, return closest
4822 integer to x / 2**shift; use round-to-even in case of a tie.
4823
4824 """
4825 b, q = 1L << shift, x >> shift
4826 return q + (2*(x & (b-1)) + (q&1) > b)
4827
4828def _div_nearest(a, b):
4829 """Closest integer to a/b, a and b positive integers; rounds to even
4830 in the case of a tie.
4831
4832 """
4833 q, r = divmod(a, b)
4834 return q + (2*r + (q&1) > b)
4835
4836def _ilog(x, M, L = 8):
4837 """Integer approximation to M*log(x/M), with absolute error boundable
4838 in terms only of x/M.
4839
4840 Given positive integers x and M, return an integer approximation to
4841 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4842 between the approximation and the exact result is at most 22. For
4843 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4844 both cases these are upper bounds on the error; it will usually be
4845 much smaller."""
4846
4847 # The basic algorithm is the following: let log1p be the function
4848 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4849 # the reduction
4850 #
4851 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4852 #
4853 # repeatedly until the argument to log1p is small (< 2**-L in
4854 # absolute value). For small y we can use the Taylor series
4855 # expansion
4856 #
4857 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4858 #
4859 # truncating at T such that y**T is small enough. The whole
4860 # computation is carried out in a form of fixed-point arithmetic,
4861 # with a real number z being represented by an integer
4862 # approximation to z*M. To avoid loss of precision, the y below
4863 # is actually an integer approximation to 2**R*y*M, where R is the
4864 # number of reductions performed so far.
4865
4866 y = x-M
4867 # argument reduction; R = number of reductions performed
4868 R = 0
4869 while (R <= L and long(abs(y)) << L-R >= M or
4870 R > L and abs(y) >> R-L >= M):
4871 y = _div_nearest(long(M*y) << 1,
4872 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4873 R += 1
4874
4875 # Taylor series with T terms
4876 T = -int(-10*len(str(M))//(3*L))
4877 yshift = _rshift_nearest(y, R)
4878 w = _div_nearest(M, T)
4879 for k in xrange(T-1, 0, -1):
4880 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4881
4882 return _div_nearest(w*y, M)
4883
4884def _dlog10(c, e, p):
4885 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4886 approximation to 10**p * log10(c*10**e), with an absolute error of
4887 at most 1. Assumes that c*10**e is not exactly 1."""
4888
4889 # increase precision by 2; compensate for this by dividing
4890 # final result by 100
4891 p += 2
4892
4893 # write c*10**e as d*10**f with either:
4894 # f >= 0 and 1 <= d <= 10, or
4895 # f <= 0 and 0.1 <= d <= 1.
4896 # Thus for c*10**e close to 1, f = 0
4897 l = len(str(c))
4898 f = e+l - (e+l >= 1)
4899
4900 if p > 0:
4901 M = 10**p
4902 k = e+p-f
4903 if k >= 0:
4904 c *= 10**k
4905 else:
4906 c = _div_nearest(c, 10**-k)
4907
4908 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004909 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004910 log_d = _div_nearest(log_d*M, log_10)
4911 log_tenpower = f*M # exact
4912 else:
4913 log_d = 0 # error < 2.31
4914 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4915
4916 return _div_nearest(log_tenpower+log_d, 100)
4917
4918def _dlog(c, e, p):
4919 """Given integers c, e and p with c > 0, compute an integer
4920 approximation to 10**p * log(c*10**e), with an absolute error of
4921 at most 1. Assumes that c*10**e is not exactly 1."""
4922
4923 # Increase precision by 2. The precision increase is compensated
4924 # for at the end with a division by 100.
4925 p += 2
4926
4927 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4928 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4929 # as 10**p * log(d) + 10**p*f * log(10).
4930 l = len(str(c))
4931 f = e+l - (e+l >= 1)
4932
4933 # compute approximation to 10**p*log(d), with error < 27
4934 if p > 0:
4935 k = e+p-f
4936 if k >= 0:
4937 c *= 10**k
4938 else:
4939 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4940
4941 # _ilog magnifies existing error in c by a factor of at most 10
4942 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4943 else:
4944 # p <= 0: just approximate the whole thing by 0; error < 2.31
4945 log_d = 0
4946
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004947 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00004948 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004949 extra = len(str(abs(f)))-1
4950 if p + extra >= 0:
4951 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4952 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4953 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00004954 else:
4955 f_log_ten = 0
4956 else:
4957 f_log_ten = 0
4958
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004959 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00004960 return _div_nearest(f_log_ten + log_d, 100)
4961
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00004962class _Log10Memoize(object):
4963 """Class to compute, store, and allow retrieval of, digits of the
4964 constant log(10) = 2.302585.... This constant is needed by
4965 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4966 def __init__(self):
4967 self.digits = "23025850929940456840179914546843642076011014886"
4968
4969 def getdigits(self, p):
4970 """Given an integer p >= 0, return floor(10**p)*log(10).
4971
4972 For example, self.getdigits(3) returns 2302.
4973 """
4974 # digits are stored as a string, for quick conversion to
4975 # integer in the case that we've already computed enough
4976 # digits; the stored digits should always be correct
4977 # (truncated, not rounded to nearest).
4978 if p < 0:
4979 raise ValueError("p should be nonnegative")
4980
4981 if p >= len(self.digits):
4982 # compute p+3, p+6, p+9, ... digits; continue until at
4983 # least one of the extra digits is nonzero
4984 extra = 3
4985 while True:
4986 # compute p+extra digits, correct to within 1ulp
4987 M = 10**(p+extra+2)
4988 digits = str(_div_nearest(_ilog(10*M, M), 100))
4989 if digits[-extra:] != '0'*extra:
4990 break
4991 extra += 3
4992 # keep all reliable digits so far; remove trailing zeros
4993 # and next nonzero digit
4994 self.digits = digits.rstrip('0')[:-1]
4995 return int(self.digits[:p+1])
4996
4997_log10_digits = _Log10Memoize().getdigits
4998
Facundo Batista353750c2007-09-13 18:13:15 +00004999def _iexp(x, M, L=8):
5000 """Given integers x and M, M > 0, such that x/M is small in absolute
5001 value, compute an integer approximation to M*exp(x/M). For 0 <=
5002 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5003 is usually much smaller)."""
5004
5005 # Algorithm: to compute exp(z) for a real number z, first divide z
5006 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5007 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5008 # series
5009 #
5010 # expm1(x) = x + x**2/2! + x**3/3! + ...
5011 #
5012 # Now use the identity
5013 #
5014 # expm1(2x) = expm1(x)*(expm1(x)+2)
5015 #
5016 # R times to compute the sequence expm1(z/2**R),
5017 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5018
5019 # Find R such that x/2**R/M <= 2**-L
5020 R = _nbits((long(x)<<L)//M)
5021
5022 # Taylor series. (2**L)**T > M
5023 T = -int(-10*len(str(M))//(3*L))
5024 y = _div_nearest(x, T)
5025 Mshift = long(M)<<R
5026 for i in xrange(T-1, 0, -1):
5027 y = _div_nearest(x*(Mshift + y), Mshift * i)
5028
5029 # Expansion
5030 for k in xrange(R-1, -1, -1):
5031 Mshift = long(M)<<(k+2)
5032 y = _div_nearest(y*(y+Mshift), Mshift)
5033
5034 return M+y
5035
5036def _dexp(c, e, p):
5037 """Compute an approximation to exp(c*10**e), with p decimal places of
5038 precision.
5039
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005040 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005041
5042 10**(p-1) <= d <= 10**p, and
5043 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5044
5045 In other words, d*10**f is an approximation to exp(c*10**e) with p
5046 digits of precision, and with an error in d of at most 1. This is
5047 almost, but not quite, the same as the error being < 1ulp: when d
5048 = 10**(p-1) the error could be up to 10 ulp."""
5049
5050 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5051 p += 2
5052
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005053 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005054 extra = max(0, e + len(str(c)) - 1)
5055 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005056
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005057 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005058 # rounding down
5059 shift = e+q
5060 if shift >= 0:
5061 cshift = c*10**shift
5062 else:
5063 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005064 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005065
5066 # reduce remainder back to original precision
5067 rem = _div_nearest(rem, 10**extra)
5068
5069 # error in result of _iexp < 120; error after division < 0.62
5070 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5071
5072def _dpower(xc, xe, yc, ye, p):
5073 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5074 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5075
5076 10**(p-1) <= c <= 10**p, and
5077 (c-1)*10**e < x**y < (c+1)*10**e
5078
5079 in other words, c*10**e is an approximation to x**y with p digits
5080 of precision, and with an error in c of at most 1. (This is
5081 almost, but not quite, the same as the error being < 1ulp: when c
5082 == 10**(p-1) we can only guarantee error < 10ulp.)
5083
5084 We assume that: x is positive and not equal to 1, and y is nonzero.
5085 """
5086
5087 # Find b such that 10**(b-1) <= |y| <= 10**b
5088 b = len(str(abs(yc))) + ye
5089
5090 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5091 lxc = _dlog(xc, xe, p+b+1)
5092
5093 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5094 shift = ye-b
5095 if shift >= 0:
5096 pc = lxc*yc*10**shift
5097 else:
5098 pc = _div_nearest(lxc*yc, 10**-shift)
5099
5100 if pc == 0:
5101 # we prefer a result that isn't exactly 1; this makes it
5102 # easier to compute a correctly rounded result in __pow__
5103 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5104 coeff, exp = 10**(p-1)+1, 1-p
5105 else:
5106 coeff, exp = 10**p-1, -p
5107 else:
5108 coeff, exp = _dexp(pc, -(p+1), p+1)
5109 coeff = _div_nearest(coeff, 10)
5110 exp += 1
5111
5112 return coeff, exp
5113
5114def _log10_lb(c, correction = {
5115 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5116 '6': 23, '7': 16, '8': 10, '9': 5}):
5117 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5118 if c <= 0:
5119 raise ValueError("The argument to _log10_lb should be nonnegative.")
5120 str_c = str(c)
5121 return 100*len(str_c) - correction[str_c[0]]
5122
Facundo Batista59c58842007-04-10 12:58:45 +00005123##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005124
Facundo Batista353750c2007-09-13 18:13:15 +00005125def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005126 """Convert other to Decimal.
5127
5128 Verifies that it's ok to use in an implicit construction.
5129 """
5130 if isinstance(other, Decimal):
5131 return other
5132 if isinstance(other, (int, long)):
5133 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005134 if raiseit:
5135 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005136 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005137
Facundo Batista59c58842007-04-10 12:58:45 +00005138##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005139
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005140# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005141# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005142
5143DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005144 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005145 traps=[DivisionByZero, Overflow, InvalidOperation],
5146 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005147 _rounding_decision=ALWAYS_ROUND,
Raymond Hettinger99148e72004-07-14 19:56:56 +00005148 Emax=999999999,
5149 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005150 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005151)
5152
5153# Pre-made alternate contexts offered by the specification
5154# Don't change these; the user should be able to select these
5155# contexts and be able to reproduce results from other implementations
5156# of the spec.
5157
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005158BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005159 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005160 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5161 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005162)
5163
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005164ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005165 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005166 traps=[],
5167 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005168)
5169
5170
Facundo Batista72bc54f2007-11-23 17:59:00 +00005171##### crud for parsing strings #############################################
5172import re
5173
5174# Regular expression used for parsing numeric strings. Additional
5175# comments:
5176#
5177# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5178# whitespace. But note that the specification disallows whitespace in
5179# a numeric string.
5180#
5181# 2. For finite numbers (not infinities and NaNs) the body of the
5182# number between the optional sign and the optional exponent must have
5183# at least one decimal digit, possibly after the decimal point. The
5184# lookahead expression '(?=\d|\.\d)' checks this.
5185#
5186# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5187# other meaning for \d than the numbers [0-9].
5188
5189import re
5190_parser = re.compile(r""" # A numeric string consists of:
5191# \s*
5192 (?P<sign>[-+])? # an optional sign, followed by either...
5193 (
5194 (?=\d|\.\d) # ...a number (with at least one digit)
5195 (?P<int>\d*) # consisting of a (possibly empty) integer part
5196 (\.(?P<frac>\d*))? # followed by an optional fractional part
5197 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5198 |
5199 Inf(inity)? # ...an infinity, or...
5200 |
5201 (?P<signal>s)? # ...an (optionally signaling)
5202 NaN # NaN
5203 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5204 )
5205# \s*
5206 $
5207""", re.VERBOSE | re.IGNORECASE).match
5208
Facundo Batista2ec74152007-12-03 17:55:00 +00005209_all_zeros = re.compile('0*$').match
5210_exact_half = re.compile('50*$').match
Facundo Batista72bc54f2007-11-23 17:59:00 +00005211del re
5212
5213
Facundo Batista59c58842007-04-10 12:58:45 +00005214##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005215
Facundo Batista59c58842007-04-10 12:58:45 +00005216# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005217Inf = Decimal('Inf')
5218negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005219NaN = Decimal('NaN')
5220Dec_0 = Decimal(0)
5221Dec_p1 = Decimal(1)
5222Dec_n1 = Decimal(-1)
5223Dec_p2 = Decimal(2)
5224Dec_n2 = Decimal(-2)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005225
Facundo Batista59c58842007-04-10 12:58:45 +00005226# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005227Infsign = (Inf, negInf)
5228
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005229
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005230
5231if __name__ == '__main__':
5232 import doctest, sys
5233 doctest.testmod(sys.modules[__name__])