blob: 34463aefa4bbb437c448d0db0f4c8fd65a777513 [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
Raymond Hettingerabe32372008-02-14 02:41:22 +000038of the expected Decimal('0.00') returned by decimal floating point).
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000039
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)
Raymond Hettingerabe32372008-02-14 02:41:22 +000045Decimal('0')
46>>> Decimal('1')
47Decimal('1')
48>>> Decimal('-.0123')
49Decimal('-0.0123')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000050>>> Decimal(123456)
Raymond Hettingerabe32372008-02-14 02:41:22 +000051Decimal('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')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000058>>> 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))
Raymond Hettingerabe32372008-02-14 02:41:22 +000094Decimal('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 Hettingera016deb2009-04-27 21:12:27 +0000137__version__ = '1.70' # Highest version of the spec this complies with
Raymond Hettingerdaeceb22009-03-10 04:49:21 +0000138
Raymond Hettingereb260842005-06-07 18:52:34 +0000139import copy as _copy
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000140import math as _math
Raymond Hettinger2c8585b2009-02-03 03:37:03 +0000141import numbers as _numbers
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000142
Raymond Hettinger097a1902008-01-11 02:24:13 +0000143try:
144 from collections import namedtuple as _namedtuple
145 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
146except ImportError:
147 DecimalTuple = lambda *args: args
148
Facundo Batista59c58842007-04-10 12:58:45 +0000149# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000150ROUND_DOWN = 'ROUND_DOWN'
151ROUND_HALF_UP = 'ROUND_HALF_UP'
152ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
153ROUND_CEILING = 'ROUND_CEILING'
154ROUND_FLOOR = 'ROUND_FLOOR'
155ROUND_UP = 'ROUND_UP'
156ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Facundo Batista353750c2007-09-13 18:13:15 +0000157ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000158
Facundo Batista59c58842007-04-10 12:58:45 +0000159# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000160
161class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000162 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000163
164 Used exceptions derive from this.
165 If an exception derives from another exception besides this (such as
166 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
167 called if the others are present. This isn't actually used for
168 anything, though.
169
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000170 handle -- Called when context._raise_error is called and the
171 trap_enabler is set. First argument is self, second is the
172 context. More arguments can be given, those being after
173 the explanation in _raise_error (For example,
174 context._raise_error(NewError, '(-x)!', self._sign) would
175 call NewError().handle(context, self._sign).)
176
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000177 To define a new exception, it should be sufficient to have it derive
178 from DecimalException.
179 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000180 def handle(self, context, *args):
181 pass
182
183
184class Clamped(DecimalException):
185 """Exponent of a 0 changed to fit bounds.
186
187 This occurs and signals clamped if the exponent of a result has been
188 altered in order to fit the constraints of a specific concrete
Facundo Batista59c58842007-04-10 12:58:45 +0000189 representation. This may occur when the exponent of a zero result would
190 be outside the bounds of a representation, or when a large normal
191 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000192 this latter case, the exponent is reduced to fit and the corresponding
193 number of zero digits are appended to the coefficient ("fold-down").
194 """
195
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000196class InvalidOperation(DecimalException):
197 """An invalid operation was performed.
198
199 Various bad things cause this:
200
201 Something creates a signaling NaN
202 -INF + INF
Facundo Batista59c58842007-04-10 12:58:45 +0000203 0 * (+-)INF
204 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000205 x % 0
206 (+-)INF % x
207 x._rescale( non-integer )
208 sqrt(-x) , x > 0
209 0 ** 0
210 x ** (non-integer)
211 x ** (+-)INF
212 An operand is invalid
Facundo Batista353750c2007-09-13 18:13:15 +0000213
214 The result of the operation after these is a quiet positive NaN,
215 except when the cause is a signaling NaN, in which case the result is
216 also a quiet NaN, but with the original sign, and an optional
217 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000218 """
219 def handle(self, context, *args):
220 if args:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000221 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
222 return ans._fix_nan(context)
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000223 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224
225class ConversionSyntax(InvalidOperation):
226 """Trying to convert badly formed string.
227
228 This occurs and signals invalid-operation if an string is being
229 converted to a number and it does not conform to the numeric string
Facundo Batista59c58842007-04-10 12:58:45 +0000230 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000231 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000232 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000233 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000234
235class DivisionByZero(DecimalException, ZeroDivisionError):
236 """Division by 0.
237
238 This occurs and signals division-by-zero if division of a finite number
239 by zero was attempted (during a divide-integer or divide operation, or a
240 power operation with negative right-hand operand), and the dividend was
241 not zero.
242
243 The result of the operation is [sign,inf], where sign is the exclusive
244 or of the signs of the operands for divide, or is 1 for an odd power of
245 -0, for power.
246 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000247
Facundo Batistacce8df22007-09-18 16:53:18 +0000248 def handle(self, context, sign, *args):
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000249 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000250
251class DivisionImpossible(InvalidOperation):
252 """Cannot perform the division adequately.
253
254 This occurs and signals invalid-operation if the integer result of a
255 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000256 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000257 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000258
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000259 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000260 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000261
262class DivisionUndefined(InvalidOperation, ZeroDivisionError):
263 """Undefined result of division.
264
265 This occurs and signals invalid-operation if division by zero was
266 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000267 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000268 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000269
Facundo Batistacce8df22007-09-18 16:53:18 +0000270 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000271 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000272
273class Inexact(DecimalException):
274 """Had to round, losing information.
275
276 This occurs and signals inexact whenever the result of an operation is
277 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000278 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000279 result in all cases is unchanged.
280
281 The inexact signal may be tested (or trapped) to determine if a given
282 operation (or sequence of operations) was inexact.
283 """
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):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000297 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000298
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 Hettinger7c85fa42004-07-01 11:01:35 +0000310
311class Subnormal(DecimalException):
312 """Exponent < Emin before rounding.
313
314 This occurs and signals subnormal whenever the result of a conversion or
315 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000316 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000317
318 The subnormal signal may be tested (or trapped) to determine if a given
319 or operation (or sequence of operations) yielded a subnormal result.
320 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000321
322class Overflow(Inexact, Rounded):
323 """Numerical overflow.
324
325 This occurs and signals overflow if the adjusted exponent of a result
326 (from a conversion or from an operation that is not an attempt to divide
327 by zero), after rounding, would be greater than the largest value that
328 can be handled by the implementation (the value Emax).
329
330 The result depends on the rounding mode:
331
332 For round-half-up and round-half-even (and for round-half-down and
333 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000334 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000335 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000336 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000338 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000340 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 will also be raised.
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000342 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000343
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000344 def handle(self, context, sign, *args):
345 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000346 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000347 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000348 if sign == 0:
349 if context.rounding == ROUND_CEILING:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000350 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000351 return _dec_from_triple(sign, '9'*context.prec,
352 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000353 if sign == 1:
354 if context.rounding == ROUND_FLOOR:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000355 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000356 return _dec_from_triple(sign, '9'*context.prec,
357 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000358
359
360class Underflow(Inexact, Rounded, Subnormal):
361 """Numerical underflow with result rounded to 0.
362
363 This occurs and signals underflow if a result is inexact and the
364 adjusted exponent of the result would be smaller (more negative) than
365 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000366 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000367
368 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000369 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000370 in 0 with the sign of the intermediate result and an exponent of Etiny.
371
372 In all cases, Inexact, Rounded, and Subnormal will also be raised.
373 """
374
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000375# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000376_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000377 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000378
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000379# Map conditions (per the spec) to signals
380_condition_map = {ConversionSyntax:InvalidOperation,
381 DivisionImpossible:InvalidOperation,
382 DivisionUndefined:InvalidOperation,
383 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000384
Facundo Batista59c58842007-04-10 12:58:45 +0000385##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000386
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000387# The getcontext() and setcontext() function manage access to a thread-local
388# current context. Py2.4 offers direct support for thread locals. If that
389# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000390# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000391# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000392
393try:
394 import threading
395except ImportError:
396 # Python was compiled without threads; create a mock object instead
397 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000398 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000399 def local(self, sys=sys):
400 return sys.modules[__name__]
401 threading = MockThreading()
402 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000403
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000404try:
405 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000406
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000407except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000408
Facundo Batista59c58842007-04-10 12:58:45 +0000409 # To fix reloading, force it to create a new context
410 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000411 if hasattr(threading.currentThread(), '__decimal_context__'):
412 del threading.currentThread().__decimal_context__
413
414 def setcontext(context):
415 """Set this thread's context to context."""
416 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000417 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000418 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000419 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000420
421 def getcontext():
422 """Returns this thread's context.
423
424 If this thread does not yet have a context, returns
425 a new context and sets this thread's context.
426 New contexts are copies of DefaultContext.
427 """
428 try:
429 return threading.currentThread().__decimal_context__
430 except AttributeError:
431 context = Context()
432 threading.currentThread().__decimal_context__ = context
433 return context
434
435else:
436
437 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000438 if hasattr(local, '__decimal_context__'):
439 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000440
441 def getcontext(_local=local):
442 """Returns this thread's context.
443
444 If this thread does not yet have a context, returns
445 a new context and sets this thread's context.
446 New contexts are copies of DefaultContext.
447 """
448 try:
449 return _local.__decimal_context__
450 except AttributeError:
451 context = Context()
452 _local.__decimal_context__ = context
453 return context
454
455 def setcontext(context, _local=local):
456 """Set this thread's context to context."""
457 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000458 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000459 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000460 _local.__decimal_context__ = context
461
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000462 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000463
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000464def localcontext(ctx=None):
465 """Return a context manager for a copy of the supplied context
466
467 Uses a copy of the current context if no context is specified
468 The returned context manager creates a local decimal context
469 in a with statement:
470 def sin(x):
471 with localcontext() as ctx:
472 ctx.prec += 2
473 # Rest of sin calculation algorithm
474 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000475 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000476
477 def sin(x):
478 with localcontext(ExtendedContext):
479 # Rest of sin calculation algorithm
480 # uses the Extended Context from the
481 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000482 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000483
Facundo Batistaee340e52008-05-02 17:39:00 +0000484 >>> setcontext(DefaultContext)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000485 >>> print getcontext().prec
486 28
487 >>> with localcontext():
488 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000489 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000490 ... print ctx.prec
491 ...
492 30
493 >>> with localcontext(ExtendedContext):
494 ... print getcontext().prec
495 ...
496 9
497 >>> print getcontext().prec
498 28
499 """
Nick Coghlanced12182006-09-02 03:54:17 +0000500 if ctx is None: ctx = getcontext()
501 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000502
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000503
Facundo Batista59c58842007-04-10 12:58:45 +0000504##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000505
506class Decimal(object):
507 """Floating point class for decimal arithmetic."""
508
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000509 __slots__ = ('_exp','_int','_sign', '_is_special')
510 # Generally, the value of the Decimal instance is given by
511 # (-1)**_sign * _int * 10**_exp
512 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000513
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000514 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000515 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000516 """Create a decimal point instance.
517
518 >>> Decimal('3.14') # string input
Raymond Hettingerabe32372008-02-14 02:41:22 +0000519 Decimal('3.14')
Facundo Batista59c58842007-04-10 12:58:45 +0000520 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000521 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 >>> Decimal(314) # int or long
Raymond Hettingerabe32372008-02-14 02:41:22 +0000523 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000524 >>> Decimal(Decimal(314)) # another decimal instance
Raymond Hettingerabe32372008-02-14 02:41:22 +0000525 Decimal('314')
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000526 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Raymond Hettingerabe32372008-02-14 02:41:22 +0000527 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000528 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529
Facundo Batista72bc54f2007-11-23 17:59:00 +0000530 # Note that the coefficient, self._int, is actually stored as
531 # a string rather than as a tuple of digits. This speeds up
532 # the "digits to integer" and "integer to digits" conversions
533 # that are used in almost every arithmetic operation on
534 # Decimals. This is an internal detail: the as_tuple function
535 # and the Decimal constructor still deal with tuples of
536 # digits.
537
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000538 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000539
Facundo Batista0d157a02007-11-30 17:15:25 +0000540 # From a string
541 # REs insist on real strings, so we can too.
542 if isinstance(value, basestring):
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000543 m = _parser(value.strip())
Facundo Batista0d157a02007-11-30 17:15:25 +0000544 if m is None:
545 if context is None:
546 context = getcontext()
547 return context._raise_error(ConversionSyntax,
548 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000549
Facundo Batista0d157a02007-11-30 17:15:25 +0000550 if m.group('sign') == "-":
551 self._sign = 1
552 else:
553 self._sign = 0
554 intpart = m.group('int')
555 if intpart is not None:
556 # finite number
Mark Dickinson4326ad82009-08-02 10:59:36 +0000557 fracpart = m.group('frac') or ''
Facundo Batista0d157a02007-11-30 17:15:25 +0000558 exp = int(m.group('exp') or '0')
Mark Dickinson4326ad82009-08-02 10:59:36 +0000559 self._int = str(int(intpart+fracpart))
560 self._exp = exp - len(fracpart)
Facundo Batista0d157a02007-11-30 17:15:25 +0000561 self._is_special = False
562 else:
563 diag = m.group('diag')
564 if diag is not None:
565 # NaN
Mark Dickinson4326ad82009-08-02 10:59:36 +0000566 self._int = str(int(diag or '0')).lstrip('0')
Facundo Batista0d157a02007-11-30 17:15:25 +0000567 if m.group('signal'):
568 self._exp = 'N'
569 else:
570 self._exp = 'n'
571 else:
572 # infinity
573 self._int = '0'
574 self._exp = 'F'
575 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000576 return self
577
578 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000579 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580 if value >= 0:
581 self._sign = 0
582 else:
583 self._sign = 1
584 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000585 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000586 self._is_special = False
587 return self
588
589 # From another decimal
590 if isinstance(value, Decimal):
591 self._exp = value._exp
592 self._sign = value._sign
593 self._int = value._int
594 self._is_special = value._is_special
595 return self
596
597 # From an internal working value
598 if isinstance(value, _WorkRep):
599 self._sign = value.sign
600 self._int = str(value.int)
601 self._exp = int(value.exp)
602 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000603 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000604
605 # tuple/list conversion (possibly from as_tuple())
606 if isinstance(value, (list,tuple)):
607 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000608 raise ValueError('Invalid tuple size in creation of Decimal '
609 'from list or tuple. The list or tuple '
610 'should have exactly three elements.')
611 # process sign. The isinstance test rejects floats
612 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
613 raise ValueError("Invalid sign. The first value in the tuple "
614 "should be an integer; either 0 for a "
615 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000616 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000617 if value[2] == 'F':
618 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000619 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000620 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000621 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000622 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000623 # process and validate the digits in value[1]
624 digits = []
625 for digit in value[1]:
626 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
627 # skip leading zeros
628 if digits or digit != 0:
629 digits.append(digit)
630 else:
631 raise ValueError("The second value in the tuple must "
632 "be composed of integers in the range "
633 "0 through 9.")
634 if value[2] in ('n', 'N'):
635 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000636 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000637 self._exp = value[2]
638 self._is_special = True
639 elif isinstance(value[2], (int, long)):
640 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000641 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000642 self._exp = value[2]
643 self._is_special = False
644 else:
645 raise ValueError("The third value in the tuple must "
646 "be an integer, or one of the "
647 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000648 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000649
Raymond Hettingerbf440692004-07-10 14:14:37 +0000650 if isinstance(value, float):
Benjamin Petersona617e202010-01-25 03:52:52 +0000651 raise TypeError("Cannot convert float in Decimal constructor. "
652 "Use from_float class method.")
Raymond Hettingerbf440692004-07-10 14:14:37 +0000653
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000654 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000655
Mark Dickinson6a961632009-01-04 21:10:56 +0000656 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
657 # don't use it (see notes on Py2.3 compatibility at top of file)
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000658 def from_float(cls, f):
659 """Converts a float to a decimal number, exactly.
660
661 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
662 Since 0.1 is not exactly representable in binary floating point, the
663 value is stored as the nearest representable value which is
664 0x1.999999999999ap-4. The exact equivalent of the value in decimal
665 is 0.1000000000000000055511151231257827021181583404541015625.
666
667 >>> Decimal.from_float(0.1)
668 Decimal('0.1000000000000000055511151231257827021181583404541015625')
669 >>> Decimal.from_float(float('nan'))
670 Decimal('NaN')
671 >>> Decimal.from_float(float('inf'))
672 Decimal('Infinity')
673 >>> Decimal.from_float(-float('inf'))
674 Decimal('-Infinity')
675 >>> Decimal.from_float(-0.0)
676 Decimal('-0')
677
678 """
679 if isinstance(f, (int, long)): # handle integer inputs
680 return cls(f)
681 if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
682 return cls(repr(f))
Mark Dickinson6a961632009-01-04 21:10:56 +0000683 if _math.copysign(1.0, f) == 1.0:
684 sign = 0
685 else:
686 sign = 1
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000687 n, d = abs(f).as_integer_ratio()
688 k = d.bit_length() - 1
689 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinson6a961632009-01-04 21:10:56 +0000690 if cls is Decimal:
691 return result
692 else:
693 return cls(result)
694 from_float = classmethod(from_float)
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000695
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000696 def _isnan(self):
697 """Returns whether the number is not actually one.
698
699 0 if a number
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000700 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000701 2 if sNaN
702 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000703 if self._is_special:
704 exp = self._exp
705 if exp == 'n':
706 return 1
707 elif exp == 'N':
708 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000709 return 0
710
711 def _isinfinity(self):
712 """Returns whether the number is infinite
713
714 0 if finite or not a number
715 1 if +INF
716 -1 if -INF
717 """
718 if self._exp == 'F':
719 if self._sign:
720 return -1
721 return 1
722 return 0
723
Facundo Batista353750c2007-09-13 18:13:15 +0000724 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000725 """Returns whether the number is not actually one.
726
727 if self, other are sNaN, signal
728 if self, other are NaN return nan
729 return 0
730
731 Done before operations.
732 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000733
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000734 self_is_nan = self._isnan()
735 if other is None:
736 other_is_nan = False
737 else:
738 other_is_nan = other._isnan()
739
740 if self_is_nan or other_is_nan:
741 if context is None:
742 context = getcontext()
743
744 if self_is_nan == 2:
745 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000746 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000747 if other_is_nan == 2:
748 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000749 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000750 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000751 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000752
Facundo Batista353750c2007-09-13 18:13:15 +0000753 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000754 return 0
755
Mark Dickinson2fc92632008-02-06 22:10:50 +0000756 def _compare_check_nans(self, other, context):
757 """Version of _check_nans used for the signaling comparisons
758 compare_signal, __le__, __lt__, __ge__, __gt__.
759
760 Signal InvalidOperation if either self or other is a (quiet
761 or signaling) NaN. Signaling NaNs take precedence over quiet
762 NaNs.
763
764 Return 0 if neither operand is a NaN.
765
766 """
767 if context is None:
768 context = getcontext()
769
770 if self._is_special or other._is_special:
771 if self.is_snan():
772 return context._raise_error(InvalidOperation,
773 'comparison involving sNaN',
774 self)
775 elif other.is_snan():
776 return context._raise_error(InvalidOperation,
777 'comparison involving sNaN',
778 other)
779 elif self.is_qnan():
780 return context._raise_error(InvalidOperation,
781 'comparison involving NaN',
782 self)
783 elif other.is_qnan():
784 return context._raise_error(InvalidOperation,
785 'comparison involving NaN',
786 other)
787 return 0
788
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000789 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000790 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000791
Facundo Batista1a191df2007-10-02 17:01:24 +0000792 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000793 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000794 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000795
Mark Dickinson2fc92632008-02-06 22:10:50 +0000796 def _cmp(self, other):
797 """Compare the two non-NaN decimal instances self and other.
798
799 Returns -1 if self < other, 0 if self == other and 1
800 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000801
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000802 if self._is_special or other._is_special:
Mark Dickinsone52c3142009-01-25 10:39:15 +0000803 self_inf = self._isinfinity()
804 other_inf = other._isinfinity()
805 if self_inf == other_inf:
806 return 0
807 elif self_inf < other_inf:
808 return -1
809 else:
810 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000811
Mark Dickinsone52c3142009-01-25 10:39:15 +0000812 # check for zeros; Decimal('0') == Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000813 if not self:
814 if not other:
815 return 0
816 else:
817 return -((-1)**other._sign)
818 if not other:
819 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000820
Facundo Batista59c58842007-04-10 12:58:45 +0000821 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000822 if other._sign < self._sign:
823 return -1
824 if self._sign < other._sign:
825 return 1
826
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000827 self_adjusted = self.adjusted()
828 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000829 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000830 self_padded = self._int + '0'*(self._exp - other._exp)
831 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone52c3142009-01-25 10:39:15 +0000832 if self_padded == other_padded:
833 return 0
834 elif self_padded < other_padded:
835 return -(-1)**self._sign
836 else:
837 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000838 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000839 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000840 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000841 return -((-1)**self._sign)
842
Mark Dickinson2fc92632008-02-06 22:10:50 +0000843 # Note: The Decimal standard doesn't cover rich comparisons for
844 # Decimals. In particular, the specification is silent on the
845 # subject of what should happen for a comparison involving a NaN.
846 # We take the following approach:
847 #
Mark Dickinsone096e822010-04-02 10:17:07 +0000848 # == comparisons involving a quiet NaN always return False
849 # != comparisons involving a quiet NaN always return True
850 # == or != comparisons involving a signaling NaN signal
851 # InvalidOperation, and return False or True as above if the
852 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000853 # <, >, <= and >= comparisons involving a (quiet or signaling)
854 # NaN signal InvalidOperation, and return False if the
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000855 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000856 #
857 # This behavior is designed to conform as closely as possible to
858 # that specified by IEEE 754.
859
Mark Dickinsone096e822010-04-02 10:17:07 +0000860 def __eq__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000861 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000862 if other is NotImplemented:
863 return other
Mark Dickinsone096e822010-04-02 10:17:07 +0000864 if self._check_nans(other, context):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000865 return False
866 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000867
Mark Dickinsone096e822010-04-02 10:17:07 +0000868 def __ne__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000869 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000870 if other is NotImplemented:
871 return other
Mark Dickinsone096e822010-04-02 10:17:07 +0000872 if self._check_nans(other, context):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000873 return True
874 return self._cmp(other) != 0
875
876 def __lt__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000877 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000878 if other is NotImplemented:
879 return other
880 ans = self._compare_check_nans(other, context)
881 if ans:
882 return False
883 return self._cmp(other) < 0
884
885 def __le__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000886 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000887 if other is NotImplemented:
888 return other
889 ans = self._compare_check_nans(other, context)
890 if ans:
891 return False
892 return self._cmp(other) <= 0
893
894 def __gt__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000895 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000896 if other is NotImplemented:
897 return other
898 ans = self._compare_check_nans(other, context)
899 if ans:
900 return False
901 return self._cmp(other) > 0
902
903 def __ge__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000904 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000905 if other is NotImplemented:
906 return other
907 ans = self._compare_check_nans(other, context)
908 if ans:
909 return False
910 return self._cmp(other) >= 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000911
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000912 def compare(self, other, context=None):
913 """Compares one to another.
914
915 -1 => a < b
916 0 => a = b
917 1 => a > b
918 NaN => one is NaN
919 Like __cmp__, but returns Decimal instances.
920 """
Facundo Batista353750c2007-09-13 18:13:15 +0000921 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000922
Facundo Batista59c58842007-04-10 12:58:45 +0000923 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000924 if (self._is_special or other and other._is_special):
925 ans = self._check_nans(other, context)
926 if ans:
927 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000928
Mark Dickinson2fc92632008-02-06 22:10:50 +0000929 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000930
931 def __hash__(self):
932 """x.__hash__() <==> hash(x)"""
933 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000934 #
935 # The hash of a nonspecial noninteger Decimal must depend only
936 # on the value of that Decimal, and not on its representation.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000937 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Mark Dickinsonf3eeca12010-04-02 10:35:12 +0000938
939 # Equality comparisons involving signaling nans can raise an
940 # exception; since equality checks are implicitly and
941 # unpredictably used when checking set and dict membership, we
942 # prevent signaling nans from being used as set elements or
943 # dict keys by making __hash__ raise an exception.
944 if self._is_special:
945 if self.is_snan():
946 raise TypeError('Cannot hash a signaling NaN value.')
947 elif self.is_nan():
948 # 0 to match hash(float('nan'))
949 return 0
950 else:
951 # values chosen to match hash(float('inf')) and
952 # hash(float('-inf')).
953 if self._sign:
954 return -271828
955 else:
956 return 314159
Mark Dickinson99d80962010-04-02 08:53:22 +0000957
958 # In Python 2.7, we're allowing comparisons (but not
959 # arithmetic operations) between floats and Decimals; so if
960 # a Decimal instance is exactly representable as a float then
Mark Dickinsonf3eeca12010-04-02 10:35:12 +0000961 # its hash should match that of the float.
Mark Dickinson99d80962010-04-02 08:53:22 +0000962 self_as_float = float(self)
963 if Decimal.from_float(self_as_float) == self:
964 return hash(self_as_float)
965
Facundo Batista8c202442007-09-19 17:53:25 +0000966 if self._isinteger():
967 op = _WorkRep(self.to_integral_value())
968 # to make computation feasible for Decimals with large
969 # exponent, we use the fact that hash(n) == hash(m) for
970 # any two nonzero integers n and m such that (i) n and m
971 # have the same sign, and (ii) n is congruent to m modulo
972 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
973 # hash((-1)**s*c*pow(10, e, 2**64-1).
974 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000975 # The value of a nonzero nonspecial Decimal instance is
976 # faithfully represented by the triple consisting of its sign,
977 # its adjusted exponent, and its coefficient with trailing
978 # zeros removed.
979 return hash((self._sign,
980 self._exp+len(self._int),
981 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000982
983 def as_tuple(self):
984 """Represents the number as a triple tuple.
985
986 To show the internals exactly as they are.
987 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000988 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000989
990 def __repr__(self):
991 """Represents the number as an instance of Decimal."""
992 # Invariant: eval(repr(d)) == d
Raymond Hettingerabe32372008-02-14 02:41:22 +0000993 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000994
Facundo Batista353750c2007-09-13 18:13:15 +0000995 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000996 """Return string representation of the number in scientific notation.
997
998 Captures all of the information in the underlying representation.
999 """
1000
Facundo Batista62edb712007-12-03 16:29:52 +00001001 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +00001002 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +00001003 if self._exp == 'F':
1004 return sign + 'Infinity'
1005 elif self._exp == 'n':
1006 return sign + 'NaN' + self._int
1007 else: # self._exp == 'N'
1008 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009
Facundo Batista62edb712007-12-03 16:29:52 +00001010 # number of digits of self._int to left of decimal point
1011 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012
Facundo Batista62edb712007-12-03 16:29:52 +00001013 # dotplace is number of digits of self._int to the left of the
1014 # decimal point in the mantissa of the output string (that is,
1015 # after adjusting the exponent)
1016 if self._exp <= 0 and leftdigits > -6:
1017 # no exponent required
1018 dotplace = leftdigits
1019 elif not eng:
1020 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +00001022 elif self._int == '0':
1023 # engineering notation, zero
1024 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025 else:
Facundo Batista62edb712007-12-03 16:29:52 +00001026 # engineering notation, nonzero
1027 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001028
Facundo Batista62edb712007-12-03 16:29:52 +00001029 if dotplace <= 0:
1030 intpart = '0'
1031 fracpart = '.' + '0'*(-dotplace) + self._int
1032 elif dotplace >= len(self._int):
1033 intpart = self._int+'0'*(dotplace-len(self._int))
1034 fracpart = ''
1035 else:
1036 intpart = self._int[:dotplace]
1037 fracpart = '.' + self._int[dotplace:]
1038 if leftdigits == dotplace:
1039 exp = ''
1040 else:
1041 if context is None:
1042 context = getcontext()
1043 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1044
1045 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001046
1047 def to_eng_string(self, context=None):
1048 """Convert to engineering-type string.
1049
1050 Engineering notation has an exponent which is a multiple of 3, so there
1051 are up to 3 digits left of the decimal place.
1052
1053 Same rules for when in exponential and when as a value as in __str__.
1054 """
Facundo Batista353750c2007-09-13 18:13:15 +00001055 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001056
1057 def __neg__(self, context=None):
1058 """Returns a copy with the sign switched.
1059
1060 Rounds, if it has reason.
1061 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001062 if self._is_special:
1063 ans = self._check_nans(context=context)
1064 if ans:
1065 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001066
1067 if not self:
1068 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001069 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001070 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001071 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001072
1073 if context is None:
1074 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001075 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001076
1077 def __pos__(self, context=None):
1078 """Returns a copy, unless it is a sNaN.
1079
1080 Rounds the number (if more then precision digits)
1081 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001082 if self._is_special:
1083 ans = self._check_nans(context=context)
1084 if ans:
1085 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001086
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001087 if not self:
1088 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001089 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +00001090 else:
1091 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001093 if context is None:
1094 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001095 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001096
Facundo Batistae64acfa2007-12-17 14:18:42 +00001097 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001098 """Returns the absolute value of self.
1099
Facundo Batistae64acfa2007-12-17 14:18:42 +00001100 If the keyword argument 'round' is false, do not round. The
1101 expression self.__abs__(round=False) is equivalent to
1102 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001103 """
Facundo Batistae64acfa2007-12-17 14:18:42 +00001104 if not round:
1105 return self.copy_abs()
1106
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001107 if self._is_special:
1108 ans = self._check_nans(context=context)
1109 if ans:
1110 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001111
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001112 if self._sign:
1113 ans = self.__neg__(context=context)
1114 else:
1115 ans = self.__pos__(context=context)
1116
1117 return ans
1118
1119 def __add__(self, other, context=None):
1120 """Returns self + other.
1121
1122 -INF + INF (or the reverse) cause InvalidOperation errors.
1123 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001124 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001125 if other is NotImplemented:
1126 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001127
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128 if context is None:
1129 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001130
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001131 if self._is_special or other._is_special:
1132 ans = self._check_nans(other, context)
1133 if ans:
1134 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001136 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001137 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001138 if self._sign != other._sign and other._isinfinity():
1139 return context._raise_error(InvalidOperation, '-INF + INF')
1140 return Decimal(self)
1141 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001142 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001143
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144 exp = min(self._exp, other._exp)
1145 negativezero = 0
1146 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001147 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148 negativezero = 1
1149
1150 if not self and not other:
1151 sign = min(self._sign, other._sign)
1152 if negativezero:
1153 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001154 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001155 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001156 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001157 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001158 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001159 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001160 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 return ans
1162 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001163 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001164 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001165 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001166 return ans
1167
1168 op1 = _WorkRep(self)
1169 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001170 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171
1172 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001174 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001175 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001176 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001177 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001178 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001179 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001180 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001181 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001182 if op1.sign == 1:
1183 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184 op1.sign, op2.sign = op2.sign, op1.sign
1185 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001186 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001187 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001188 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001189 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001190 op1.sign, op2.sign = (0, 0)
1191 else:
1192 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001193 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194
Raymond Hettinger17931de2004-10-27 06:21:46 +00001195 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001196 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001197 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001198 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001199
1200 result.exp = op1.exp
1201 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001202 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001203 return ans
1204
1205 __radd__ = __add__
1206
1207 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001208 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001209 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001210 if other is NotImplemented:
1211 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001212
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001213 if self._is_special or other._is_special:
1214 ans = self._check_nans(other, context=context)
1215 if ans:
1216 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001217
Facundo Batista353750c2007-09-13 18:13:15 +00001218 # self - other is computed as self + other.copy_negate()
1219 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001220
1221 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001222 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001223 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001224 if other is NotImplemented:
1225 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001226
Facundo Batista353750c2007-09-13 18:13:15 +00001227 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001229 def __mul__(self, other, context=None):
1230 """Return self * other.
1231
1232 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1233 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001234 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001235 if other is NotImplemented:
1236 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001237
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001238 if context is None:
1239 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001241 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001242
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001243 if self._is_special or other._is_special:
1244 ans = self._check_nans(other, context)
1245 if ans:
1246 return ans
1247
1248 if self._isinfinity():
1249 if not other:
1250 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001251 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001252
1253 if other._isinfinity():
1254 if not self:
1255 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001256 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001257
1258 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001259
1260 # Special case for multiplying by zero
1261 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001262 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001263 # Fixing in case the exponent is out of bounds
1264 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001265 return ans
1266
1267 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001268 if self._int == '1':
1269 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001270 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001271 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001272 if other._int == '1':
1273 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001274 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001275 return ans
1276
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001277 op1 = _WorkRep(self)
1278 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001279
Facundo Batista72bc54f2007-11-23 17:59:00 +00001280 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001281 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001282
1283 return ans
1284 __rmul__ = __mul__
1285
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001286 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001287 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001288 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001289 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001290 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001291
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001292 if context is None:
1293 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001294
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001295 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001296
1297 if self._is_special or other._is_special:
1298 ans = self._check_nans(other, context)
1299 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001300 return ans
1301
1302 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001303 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001304
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001305 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001306 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001307
1308 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001309 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001310 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001311
1312 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001313 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001314 if not self:
1315 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001316 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001317
Facundo Batistacce8df22007-09-18 16:53:18 +00001318 if not self:
1319 exp = self._exp - other._exp
1320 coeff = 0
1321 else:
1322 # OK, so neither = 0, INF or NaN
1323 shift = len(other._int) - len(self._int) + context.prec + 1
1324 exp = self._exp - other._exp - shift
1325 op1 = _WorkRep(self)
1326 op2 = _WorkRep(other)
1327 if shift >= 0:
1328 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1329 else:
1330 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1331 if remainder:
1332 # result is not exact; adjust to ensure correct rounding
1333 if coeff % 5 == 0:
1334 coeff += 1
1335 else:
1336 # result is exact; get as close to ideal exponent as possible
1337 ideal_exp = self._exp - other._exp
1338 while exp < ideal_exp and coeff % 10 == 0:
1339 coeff //= 10
1340 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001341
Facundo Batista72bc54f2007-11-23 17:59:00 +00001342 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001343 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001344
Facundo Batistacce8df22007-09-18 16:53:18 +00001345 def _divide(self, other, context):
1346 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001347
Facundo Batistacce8df22007-09-18 16:53:18 +00001348 Assumes that neither self nor other is a NaN, that self is not
1349 infinite and that other is nonzero.
1350 """
1351 sign = self._sign ^ other._sign
1352 if other._isinfinity():
1353 ideal_exp = self._exp
1354 else:
1355 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001356
Facundo Batistacce8df22007-09-18 16:53:18 +00001357 expdiff = self.adjusted() - other.adjusted()
1358 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001359 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001360 self._rescale(ideal_exp, context.rounding))
1361 if expdiff <= context.prec:
1362 op1 = _WorkRep(self)
1363 op2 = _WorkRep(other)
1364 if op1.exp >= op2.exp:
1365 op1.int *= 10**(op1.exp - op2.exp)
1366 else:
1367 op2.int *= 10**(op2.exp - op1.exp)
1368 q, r = divmod(op1.int, op2.int)
1369 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001370 return (_dec_from_triple(sign, str(q), 0),
1371 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001372
Facundo Batistacce8df22007-09-18 16:53:18 +00001373 # Here the quotient is too large to be representable
1374 ans = context._raise_error(DivisionImpossible,
1375 'quotient too large in //, % or divmod')
1376 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001377
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001378 def __rtruediv__(self, other, context=None):
1379 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001380 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001381 if other is NotImplemented:
1382 return other
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001383 return other.__truediv__(self, context=context)
1384
1385 __div__ = __truediv__
1386 __rdiv__ = __rtruediv__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001387
1388 def __divmod__(self, other, context=None):
1389 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001390 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001391 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001392 other = _convert_other(other)
1393 if other is NotImplemented:
1394 return other
1395
1396 if context is None:
1397 context = getcontext()
1398
1399 ans = self._check_nans(other, context)
1400 if ans:
1401 return (ans, ans)
1402
1403 sign = self._sign ^ other._sign
1404 if self._isinfinity():
1405 if other._isinfinity():
1406 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1407 return ans, ans
1408 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001409 return (_SignedInfinity[sign],
Facundo Batistacce8df22007-09-18 16:53:18 +00001410 context._raise_error(InvalidOperation, 'INF % x'))
1411
1412 if not other:
1413 if not self:
1414 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1415 return ans, ans
1416 else:
1417 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1418 context._raise_error(InvalidOperation, 'x % 0'))
1419
1420 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001421 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001422 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001423
1424 def __rdivmod__(self, other, context=None):
1425 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001426 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001427 if other is NotImplemented:
1428 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001429 return other.__divmod__(self, context=context)
1430
1431 def __mod__(self, other, context=None):
1432 """
1433 self % other
1434 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001435 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001436 if other is NotImplemented:
1437 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001438
Facundo Batistacce8df22007-09-18 16:53:18 +00001439 if context is None:
1440 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001441
Facundo Batistacce8df22007-09-18 16:53:18 +00001442 ans = self._check_nans(other, context)
1443 if ans:
1444 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001445
Facundo Batistacce8df22007-09-18 16:53:18 +00001446 if self._isinfinity():
1447 return context._raise_error(InvalidOperation, 'INF % x')
1448 elif not other:
1449 if self:
1450 return context._raise_error(InvalidOperation, 'x % 0')
1451 else:
1452 return context._raise_error(DivisionUndefined, '0 % 0')
1453
1454 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001455 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001456 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001457
1458 def __rmod__(self, other, context=None):
1459 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001460 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001461 if other is NotImplemented:
1462 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001463 return other.__mod__(self, context=context)
1464
1465 def remainder_near(self, other, context=None):
1466 """
1467 Remainder nearest to 0- abs(remainder-near) <= other/2
1468 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001469 if context is None:
1470 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001471
Facundo Batista353750c2007-09-13 18:13:15 +00001472 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001473
Facundo Batista353750c2007-09-13 18:13:15 +00001474 ans = self._check_nans(other, context)
1475 if ans:
1476 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001477
Facundo Batista353750c2007-09-13 18:13:15 +00001478 # self == +/-infinity -> InvalidOperation
1479 if self._isinfinity():
1480 return context._raise_error(InvalidOperation,
1481 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001482
Facundo Batista353750c2007-09-13 18:13:15 +00001483 # other == 0 -> either InvalidOperation or DivisionUndefined
1484 if not other:
1485 if self:
1486 return context._raise_error(InvalidOperation,
1487 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001488 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001489 return context._raise_error(DivisionUndefined,
1490 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001491
Facundo Batista353750c2007-09-13 18:13:15 +00001492 # other = +/-infinity -> remainder = self
1493 if other._isinfinity():
1494 ans = Decimal(self)
1495 return ans._fix(context)
1496
1497 # self = 0 -> remainder = self, with ideal exponent
1498 ideal_exponent = min(self._exp, other._exp)
1499 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001500 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001501 return ans._fix(context)
1502
1503 # catch most cases of large or small quotient
1504 expdiff = self.adjusted() - other.adjusted()
1505 if expdiff >= context.prec + 1:
1506 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001507 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001508 if expdiff <= -2:
1509 # expdiff <= -2 => abs(self/other) < 0.1
1510 ans = self._rescale(ideal_exponent, context.rounding)
1511 return ans._fix(context)
1512
1513 # adjust both arguments to have the same exponent, then divide
1514 op1 = _WorkRep(self)
1515 op2 = _WorkRep(other)
1516 if op1.exp >= op2.exp:
1517 op1.int *= 10**(op1.exp - op2.exp)
1518 else:
1519 op2.int *= 10**(op2.exp - op1.exp)
1520 q, r = divmod(op1.int, op2.int)
1521 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1522 # 10**ideal_exponent. Apply correction to ensure that
1523 # abs(remainder) <= abs(other)/2
1524 if 2*r + (q&1) > op2.int:
1525 r -= op2.int
1526 q += 1
1527
1528 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001529 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001530
1531 # result has same sign as self unless r is negative
1532 sign = self._sign
1533 if r < 0:
1534 sign = 1-sign
1535 r = -r
1536
Facundo Batista72bc54f2007-11-23 17:59:00 +00001537 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001538 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001539
1540 def __floordiv__(self, other, context=None):
1541 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001542 other = _convert_other(other)
1543 if other is NotImplemented:
1544 return other
1545
1546 if context is None:
1547 context = getcontext()
1548
1549 ans = self._check_nans(other, context)
1550 if ans:
1551 return ans
1552
1553 if self._isinfinity():
1554 if other._isinfinity():
1555 return context._raise_error(InvalidOperation, 'INF // INF')
1556 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001557 return _SignedInfinity[self._sign ^ other._sign]
Facundo Batistacce8df22007-09-18 16:53:18 +00001558
1559 if not other:
1560 if self:
1561 return context._raise_error(DivisionByZero, 'x // 0',
1562 self._sign ^ other._sign)
1563 else:
1564 return context._raise_error(DivisionUndefined, '0 // 0')
1565
1566 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001567
1568 def __rfloordiv__(self, other, context=None):
1569 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001570 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001571 if other is NotImplemented:
1572 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001573 return other.__floordiv__(self, context=context)
1574
1575 def __float__(self):
1576 """Float representation."""
1577 return float(str(self))
1578
1579 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001580 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001581 if self._is_special:
1582 if self._isnan():
Mark Dickinson968f1692009-09-07 18:04:58 +00001583 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001584 elif self._isinfinity():
Mark Dickinson968f1692009-09-07 18:04:58 +00001585 raise OverflowError("Cannot convert infinity to integer")
Facundo Batista353750c2007-09-13 18:13:15 +00001586 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001587 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001588 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001589 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001590 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001591
Raymond Hettinger5a053642008-01-24 19:05:29 +00001592 __trunc__ = __int__
1593
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001594 def real(self):
1595 return self
Mark Dickinson65808ff2009-01-04 21:22:02 +00001596 real = property(real)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001597
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001598 def imag(self):
1599 return Decimal(0)
Mark Dickinson65808ff2009-01-04 21:22:02 +00001600 imag = property(imag)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001601
1602 def conjugate(self):
1603 return self
1604
1605 def __complex__(self):
1606 return complex(float(self))
1607
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001608 def __long__(self):
1609 """Converts to a long.
1610
1611 Equivalent to long(int(self))
1612 """
1613 return long(self.__int__())
1614
Facundo Batista353750c2007-09-13 18:13:15 +00001615 def _fix_nan(self, context):
1616 """Decapitate the payload of a NaN to fit the context"""
1617 payload = self._int
1618
1619 # maximum length of payload is precision if _clamp=0,
1620 # precision-1 if _clamp=1.
1621 max_payload_len = context.prec - context._clamp
1622 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001623 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1624 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001625 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001626
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001627 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001628 """Round if it is necessary to keep self within prec precision.
1629
1630 Rounds and fixes the exponent. Does not raise on a sNaN.
1631
1632 Arguments:
1633 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001634 context - context used.
1635 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001636
Facundo Batista353750c2007-09-13 18:13:15 +00001637 if self._is_special:
1638 if self._isnan():
1639 # decapitate payload if necessary
1640 return self._fix_nan(context)
1641 else:
1642 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001643 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001644
Facundo Batista353750c2007-09-13 18:13:15 +00001645 # if self is zero then exponent should be between Etiny and
1646 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1647 Etiny = context.Etiny()
1648 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001649 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001650 exp_max = [context.Emax, Etop][context._clamp]
1651 new_exp = min(max(self._exp, Etiny), exp_max)
1652 if new_exp != self._exp:
1653 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001654 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001655 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001656 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001657
1658 # exp_min is the smallest allowable exponent of the result,
1659 # equal to max(self.adjusted()-context.prec+1, Etiny)
1660 exp_min = len(self._int) + self._exp - context.prec
1661 if exp_min > Etop:
1662 # overflow: exp_min > Etop iff self.adjusted() > Emax
1663 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001664 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001665 return context._raise_error(Overflow, 'above Emax', self._sign)
1666 self_is_subnormal = exp_min < Etiny
1667 if self_is_subnormal:
1668 context._raise_error(Subnormal)
1669 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001670
Facundo Batista353750c2007-09-13 18:13:15 +00001671 # round if self has too many digits
1672 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001673 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001674 digits = len(self._int) + self._exp - exp_min
1675 if digits < 0:
1676 self = _dec_from_triple(self._sign, '1', exp_min-1)
1677 digits = 0
1678 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1679 changed = this_function(digits)
1680 coeff = self._int[:digits] or '0'
1681 if changed == 1:
1682 coeff = str(int(coeff)+1)
1683 ans = _dec_from_triple(self._sign, coeff, exp_min)
1684
1685 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001686 context._raise_error(Inexact)
1687 if self_is_subnormal:
1688 context._raise_error(Underflow)
1689 if not ans:
1690 # raise Clamped on underflow to 0
1691 context._raise_error(Clamped)
1692 elif len(ans._int) == context.prec+1:
1693 # we get here only if rescaling rounds the
1694 # cofficient up to exactly 10**context.prec
1695 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001696 ans = _dec_from_triple(ans._sign,
1697 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001698 else:
1699 # Inexact and Rounded have already been raised
1700 ans = context._raise_error(Overflow, 'above Emax',
1701 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001702 return ans
1703
Facundo Batista353750c2007-09-13 18:13:15 +00001704 # fold down if _clamp == 1 and self has too few digits
1705 if context._clamp == 1 and self._exp > Etop:
1706 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001707 self_padded = self._int + '0'*(self._exp - Etop)
1708 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001709
Facundo Batista353750c2007-09-13 18:13:15 +00001710 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001711 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001712
1713 _pick_rounding_function = {}
1714
Facundo Batista353750c2007-09-13 18:13:15 +00001715 # for each of the rounding functions below:
1716 # self is a finite, nonzero Decimal
1717 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001718 #
1719 # each function returns either -1, 0, or 1, as follows:
1720 # 1 indicates that self should be rounded up (away from zero)
1721 # 0 indicates that self should be truncated, and that all the
1722 # digits to be truncated are zeros (so the value is unchanged)
1723 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001724
1725 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001726 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001727 if _all_zeros(self._int, prec):
1728 return 0
1729 else:
1730 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001731
Facundo Batista353750c2007-09-13 18:13:15 +00001732 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001733 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001734 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001735
Facundo Batista353750c2007-09-13 18:13:15 +00001736 def _round_half_up(self, prec):
1737 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001738 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001739 return 1
1740 elif _all_zeros(self._int, prec):
1741 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001742 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001743 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001744
1745 def _round_half_down(self, prec):
1746 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001747 if _exact_half(self._int, prec):
1748 return -1
1749 else:
1750 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001751
1752 def _round_half_even(self, prec):
1753 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001754 if _exact_half(self._int, prec) and \
1755 (prec == 0 or self._int[prec-1] in '02468'):
1756 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001757 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001758 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001759
1760 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001761 """Rounds up (not away from 0 if negative.)"""
1762 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001763 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001764 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001765 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001766
Facundo Batista353750c2007-09-13 18:13:15 +00001767 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001768 """Rounds down (not towards 0 if negative)"""
1769 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001770 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001771 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001772 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001773
Facundo Batista353750c2007-09-13 18:13:15 +00001774 def _round_05up(self, prec):
1775 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001776 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001777 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001778 else:
1779 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001780
Facundo Batista353750c2007-09-13 18:13:15 +00001781 def fma(self, other, third, context=None):
1782 """Fused multiply-add.
1783
1784 Returns self*other+third with no rounding of the intermediate
1785 product self*other.
1786
1787 self and other are multiplied together, with no rounding of
1788 the result. The third operand is then added to the result,
1789 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001790 """
Facundo Batista353750c2007-09-13 18:13:15 +00001791
1792 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001793
1794 # compute product; raise InvalidOperation if either operand is
1795 # a signaling NaN or if the product is zero times infinity.
1796 if self._is_special or other._is_special:
1797 if context is None:
1798 context = getcontext()
1799 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001800 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001801 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001802 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001803 if self._exp == 'n':
1804 product = self
1805 elif other._exp == 'n':
1806 product = other
1807 elif self._exp == 'F':
1808 if not other:
1809 return context._raise_error(InvalidOperation,
1810 'INF * 0 in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001811 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001812 elif other._exp == 'F':
1813 if not self:
1814 return context._raise_error(InvalidOperation,
1815 '0 * INF in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001816 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001817 else:
1818 product = _dec_from_triple(self._sign ^ other._sign,
1819 str(int(self._int) * int(other._int)),
1820 self._exp + other._exp)
1821
Facundo Batista353750c2007-09-13 18:13:15 +00001822 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001823 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001824
Facundo Batista353750c2007-09-13 18:13:15 +00001825 def _power_modulo(self, other, modulo, context=None):
1826 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001827
Facundo Batista353750c2007-09-13 18:13:15 +00001828 # if can't convert other and modulo to Decimal, raise
1829 # TypeError; there's no point returning NotImplemented (no
1830 # equivalent of __rpow__ for three argument pow)
1831 other = _convert_other(other, raiseit=True)
1832 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001833
Facundo Batista353750c2007-09-13 18:13:15 +00001834 if context is None:
1835 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001836
Facundo Batista353750c2007-09-13 18:13:15 +00001837 # deal with NaNs: if there are any sNaNs then first one wins,
1838 # (i.e. behaviour for NaNs is identical to that of fma)
1839 self_is_nan = self._isnan()
1840 other_is_nan = other._isnan()
1841 modulo_is_nan = modulo._isnan()
1842 if self_is_nan or other_is_nan or modulo_is_nan:
1843 if self_is_nan == 2:
1844 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001845 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001846 if other_is_nan == 2:
1847 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001848 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001849 if modulo_is_nan == 2:
1850 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001851 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001852 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001853 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001854 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001855 return other._fix_nan(context)
1856 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001857
Facundo Batista353750c2007-09-13 18:13:15 +00001858 # check inputs: we apply same restrictions as Python's pow()
1859 if not (self._isinteger() and
1860 other._isinteger() and
1861 modulo._isinteger()):
1862 return context._raise_error(InvalidOperation,
1863 'pow() 3rd argument not allowed '
1864 'unless all arguments are integers')
1865 if other < 0:
1866 return context._raise_error(InvalidOperation,
1867 'pow() 2nd argument cannot be '
1868 'negative when 3rd argument specified')
1869 if not modulo:
1870 return context._raise_error(InvalidOperation,
1871 'pow() 3rd argument cannot be 0')
1872
1873 # additional restriction for decimal: the modulus must be less
1874 # than 10**prec in absolute value
1875 if modulo.adjusted() >= context.prec:
1876 return context._raise_error(InvalidOperation,
1877 'insufficient precision: pow() 3rd '
1878 'argument must not have more than '
1879 'precision digits')
1880
1881 # define 0**0 == NaN, for consistency with two-argument pow
1882 # (even though it hurts!)
1883 if not other and not self:
1884 return context._raise_error(InvalidOperation,
1885 'at least one of pow() 1st argument '
1886 'and 2nd argument must be nonzero ;'
1887 '0**0 is not defined')
1888
1889 # compute sign of result
1890 if other._iseven():
1891 sign = 0
1892 else:
1893 sign = self._sign
1894
1895 # convert modulo to a Python integer, and self and other to
1896 # Decimal integers (i.e. force their exponents to be >= 0)
1897 modulo = abs(int(modulo))
1898 base = _WorkRep(self.to_integral_value())
1899 exponent = _WorkRep(other.to_integral_value())
1900
1901 # compute result using integer pow()
1902 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1903 for i in xrange(exponent.exp):
1904 base = pow(base, 10, modulo)
1905 base = pow(base, exponent.int, modulo)
1906
Facundo Batista72bc54f2007-11-23 17:59:00 +00001907 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001908
1909 def _power_exact(self, other, p):
1910 """Attempt to compute self**other exactly.
1911
1912 Given Decimals self and other and an integer p, attempt to
1913 compute an exact result for the power self**other, with p
1914 digits of precision. Return None if self**other is not
1915 exactly representable in p digits.
1916
1917 Assumes that elimination of special cases has already been
1918 performed: self and other must both be nonspecial; self must
1919 be positive and not numerically equal to 1; other must be
1920 nonzero. For efficiency, other._exp should not be too large,
1921 so that 10**abs(other._exp) is a feasible calculation."""
1922
1923 # In the comments below, we write x for the value of self and
1924 # y for the value of other. Write x = xc*10**xe and y =
1925 # yc*10**ye.
1926
1927 # The main purpose of this method is to identify the *failure*
1928 # of x**y to be exactly representable with as little effort as
1929 # possible. So we look for cheap and easy tests that
1930 # eliminate the possibility of x**y being exact. Only if all
1931 # these tests are passed do we go on to actually compute x**y.
1932
1933 # Here's the main idea. First normalize both x and y. We
1934 # express y as a rational m/n, with m and n relatively prime
1935 # and n>0. Then for x**y to be exactly representable (at
1936 # *any* precision), xc must be the nth power of a positive
1937 # integer and xe must be divisible by n. If m is negative
1938 # then additionally xc must be a power of either 2 or 5, hence
1939 # a power of 2**n or 5**n.
1940 #
1941 # There's a limit to how small |y| can be: if y=m/n as above
1942 # then:
1943 #
1944 # (1) if xc != 1 then for the result to be representable we
1945 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1946 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1947 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1948 # representable.
1949 #
1950 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1951 # |y| < 1/|xe| then the result is not representable.
1952 #
1953 # Note that since x is not equal to 1, at least one of (1) and
1954 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1955 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1956 #
1957 # There's also a limit to how large y can be, at least if it's
1958 # positive: the normalized result will have coefficient xc**y,
1959 # so if it's representable then xc**y < 10**p, and y <
1960 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1961 # not exactly representable.
1962
1963 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1964 # so |y| < 1/xe and the result is not representable.
1965 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1966 # < 1/nbits(xc).
1967
1968 x = _WorkRep(self)
1969 xc, xe = x.int, x.exp
1970 while xc % 10 == 0:
1971 xc //= 10
1972 xe += 1
1973
1974 y = _WorkRep(other)
1975 yc, ye = y.int, y.exp
1976 while yc % 10 == 0:
1977 yc //= 10
1978 ye += 1
1979
1980 # case where xc == 1: result is 10**(xe*y), with xe*y
1981 # required to be an integer
1982 if xc == 1:
1983 if ye >= 0:
1984 exponent = xe*yc*10**ye
1985 else:
1986 exponent, remainder = divmod(xe*yc, 10**-ye)
1987 if remainder:
1988 return None
1989 if y.sign == 1:
1990 exponent = -exponent
1991 # if other is a nonnegative integer, use ideal exponent
1992 if other._isinteger() and other._sign == 0:
1993 ideal_exponent = self._exp*int(other)
1994 zeros = min(exponent-ideal_exponent, p-1)
1995 else:
1996 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001997 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001998
1999 # case where y is negative: xc must be either a power
2000 # of 2 or a power of 5.
2001 if y.sign == 1:
2002 last_digit = xc % 10
2003 if last_digit in (2,4,6,8):
2004 # quick test for power of 2
2005 if xc & -xc != xc:
2006 return None
2007 # now xc is a power of 2; e is its exponent
2008 e = _nbits(xc)-1
2009 # find e*y and xe*y; both must be integers
2010 if ye >= 0:
2011 y_as_int = yc*10**ye
2012 e = e*y_as_int
2013 xe = xe*y_as_int
2014 else:
2015 ten_pow = 10**-ye
2016 e, remainder = divmod(e*yc, ten_pow)
2017 if remainder:
2018 return None
2019 xe, remainder = divmod(xe*yc, ten_pow)
2020 if remainder:
2021 return None
2022
2023 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2024 return None
2025 xc = 5**e
2026
2027 elif last_digit == 5:
2028 # e >= log_5(xc) if xc is a power of 5; we have
2029 # equality all the way up to xc=5**2658
2030 e = _nbits(xc)*28//65
2031 xc, remainder = divmod(5**e, xc)
2032 if remainder:
2033 return None
2034 while xc % 5 == 0:
2035 xc //= 5
2036 e -= 1
2037 if ye >= 0:
2038 y_as_integer = yc*10**ye
2039 e = e*y_as_integer
2040 xe = xe*y_as_integer
2041 else:
2042 ten_pow = 10**-ye
2043 e, remainder = divmod(e*yc, ten_pow)
2044 if remainder:
2045 return None
2046 xe, remainder = divmod(xe*yc, ten_pow)
2047 if remainder:
2048 return None
2049 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2050 return None
2051 xc = 2**e
2052 else:
2053 return None
2054
2055 if xc >= 10**p:
2056 return None
2057 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00002058 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00002059
2060 # now y is positive; find m and n such that y = m/n
2061 if ye >= 0:
2062 m, n = yc*10**ye, 1
2063 else:
2064 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2065 return None
2066 xc_bits = _nbits(xc)
2067 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2068 return None
2069 m, n = yc, 10**(-ye)
2070 while m % 2 == n % 2 == 0:
2071 m //= 2
2072 n //= 2
2073 while m % 5 == n % 5 == 0:
2074 m //= 5
2075 n //= 5
2076
2077 # compute nth root of xc*10**xe
2078 if n > 1:
2079 # if 1 < xc < 2**n then xc isn't an nth power
2080 if xc != 1 and xc_bits <= n:
2081 return None
2082
2083 xe, rem = divmod(xe, n)
2084 if rem != 0:
2085 return None
2086
2087 # compute nth root of xc using Newton's method
2088 a = 1L << -(-_nbits(xc)//n) # initial estimate
2089 while True:
2090 q, r = divmod(xc, a**(n-1))
2091 if a <= q:
2092 break
2093 else:
2094 a = (a*(n-1) + q)//n
2095 if not (a == q and r == 0):
2096 return None
2097 xc = a
2098
2099 # now xc*10**xe is the nth root of the original xc*10**xe
2100 # compute mth power of xc*10**xe
2101
2102 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2103 # 10**p and the result is not representable.
2104 if xc > 1 and m > p*100//_log10_lb(xc):
2105 return None
2106 xc = xc**m
2107 xe *= m
2108 if xc > 10**p:
2109 return None
2110
2111 # by this point the result *is* exactly representable
2112 # adjust the exponent to get as close as possible to the ideal
2113 # exponent, if necessary
2114 str_xc = str(xc)
2115 if other._isinteger() and other._sign == 0:
2116 ideal_exponent = self._exp*int(other)
2117 zeros = min(xe-ideal_exponent, p-len(str_xc))
2118 else:
2119 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002120 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002121
2122 def __pow__(self, other, modulo=None, context=None):
2123 """Return self ** other [ % modulo].
2124
2125 With two arguments, compute self**other.
2126
2127 With three arguments, compute (self**other) % modulo. For the
2128 three argument form, the following restrictions on the
2129 arguments hold:
2130
2131 - all three arguments must be integral
2132 - other must be nonnegative
2133 - either self or other (or both) must be nonzero
2134 - modulo must be nonzero and must have at most p digits,
2135 where p is the context precision.
2136
2137 If any of these restrictions is violated the InvalidOperation
2138 flag is raised.
2139
2140 The result of pow(self, other, modulo) is identical to the
2141 result that would be obtained by computing (self**other) %
2142 modulo with unbounded precision, but is computed more
2143 efficiently. It is always exact.
2144 """
2145
2146 if modulo is not None:
2147 return self._power_modulo(other, modulo, context)
2148
2149 other = _convert_other(other)
2150 if other is NotImplemented:
2151 return other
2152
2153 if context is None:
2154 context = getcontext()
2155
2156 # either argument is a NaN => result is NaN
2157 ans = self._check_nans(other, context)
2158 if ans:
2159 return ans
2160
2161 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2162 if not other:
2163 if not self:
2164 return context._raise_error(InvalidOperation, '0 ** 0')
2165 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002166 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002167
2168 # result has sign 1 iff self._sign is 1 and other is an odd integer
2169 result_sign = 0
2170 if self._sign == 1:
2171 if other._isinteger():
2172 if not other._iseven():
2173 result_sign = 1
2174 else:
2175 # -ve**noninteger = NaN
2176 # (-0)**noninteger = 0**noninteger
2177 if self:
2178 return context._raise_error(InvalidOperation,
2179 'x ** y with x negative and y not an integer')
2180 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002181 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002182
2183 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2184 if not self:
2185 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002186 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002187 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002188 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002189
2190 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002191 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002192 if other._sign == 0:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002193 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002194 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002195 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002196
Facundo Batista353750c2007-09-13 18:13:15 +00002197 # 1**other = 1, but the choice of exponent and the flags
2198 # depend on the exponent of self, and on whether other is a
2199 # positive integer, a negative integer, or neither
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002200 if self == _One:
Facundo Batista353750c2007-09-13 18:13:15 +00002201 if other._isinteger():
2202 # exp = max(self._exp*max(int(other), 0),
2203 # 1-context.prec) but evaluating int(other) directly
2204 # is dangerous until we know other is small (other
2205 # could be 1e999999999)
2206 if other._sign == 1:
2207 multiplier = 0
2208 elif other > context.prec:
2209 multiplier = context.prec
2210 else:
2211 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002212
Facundo Batista353750c2007-09-13 18:13:15 +00002213 exp = self._exp * multiplier
2214 if exp < 1-context.prec:
2215 exp = 1-context.prec
2216 context._raise_error(Rounded)
2217 else:
2218 context._raise_error(Inexact)
2219 context._raise_error(Rounded)
2220 exp = 1-context.prec
2221
Facundo Batista72bc54f2007-11-23 17:59:00 +00002222 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002223
2224 # compute adjusted exponent of self
2225 self_adj = self.adjusted()
2226
2227 # self ** infinity is infinity if self > 1, 0 if self < 1
2228 # self ** -infinity is infinity if self < 1, 0 if self > 1
2229 if other._isinfinity():
2230 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002231 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002232 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002233 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002234
2235 # from here on, the result always goes through the call
2236 # to _fix at the end of this function.
2237 ans = None
2238
2239 # crude test to catch cases of extreme overflow/underflow. If
2240 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2241 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2242 # self**other >= 10**(Emax+1), so overflow occurs. The test
2243 # for underflow is similar.
2244 bound = self._log10_exp_bound() + other.adjusted()
2245 if (self_adj >= 0) == (other._sign == 0):
2246 # self > 1 and other +ve, or self < 1 and other -ve
2247 # possibility of overflow
2248 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002249 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002250 else:
2251 # self > 1 and other -ve, or self < 1 and other +ve
2252 # possibility of underflow to 0
2253 Etiny = context.Etiny()
2254 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002255 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002256
2257 # try for an exact result with precision +1
2258 if ans is None:
2259 ans = self._power_exact(other, context.prec + 1)
2260 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002261 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002262
2263 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2264 if ans is None:
2265 p = context.prec
2266 x = _WorkRep(self)
2267 xc, xe = x.int, x.exp
2268 y = _WorkRep(other)
2269 yc, ye = y.int, y.exp
2270 if y.sign == 1:
2271 yc = -yc
2272
2273 # compute correctly rounded result: start with precision +3,
2274 # then increase precision until result is unambiguously roundable
2275 extra = 3
2276 while True:
2277 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2278 if coeff % (5*10**(len(str(coeff))-p-1)):
2279 break
2280 extra += 3
2281
Facundo Batista72bc54f2007-11-23 17:59:00 +00002282 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002283
2284 # the specification says that for non-integer other we need to
2285 # raise Inexact, even when the result is actually exact. In
2286 # the same way, we need to raise Underflow here if the result
2287 # is subnormal. (The call to _fix will take care of raising
2288 # Rounded and Subnormal, as usual.)
2289 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002290 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002291 # pad with zeros up to length context.prec+1 if necessary
2292 if len(ans._int) <= context.prec:
2293 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002294 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2295 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002296 if ans.adjusted() < context.Emin:
2297 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002298
Facundo Batista353750c2007-09-13 18:13:15 +00002299 # unlike exp, ln and log10, the power function respects the
2300 # rounding mode; no need to use ROUND_HALF_EVEN here
2301 ans = ans._fix(context)
2302 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002303
2304 def __rpow__(self, other, context=None):
2305 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002306 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002307 if other is NotImplemented:
2308 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002309 return other.__pow__(self, context=context)
2310
2311 def normalize(self, context=None):
2312 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002313
Facundo Batista353750c2007-09-13 18:13:15 +00002314 if context is None:
2315 context = getcontext()
2316
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002317 if self._is_special:
2318 ans = self._check_nans(context=context)
2319 if ans:
2320 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002321
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002322 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002323 if dup._isinfinity():
2324 return dup
2325
2326 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002327 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002328 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002329 end = len(dup._int)
2330 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002331 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002332 exp += 1
2333 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002334 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002335
Facundo Batistabd2fe832007-09-13 18:42:09 +00002336 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002337 """Quantize self so its exponent is the same as that of exp.
2338
2339 Similar to self._rescale(exp._exp) but with error checking.
2340 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002341 exp = _convert_other(exp, raiseit=True)
2342
Facundo Batista353750c2007-09-13 18:13:15 +00002343 if context is None:
2344 context = getcontext()
2345 if rounding is None:
2346 rounding = context.rounding
2347
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002348 if self._is_special or exp._is_special:
2349 ans = self._check_nans(exp, context)
2350 if ans:
2351 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002352
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002353 if exp._isinfinity() or self._isinfinity():
2354 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002355 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002356 return context._raise_error(InvalidOperation,
2357 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002358
Facundo Batistabd2fe832007-09-13 18:42:09 +00002359 # if we're not watching exponents, do a simple rescale
2360 if not watchexp:
2361 ans = self._rescale(exp._exp, rounding)
2362 # raise Inexact and Rounded where appropriate
2363 if ans._exp > self._exp:
2364 context._raise_error(Rounded)
2365 if ans != self:
2366 context._raise_error(Inexact)
2367 return ans
2368
Facundo Batista353750c2007-09-13 18:13:15 +00002369 # exp._exp should be between Etiny and Emax
2370 if not (context.Etiny() <= exp._exp <= context.Emax):
2371 return context._raise_error(InvalidOperation,
2372 'target exponent out of bounds in quantize')
2373
2374 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002375 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002376 return ans._fix(context)
2377
2378 self_adjusted = self.adjusted()
2379 if self_adjusted > context.Emax:
2380 return context._raise_error(InvalidOperation,
2381 'exponent of quantize result too large for current context')
2382 if self_adjusted - exp._exp + 1 > context.prec:
2383 return context._raise_error(InvalidOperation,
2384 'quantize result has too many digits for current context')
2385
2386 ans = self._rescale(exp._exp, rounding)
2387 if ans.adjusted() > context.Emax:
2388 return context._raise_error(InvalidOperation,
2389 'exponent of quantize result too large for current context')
2390 if len(ans._int) > context.prec:
2391 return context._raise_error(InvalidOperation,
2392 'quantize result has too many digits for current context')
2393
2394 # raise appropriate flags
2395 if ans._exp > self._exp:
2396 context._raise_error(Rounded)
2397 if ans != self:
2398 context._raise_error(Inexact)
2399 if ans and ans.adjusted() < context.Emin:
2400 context._raise_error(Subnormal)
2401
2402 # call to fix takes care of any necessary folddown
2403 ans = ans._fix(context)
2404 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002405
2406 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002407 """Return True if self and other have the same exponent; otherwise
2408 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002409
Facundo Batista1a191df2007-10-02 17:01:24 +00002410 If either operand is a special value, the following rules are used:
2411 * return True if both operands are infinities
2412 * return True if both operands are NaNs
2413 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002414 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002415 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002416 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002417 return (self.is_nan() and other.is_nan() or
2418 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002419 return self._exp == other._exp
2420
Facundo Batista353750c2007-09-13 18:13:15 +00002421 def _rescale(self, exp, rounding):
2422 """Rescale self so that the exponent is exp, either by padding with zeros
2423 or by truncating digits, using the given rounding mode.
2424
2425 Specials are returned without change. This operation is
2426 quiet: it raises no flags, and uses no information from the
2427 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002428
2429 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002430 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002431 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002432 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002433 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002434 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002435 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002436
Facundo Batista353750c2007-09-13 18:13:15 +00002437 if self._exp >= exp:
2438 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002439 return _dec_from_triple(self._sign,
2440 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002441
Facundo Batista353750c2007-09-13 18:13:15 +00002442 # too many digits; round and lose data. If self.adjusted() <
2443 # exp-1, replace self by 10**(exp-1) before rounding
2444 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002445 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002446 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002447 digits = 0
2448 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002449 changed = this_function(digits)
2450 coeff = self._int[:digits] or '0'
2451 if changed == 1:
2452 coeff = str(int(coeff)+1)
2453 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002454
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00002455 def _round(self, places, rounding):
2456 """Round a nonzero, nonspecial Decimal to a fixed number of
2457 significant figures, using the given rounding mode.
2458
2459 Infinities, NaNs and zeros are returned unaltered.
2460
2461 This operation is quiet: it raises no flags, and uses no
2462 information from the context.
2463
2464 """
2465 if places <= 0:
2466 raise ValueError("argument should be at least 1 in _round")
2467 if self._is_special or not self:
2468 return Decimal(self)
2469 ans = self._rescale(self.adjusted()+1-places, rounding)
2470 # it can happen that the rescale alters the adjusted exponent;
2471 # for example when rounding 99.97 to 3 significant figures.
2472 # When this happens we end up with an extra 0 at the end of
2473 # the number; a second rescale fixes this.
2474 if ans.adjusted() != self.adjusted():
2475 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2476 return ans
2477
Facundo Batista353750c2007-09-13 18:13:15 +00002478 def to_integral_exact(self, rounding=None, context=None):
2479 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002480
Facundo Batista353750c2007-09-13 18:13:15 +00002481 If no rounding mode is specified, take the rounding mode from
2482 the context. This method raises the Rounded and Inexact flags
2483 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002484
Facundo Batista353750c2007-09-13 18:13:15 +00002485 See also: to_integral_value, which does exactly the same as
2486 this method except that it doesn't raise Inexact or Rounded.
2487 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002488 if self._is_special:
2489 ans = self._check_nans(context=context)
2490 if ans:
2491 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002492 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002493 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002494 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002495 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002496 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002497 if context is None:
2498 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002499 if rounding is None:
2500 rounding = context.rounding
2501 context._raise_error(Rounded)
2502 ans = self._rescale(0, rounding)
2503 if ans != self:
2504 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505 return ans
2506
Facundo Batista353750c2007-09-13 18:13:15 +00002507 def to_integral_value(self, rounding=None, context=None):
2508 """Rounds to the nearest integer, without raising inexact, rounded."""
2509 if context is None:
2510 context = getcontext()
2511 if rounding is None:
2512 rounding = context.rounding
2513 if self._is_special:
2514 ans = self._check_nans(context=context)
2515 if ans:
2516 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002517 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002518 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002519 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002520 else:
2521 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002522
Facundo Batista353750c2007-09-13 18:13:15 +00002523 # the method name changed, but we provide also the old one, for compatibility
2524 to_integral = to_integral_value
2525
2526 def sqrt(self, context=None):
2527 """Return the square root of self."""
Mark Dickinson3b24ccb2008-03-25 14:33:23 +00002528 if context is None:
2529 context = getcontext()
2530
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002531 if self._is_special:
2532 ans = self._check_nans(context=context)
2533 if ans:
2534 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002535
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002536 if self._isinfinity() and self._sign == 0:
2537 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002538
2539 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002540 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002541 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002542 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002543
2544 if self._sign == 1:
2545 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2546
Facundo Batista353750c2007-09-13 18:13:15 +00002547 # At this point self represents a positive number. Let p be
2548 # the desired precision and express self in the form c*100**e
2549 # with c a positive real number and e an integer, c and e
2550 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2551 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2552 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2553 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2554 # the closest integer to sqrt(c) with the even integer chosen
2555 # in the case of a tie.
2556 #
2557 # To ensure correct rounding in all cases, we use the
2558 # following trick: we compute the square root to an extra
2559 # place (precision p+1 instead of precision p), rounding down.
2560 # Then, if the result is inexact and its last digit is 0 or 5,
2561 # we increase the last digit to 1 or 6 respectively; if it's
2562 # exact we leave the last digit alone. Now the final round to
2563 # p places (or fewer in the case of underflow) will round
2564 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002565
Facundo Batista353750c2007-09-13 18:13:15 +00002566 # use an extra digit of precision
2567 prec = context.prec+1
2568
2569 # write argument in the form c*100**e where e = self._exp//2
2570 # is the 'ideal' exponent, to be used if the square root is
2571 # exactly representable. l is the number of 'digits' of c in
2572 # base 100, so that 100**(l-1) <= c < 100**l.
2573 op = _WorkRep(self)
2574 e = op.exp >> 1
2575 if op.exp & 1:
2576 c = op.int * 10
2577 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002578 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002579 c = op.int
2580 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002581
Facundo Batista353750c2007-09-13 18:13:15 +00002582 # rescale so that c has exactly prec base 100 'digits'
2583 shift = prec-l
2584 if shift >= 0:
2585 c *= 100**shift
2586 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002587 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002588 c, remainder = divmod(c, 100**-shift)
2589 exact = not remainder
2590 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002591
Facundo Batista353750c2007-09-13 18:13:15 +00002592 # find n = floor(sqrt(c)) using Newton's method
2593 n = 10**prec
2594 while True:
2595 q = c//n
2596 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002597 break
Facundo Batista353750c2007-09-13 18:13:15 +00002598 else:
2599 n = n + q >> 1
2600 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002601
Facundo Batista353750c2007-09-13 18:13:15 +00002602 if exact:
2603 # result is exact; rescale to use ideal exponent e
2604 if shift >= 0:
2605 # assert n % 10**shift == 0
2606 n //= 10**shift
2607 else:
2608 n *= 10**-shift
2609 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002610 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002611 # result is not exact; fix last digit as described above
2612 if n % 5 == 0:
2613 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002614
Facundo Batista72bc54f2007-11-23 17:59:00 +00002615 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002616
Facundo Batista353750c2007-09-13 18:13:15 +00002617 # round, and fit to current context
2618 context = context._shallow_copy()
2619 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002620 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002621 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002622
Facundo Batista353750c2007-09-13 18:13:15 +00002623 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002624
2625 def max(self, other, context=None):
2626 """Returns the larger value.
2627
Facundo Batista353750c2007-09-13 18:13:15 +00002628 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002629 NaN (and signals if one is sNaN). Also rounds.
2630 """
Facundo Batista353750c2007-09-13 18:13:15 +00002631 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002632
Facundo Batista6c398da2007-09-17 17:30:13 +00002633 if context is None:
2634 context = getcontext()
2635
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002636 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002637 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002638 # number is always returned
2639 sn = self._isnan()
2640 on = other._isnan()
2641 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002642 if on == 1 and sn == 0:
2643 return self._fix(context)
2644 if sn == 1 and on == 0:
2645 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002646 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002647
Mark Dickinson2fc92632008-02-06 22:10:50 +00002648 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002649 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002650 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002651 # then an ordering is applied:
2652 #
Facundo Batista59c58842007-04-10 12:58:45 +00002653 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002654 # positive sign and min returns the operand with the negative sign
2655 #
Facundo Batista59c58842007-04-10 12:58:45 +00002656 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002657 # the result. This is exactly the ordering used in compare_total.
2658 c = self.compare_total(other)
2659
2660 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002661 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002662 else:
2663 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002664
Facundo Batistae64acfa2007-12-17 14:18:42 +00002665 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002666
2667 def min(self, other, context=None):
2668 """Returns the smaller value.
2669
Facundo Batista59c58842007-04-10 12:58:45 +00002670 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002671 NaN (and signals if one is sNaN). Also rounds.
2672 """
Facundo Batista353750c2007-09-13 18:13:15 +00002673 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002674
Facundo Batista6c398da2007-09-17 17:30:13 +00002675 if context is None:
2676 context = getcontext()
2677
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002678 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002679 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002680 # number is always returned
2681 sn = self._isnan()
2682 on = other._isnan()
2683 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002684 if on == 1 and sn == 0:
2685 return self._fix(context)
2686 if sn == 1 and on == 0:
2687 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002688 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002689
Mark Dickinson2fc92632008-02-06 22:10:50 +00002690 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002691 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002692 c = self.compare_total(other)
2693
2694 if c == -1:
2695 ans = self
2696 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002697 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002698
Facundo Batistae64acfa2007-12-17 14:18:42 +00002699 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002700
2701 def _isinteger(self):
2702 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002703 if self._is_special:
2704 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002705 if self._exp >= 0:
2706 return True
2707 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002708 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002709
2710 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002711 """Returns True if self is even. Assumes self is an integer."""
2712 if not self or self._exp > 0:
2713 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002714 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002715
2716 def adjusted(self):
2717 """Return the adjusted exponent of self"""
2718 try:
2719 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002720 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002721 except TypeError:
2722 return 0
2723
Facundo Batista353750c2007-09-13 18:13:15 +00002724 def canonical(self, context=None):
2725 """Returns the same Decimal object.
2726
2727 As we do not have different encodings for the same number, the
2728 received object already is in its canonical form.
2729 """
2730 return self
2731
2732 def compare_signal(self, other, context=None):
2733 """Compares self to the other operand numerically.
2734
2735 It's pretty much like compare(), but all NaNs signal, with signaling
2736 NaNs taking precedence over quiet NaNs.
2737 """
Mark Dickinson2fc92632008-02-06 22:10:50 +00002738 other = _convert_other(other, raiseit = True)
2739 ans = self._compare_check_nans(other, context)
2740 if ans:
2741 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002742 return self.compare(other, context=context)
2743
2744 def compare_total(self, other):
2745 """Compares self to other using the abstract representations.
2746
2747 This is not like the standard compare, which use their numerical
2748 value. Note that a total ordering is defined for all possible abstract
2749 representations.
2750 """
Mark Dickinson0c673122009-10-29 12:04:00 +00002751 other = _convert_other(other, raiseit=True)
2752
Facundo Batista353750c2007-09-13 18:13:15 +00002753 # if one is negative and the other is positive, it's easy
2754 if self._sign and not other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002755 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002756 if not self._sign and other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002757 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002758 sign = self._sign
2759
2760 # let's handle both NaN types
2761 self_nan = self._isnan()
2762 other_nan = other._isnan()
2763 if self_nan or other_nan:
2764 if self_nan == other_nan:
Mark Dickinson7a7739d2009-08-28 13:25:02 +00002765 # compare payloads as though they're integers
2766 self_key = len(self._int), self._int
2767 other_key = len(other._int), other._int
2768 if self_key < other_key:
Facundo Batista353750c2007-09-13 18:13:15 +00002769 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002770 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002771 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002772 return _NegativeOne
Mark Dickinson7a7739d2009-08-28 13:25:02 +00002773 if self_key > other_key:
Facundo Batista353750c2007-09-13 18:13:15 +00002774 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002775 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002776 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002777 return _One
2778 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002779
2780 if sign:
2781 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002782 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002783 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002784 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002785 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002786 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002787 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002788 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002789 else:
2790 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002791 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002792 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002793 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002794 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002795 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002796 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002797 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002798
2799 if self < other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002800 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002801 if self > other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002802 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002803
2804 if self._exp < other._exp:
2805 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002806 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002807 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002808 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002809 if self._exp > other._exp:
2810 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002811 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002812 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002813 return _One
2814 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002815
2816
2817 def compare_total_mag(self, other):
2818 """Compares self to other using abstract repr., ignoring sign.
2819
2820 Like compare_total, but with operand's sign ignored and assumed to be 0.
2821 """
Mark Dickinson0c673122009-10-29 12:04:00 +00002822 other = _convert_other(other, raiseit=True)
2823
Facundo Batista353750c2007-09-13 18:13:15 +00002824 s = self.copy_abs()
2825 o = other.copy_abs()
2826 return s.compare_total(o)
2827
2828 def copy_abs(self):
2829 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002830 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002831
2832 def copy_negate(self):
2833 """Returns a copy with the sign inverted."""
2834 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002835 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002836 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002837 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002838
2839 def copy_sign(self, other):
2840 """Returns self with the sign of other."""
Mark Dickinson6d8effb2010-02-18 14:27:02 +00002841 other = _convert_other(other, raiseit=True)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002842 return _dec_from_triple(other._sign, self._int,
2843 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002844
2845 def exp(self, context=None):
2846 """Returns e ** self."""
2847
2848 if context is None:
2849 context = getcontext()
2850
2851 # exp(NaN) = NaN
2852 ans = self._check_nans(context=context)
2853 if ans:
2854 return ans
2855
2856 # exp(-Infinity) = 0
2857 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002858 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002859
2860 # exp(0) = 1
2861 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002862 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002863
2864 # exp(Infinity) = Infinity
2865 if self._isinfinity() == 1:
2866 return Decimal(self)
2867
2868 # the result is now guaranteed to be inexact (the true
2869 # mathematical result is transcendental). There's no need to
2870 # raise Rounded and Inexact here---they'll always be raised as
2871 # a result of the call to _fix.
2872 p = context.prec
2873 adj = self.adjusted()
2874
2875 # we only need to do any computation for quite a small range
2876 # of adjusted exponents---for example, -29 <= adj <= 10 for
2877 # the default context. For smaller exponent the result is
2878 # indistinguishable from 1 at the given precision, while for
2879 # larger exponent the result either overflows or underflows.
2880 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2881 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002882 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002883 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2884 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002885 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002886 elif self._sign == 0 and adj < -p:
2887 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002888 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002889 elif self._sign == 1 and adj < -p-1:
2890 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002891 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002892 # general case
2893 else:
2894 op = _WorkRep(self)
2895 c, e = op.int, op.exp
2896 if op.sign == 1:
2897 c = -c
2898
2899 # compute correctly rounded result: increase precision by
2900 # 3 digits at a time until we get an unambiguously
2901 # roundable result
2902 extra = 3
2903 while True:
2904 coeff, exp = _dexp(c, e, p+extra)
2905 if coeff % (5*10**(len(str(coeff))-p-1)):
2906 break
2907 extra += 3
2908
Facundo Batista72bc54f2007-11-23 17:59:00 +00002909 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002910
2911 # at this stage, ans should round correctly with *any*
2912 # rounding mode, not just with ROUND_HALF_EVEN
2913 context = context._shallow_copy()
2914 rounding = context._set_rounding(ROUND_HALF_EVEN)
2915 ans = ans._fix(context)
2916 context.rounding = rounding
2917
2918 return ans
2919
2920 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002921 """Return True if self is canonical; otherwise return False.
2922
2923 Currently, the encoding of a Decimal instance is always
2924 canonical, so this method returns True for any Decimal.
2925 """
2926 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002927
2928 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002929 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002930
Facundo Batista1a191df2007-10-02 17:01:24 +00002931 A Decimal instance is considered finite if it is neither
2932 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002933 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002934 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002935
2936 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002937 """Return True if self is infinite; otherwise return False."""
2938 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002939
2940 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002941 """Return True if self is a qNaN or sNaN; otherwise return False."""
2942 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002943
2944 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002945 """Return True if self is a normal number; otherwise return False."""
2946 if self._is_special or not self:
2947 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002948 if context is None:
2949 context = getcontext()
Mark Dickinsona7a52ab2009-10-20 13:33:03 +00002950 return context.Emin <= self.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +00002951
2952 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002953 """Return True if self is a quiet NaN; otherwise return False."""
2954 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002955
2956 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002957 """Return True if self is negative; otherwise return False."""
2958 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002959
2960 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002961 """Return True if self is a signaling NaN; otherwise return False."""
2962 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002963
2964 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002965 """Return True if self is subnormal; otherwise return False."""
2966 if self._is_special or not self:
2967 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002968 if context is None:
2969 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002970 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002971
2972 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002973 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002974 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002975
2976 def _ln_exp_bound(self):
2977 """Compute a lower bound for the adjusted exponent of self.ln().
2978 In other words, compute r such that self.ln() >= 10**r. Assumes
2979 that self is finite and positive and that self != 1.
2980 """
2981
2982 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2983 adj = self._exp + len(self._int) - 1
2984 if adj >= 1:
2985 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2986 return len(str(adj*23//10)) - 1
2987 if adj <= -2:
2988 # argument <= 0.1
2989 return len(str((-1-adj)*23//10)) - 1
2990 op = _WorkRep(self)
2991 c, e = op.int, op.exp
2992 if adj == 0:
2993 # 1 < self < 10
2994 num = str(c-10**-e)
2995 den = str(c)
2996 return len(num) - len(den) - (num < den)
2997 # adj == -1, 0.1 <= self < 1
2998 return e + len(str(10**-e - c)) - 1
2999
3000
3001 def ln(self, context=None):
3002 """Returns the natural (base e) logarithm of self."""
3003
3004 if context is None:
3005 context = getcontext()
3006
3007 # ln(NaN) = NaN
3008 ans = self._check_nans(context=context)
3009 if ans:
3010 return ans
3011
3012 # ln(0.0) == -Infinity
3013 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003014 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003015
3016 # ln(Infinity) = Infinity
3017 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003018 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003019
3020 # ln(1.0) == 0.0
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003021 if self == _One:
3022 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00003023
3024 # ln(negative) raises InvalidOperation
3025 if self._sign == 1:
3026 return context._raise_error(InvalidOperation,
3027 'ln of a negative value')
3028
3029 # result is irrational, so necessarily inexact
3030 op = _WorkRep(self)
3031 c, e = op.int, op.exp
3032 p = context.prec
3033
3034 # correctly rounded result: repeatedly increase precision by 3
3035 # until we get an unambiguously roundable result
3036 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3037 while True:
3038 coeff = _dlog(c, e, places)
3039 # assert len(str(abs(coeff)))-p >= 1
3040 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3041 break
3042 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003043 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003044
3045 context = context._shallow_copy()
3046 rounding = context._set_rounding(ROUND_HALF_EVEN)
3047 ans = ans._fix(context)
3048 context.rounding = rounding
3049 return ans
3050
3051 def _log10_exp_bound(self):
3052 """Compute a lower bound for the adjusted exponent of self.log10().
3053 In other words, find r such that self.log10() >= 10**r.
3054 Assumes that self is finite and positive and that self != 1.
3055 """
3056
3057 # For x >= 10 or x < 0.1 we only need a bound on the integer
3058 # part of log10(self), and this comes directly from the
3059 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3060 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3061 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3062
3063 adj = self._exp + len(self._int) - 1
3064 if adj >= 1:
3065 # self >= 10
3066 return len(str(adj))-1
3067 if adj <= -2:
3068 # self < 0.1
3069 return len(str(-1-adj))-1
3070 op = _WorkRep(self)
3071 c, e = op.int, op.exp
3072 if adj == 0:
3073 # 1 < self < 10
3074 num = str(c-10**-e)
3075 den = str(231*c)
3076 return len(num) - len(den) - (num < den) + 2
3077 # adj == -1, 0.1 <= self < 1
3078 num = str(10**-e-c)
3079 return len(num) + e - (num < "231") - 1
3080
3081 def log10(self, context=None):
3082 """Returns the base 10 logarithm of self."""
3083
3084 if context is None:
3085 context = getcontext()
3086
3087 # log10(NaN) = NaN
3088 ans = self._check_nans(context=context)
3089 if ans:
3090 return ans
3091
3092 # log10(0.0) == -Infinity
3093 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003094 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003095
3096 # log10(Infinity) = Infinity
3097 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003098 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003099
3100 # log10(negative or -Infinity) raises InvalidOperation
3101 if self._sign == 1:
3102 return context._raise_error(InvalidOperation,
3103 'log10 of a negative value')
3104
3105 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00003106 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00003107 # answer may need rounding
3108 ans = Decimal(self._exp + len(self._int) - 1)
3109 else:
3110 # result is irrational, so necessarily inexact
3111 op = _WorkRep(self)
3112 c, e = op.int, op.exp
3113 p = context.prec
3114
3115 # correctly rounded result: repeatedly increase precision
3116 # until result is unambiguously roundable
3117 places = p-self._log10_exp_bound()+2
3118 while True:
3119 coeff = _dlog10(c, e, places)
3120 # assert len(str(abs(coeff)))-p >= 1
3121 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3122 break
3123 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003124 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003125
3126 context = context._shallow_copy()
3127 rounding = context._set_rounding(ROUND_HALF_EVEN)
3128 ans = ans._fix(context)
3129 context.rounding = rounding
3130 return ans
3131
3132 def logb(self, context=None):
3133 """ Returns the exponent of the magnitude of self's MSD.
3134
3135 The result is the integer which is the exponent of the magnitude
3136 of the most significant digit of self (as though it were truncated
3137 to a single digit while maintaining the value of that digit and
3138 without limiting the resulting exponent).
3139 """
3140 # logb(NaN) = NaN
3141 ans = self._check_nans(context=context)
3142 if ans:
3143 return ans
3144
3145 if context is None:
3146 context = getcontext()
3147
3148 # logb(+/-Inf) = +Inf
3149 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003150 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003151
3152 # logb(0) = -Inf, DivisionByZero
3153 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003154 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003155
3156 # otherwise, simply return the adjusted exponent of self, as a
3157 # Decimal. Note that no attempt is made to fit the result
3158 # into the current context.
Mark Dickinson15ae41c2009-10-07 19:22:05 +00003159 ans = Decimal(self.adjusted())
3160 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003161
3162 def _islogical(self):
3163 """Return True if self is a logical operand.
3164
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00003165 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00003166 an exponent of 0, and a coefficient whose digits must all be
3167 either 0 or 1.
3168 """
3169 if self._sign != 0 or self._exp != 0:
3170 return False
3171 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003172 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003173 return False
3174 return True
3175
3176 def _fill_logical(self, context, opa, opb):
3177 dif = context.prec - len(opa)
3178 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003179 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003180 elif dif < 0:
3181 opa = opa[-context.prec:]
3182 dif = context.prec - len(opb)
3183 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003184 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003185 elif dif < 0:
3186 opb = opb[-context.prec:]
3187 return opa, opb
3188
3189 def logical_and(self, other, context=None):
3190 """Applies an 'and' operation between self and other's digits."""
3191 if context is None:
3192 context = getcontext()
Mark Dickinson0c673122009-10-29 12:04:00 +00003193
3194 other = _convert_other(other, raiseit=True)
3195
Facundo Batista353750c2007-09-13 18:13:15 +00003196 if not self._islogical() or not other._islogical():
3197 return context._raise_error(InvalidOperation)
3198
3199 # fill to context.prec
3200 (opa, opb) = self._fill_logical(context, self._int, other._int)
3201
3202 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003203 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3204 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003205
3206 def logical_invert(self, context=None):
3207 """Invert all its digits."""
3208 if context is None:
3209 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003210 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3211 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003212
3213 def logical_or(self, other, context=None):
3214 """Applies an 'or' operation between self and other's digits."""
3215 if context is None:
3216 context = getcontext()
Mark Dickinson0c673122009-10-29 12:04:00 +00003217
3218 other = _convert_other(other, raiseit=True)
3219
Facundo Batista353750c2007-09-13 18:13:15 +00003220 if not self._islogical() or not other._islogical():
3221 return context._raise_error(InvalidOperation)
3222
3223 # fill to context.prec
3224 (opa, opb) = self._fill_logical(context, self._int, other._int)
3225
3226 # make the operation, and clean starting zeroes
Mark Dickinson65808ff2009-01-04 21:22:02 +00003227 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003228 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003229
3230 def logical_xor(self, other, context=None):
3231 """Applies an 'xor' operation between self and other's digits."""
3232 if context is None:
3233 context = getcontext()
Mark Dickinson0c673122009-10-29 12:04:00 +00003234
3235 other = _convert_other(other, raiseit=True)
3236
Facundo Batista353750c2007-09-13 18:13:15 +00003237 if not self._islogical() or not other._islogical():
3238 return context._raise_error(InvalidOperation)
3239
3240 # fill to context.prec
3241 (opa, opb) = self._fill_logical(context, self._int, other._int)
3242
3243 # make the operation, and clean starting zeroes
Mark Dickinson65808ff2009-01-04 21:22:02 +00003244 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003245 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003246
3247 def max_mag(self, other, context=None):
3248 """Compares the values numerically with their sign ignored."""
3249 other = _convert_other(other, raiseit=True)
3250
Facundo Batista6c398da2007-09-17 17:30:13 +00003251 if context is None:
3252 context = getcontext()
3253
Facundo Batista353750c2007-09-13 18:13:15 +00003254 if self._is_special or other._is_special:
3255 # If one operand is a quiet NaN and the other is number, then the
3256 # number is always returned
3257 sn = self._isnan()
3258 on = other._isnan()
3259 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003260 if on == 1 and sn == 0:
3261 return self._fix(context)
3262 if sn == 1 and on == 0:
3263 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003264 return self._check_nans(other, context)
3265
Mark Dickinson2fc92632008-02-06 22:10:50 +00003266 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003267 if c == 0:
3268 c = self.compare_total(other)
3269
3270 if c == -1:
3271 ans = other
3272 else:
3273 ans = self
3274
Facundo Batistae64acfa2007-12-17 14:18:42 +00003275 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003276
3277 def min_mag(self, other, context=None):
3278 """Compares the values numerically with their sign ignored."""
3279 other = _convert_other(other, raiseit=True)
3280
Facundo Batista6c398da2007-09-17 17:30:13 +00003281 if context is None:
3282 context = getcontext()
3283
Facundo Batista353750c2007-09-13 18:13:15 +00003284 if self._is_special or other._is_special:
3285 # If one operand is a quiet NaN and the other is number, then the
3286 # number is always returned
3287 sn = self._isnan()
3288 on = other._isnan()
3289 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003290 if on == 1 and sn == 0:
3291 return self._fix(context)
3292 if sn == 1 and on == 0:
3293 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003294 return self._check_nans(other, context)
3295
Mark Dickinson2fc92632008-02-06 22:10:50 +00003296 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003297 if c == 0:
3298 c = self.compare_total(other)
3299
3300 if c == -1:
3301 ans = self
3302 else:
3303 ans = other
3304
Facundo Batistae64acfa2007-12-17 14:18:42 +00003305 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003306
3307 def next_minus(self, context=None):
3308 """Returns the largest representable number smaller than itself."""
3309 if context is None:
3310 context = getcontext()
3311
3312 ans = self._check_nans(context=context)
3313 if ans:
3314 return ans
3315
3316 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003317 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003318 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003319 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003320
3321 context = context.copy()
3322 context._set_rounding(ROUND_FLOOR)
3323 context._ignore_all_flags()
3324 new_self = self._fix(context)
3325 if new_self != self:
3326 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003327 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3328 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003329
3330 def next_plus(self, context=None):
3331 """Returns the smallest representable number larger than itself."""
3332 if context is None:
3333 context = getcontext()
3334
3335 ans = self._check_nans(context=context)
3336 if ans:
3337 return ans
3338
3339 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003340 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003341 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003342 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003343
3344 context = context.copy()
3345 context._set_rounding(ROUND_CEILING)
3346 context._ignore_all_flags()
3347 new_self = self._fix(context)
3348 if new_self != self:
3349 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003350 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3351 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003352
3353 def next_toward(self, other, context=None):
3354 """Returns the number closest to self, in the direction towards other.
3355
3356 The result is the closest representable number to self
3357 (excluding self) that is in the direction towards other,
3358 unless both have the same value. If the two operands are
3359 numerically equal, then the result is a copy of self with the
3360 sign set to be the same as the sign of other.
3361 """
3362 other = _convert_other(other, raiseit=True)
3363
3364 if context is None:
3365 context = getcontext()
3366
3367 ans = self._check_nans(other, context)
3368 if ans:
3369 return ans
3370
Mark Dickinson2fc92632008-02-06 22:10:50 +00003371 comparison = self._cmp(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003372 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003373 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003374
3375 if comparison == -1:
3376 ans = self.next_plus(context)
3377 else: # comparison == 1
3378 ans = self.next_minus(context)
3379
3380 # decide which flags to raise using value of ans
3381 if ans._isinfinity():
3382 context._raise_error(Overflow,
3383 'Infinite result from next_toward',
3384 ans._sign)
3385 context._raise_error(Rounded)
3386 context._raise_error(Inexact)
3387 elif ans.adjusted() < context.Emin:
3388 context._raise_error(Underflow)
3389 context._raise_error(Subnormal)
3390 context._raise_error(Rounded)
3391 context._raise_error(Inexact)
3392 # if precision == 1 then we don't raise Clamped for a
3393 # result 0E-Etiny.
3394 if not ans:
3395 context._raise_error(Clamped)
3396
3397 return ans
3398
3399 def number_class(self, context=None):
3400 """Returns an indication of the class of self.
3401
3402 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003403 sNaN
3404 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003405 -Infinity
3406 -Normal
3407 -Subnormal
3408 -Zero
3409 +Zero
3410 +Subnormal
3411 +Normal
3412 +Infinity
3413 """
3414 if self.is_snan():
3415 return "sNaN"
3416 if self.is_qnan():
3417 return "NaN"
3418 inf = self._isinfinity()
3419 if inf == 1:
3420 return "+Infinity"
3421 if inf == -1:
3422 return "-Infinity"
3423 if self.is_zero():
3424 if self._sign:
3425 return "-Zero"
3426 else:
3427 return "+Zero"
3428 if context is None:
3429 context = getcontext()
3430 if self.is_subnormal(context=context):
3431 if self._sign:
3432 return "-Subnormal"
3433 else:
3434 return "+Subnormal"
3435 # just a normal, regular, boring number, :)
3436 if self._sign:
3437 return "-Normal"
3438 else:
3439 return "+Normal"
3440
3441 def radix(self):
3442 """Just returns 10, as this is Decimal, :)"""
3443 return Decimal(10)
3444
3445 def rotate(self, other, context=None):
3446 """Returns a rotated copy of self, value-of-other times."""
3447 if context is None:
3448 context = getcontext()
3449
Mark Dickinson0c673122009-10-29 12:04:00 +00003450 other = _convert_other(other, raiseit=True)
3451
Facundo Batista353750c2007-09-13 18:13:15 +00003452 ans = self._check_nans(other, context)
3453 if ans:
3454 return ans
3455
3456 if other._exp != 0:
3457 return context._raise_error(InvalidOperation)
3458 if not (-context.prec <= int(other) <= context.prec):
3459 return context._raise_error(InvalidOperation)
3460
3461 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003462 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003463
3464 # get values, pad if necessary
3465 torot = int(other)
3466 rotdig = self._int
3467 topad = context.prec - len(rotdig)
Mark Dickinson6f390012009-10-29 12:11:18 +00003468 if topad > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003469 rotdig = '0'*topad + rotdig
Mark Dickinson6f390012009-10-29 12:11:18 +00003470 elif topad < 0:
3471 rotdig = rotdig[-topad:]
Facundo Batista353750c2007-09-13 18:13:15 +00003472
3473 # let's rotate!
3474 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003475 return _dec_from_triple(self._sign,
3476 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003477
Mark Dickinson0c673122009-10-29 12:04:00 +00003478 def scaleb(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00003479 """Returns self operand after adding the second value to its exp."""
3480 if context is None:
3481 context = getcontext()
3482
Mark Dickinson0c673122009-10-29 12:04:00 +00003483 other = _convert_other(other, raiseit=True)
3484
Facundo Batista353750c2007-09-13 18:13:15 +00003485 ans = self._check_nans(other, context)
3486 if ans:
3487 return ans
3488
3489 if other._exp != 0:
3490 return context._raise_error(InvalidOperation)
3491 liminf = -2 * (context.Emax + context.prec)
3492 limsup = 2 * (context.Emax + context.prec)
3493 if not (liminf <= int(other) <= limsup):
3494 return context._raise_error(InvalidOperation)
3495
3496 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003497 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003498
Facundo Batista72bc54f2007-11-23 17:59:00 +00003499 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003500 d = d._fix(context)
3501 return d
3502
3503 def shift(self, other, context=None):
3504 """Returns a shifted copy of self, value-of-other times."""
3505 if context is None:
3506 context = getcontext()
3507
Mark Dickinson0c673122009-10-29 12:04:00 +00003508 other = _convert_other(other, raiseit=True)
3509
Facundo Batista353750c2007-09-13 18:13:15 +00003510 ans = self._check_nans(other, context)
3511 if ans:
3512 return ans
3513
3514 if other._exp != 0:
3515 return context._raise_error(InvalidOperation)
3516 if not (-context.prec <= int(other) <= context.prec):
3517 return context._raise_error(InvalidOperation)
3518
3519 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003520 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003521
3522 # get values, pad if necessary
3523 torot = int(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003524 rotdig = self._int
3525 topad = context.prec - len(rotdig)
Mark Dickinson6f390012009-10-29 12:11:18 +00003526 if topad > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003527 rotdig = '0'*topad + rotdig
Mark Dickinson6f390012009-10-29 12:11:18 +00003528 elif topad < 0:
3529 rotdig = rotdig[-topad:]
Facundo Batista353750c2007-09-13 18:13:15 +00003530
3531 # let's shift!
3532 if torot < 0:
Mark Dickinson6f390012009-10-29 12:11:18 +00003533 shifted = rotdig[:torot]
Facundo Batista353750c2007-09-13 18:13:15 +00003534 else:
Mark Dickinson6f390012009-10-29 12:11:18 +00003535 shifted = rotdig + '0'*torot
3536 shifted = shifted[-context.prec:]
Facundo Batista353750c2007-09-13 18:13:15 +00003537
Facundo Batista72bc54f2007-11-23 17:59:00 +00003538 return _dec_from_triple(self._sign,
Mark Dickinson6f390012009-10-29 12:11:18 +00003539 shifted.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003540
Facundo Batista59c58842007-04-10 12:58:45 +00003541 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003542 def __reduce__(self):
3543 return (self.__class__, (str(self),))
3544
3545 def __copy__(self):
Benjamin Peterson28e369a2010-01-25 03:58:21 +00003546 if type(self) is Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003547 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003548 return self.__class__(str(self))
3549
3550 def __deepcopy__(self, memo):
Benjamin Peterson28e369a2010-01-25 03:58:21 +00003551 if type(self) is Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003552 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003553 return self.__class__(str(self))
3554
Mark Dickinson277859d2009-03-17 23:03:46 +00003555 # PEP 3101 support. the _localeconv keyword argument should be
3556 # considered private: it's provided for ease of testing only.
3557 def __format__(self, specifier, context=None, _localeconv=None):
Mark Dickinsonf4da7772008-02-29 03:29:17 +00003558 """Format a Decimal instance according to the given specifier.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003559
3560 The specifier should be a standard format specifier, with the
3561 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson277859d2009-03-17 23:03:46 +00003562 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3563 type is omitted it defaults to 'g' or 'G', depending on the
3564 value of context.capitals.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003565 """
3566
3567 # Note: PEP 3101 says that if the type is not present then
3568 # there should be at least one digit after the decimal point.
3569 # We take the liberty of ignoring this requirement for
3570 # Decimal---it's presumably there to make sure that
3571 # format(float, '') behaves similarly to str(float).
3572 if context is None:
3573 context = getcontext()
3574
Mark Dickinson277859d2009-03-17 23:03:46 +00003575 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003576
Mark Dickinson277859d2009-03-17 23:03:46 +00003577 # special values don't care about the type or precision
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003578 if self._is_special:
Mark Dickinson277859d2009-03-17 23:03:46 +00003579 sign = _format_sign(self._sign, spec)
3580 body = str(self.copy_abs())
3581 return _format_align(sign, body, spec)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003582
3583 # a type of None defaults to 'g' or 'G', depending on context
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003584 if spec['type'] is None:
3585 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson277859d2009-03-17 23:03:46 +00003586
3587 # if type is '%', adjust exponent of self accordingly
3588 if spec['type'] == '%':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003589 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3590
3591 # round if necessary, taking rounding mode from the context
3592 rounding = context.rounding
3593 precision = spec['precision']
3594 if precision is not None:
3595 if spec['type'] in 'eE':
3596 self = self._round(precision+1, rounding)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003597 elif spec['type'] in 'fF%':
3598 self = self._rescale(-precision, rounding)
Mark Dickinson277859d2009-03-17 23:03:46 +00003599 elif spec['type'] in 'gG' and len(self._int) > precision:
3600 self = self._round(precision, rounding)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003601 # special case: zeros with a positive exponent can't be
3602 # represented in fixed point; rescale them to 0e0.
Mark Dickinson277859d2009-03-17 23:03:46 +00003603 if not self and self._exp > 0 and spec['type'] in 'fF%':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003604 self = self._rescale(0, rounding)
3605
3606 # figure out placement of the decimal point
3607 leftdigits = self._exp + len(self._int)
Mark Dickinson277859d2009-03-17 23:03:46 +00003608 if spec['type'] in 'eE':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003609 if not self and precision is not None:
3610 dotplace = 1 - precision
3611 else:
3612 dotplace = 1
Mark Dickinson277859d2009-03-17 23:03:46 +00003613 elif spec['type'] in 'fF%':
3614 dotplace = leftdigits
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003615 elif spec['type'] in 'gG':
3616 if self._exp <= 0 and leftdigits > -6:
3617 dotplace = leftdigits
3618 else:
3619 dotplace = 1
3620
Mark Dickinson277859d2009-03-17 23:03:46 +00003621 # find digits before and after decimal point, and get exponent
3622 if dotplace < 0:
3623 intpart = '0'
3624 fracpart = '0'*(-dotplace) + self._int
3625 elif dotplace > len(self._int):
3626 intpart = self._int + '0'*(dotplace-len(self._int))
3627 fracpart = ''
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003628 else:
Mark Dickinson277859d2009-03-17 23:03:46 +00003629 intpart = self._int[:dotplace] or '0'
3630 fracpart = self._int[dotplace:]
3631 exp = leftdigits-dotplace
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003632
Mark Dickinson277859d2009-03-17 23:03:46 +00003633 # done with the decimal-specific stuff; hand over the rest
3634 # of the formatting to the _format_number function
3635 return _format_number(self._sign, intpart, fracpart, exp, spec)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003636
Facundo Batista72bc54f2007-11-23 17:59:00 +00003637def _dec_from_triple(sign, coefficient, exponent, special=False):
3638 """Create a decimal instance directly, without any validation,
3639 normalization (e.g. removal of leading zeros) or argument
3640 conversion.
3641
3642 This function is for *internal use only*.
3643 """
3644
3645 self = object.__new__(Decimal)
3646 self._sign = sign
3647 self._int = coefficient
3648 self._exp = exponent
3649 self._is_special = special
3650
3651 return self
3652
Raymond Hettinger2c8585b2009-02-03 03:37:03 +00003653# Register Decimal as a kind of Number (an abstract base class).
3654# However, do not register it as Real (because Decimals are not
3655# interoperable with floats).
3656_numbers.Number.register(Decimal)
3657
3658
Facundo Batista59c58842007-04-10 12:58:45 +00003659##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003660
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003661
3662# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003663rounding_functions = [name for name in Decimal.__dict__.keys()
3664 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003665for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003666 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003667 globalname = name[1:].upper()
3668 val = globals()[globalname]
3669 Decimal._pick_rounding_function[val] = name
3670
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003671del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003672
Nick Coghlanced12182006-09-02 03:54:17 +00003673class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003674 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003675
Nick Coghlanced12182006-09-02 03:54:17 +00003676 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003677 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003678 """
3679 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003680 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003681 def __enter__(self):
3682 self.saved_context = getcontext()
3683 setcontext(self.new_context)
3684 return self.new_context
3685 def __exit__(self, t, v, tb):
3686 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003687
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003688class Context(object):
3689 """Contains the context for a Decimal instance.
3690
3691 Contains:
3692 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003693 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003694 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003695 raised when it is caused. Otherwise, a value is
3696 substituted in.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003697 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003698 (Whether or not the trap_enabler is set)
3699 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003700 Emin - Minimum exponent
3701 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003702 capitals - If 1, 1*10^1 is printed as 1E+1.
3703 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003704 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003705 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003706
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003707 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003708 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003709 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003710 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003711 _ignored_flags=None):
3712 if flags is None:
3713 flags = []
3714 if _ignored_flags is None:
3715 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003716 if not isinstance(flags, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003717 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003718 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003719 if traps is not None and not isinstance(traps, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003720 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003721 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003722 for name, val in locals().items():
3723 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003724 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003725 else:
3726 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003727 del self.self
3728
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003729 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003730 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003731 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003732 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3733 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3734 % vars(self))
3735 names = [f.__name__ for f, v in self.flags.items() if v]
3736 s.append('flags=[' + ', '.join(names) + ']')
3737 names = [t.__name__ for t, v in self.traps.items() if v]
3738 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003739 return ', '.join(s) + ')'
3740
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003741 def clear_flags(self):
3742 """Reset all flags to zero"""
3743 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003744 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003745
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003746 def _shallow_copy(self):
3747 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003748 nc = Context(self.prec, self.rounding, self.traps,
3749 self.flags, self.Emin, self.Emax,
3750 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003751 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003752
3753 def copy(self):
3754 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003755 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003756 self.flags.copy(), self.Emin, self.Emax,
3757 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003758 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003759 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003760
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003761 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003762 """Handles an error
3763
3764 If the flag is in _ignored_flags, returns the default response.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003765 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003766 trap_enabler is set, it reaises the exception. Otherwise, it returns
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003767 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003768 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003769 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003770 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003771 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003772 return error().handle(self, *args)
3773
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003774 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003775 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003776 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003777 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003778
3779 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003780 # self._ignored_flags = []
Mark Dickinson8aca9d02008-05-04 02:05:06 +00003781 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003782
3783 def _ignore_all_flags(self):
3784 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003785 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003786
3787 def _ignore_flags(self, *flags):
3788 """Ignore the flags, if they are raised"""
3789 # Do not mutate-- This way, copies of a context leave the original
3790 # alone.
3791 self._ignored_flags = (self._ignored_flags + list(flags))
3792 return list(flags)
3793
3794 def _regard_flags(self, *flags):
3795 """Stop ignoring the flags, if they are raised"""
3796 if flags and isinstance(flags[0], (tuple,list)):
3797 flags = flags[0]
3798 for flag in flags:
3799 self._ignored_flags.remove(flag)
3800
Nick Coghlan53663a62008-07-15 14:27:37 +00003801 # We inherit object.__hash__, so we must deny this explicitly
3802 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003803
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003804 def Etiny(self):
3805 """Returns Etiny (= Emin - prec + 1)"""
3806 return int(self.Emin - self.prec + 1)
3807
3808 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003809 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003810 return int(self.Emax - self.prec + 1)
3811
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003812 def _set_rounding(self, type):
3813 """Sets the rounding type.
3814
3815 Sets the rounding type, and returns the current (previous)
3816 rounding type. Often used like:
3817
3818 context = context.copy()
3819 # so you don't change the calling context
3820 # if an error occurs in the middle.
3821 rounding = context._set_rounding(ROUND_UP)
3822 val = self.__sub__(other, context=context)
3823 context._set_rounding(rounding)
3824
3825 This will make it round up for that operation.
3826 """
3827 rounding = self.rounding
3828 self.rounding= type
3829 return rounding
3830
Raymond Hettingerfed52962004-07-14 15:41:57 +00003831 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003832 """Creates a new Decimal instance but using self as context.
3833
3834 This method implements the to-number operation of the
3835 IBM Decimal specification."""
3836
3837 if isinstance(num, basestring) and num != num.strip():
3838 return self._raise_error(ConversionSyntax,
3839 "no trailing or leading whitespace is "
3840 "permitted.")
3841
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003842 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003843 if d._isnan() and len(d._int) > self.prec - self._clamp:
3844 return self._raise_error(ConversionSyntax,
3845 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003846 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003847
Raymond Hettingerf4d85972009-01-03 19:02:23 +00003848 def create_decimal_from_float(self, f):
3849 """Creates a new Decimal instance from a float but rounding using self
3850 as the context.
3851
3852 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3853 >>> context.create_decimal_from_float(3.1415926535897932)
3854 Decimal('3.1415')
3855 >>> context = Context(prec=5, traps=[Inexact])
3856 >>> context.create_decimal_from_float(3.1415926535897932)
3857 Traceback (most recent call last):
3858 ...
3859 Inexact: None
3860
3861 """
3862 d = Decimal.from_float(f) # An exact conversion
3863 return d._fix(self) # Apply the context rounding
3864
Facundo Batista59c58842007-04-10 12:58:45 +00003865 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003866 def abs(self, a):
3867 """Returns the absolute value of the operand.
3868
3869 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003870 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003871 the plus operation on the operand.
3872
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003873 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003874 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003875 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003876 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003877 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003878 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003879 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003880 Decimal('101.5')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003881 >>> ExtendedContext.abs(-1)
3882 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003883 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003884 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003885 return a.__abs__(context=self)
3886
3887 def add(self, a, b):
3888 """Return the sum of the two operands.
3889
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003890 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003891 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003892 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003893 Decimal('1.02E+4')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003894 >>> ExtendedContext.add(1, Decimal(2))
3895 Decimal('3')
3896 >>> ExtendedContext.add(Decimal(8), 5)
3897 Decimal('13')
3898 >>> ExtendedContext.add(5, 5)
3899 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003900 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003901 a = _convert_other(a, raiseit=True)
3902 r = a.__add__(b, context=self)
3903 if r is NotImplemented:
3904 raise TypeError("Unable to convert %s to Decimal" % b)
3905 else:
3906 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003907
3908 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003909 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003910
Facundo Batista353750c2007-09-13 18:13:15 +00003911 def canonical(self, a):
3912 """Returns the same Decimal object.
3913
3914 As we do not have different encodings for the same number, the
3915 received object already is in its canonical form.
3916
3917 >>> ExtendedContext.canonical(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003918 Decimal('2.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003919 """
3920 return a.canonical(context=self)
3921
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003922 def compare(self, a, b):
3923 """Compares values numerically.
3924
3925 If the signs of the operands differ, a value representing each operand
3926 ('-1' if the operand is less than zero, '0' if the operand is zero or
3927 negative zero, or '1' if the operand is greater than zero) is used in
3928 place of that operand for the comparison instead of the actual
3929 operand.
3930
3931 The comparison is then effected by subtracting the second operand from
3932 the first and then returning a value according to the result of the
3933 subtraction: '-1' if the result is less than zero, '0' if the result is
3934 zero or negative zero, or '1' if the result is greater than zero.
3935
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003936 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003937 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003938 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003939 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003940 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003941 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003942 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003943 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003944 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003945 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003946 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003947 Decimal('-1')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003948 >>> ExtendedContext.compare(1, 2)
3949 Decimal('-1')
3950 >>> ExtendedContext.compare(Decimal(1), 2)
3951 Decimal('-1')
3952 >>> ExtendedContext.compare(1, Decimal(2))
3953 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003954 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003955 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003956 return a.compare(b, context=self)
3957
Facundo Batista353750c2007-09-13 18:13:15 +00003958 def compare_signal(self, a, b):
3959 """Compares the values of the two operands numerically.
3960
3961 It's pretty much like compare(), but all NaNs signal, with signaling
3962 NaNs taking precedence over quiet NaNs.
3963
3964 >>> c = ExtendedContext
3965 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003966 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003967 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003968 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003969 >>> c.flags[InvalidOperation] = 0
3970 >>> print c.flags[InvalidOperation]
3971 0
3972 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003973 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003974 >>> print c.flags[InvalidOperation]
3975 1
3976 >>> c.flags[InvalidOperation] = 0
3977 >>> print c.flags[InvalidOperation]
3978 0
3979 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003980 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003981 >>> print c.flags[InvalidOperation]
3982 1
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003983 >>> c.compare_signal(-1, 2)
3984 Decimal('-1')
3985 >>> c.compare_signal(Decimal(-1), 2)
3986 Decimal('-1')
3987 >>> c.compare_signal(-1, Decimal(2))
3988 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003989 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003990 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00003991 return a.compare_signal(b, context=self)
3992
3993 def compare_total(self, a, b):
3994 """Compares two operands using their abstract representation.
3995
3996 This is not like the standard compare, which use their numerical
3997 value. Note that a total ordering is defined for all possible abstract
3998 representations.
3999
4000 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004001 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004002 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004003 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004004 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004005 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004006 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004007 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004008 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004009 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004010 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004011 Decimal('-1')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004012 >>> ExtendedContext.compare_total(1, 2)
4013 Decimal('-1')
4014 >>> ExtendedContext.compare_total(Decimal(1), 2)
4015 Decimal('-1')
4016 >>> ExtendedContext.compare_total(1, Decimal(2))
4017 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004018 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004019 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004020 return a.compare_total(b)
4021
4022 def compare_total_mag(self, a, b):
4023 """Compares two operands using their abstract representation ignoring sign.
4024
4025 Like compare_total, but with operand's sign ignored and assumed to be 0.
4026 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004027 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004028 return a.compare_total_mag(b)
4029
4030 def copy_abs(self, a):
4031 """Returns a copy of the operand with the sign set to 0.
4032
4033 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004034 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00004035 >>> ExtendedContext.copy_abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004036 Decimal('100')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004037 >>> ExtendedContext.copy_abs(-1)
4038 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004039 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004040 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004041 return a.copy_abs()
4042
4043 def copy_decimal(self, a):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004044 """Returns a copy of the decimal object.
Facundo Batista353750c2007-09-13 18:13:15 +00004045
4046 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004047 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00004048 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004049 Decimal('-1.00')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004050 >>> ExtendedContext.copy_decimal(1)
4051 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004052 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004053 a = _convert_other(a, raiseit=True)
Facundo Batista6c398da2007-09-17 17:30:13 +00004054 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00004055
4056 def copy_negate(self, a):
4057 """Returns a copy of the operand with the sign inverted.
4058
4059 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004060 Decimal('-101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00004061 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004062 Decimal('101.5')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004063 >>> ExtendedContext.copy_negate(1)
4064 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004065 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004066 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004067 return a.copy_negate()
4068
4069 def copy_sign(self, a, b):
4070 """Copies the second operand's sign to the first one.
4071
4072 In detail, it returns a copy of the first operand with the sign
4073 equal to the sign of the second operand.
4074
4075 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004076 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004077 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004078 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004079 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004080 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004081 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004082 Decimal('-1.50')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004083 >>> ExtendedContext.copy_sign(1, -2)
4084 Decimal('-1')
4085 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4086 Decimal('-1')
4087 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4088 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004089 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004090 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004091 return a.copy_sign(b)
4092
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004093 def divide(self, a, b):
4094 """Decimal division in a specified context.
4095
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004096 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004097 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004098 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004099 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004100 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004101 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004102 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004103 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004104 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004105 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004106 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004107 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004108 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004109 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004110 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004111 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004112 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004113 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004114 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004115 Decimal('1.20E+6')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004116 >>> ExtendedContext.divide(5, 5)
4117 Decimal('1')
4118 >>> ExtendedContext.divide(Decimal(5), 5)
4119 Decimal('1')
4120 >>> ExtendedContext.divide(5, Decimal(5))
4121 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004122 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004123 a = _convert_other(a, raiseit=True)
4124 r = a.__div__(b, context=self)
4125 if r is NotImplemented:
4126 raise TypeError("Unable to convert %s to Decimal" % b)
4127 else:
4128 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004129
4130 def divide_int(self, a, b):
4131 """Divides two numbers and returns the integer part of the result.
4132
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004133 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004134 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004135 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004136 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004137 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004138 Decimal('3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004139 >>> ExtendedContext.divide_int(10, 3)
4140 Decimal('3')
4141 >>> ExtendedContext.divide_int(Decimal(10), 3)
4142 Decimal('3')
4143 >>> ExtendedContext.divide_int(10, Decimal(3))
4144 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004145 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004146 a = _convert_other(a, raiseit=True)
4147 r = a.__floordiv__(b, context=self)
4148 if r is NotImplemented:
4149 raise TypeError("Unable to convert %s to Decimal" % b)
4150 else:
4151 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004152
4153 def divmod(self, a, b):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004154 """Return (a // b, a % b).
Mark Dickinson202eb902010-01-06 16:20:22 +00004155
4156 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4157 (Decimal('2'), Decimal('2'))
4158 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4159 (Decimal('2'), Decimal('0'))
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004160 >>> ExtendedContext.divmod(8, 4)
4161 (Decimal('2'), Decimal('0'))
4162 >>> ExtendedContext.divmod(Decimal(8), 4)
4163 (Decimal('2'), Decimal('0'))
4164 >>> ExtendedContext.divmod(8, Decimal(4))
4165 (Decimal('2'), Decimal('0'))
Mark Dickinson202eb902010-01-06 16:20:22 +00004166 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004167 a = _convert_other(a, raiseit=True)
4168 r = a.__divmod__(b, context=self)
4169 if r is NotImplemented:
4170 raise TypeError("Unable to convert %s to Decimal" % b)
4171 else:
4172 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004173
Facundo Batista353750c2007-09-13 18:13:15 +00004174 def exp(self, a):
4175 """Returns e ** a.
4176
4177 >>> c = ExtendedContext.copy()
4178 >>> c.Emin = -999
4179 >>> c.Emax = 999
4180 >>> c.exp(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004181 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004182 >>> c.exp(Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004183 Decimal('0.367879441')
Facundo Batista353750c2007-09-13 18:13:15 +00004184 >>> c.exp(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004185 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004186 >>> c.exp(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004187 Decimal('2.71828183')
Facundo Batista353750c2007-09-13 18:13:15 +00004188 >>> c.exp(Decimal('0.693147181'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004189 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004190 >>> c.exp(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004191 Decimal('Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004192 >>> c.exp(10)
4193 Decimal('22026.4658')
Facundo Batista353750c2007-09-13 18:13:15 +00004194 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004195 a =_convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004196 return a.exp(context=self)
4197
4198 def fma(self, a, b, c):
4199 """Returns a multiplied by b, plus c.
4200
4201 The first two operands are multiplied together, using multiply,
4202 the third operand is then added to the result of that
4203 multiplication, using add, all with only one final rounding.
4204
4205 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004206 Decimal('22')
Facundo Batista353750c2007-09-13 18:13:15 +00004207 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004208 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004209 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004210 Decimal('1.38435736E+12')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004211 >>> ExtendedContext.fma(1, 3, 4)
4212 Decimal('7')
4213 >>> ExtendedContext.fma(1, Decimal(3), 4)
4214 Decimal('7')
4215 >>> ExtendedContext.fma(1, 3, Decimal(4))
4216 Decimal('7')
Facundo Batista353750c2007-09-13 18:13:15 +00004217 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004218 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004219 return a.fma(b, c, context=self)
4220
4221 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004222 """Return True if the operand is canonical; otherwise return False.
4223
4224 Currently, the encoding of a Decimal instance is always
4225 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00004226
4227 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004228 True
Facundo Batista353750c2007-09-13 18:13:15 +00004229 """
Facundo Batista1a191df2007-10-02 17:01:24 +00004230 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00004231
4232 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004233 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004234
Facundo Batista1a191df2007-10-02 17:01:24 +00004235 A Decimal instance is considered finite if it is neither
4236 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00004237
4238 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004239 True
Facundo Batista353750c2007-09-13 18:13:15 +00004240 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004241 True
Facundo Batista353750c2007-09-13 18:13:15 +00004242 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004243 True
Facundo Batista353750c2007-09-13 18:13:15 +00004244 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004245 False
Facundo Batista353750c2007-09-13 18:13:15 +00004246 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004247 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004248 >>> ExtendedContext.is_finite(1)
4249 True
Facundo Batista353750c2007-09-13 18:13:15 +00004250 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004251 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004252 return a.is_finite()
4253
4254 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004255 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004256
4257 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004258 False
Facundo Batista353750c2007-09-13 18:13:15 +00004259 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004260 True
Facundo Batista353750c2007-09-13 18:13:15 +00004261 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004262 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004263 >>> ExtendedContext.is_infinite(1)
4264 False
Facundo Batista353750c2007-09-13 18:13:15 +00004265 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004266 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004267 return a.is_infinite()
4268
4269 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004270 """Return True if the operand is a qNaN or sNaN;
4271 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004272
4273 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004274 False
Facundo Batista353750c2007-09-13 18:13:15 +00004275 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004276 True
Facundo Batista353750c2007-09-13 18:13:15 +00004277 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004278 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004279 >>> ExtendedContext.is_nan(1)
4280 False
Facundo Batista353750c2007-09-13 18:13:15 +00004281 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004282 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004283 return a.is_nan()
4284
4285 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004286 """Return True if the operand is a normal number;
4287 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004288
4289 >>> c = ExtendedContext.copy()
4290 >>> c.Emin = -999
4291 >>> c.Emax = 999
4292 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004293 True
Facundo Batista353750c2007-09-13 18:13:15 +00004294 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004295 False
Facundo Batista353750c2007-09-13 18:13:15 +00004296 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004297 False
Facundo Batista353750c2007-09-13 18:13:15 +00004298 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004299 False
Facundo Batista353750c2007-09-13 18:13:15 +00004300 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004301 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004302 >>> c.is_normal(1)
4303 True
Facundo Batista353750c2007-09-13 18:13:15 +00004304 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004305 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004306 return a.is_normal(context=self)
4307
4308 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004309 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004310
4311 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004312 False
Facundo Batista353750c2007-09-13 18:13:15 +00004313 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004314 True
Facundo Batista353750c2007-09-13 18:13:15 +00004315 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004316 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004317 >>> ExtendedContext.is_qnan(1)
4318 False
Facundo Batista353750c2007-09-13 18:13:15 +00004319 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004320 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004321 return a.is_qnan()
4322
4323 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004324 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004325
4326 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004327 False
Facundo Batista353750c2007-09-13 18:13:15 +00004328 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004329 True
Facundo Batista353750c2007-09-13 18:13:15 +00004330 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004331 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004332 >>> ExtendedContext.is_signed(8)
4333 False
4334 >>> ExtendedContext.is_signed(-8)
4335 True
Facundo Batista353750c2007-09-13 18:13:15 +00004336 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004337 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004338 return a.is_signed()
4339
4340 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004341 """Return True if the operand is a signaling NaN;
4342 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004343
4344 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004345 False
Facundo Batista353750c2007-09-13 18:13:15 +00004346 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004347 False
Facundo Batista353750c2007-09-13 18:13:15 +00004348 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004349 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004350 >>> ExtendedContext.is_snan(1)
4351 False
Facundo Batista353750c2007-09-13 18:13:15 +00004352 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004353 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004354 return a.is_snan()
4355
4356 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004357 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004358
4359 >>> c = ExtendedContext.copy()
4360 >>> c.Emin = -999
4361 >>> c.Emax = 999
4362 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004363 False
Facundo Batista353750c2007-09-13 18:13:15 +00004364 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004365 True
Facundo Batista353750c2007-09-13 18:13:15 +00004366 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004367 False
Facundo Batista353750c2007-09-13 18:13:15 +00004368 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004369 False
Facundo Batista353750c2007-09-13 18:13:15 +00004370 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004371 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004372 >>> c.is_subnormal(1)
4373 False
Facundo Batista353750c2007-09-13 18:13:15 +00004374 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004375 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004376 return a.is_subnormal(context=self)
4377
4378 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004379 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004380
4381 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004382 True
Facundo Batista353750c2007-09-13 18:13:15 +00004383 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004384 False
Facundo Batista353750c2007-09-13 18:13:15 +00004385 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004386 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004387 >>> ExtendedContext.is_zero(1)
4388 False
4389 >>> ExtendedContext.is_zero(0)
4390 True
Facundo Batista353750c2007-09-13 18:13:15 +00004391 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004392 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004393 return a.is_zero()
4394
4395 def ln(self, a):
4396 """Returns the natural (base e) logarithm of the operand.
4397
4398 >>> c = ExtendedContext.copy()
4399 >>> c.Emin = -999
4400 >>> c.Emax = 999
4401 >>> c.ln(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004402 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004403 >>> c.ln(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004404 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004405 >>> c.ln(Decimal('2.71828183'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004406 Decimal('1.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004407 >>> c.ln(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004408 Decimal('2.30258509')
Facundo Batista353750c2007-09-13 18:13:15 +00004409 >>> c.ln(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004410 Decimal('Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004411 >>> c.ln(1)
4412 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004413 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004414 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004415 return a.ln(context=self)
4416
4417 def log10(self, a):
4418 """Returns the base 10 logarithm of the operand.
4419
4420 >>> c = ExtendedContext.copy()
4421 >>> c.Emin = -999
4422 >>> c.Emax = 999
4423 >>> c.log10(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004424 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004425 >>> c.log10(Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004426 Decimal('-3')
Facundo Batista353750c2007-09-13 18:13:15 +00004427 >>> c.log10(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004428 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004429 >>> c.log10(Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004430 Decimal('0.301029996')
Facundo Batista353750c2007-09-13 18:13:15 +00004431 >>> c.log10(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004432 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004433 >>> c.log10(Decimal('70'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004434 Decimal('1.84509804')
Facundo Batista353750c2007-09-13 18:13:15 +00004435 >>> c.log10(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004436 Decimal('Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004437 >>> c.log10(0)
4438 Decimal('-Infinity')
4439 >>> c.log10(1)
4440 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004441 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004442 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004443 return a.log10(context=self)
4444
4445 def logb(self, a):
4446 """ Returns the exponent of the magnitude of the operand's MSD.
4447
4448 The result is the integer which is the exponent of the magnitude
4449 of the most significant digit of the operand (as though the
4450 operand were truncated to a single digit while maintaining the
4451 value of that digit and without limiting the resulting exponent).
4452
4453 >>> ExtendedContext.logb(Decimal('250'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004454 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004455 >>> ExtendedContext.logb(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004456 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004457 >>> ExtendedContext.logb(Decimal('0.03'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004458 Decimal('-2')
Facundo Batista353750c2007-09-13 18:13:15 +00004459 >>> ExtendedContext.logb(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004460 Decimal('-Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004461 >>> ExtendedContext.logb(1)
4462 Decimal('0')
4463 >>> ExtendedContext.logb(10)
4464 Decimal('1')
4465 >>> ExtendedContext.logb(100)
4466 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004467 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004468 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004469 return a.logb(context=self)
4470
4471 def logical_and(self, a, b):
4472 """Applies the logical operation 'and' between each operand's digits.
4473
4474 The operands must be both logical numbers.
4475
4476 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004477 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004478 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004479 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004480 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004481 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004482 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004483 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004484 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004485 Decimal('1000')
Facundo Batista353750c2007-09-13 18:13:15 +00004486 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004487 Decimal('10')
Mark Dickinson456e1652010-02-18 14:45:33 +00004488 >>> ExtendedContext.logical_and(110, 1101)
4489 Decimal('100')
4490 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4491 Decimal('100')
4492 >>> ExtendedContext.logical_and(110, Decimal(1101))
4493 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004494 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004495 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004496 return a.logical_and(b, context=self)
4497
4498 def logical_invert(self, a):
4499 """Invert all the digits in the operand.
4500
4501 The operand must be a logical number.
4502
4503 >>> ExtendedContext.logical_invert(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004504 Decimal('111111111')
Facundo Batista353750c2007-09-13 18:13:15 +00004505 >>> ExtendedContext.logical_invert(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004506 Decimal('111111110')
Facundo Batista353750c2007-09-13 18:13:15 +00004507 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004508 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004509 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004510 Decimal('10101010')
Mark Dickinson456e1652010-02-18 14:45:33 +00004511 >>> ExtendedContext.logical_invert(1101)
4512 Decimal('111110010')
Facundo Batista353750c2007-09-13 18:13:15 +00004513 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004514 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004515 return a.logical_invert(context=self)
4516
4517 def logical_or(self, a, b):
4518 """Applies the logical operation 'or' between each operand's digits.
4519
4520 The operands must be both logical numbers.
4521
4522 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004523 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004524 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004525 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004526 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004527 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004528 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004529 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004530 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004531 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004532 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004533 Decimal('1110')
Mark Dickinson456e1652010-02-18 14:45:33 +00004534 >>> ExtendedContext.logical_or(110, 1101)
4535 Decimal('1111')
4536 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4537 Decimal('1111')
4538 >>> ExtendedContext.logical_or(110, Decimal(1101))
4539 Decimal('1111')
Facundo Batista353750c2007-09-13 18:13:15 +00004540 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004541 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004542 return a.logical_or(b, context=self)
4543
4544 def logical_xor(self, a, b):
4545 """Applies the logical operation 'xor' between each operand's digits.
4546
4547 The operands must be both logical numbers.
4548
4549 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004550 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004551 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004552 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004553 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004554 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004555 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004556 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004557 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004558 Decimal('110')
Facundo Batista353750c2007-09-13 18:13:15 +00004559 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004560 Decimal('1101')
Mark Dickinson456e1652010-02-18 14:45:33 +00004561 >>> ExtendedContext.logical_xor(110, 1101)
4562 Decimal('1011')
4563 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4564 Decimal('1011')
4565 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4566 Decimal('1011')
Facundo Batista353750c2007-09-13 18:13:15 +00004567 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004568 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004569 return a.logical_xor(b, context=self)
4570
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004571 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004572 """max compares two values numerically and returns the maximum.
4573
4574 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004575 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004576 operation. If they are numerically equal then the left-hand operand
4577 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004578 infinity) of the two operands is chosen as the result.
4579
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004580 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004581 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004582 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004583 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004584 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004585 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004586 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004587 Decimal('7')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004588 >>> ExtendedContext.max(1, 2)
4589 Decimal('2')
4590 >>> ExtendedContext.max(Decimal(1), 2)
4591 Decimal('2')
4592 >>> ExtendedContext.max(1, Decimal(2))
4593 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004594 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004595 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004596 return a.max(b, context=self)
4597
Facundo Batista353750c2007-09-13 18:13:15 +00004598 def max_mag(self, a, b):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004599 """Compares the values numerically with their sign ignored.
4600
4601 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4602 Decimal('7')
4603 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4604 Decimal('-10')
4605 >>> ExtendedContext.max_mag(1, -2)
4606 Decimal('-2')
4607 >>> ExtendedContext.max_mag(Decimal(1), -2)
4608 Decimal('-2')
4609 >>> ExtendedContext.max_mag(1, Decimal(-2))
4610 Decimal('-2')
4611 """
4612 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004613 return a.max_mag(b, context=self)
4614
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004615 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004616 """min compares two values numerically and returns the minimum.
4617
4618 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004619 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004620 operation. If they are numerically equal then the left-hand operand
4621 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004622 infinity) of the two operands is chosen as the result.
4623
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004624 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004625 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004626 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004627 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004628 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004629 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004630 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004631 Decimal('7')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004632 >>> ExtendedContext.min(1, 2)
4633 Decimal('1')
4634 >>> ExtendedContext.min(Decimal(1), 2)
4635 Decimal('1')
4636 >>> ExtendedContext.min(1, Decimal(29))
4637 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004638 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004639 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004640 return a.min(b, context=self)
4641
Facundo Batista353750c2007-09-13 18:13:15 +00004642 def min_mag(self, a, b):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004643 """Compares the values numerically with their sign ignored.
4644
4645 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4646 Decimal('-2')
4647 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4648 Decimal('-3')
4649 >>> ExtendedContext.min_mag(1, -2)
4650 Decimal('1')
4651 >>> ExtendedContext.min_mag(Decimal(1), -2)
4652 Decimal('1')
4653 >>> ExtendedContext.min_mag(1, Decimal(-2))
4654 Decimal('1')
4655 """
4656 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004657 return a.min_mag(b, context=self)
4658
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004659 def minus(self, a):
4660 """Minus corresponds to unary prefix minus in Python.
4661
4662 The operation is evaluated using the same rules as subtract; the
4663 operation minus(a) is calculated as subtract('0', a) where the '0'
4664 has the same exponent as the operand.
4665
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004666 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004667 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004668 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004669 Decimal('1.3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004670 >>> ExtendedContext.minus(1)
4671 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004672 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004673 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004674 return a.__neg__(context=self)
4675
4676 def multiply(self, a, b):
4677 """multiply multiplies two operands.
4678
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004679 If either operand is a special value then the general rules apply.
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004680 Otherwise, the operands are multiplied together
4681 ('long multiplication'), resulting in a number which may be as long as
4682 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004683
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004684 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004685 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004686 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004687 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004688 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004689 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004690 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004691 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004692 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004693 Decimal('4.28135971E+11')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004694 >>> ExtendedContext.multiply(7, 7)
4695 Decimal('49')
4696 >>> ExtendedContext.multiply(Decimal(7), 7)
4697 Decimal('49')
4698 >>> ExtendedContext.multiply(7, Decimal(7))
4699 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004700 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004701 a = _convert_other(a, raiseit=True)
4702 r = a.__mul__(b, context=self)
4703 if r is NotImplemented:
4704 raise TypeError("Unable to convert %s to Decimal" % b)
4705 else:
4706 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004707
Facundo Batista353750c2007-09-13 18:13:15 +00004708 def next_minus(self, a):
4709 """Returns the largest representable number smaller than a.
4710
4711 >>> c = ExtendedContext.copy()
4712 >>> c.Emin = -999
4713 >>> c.Emax = 999
4714 >>> ExtendedContext.next_minus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004715 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004716 >>> c.next_minus(Decimal('1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004717 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004718 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004719 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004720 >>> c.next_minus(Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004721 Decimal('9.99999999E+999')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004722 >>> c.next_minus(1)
4723 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004724 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004725 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004726 return a.next_minus(context=self)
4727
4728 def next_plus(self, a):
4729 """Returns the smallest representable number larger than a.
4730
4731 >>> c = ExtendedContext.copy()
4732 >>> c.Emin = -999
4733 >>> c.Emax = 999
4734 >>> ExtendedContext.next_plus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004735 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004736 >>> c.next_plus(Decimal('-1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004737 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004738 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004739 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004740 >>> c.next_plus(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004741 Decimal('-9.99999999E+999')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004742 >>> c.next_plus(1)
4743 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004744 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004745 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004746 return a.next_plus(context=self)
4747
4748 def next_toward(self, a, b):
4749 """Returns the number closest to a, in direction towards b.
4750
4751 The result is the closest representable number from the first
4752 operand (but not the first operand) that is in the direction
4753 towards the second operand, unless the operands have the same
4754 value.
4755
4756 >>> c = ExtendedContext.copy()
4757 >>> c.Emin = -999
4758 >>> c.Emax = 999
4759 >>> c.next_toward(Decimal('1'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004760 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004761 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004762 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004763 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004764 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004765 >>> c.next_toward(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004766 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004767 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004768 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004769 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004770 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004771 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004772 Decimal('-0.00')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004773 >>> c.next_toward(0, 1)
4774 Decimal('1E-1007')
4775 >>> c.next_toward(Decimal(0), 1)
4776 Decimal('1E-1007')
4777 >>> c.next_toward(0, Decimal(1))
4778 Decimal('1E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004779 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004780 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004781 return a.next_toward(b, context=self)
4782
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004783 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004784 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004785
4786 Essentially a plus operation with all trailing zeros removed from the
4787 result.
4788
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004789 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004790 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004791 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004792 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004793 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004794 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004795 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004796 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004797 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004798 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004799 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004800 Decimal('0')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004801 >>> ExtendedContext.normalize(6)
4802 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004803 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004804 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004805 return a.normalize(context=self)
4806
Facundo Batista353750c2007-09-13 18:13:15 +00004807 def number_class(self, a):
4808 """Returns an indication of the class of the operand.
4809
4810 The class is one of the following strings:
4811 -sNaN
4812 -NaN
4813 -Infinity
4814 -Normal
4815 -Subnormal
4816 -Zero
4817 +Zero
4818 +Subnormal
4819 +Normal
4820 +Infinity
4821
4822 >>> c = Context(ExtendedContext)
4823 >>> c.Emin = -999
4824 >>> c.Emax = 999
4825 >>> c.number_class(Decimal('Infinity'))
4826 '+Infinity'
4827 >>> c.number_class(Decimal('1E-10'))
4828 '+Normal'
4829 >>> c.number_class(Decimal('2.50'))
4830 '+Normal'
4831 >>> c.number_class(Decimal('0.1E-999'))
4832 '+Subnormal'
4833 >>> c.number_class(Decimal('0'))
4834 '+Zero'
4835 >>> c.number_class(Decimal('-0'))
4836 '-Zero'
4837 >>> c.number_class(Decimal('-0.1E-999'))
4838 '-Subnormal'
4839 >>> c.number_class(Decimal('-1E-10'))
4840 '-Normal'
4841 >>> c.number_class(Decimal('-2.50'))
4842 '-Normal'
4843 >>> c.number_class(Decimal('-Infinity'))
4844 '-Infinity'
4845 >>> c.number_class(Decimal('NaN'))
4846 'NaN'
4847 >>> c.number_class(Decimal('-NaN'))
4848 'NaN'
4849 >>> c.number_class(Decimal('sNaN'))
4850 'sNaN'
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004851 >>> c.number_class(123)
4852 '+Normal'
Facundo Batista353750c2007-09-13 18:13:15 +00004853 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004854 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004855 return a.number_class(context=self)
4856
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004857 def plus(self, a):
4858 """Plus corresponds to unary prefix plus in Python.
4859
4860 The operation is evaluated using the same rules as add; the
4861 operation plus(a) is calculated as add('0', a) where the '0'
4862 has the same exponent as the operand.
4863
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004864 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004865 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004866 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004867 Decimal('-1.3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004868 >>> ExtendedContext.plus(-1)
4869 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004870 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004871 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004872 return a.__pos__(context=self)
4873
4874 def power(self, a, b, modulo=None):
4875 """Raises a to the power of b, to modulo if given.
4876
Facundo Batista353750c2007-09-13 18:13:15 +00004877 With two arguments, compute a**b. If a is negative then b
4878 must be integral. The result will be inexact unless b is
4879 integral and the result is finite and can be expressed exactly
4880 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004881
Facundo Batista353750c2007-09-13 18:13:15 +00004882 With three arguments, compute (a**b) % modulo. For the
4883 three argument form, the following restrictions on the
4884 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004885
Facundo Batista353750c2007-09-13 18:13:15 +00004886 - all three arguments must be integral
4887 - b must be nonnegative
4888 - at least one of a or b must be nonzero
4889 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004890
Facundo Batista353750c2007-09-13 18:13:15 +00004891 The result of pow(a, b, modulo) is identical to the result
4892 that would be obtained by computing (a**b) % modulo with
4893 unbounded precision, but is computed more efficiently. It is
4894 always exact.
4895
4896 >>> c = ExtendedContext.copy()
4897 >>> c.Emin = -999
4898 >>> c.Emax = 999
4899 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004900 Decimal('8')
Facundo Batista353750c2007-09-13 18:13:15 +00004901 >>> c.power(Decimal('-2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004902 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004903 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004904 Decimal('0.125')
Facundo Batista353750c2007-09-13 18:13:15 +00004905 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004906 Decimal('69.7575744')
Facundo Batista353750c2007-09-13 18:13:15 +00004907 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004908 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004909 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004910 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004911 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004912 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004913 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004914 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004915 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004916 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004917 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004918 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004919 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004920 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004921 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004922 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004923 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004924 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00004925
4926 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004927 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004928 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004929 Decimal('-11')
Facundo Batista353750c2007-09-13 18:13:15 +00004930 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004931 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004932 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004933 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004934 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004935 Decimal('11729830')
Facundo Batista353750c2007-09-13 18:13:15 +00004936 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004937 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004938 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004939 Decimal('1')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004940 >>> ExtendedContext.power(7, 7)
4941 Decimal('823543')
4942 >>> ExtendedContext.power(Decimal(7), 7)
4943 Decimal('823543')
4944 >>> ExtendedContext.power(7, Decimal(7), 2)
4945 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004946 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004947 a = _convert_other(a, raiseit=True)
4948 r = a.__pow__(b, modulo, context=self)
4949 if r is NotImplemented:
4950 raise TypeError("Unable to convert %s to Decimal" % b)
4951 else:
4952 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004953
4954 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004955 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004956
4957 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004958 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004959 exponent is being increased), multiplied by a positive power of ten (if
4960 the exponent is being decreased), or is unchanged (if the exponent is
4961 already equal to that of the right-hand operand).
4962
4963 Unlike other operations, if the length of the coefficient after the
4964 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004965 operation condition is raised. This guarantees that, unless there is
4966 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004967 equal to that of the right-hand operand.
4968
4969 Also unlike other operations, quantize will never raise Underflow, even
4970 if the result is subnormal and inexact.
4971
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004972 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004973 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004974 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004975 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004976 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004977 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004978 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004979 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004980 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004981 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004982 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004983 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004984 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004985 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004986 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004987 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004988 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004989 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004990 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004991 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004992 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004993 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004994 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004995 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004996 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004997 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004998 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004999 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005000 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005001 Decimal('2E+2')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005002 >>> ExtendedContext.quantize(1, 2)
5003 Decimal('1')
5004 >>> ExtendedContext.quantize(Decimal(1), 2)
5005 Decimal('1')
5006 >>> ExtendedContext.quantize(1, Decimal(2))
5007 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005008 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005009 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005010 return a.quantize(b, context=self)
5011
Facundo Batista353750c2007-09-13 18:13:15 +00005012 def radix(self):
5013 """Just returns 10, as this is Decimal, :)
5014
5015 >>> ExtendedContext.radix()
Raymond Hettingerabe32372008-02-14 02:41:22 +00005016 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00005017 """
5018 return Decimal(10)
5019
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005020 def remainder(self, a, b):
5021 """Returns the remainder from integer division.
5022
5023 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00005024 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00005025 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00005026 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005027
5028 This operation will fail under the same conditions as integer division
5029 (that is, if integer division on the same two operands would fail, the
5030 remainder cannot be calculated).
5031
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005032 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005033 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005034 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005035 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005036 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005037 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005038 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005039 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005040 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005041 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005042 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005043 Decimal('1.0')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005044 >>> ExtendedContext.remainder(22, 6)
5045 Decimal('4')
5046 >>> ExtendedContext.remainder(Decimal(22), 6)
5047 Decimal('4')
5048 >>> ExtendedContext.remainder(22, Decimal(6))
5049 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005050 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005051 a = _convert_other(a, raiseit=True)
5052 r = a.__mod__(b, context=self)
5053 if r is NotImplemented:
5054 raise TypeError("Unable to convert %s to Decimal" % b)
5055 else:
5056 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005057
5058 def remainder_near(self, a, b):
5059 """Returns to be "a - b * n", where n is the integer nearest the exact
5060 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00005061 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005062 sign of a.
5063
5064 This operation will fail under the same conditions as integer division
5065 (that is, if integer division on the same two operands would fail, the
5066 remainder cannot be calculated).
5067
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005068 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005069 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005070 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005071 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005072 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005073 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005074 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005075 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005076 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005077 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005078 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005079 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005080 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005081 Decimal('-0.3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005082 >>> ExtendedContext.remainder_near(3, 11)
5083 Decimal('3')
5084 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5085 Decimal('3')
5086 >>> ExtendedContext.remainder_near(3, Decimal(11))
5087 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005088 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005089 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005090 return a.remainder_near(b, context=self)
5091
Facundo Batista353750c2007-09-13 18:13:15 +00005092 def rotate(self, a, b):
5093 """Returns a rotated copy of a, b times.
5094
5095 The coefficient of the result is a rotated copy of the digits in
5096 the coefficient of the first operand. The number of places of
5097 rotation is taken from the absolute value of the second operand,
5098 with the rotation being to the left if the second operand is
5099 positive or to the right otherwise.
5100
5101 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005102 Decimal('400000003')
Facundo Batista353750c2007-09-13 18:13:15 +00005103 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005104 Decimal('12')
Facundo Batista353750c2007-09-13 18:13:15 +00005105 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005106 Decimal('891234567')
Facundo Batista353750c2007-09-13 18:13:15 +00005107 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005108 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00005109 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005110 Decimal('345678912')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005111 >>> ExtendedContext.rotate(1333333, 1)
5112 Decimal('13333330')
5113 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5114 Decimal('13333330')
5115 >>> ExtendedContext.rotate(1333333, Decimal(1))
5116 Decimal('13333330')
Facundo Batista353750c2007-09-13 18:13:15 +00005117 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005118 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005119 return a.rotate(b, context=self)
5120
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005121 def same_quantum(self, a, b):
5122 """Returns True if the two operands have the same exponent.
5123
5124 The result is never affected by either the sign or the coefficient of
5125 either operand.
5126
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005127 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005128 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005129 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005130 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005131 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005132 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005133 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005134 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005135 >>> ExtendedContext.same_quantum(10000, -1)
5136 True
5137 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5138 True
5139 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5140 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005141 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005142 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005143 return a.same_quantum(b)
5144
Facundo Batista353750c2007-09-13 18:13:15 +00005145 def scaleb (self, a, b):
5146 """Returns the first operand after adding the second value its exp.
5147
5148 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005149 Decimal('0.0750')
Facundo Batista353750c2007-09-13 18:13:15 +00005150 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005151 Decimal('7.50')
Facundo Batista353750c2007-09-13 18:13:15 +00005152 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005153 Decimal('7.50E+3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005154 >>> ExtendedContext.scaleb(1, 4)
5155 Decimal('1E+4')
5156 >>> ExtendedContext.scaleb(Decimal(1), 4)
5157 Decimal('1E+4')
5158 >>> ExtendedContext.scaleb(1, Decimal(4))
5159 Decimal('1E+4')
Facundo Batista353750c2007-09-13 18:13:15 +00005160 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005161 a = _convert_other(a, raiseit=True)
5162 return a.scaleb(b, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00005163
5164 def shift(self, a, b):
5165 """Returns a shifted copy of a, b times.
5166
5167 The coefficient of the result is a shifted copy of the digits
5168 in the coefficient of the first operand. The number of places
5169 to shift is taken from the absolute value of the second operand,
5170 with the shift being to the left if the second operand is
5171 positive or to the right otherwise. Digits shifted into the
5172 coefficient are zeros.
5173
5174 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005175 Decimal('400000000')
Facundo Batista353750c2007-09-13 18:13:15 +00005176 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005177 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00005178 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005179 Decimal('1234567')
Facundo Batista353750c2007-09-13 18:13:15 +00005180 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005181 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00005182 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005183 Decimal('345678900')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005184 >>> ExtendedContext.shift(88888888, 2)
5185 Decimal('888888800')
5186 >>> ExtendedContext.shift(Decimal(88888888), 2)
5187 Decimal('888888800')
5188 >>> ExtendedContext.shift(88888888, Decimal(2))
5189 Decimal('888888800')
Facundo Batista353750c2007-09-13 18:13:15 +00005190 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005191 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005192 return a.shift(b, context=self)
5193
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005194 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00005195 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005196
5197 If the result must be inexact, it is rounded using the round-half-even
5198 algorithm.
5199
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005200 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005201 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005202 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005203 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005204 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005205 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005206 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005207 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005208 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005209 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005210 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005211 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005212 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005213 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005214 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005215 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005216 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005217 Decimal('3.16227766')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005218 >>> ExtendedContext.sqrt(2)
5219 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005220 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005221 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005222 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005223 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005224 return a.sqrt(context=self)
5225
5226 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005227 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005228
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005229 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005230 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005231 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005232 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005233 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005234 Decimal('-0.77')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005235 >>> ExtendedContext.subtract(8, 5)
5236 Decimal('3')
5237 >>> ExtendedContext.subtract(Decimal(8), 5)
5238 Decimal('3')
5239 >>> ExtendedContext.subtract(8, Decimal(5))
5240 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005241 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005242 a = _convert_other(a, raiseit=True)
5243 r = a.__sub__(b, context=self)
5244 if r is NotImplemented:
5245 raise TypeError("Unable to convert %s to Decimal" % b)
5246 else:
5247 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005248
5249 def to_eng_string(self, a):
5250 """Converts a number to a string, using scientific notation.
5251
5252 The operation is not affected by the context.
5253 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005254 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005255 return a.to_eng_string(context=self)
5256
5257 def to_sci_string(self, a):
5258 """Converts a number to a string, using scientific notation.
5259
5260 The operation is not affected by the context.
5261 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005262 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005263 return a.__str__(context=self)
5264
Facundo Batista353750c2007-09-13 18:13:15 +00005265 def to_integral_exact(self, a):
5266 """Rounds to an integer.
5267
5268 When the operand has a negative exponent, the result is the same
5269 as using the quantize() operation using the given operand as the
5270 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5271 of the operand as the precision setting; Inexact and Rounded flags
5272 are allowed in this operation. The rounding mode is taken from the
5273 context.
5274
5275 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005276 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00005277 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005278 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005279 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005280 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005281 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005282 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00005283 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005284 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00005285 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005286 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00005287 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005288 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00005289 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005290 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00005291 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005292 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005293 return a.to_integral_exact(context=self)
5294
5295 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005296 """Rounds to an integer.
5297
5298 When the operand has a negative exponent, the result is the same
5299 as using the quantize() operation using the given operand as the
5300 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5301 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00005302 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005303
Facundo Batista353750c2007-09-13 18:13:15 +00005304 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005305 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00005306 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005307 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005308 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005309 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005310 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005311 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00005312 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005313 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00005314 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005315 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00005316 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005317 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00005318 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005319 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005320 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005321 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005322 return a.to_integral_value(context=self)
5323
5324 # the method name changed, but we provide also the old one, for compatibility
5325 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005326
5327class _WorkRep(object):
5328 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005329 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005330 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005331 # exp: None, int, or string
5332
5333 def __init__(self, value=None):
5334 if value is None:
5335 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005336 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005337 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005338 elif isinstance(value, Decimal):
5339 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00005340 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005341 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005342 else:
5343 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005344 self.sign = value[0]
5345 self.int = value[1]
5346 self.exp = value[2]
5347
5348 def __repr__(self):
5349 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5350
5351 __str__ = __repr__
5352
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005353
5354
Facundo Batistae64acfa2007-12-17 14:18:42 +00005355def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005356 """Normalizes op1, op2 to have the same exp and length of coefficient.
5357
5358 Done during addition.
5359 """
Facundo Batista353750c2007-09-13 18:13:15 +00005360 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005361 tmp = op2
5362 other = op1
5363 else:
5364 tmp = op1
5365 other = op2
5366
Facundo Batista353750c2007-09-13 18:13:15 +00005367 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5368 # Then adding 10**exp to tmp has the same effect (after rounding)
5369 # as adding any positive quantity smaller than 10**exp; similarly
5370 # for subtraction. So if other is smaller than 10**exp we replace
5371 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00005372 tmp_len = len(str(tmp.int))
5373 other_len = len(str(other.int))
5374 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5375 if other_len + other.exp - 1 < exp:
5376 other.int = 1
5377 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005378
Facundo Batista353750c2007-09-13 18:13:15 +00005379 tmp.int *= 10 ** (tmp.exp - other.exp)
5380 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005381 return op1, op2
5382
Facundo Batista353750c2007-09-13 18:13:15 +00005383##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
5384
5385# This function from Tim Peters was taken from here:
5386# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5387# The correction being in the function definition is for speed, and
5388# the whole function is not resolved with math.log because of avoiding
5389# the use of floats.
5390def _nbits(n, correction = {
5391 '0': 4, '1': 3, '2': 2, '3': 2,
5392 '4': 1, '5': 1, '6': 1, '7': 1,
5393 '8': 0, '9': 0, 'a': 0, 'b': 0,
5394 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5395 """Number of bits in binary representation of the positive integer n,
5396 or 0 if n == 0.
5397 """
5398 if n < 0:
5399 raise ValueError("The argument to _nbits should be nonnegative.")
5400 hex_n = "%x" % n
5401 return 4*len(hex_n) - correction[hex_n[0]]
5402
5403def _sqrt_nearest(n, a):
5404 """Closest integer to the square root of the positive integer n. a is
5405 an initial approximation to the square root. Any positive integer
5406 will do for a, but the closer a is to the square root of n the
5407 faster convergence will be.
5408
5409 """
5410 if n <= 0 or a <= 0:
5411 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5412
5413 b=0
5414 while a != b:
5415 b, a = a, a--n//a>>1
5416 return a
5417
5418def _rshift_nearest(x, shift):
5419 """Given an integer x and a nonnegative integer shift, return closest
5420 integer to x / 2**shift; use round-to-even in case of a tie.
5421
5422 """
5423 b, q = 1L << shift, x >> shift
5424 return q + (2*(x & (b-1)) + (q&1) > b)
5425
5426def _div_nearest(a, b):
5427 """Closest integer to a/b, a and b positive integers; rounds to even
5428 in the case of a tie.
5429
5430 """
5431 q, r = divmod(a, b)
5432 return q + (2*r + (q&1) > b)
5433
5434def _ilog(x, M, L = 8):
5435 """Integer approximation to M*log(x/M), with absolute error boundable
5436 in terms only of x/M.
5437
5438 Given positive integers x and M, return an integer approximation to
5439 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5440 between the approximation and the exact result is at most 22. For
5441 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5442 both cases these are upper bounds on the error; it will usually be
5443 much smaller."""
5444
5445 # The basic algorithm is the following: let log1p be the function
5446 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5447 # the reduction
5448 #
5449 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5450 #
5451 # repeatedly until the argument to log1p is small (< 2**-L in
5452 # absolute value). For small y we can use the Taylor series
5453 # expansion
5454 #
5455 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5456 #
5457 # truncating at T such that y**T is small enough. The whole
5458 # computation is carried out in a form of fixed-point arithmetic,
5459 # with a real number z being represented by an integer
5460 # approximation to z*M. To avoid loss of precision, the y below
5461 # is actually an integer approximation to 2**R*y*M, where R is the
5462 # number of reductions performed so far.
5463
5464 y = x-M
5465 # argument reduction; R = number of reductions performed
5466 R = 0
5467 while (R <= L and long(abs(y)) << L-R >= M or
5468 R > L and abs(y) >> R-L >= M):
5469 y = _div_nearest(long(M*y) << 1,
5470 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5471 R += 1
5472
5473 # Taylor series with T terms
5474 T = -int(-10*len(str(M))//(3*L))
5475 yshift = _rshift_nearest(y, R)
5476 w = _div_nearest(M, T)
5477 for k in xrange(T-1, 0, -1):
5478 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5479
5480 return _div_nearest(w*y, M)
5481
5482def _dlog10(c, e, p):
5483 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5484 approximation to 10**p * log10(c*10**e), with an absolute error of
5485 at most 1. Assumes that c*10**e is not exactly 1."""
5486
5487 # increase precision by 2; compensate for this by dividing
5488 # final result by 100
5489 p += 2
5490
5491 # write c*10**e as d*10**f with either:
5492 # f >= 0 and 1 <= d <= 10, or
5493 # f <= 0 and 0.1 <= d <= 1.
5494 # Thus for c*10**e close to 1, f = 0
5495 l = len(str(c))
5496 f = e+l - (e+l >= 1)
5497
5498 if p > 0:
5499 M = 10**p
5500 k = e+p-f
5501 if k >= 0:
5502 c *= 10**k
5503 else:
5504 c = _div_nearest(c, 10**-k)
5505
5506 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005507 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005508 log_d = _div_nearest(log_d*M, log_10)
5509 log_tenpower = f*M # exact
5510 else:
5511 log_d = 0 # error < 2.31
Neal Norwitz18aa3882008-08-24 05:04:52 +00005512 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Facundo Batista353750c2007-09-13 18:13:15 +00005513
5514 return _div_nearest(log_tenpower+log_d, 100)
5515
5516def _dlog(c, e, p):
5517 """Given integers c, e and p with c > 0, compute an integer
5518 approximation to 10**p * log(c*10**e), with an absolute error of
5519 at most 1. Assumes that c*10**e is not exactly 1."""
5520
5521 # Increase precision by 2. The precision increase is compensated
5522 # for at the end with a division by 100.
5523 p += 2
5524
5525 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5526 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5527 # as 10**p * log(d) + 10**p*f * log(10).
5528 l = len(str(c))
5529 f = e+l - (e+l >= 1)
5530
5531 # compute approximation to 10**p*log(d), with error < 27
5532 if p > 0:
5533 k = e+p-f
5534 if k >= 0:
5535 c *= 10**k
5536 else:
5537 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5538
5539 # _ilog magnifies existing error in c by a factor of at most 10
5540 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5541 else:
5542 # p <= 0: just approximate the whole thing by 0; error < 2.31
5543 log_d = 0
5544
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005545 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00005546 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005547 extra = len(str(abs(f)))-1
5548 if p + extra >= 0:
5549 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5550 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5551 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00005552 else:
5553 f_log_ten = 0
5554 else:
5555 f_log_ten = 0
5556
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005557 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005558 return _div_nearest(f_log_ten + log_d, 100)
5559
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005560class _Log10Memoize(object):
5561 """Class to compute, store, and allow retrieval of, digits of the
5562 constant log(10) = 2.302585.... This constant is needed by
5563 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5564 def __init__(self):
5565 self.digits = "23025850929940456840179914546843642076011014886"
5566
5567 def getdigits(self, p):
5568 """Given an integer p >= 0, return floor(10**p)*log(10).
5569
5570 For example, self.getdigits(3) returns 2302.
5571 """
5572 # digits are stored as a string, for quick conversion to
5573 # integer in the case that we've already computed enough
5574 # digits; the stored digits should always be correct
5575 # (truncated, not rounded to nearest).
5576 if p < 0:
5577 raise ValueError("p should be nonnegative")
5578
5579 if p >= len(self.digits):
5580 # compute p+3, p+6, p+9, ... digits; continue until at
5581 # least one of the extra digits is nonzero
5582 extra = 3
5583 while True:
5584 # compute p+extra digits, correct to within 1ulp
5585 M = 10**(p+extra+2)
5586 digits = str(_div_nearest(_ilog(10*M, M), 100))
5587 if digits[-extra:] != '0'*extra:
5588 break
5589 extra += 3
5590 # keep all reliable digits so far; remove trailing zeros
5591 # and next nonzero digit
5592 self.digits = digits.rstrip('0')[:-1]
5593 return int(self.digits[:p+1])
5594
5595_log10_digits = _Log10Memoize().getdigits
5596
Facundo Batista353750c2007-09-13 18:13:15 +00005597def _iexp(x, M, L=8):
5598 """Given integers x and M, M > 0, such that x/M is small in absolute
5599 value, compute an integer approximation to M*exp(x/M). For 0 <=
5600 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5601 is usually much smaller)."""
5602
5603 # Algorithm: to compute exp(z) for a real number z, first divide z
5604 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5605 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5606 # series
5607 #
5608 # expm1(x) = x + x**2/2! + x**3/3! + ...
5609 #
5610 # Now use the identity
5611 #
5612 # expm1(2x) = expm1(x)*(expm1(x)+2)
5613 #
5614 # R times to compute the sequence expm1(z/2**R),
5615 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5616
5617 # Find R such that x/2**R/M <= 2**-L
5618 R = _nbits((long(x)<<L)//M)
5619
5620 # Taylor series. (2**L)**T > M
5621 T = -int(-10*len(str(M))//(3*L))
5622 y = _div_nearest(x, T)
5623 Mshift = long(M)<<R
5624 for i in xrange(T-1, 0, -1):
5625 y = _div_nearest(x*(Mshift + y), Mshift * i)
5626
5627 # Expansion
5628 for k in xrange(R-1, -1, -1):
5629 Mshift = long(M)<<(k+2)
5630 y = _div_nearest(y*(y+Mshift), Mshift)
5631
5632 return M+y
5633
5634def _dexp(c, e, p):
5635 """Compute an approximation to exp(c*10**e), with p decimal places of
5636 precision.
5637
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005638 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005639
5640 10**(p-1) <= d <= 10**p, and
5641 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5642
5643 In other words, d*10**f is an approximation to exp(c*10**e) with p
5644 digits of precision, and with an error in d of at most 1. This is
5645 almost, but not quite, the same as the error being < 1ulp: when d
5646 = 10**(p-1) the error could be up to 10 ulp."""
5647
5648 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5649 p += 2
5650
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005651 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005652 extra = max(0, e + len(str(c)) - 1)
5653 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005654
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005655 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005656 # rounding down
5657 shift = e+q
5658 if shift >= 0:
5659 cshift = c*10**shift
5660 else:
5661 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005662 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005663
5664 # reduce remainder back to original precision
5665 rem = _div_nearest(rem, 10**extra)
5666
5667 # error in result of _iexp < 120; error after division < 0.62
5668 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5669
5670def _dpower(xc, xe, yc, ye, p):
5671 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5672 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5673
5674 10**(p-1) <= c <= 10**p, and
5675 (c-1)*10**e < x**y < (c+1)*10**e
5676
5677 in other words, c*10**e is an approximation to x**y with p digits
5678 of precision, and with an error in c of at most 1. (This is
5679 almost, but not quite, the same as the error being < 1ulp: when c
5680 == 10**(p-1) we can only guarantee error < 10ulp.)
5681
5682 We assume that: x is positive and not equal to 1, and y is nonzero.
5683 """
5684
5685 # Find b such that 10**(b-1) <= |y| <= 10**b
5686 b = len(str(abs(yc))) + ye
5687
5688 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5689 lxc = _dlog(xc, xe, p+b+1)
5690
5691 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5692 shift = ye-b
5693 if shift >= 0:
5694 pc = lxc*yc*10**shift
5695 else:
5696 pc = _div_nearest(lxc*yc, 10**-shift)
5697
5698 if pc == 0:
5699 # we prefer a result that isn't exactly 1; this makes it
5700 # easier to compute a correctly rounded result in __pow__
5701 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5702 coeff, exp = 10**(p-1)+1, 1-p
5703 else:
5704 coeff, exp = 10**p-1, -p
5705 else:
5706 coeff, exp = _dexp(pc, -(p+1), p+1)
5707 coeff = _div_nearest(coeff, 10)
5708 exp += 1
5709
5710 return coeff, exp
5711
5712def _log10_lb(c, correction = {
5713 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5714 '6': 23, '7': 16, '8': 10, '9': 5}):
5715 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5716 if c <= 0:
5717 raise ValueError("The argument to _log10_lb should be nonnegative.")
5718 str_c = str(c)
5719 return 100*len(str_c) - correction[str_c[0]]
5720
Facundo Batista59c58842007-04-10 12:58:45 +00005721##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005722
Mark Dickinson99d80962010-04-02 08:53:22 +00005723def _convert_other(other, raiseit=False, allow_float=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005724 """Convert other to Decimal.
5725
5726 Verifies that it's ok to use in an implicit construction.
Mark Dickinson99d80962010-04-02 08:53:22 +00005727 If allow_float is true, allow conversion from float; this
5728 is used in the comparison methods (__eq__ and friends).
5729
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005730 """
5731 if isinstance(other, Decimal):
5732 return other
5733 if isinstance(other, (int, long)):
5734 return Decimal(other)
Mark Dickinson99d80962010-04-02 08:53:22 +00005735 if allow_float and isinstance(other, float):
5736 return Decimal.from_float(other)
5737
Facundo Batista353750c2007-09-13 18:13:15 +00005738 if raiseit:
5739 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005740 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005741
Facundo Batista59c58842007-04-10 12:58:45 +00005742##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005743
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005744# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005745# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005746
5747DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005748 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005749 traps=[DivisionByZero, Overflow, InvalidOperation],
5750 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005751 Emax=999999999,
5752 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005753 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005754)
5755
5756# Pre-made alternate contexts offered by the specification
5757# Don't change these; the user should be able to select these
5758# contexts and be able to reproduce results from other implementations
5759# of the spec.
5760
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005761BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005762 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005763 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5764 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005765)
5766
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005767ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005768 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005769 traps=[],
5770 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005771)
5772
5773
Facundo Batista72bc54f2007-11-23 17:59:00 +00005774##### crud for parsing strings #############################################
Mark Dickinson6a123cb2008-02-24 18:12:36 +00005775#
Facundo Batista72bc54f2007-11-23 17:59:00 +00005776# Regular expression used for parsing numeric strings. Additional
5777# comments:
5778#
5779# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5780# whitespace. But note that the specification disallows whitespace in
5781# a numeric string.
5782#
5783# 2. For finite numbers (not infinities and NaNs) the body of the
5784# number between the optional sign and the optional exponent must have
5785# at least one decimal digit, possibly after the decimal point. The
5786# lookahead expression '(?=\d|\.\d)' checks this.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005787
5788import re
Mark Dickinson70c32892008-07-02 09:37:01 +00005789_parser = re.compile(r""" # A numeric string consists of:
Facundo Batista72bc54f2007-11-23 17:59:00 +00005790# \s*
Mark Dickinson70c32892008-07-02 09:37:01 +00005791 (?P<sign>[-+])? # an optional sign, followed by either...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005792 (
Mark Dickinson4326ad82009-08-02 10:59:36 +00005793 (?=\d|\.\d) # ...a number (with at least one digit)
5794 (?P<int>\d*) # having a (possibly empty) integer part
5795 (\.(?P<frac>\d*))? # followed by an optional fractional part
5796 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005797 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005798 Inf(inity)? # ...an infinity, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005799 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005800 (?P<signal>s)? # ...an (optionally signaling)
5801 NaN # NaN
Mark Dickinson4326ad82009-08-02 10:59:36 +00005802 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005803 )
5804# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005805 \Z
Mark Dickinson4326ad82009-08-02 10:59:36 +00005806""", re.VERBOSE | re.IGNORECASE | re.UNICODE).match
Facundo Batista72bc54f2007-11-23 17:59:00 +00005807
Facundo Batista2ec74152007-12-03 17:55:00 +00005808_all_zeros = re.compile('0*$').match
5809_exact_half = re.compile('50*$').match
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005810
5811##### PEP3101 support functions ##############################################
Mark Dickinson277859d2009-03-17 23:03:46 +00005812# The functions in this section have little to do with the Decimal
5813# class, and could potentially be reused or adapted for other pure
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005814# Python numeric classes that want to implement __format__
5815#
5816# A format specifier for Decimal looks like:
5817#
Mark Dickinson277859d2009-03-17 23:03:46 +00005818# [[fill]align][sign][0][minimumwidth][,][.precision][type]
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005819
5820_parse_format_specifier_regex = re.compile(r"""\A
5821(?:
5822 (?P<fill>.)?
5823 (?P<align>[<>=^])
5824)?
5825(?P<sign>[-+ ])?
5826(?P<zeropad>0)?
5827(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson277859d2009-03-17 23:03:46 +00005828(?P<thousands_sep>,)?
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005829(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson277859d2009-03-17 23:03:46 +00005830(?P<type>[eEfFgGn%])?
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005831\Z
5832""", re.VERBOSE)
5833
Facundo Batista72bc54f2007-11-23 17:59:00 +00005834del re
5835
Mark Dickinson277859d2009-03-17 23:03:46 +00005836# The locale module is only needed for the 'n' format specifier. The
5837# rest of the PEP 3101 code functions quite happily without it, so we
5838# don't care too much if locale isn't present.
5839try:
5840 import locale as _locale
5841except ImportError:
5842 pass
5843
5844def _parse_format_specifier(format_spec, _localeconv=None):
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005845 """Parse and validate a format specifier.
5846
5847 Turns a standard numeric format specifier into a dict, with the
5848 following entries:
5849
5850 fill: fill character to pad field to minimum width
5851 align: alignment type, either '<', '>', '=' or '^'
5852 sign: either '+', '-' or ' '
5853 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson277859d2009-03-17 23:03:46 +00005854 zeropad: boolean, indicating whether to pad with zeros
5855 thousands_sep: string to use as thousands separator, or ''
5856 grouping: grouping for thousands separators, in format
5857 used by localeconv
5858 decimal_point: string to use for decimal point
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005859 precision: nonnegative integer giving precision, or None
5860 type: one of the characters 'eEfFgG%', or None
Mark Dickinson277859d2009-03-17 23:03:46 +00005861 unicode: boolean (always True for Python 3.x)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005862
5863 """
5864 m = _parse_format_specifier_regex.match(format_spec)
5865 if m is None:
5866 raise ValueError("Invalid format specifier: " + format_spec)
5867
5868 # get the dictionary
5869 format_dict = m.groupdict()
5870
Mark Dickinson277859d2009-03-17 23:03:46 +00005871 # zeropad; defaults for fill and alignment. If zero padding
5872 # is requested, the fill and align fields should be absent.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005873 fill = format_dict['fill']
5874 align = format_dict['align']
Mark Dickinson277859d2009-03-17 23:03:46 +00005875 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
5876 if format_dict['zeropad']:
5877 if fill is not None:
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005878 raise ValueError("Fill character conflicts with '0'"
5879 " in format specifier: " + format_spec)
Mark Dickinson277859d2009-03-17 23:03:46 +00005880 if align is not None:
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005881 raise ValueError("Alignment conflicts with '0' in "
5882 "format specifier: " + format_spec)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005883 format_dict['fill'] = fill or ' '
Mark Dickinson5cfa8042009-09-08 20:20:19 +00005884 # PEP 3101 originally specified that the default alignment should
5885 # be left; it was later agreed that right-aligned makes more sense
5886 # for numeric types. See http://bugs.python.org/issue6857.
5887 format_dict['align'] = align or '>'
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005888
Mark Dickinson277859d2009-03-17 23:03:46 +00005889 # default sign handling: '-' for negative, '' for positive
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005890 if format_dict['sign'] is None:
5891 format_dict['sign'] = '-'
5892
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005893 # minimumwidth defaults to 0; precision remains None if not given
5894 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5895 if format_dict['precision'] is not None:
5896 format_dict['precision'] = int(format_dict['precision'])
5897
5898 # if format type is 'g' or 'G' then a precision of 0 makes little
5899 # sense; convert it to 1. Same if format type is unspecified.
5900 if format_dict['precision'] == 0:
Mark Dickinson491ea552009-09-07 16:17:41 +00005901 if format_dict['type'] is None or format_dict['type'] in 'gG':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005902 format_dict['precision'] = 1
5903
Mark Dickinson277859d2009-03-17 23:03:46 +00005904 # determine thousands separator, grouping, and decimal separator, and
5905 # add appropriate entries to format_dict
5906 if format_dict['type'] == 'n':
5907 # apart from separators, 'n' behaves just like 'g'
5908 format_dict['type'] = 'g'
5909 if _localeconv is None:
5910 _localeconv = _locale.localeconv()
5911 if format_dict['thousands_sep'] is not None:
5912 raise ValueError("Explicit thousands separator conflicts with "
5913 "'n' type in format specifier: " + format_spec)
5914 format_dict['thousands_sep'] = _localeconv['thousands_sep']
5915 format_dict['grouping'] = _localeconv['grouping']
5916 format_dict['decimal_point'] = _localeconv['decimal_point']
5917 else:
5918 if format_dict['thousands_sep'] is None:
5919 format_dict['thousands_sep'] = ''
5920 format_dict['grouping'] = [3, 0]
5921 format_dict['decimal_point'] = '.'
5922
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005923 # record whether return type should be str or unicode
5924 format_dict['unicode'] = isinstance(format_spec, unicode)
5925
5926 return format_dict
5927
Mark Dickinson277859d2009-03-17 23:03:46 +00005928def _format_align(sign, body, spec):
5929 """Given an unpadded, non-aligned numeric string 'body' and sign
5930 string 'sign', add padding and aligment conforming to the given
5931 format specifier dictionary 'spec' (as produced by
5932 parse_format_specifier).
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005933
Mark Dickinson277859d2009-03-17 23:03:46 +00005934 Also converts result to unicode if necessary.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005935
5936 """
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005937 # how much extra space do we have to play with?
Mark Dickinson277859d2009-03-17 23:03:46 +00005938 minimumwidth = spec['minimumwidth']
5939 fill = spec['fill']
5940 padding = fill*(minimumwidth - len(sign) - len(body))
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005941
Mark Dickinson277859d2009-03-17 23:03:46 +00005942 align = spec['align']
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005943 if align == '<':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005944 result = sign + body + padding
Mark Dickinsonb065e522009-03-17 18:01:03 +00005945 elif align == '>':
5946 result = padding + sign + body
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005947 elif align == '=':
5948 result = sign + padding + body
Mark Dickinson277859d2009-03-17 23:03:46 +00005949 elif align == '^':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005950 half = len(padding)//2
5951 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson277859d2009-03-17 23:03:46 +00005952 else:
5953 raise ValueError('Unrecognised alignment field')
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005954
5955 # make sure that result is unicode if necessary
Mark Dickinson277859d2009-03-17 23:03:46 +00005956 if spec['unicode']:
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005957 result = unicode(result)
5958
5959 return result
Facundo Batista72bc54f2007-11-23 17:59:00 +00005960
Mark Dickinson277859d2009-03-17 23:03:46 +00005961def _group_lengths(grouping):
5962 """Convert a localeconv-style grouping into a (possibly infinite)
5963 iterable of integers representing group lengths.
5964
5965 """
5966 # The result from localeconv()['grouping'], and the input to this
5967 # function, should be a list of integers in one of the
5968 # following three forms:
5969 #
5970 # (1) an empty list, or
5971 # (2) nonempty list of positive integers + [0]
5972 # (3) list of positive integers + [locale.CHAR_MAX], or
5973
5974 from itertools import chain, repeat
5975 if not grouping:
5976 return []
5977 elif grouping[-1] == 0 and len(grouping) >= 2:
5978 return chain(grouping[:-1], repeat(grouping[-2]))
5979 elif grouping[-1] == _locale.CHAR_MAX:
5980 return grouping[:-1]
5981 else:
5982 raise ValueError('unrecognised format for grouping')
5983
5984def _insert_thousands_sep(digits, spec, min_width=1):
5985 """Insert thousands separators into a digit string.
5986
5987 spec is a dictionary whose keys should include 'thousands_sep' and
5988 'grouping'; typically it's the result of parsing the format
5989 specifier using _parse_format_specifier.
5990
5991 The min_width keyword argument gives the minimum length of the
5992 result, which will be padded on the left with zeros if necessary.
5993
5994 If necessary, the zero padding adds an extra '0' on the left to
5995 avoid a leading thousands separator. For example, inserting
5996 commas every three digits in '123456', with min_width=8, gives
5997 '0,123,456', even though that has length 9.
5998
5999 """
6000
6001 sep = spec['thousands_sep']
6002 grouping = spec['grouping']
6003
6004 groups = []
6005 for l in _group_lengths(grouping):
Mark Dickinson277859d2009-03-17 23:03:46 +00006006 if l <= 0:
6007 raise ValueError("group length should be positive")
6008 # max(..., 1) forces at least 1 digit to the left of a separator
6009 l = min(max(len(digits), min_width, 1), l)
6010 groups.append('0'*(l - len(digits)) + digits[-l:])
6011 digits = digits[:-l]
6012 min_width -= l
6013 if not digits and min_width <= 0:
6014 break
Mark Dickinsonb14514a2009-03-18 08:22:51 +00006015 min_width -= len(sep)
Mark Dickinson277859d2009-03-17 23:03:46 +00006016 else:
6017 l = max(len(digits), min_width, 1)
6018 groups.append('0'*(l - len(digits)) + digits[-l:])
6019 return sep.join(reversed(groups))
6020
6021def _format_sign(is_negative, spec):
6022 """Determine sign character."""
6023
6024 if is_negative:
6025 return '-'
6026 elif spec['sign'] in ' +':
6027 return spec['sign']
6028 else:
6029 return ''
6030
6031def _format_number(is_negative, intpart, fracpart, exp, spec):
6032 """Format a number, given the following data:
6033
6034 is_negative: true if the number is negative, else false
6035 intpart: string of digits that must appear before the decimal point
6036 fracpart: string of digits that must come after the point
6037 exp: exponent, as an integer
6038 spec: dictionary resulting from parsing the format specifier
6039
6040 This function uses the information in spec to:
6041 insert separators (decimal separator and thousands separators)
6042 format the sign
6043 format the exponent
6044 add trailing '%' for the '%' type
6045 zero-pad if necessary
6046 fill and align if necessary
6047 """
6048
6049 sign = _format_sign(is_negative, spec)
6050
6051 if fracpart:
6052 fracpart = spec['decimal_point'] + fracpart
6053
6054 if exp != 0 or spec['type'] in 'eE':
6055 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6056 fracpart += "{0}{1:+}".format(echar, exp)
6057 if spec['type'] == '%':
6058 fracpart += '%'
6059
6060 if spec['zeropad']:
6061 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6062 else:
6063 min_width = 0
6064 intpart = _insert_thousands_sep(intpart, spec, min_width)
6065
6066 return _format_align(sign, intpart+fracpart, spec)
6067
6068
Facundo Batista59c58842007-04-10 12:58:45 +00006069##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006070
Facundo Batista59c58842007-04-10 12:58:45 +00006071# Reusable defaults
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00006072_Infinity = Decimal('Inf')
6073_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonc5de0962009-01-02 23:07:08 +00006074_NaN = Decimal('NaN')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00006075_Zero = Decimal(0)
6076_One = Decimal(1)
6077_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006078
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00006079# _SignedInfinity[sign] is infinity w/ that sign
6080_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006081
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006082
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006083
6084if __name__ == '__main__':
6085 import doctest, sys
6086 doctest.testmod(sys.modules[__name__])