blob: d274552cd2493c43b4d3e0822aded54a1c861a73 [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
Raymond Hettinger8a9369b2011-08-24 19:13:17 -070024 http://speleotrove.com/decimal/decarith.html
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000025
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000026and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000027
Senthil Kumaran023c3e72013-09-07 23:18:53 -070028 http://en.wikipedia.org/wiki/IEEE_854-1987
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000029
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 Hettingerf4d85972009-01-03 19:02:23 +0000139import math as _math
Raymond Hettinger2c8585b2009-02-03 03:37:03 +0000140import numbers as _numbers
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000141
Raymond Hettinger097a1902008-01-11 02:24:13 +0000142try:
143 from collections import namedtuple as _namedtuple
144 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
145except ImportError:
146 DecimalTuple = lambda *args: args
147
Facundo Batista59c58842007-04-10 12:58:45 +0000148# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000149ROUND_DOWN = 'ROUND_DOWN'
150ROUND_HALF_UP = 'ROUND_HALF_UP'
151ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
152ROUND_CEILING = 'ROUND_CEILING'
153ROUND_FLOOR = 'ROUND_FLOOR'
154ROUND_UP = 'ROUND_UP'
155ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Facundo Batista353750c2007-09-13 18:13:15 +0000156ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000157
Facundo Batista59c58842007-04-10 12:58:45 +0000158# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000159
160class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000161 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000162
163 Used exceptions derive from this.
164 If an exception derives from another exception besides this (such as
165 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
166 called if the others are present. This isn't actually used for
167 anything, though.
168
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000169 handle -- Called when context._raise_error is called and the
Stefan Krah8a6f3fe2010-05-19 15:46:39 +0000170 trap_enabler is not set. First argument is self, second is the
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000171 context. More arguments can be given, those being after
172 the explanation in _raise_error (For example,
173 context._raise_error(NewError, '(-x)!', self._sign) would
174 call NewError().handle(context, self._sign).)
175
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000176 To define a new exception, it should be sufficient to have it derive
177 from DecimalException.
178 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000179 def handle(self, context, *args):
180 pass
181
182
183class Clamped(DecimalException):
184 """Exponent of a 0 changed to fit bounds.
185
186 This occurs and signals clamped if the exponent of a result has been
187 altered in order to fit the constraints of a specific concrete
Facundo Batista59c58842007-04-10 12:58:45 +0000188 representation. This may occur when the exponent of a zero result would
189 be outside the bounds of a representation, or when a large normal
190 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000191 this latter case, the exponent is reduced to fit and the corresponding
192 number of zero digits are appended to the coefficient ("fold-down").
193 """
194
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000195class InvalidOperation(DecimalException):
196 """An invalid operation was performed.
197
198 Various bad things cause this:
199
200 Something creates a signaling NaN
201 -INF + INF
Facundo Batista59c58842007-04-10 12:58:45 +0000202 0 * (+-)INF
203 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000204 x % 0
205 (+-)INF % x
206 x._rescale( non-integer )
207 sqrt(-x) , x > 0
208 0 ** 0
209 x ** (non-integer)
210 x ** (+-)INF
211 An operand is invalid
Facundo Batista353750c2007-09-13 18:13:15 +0000212
213 The result of the operation after these is a quiet positive NaN,
214 except when the cause is a signaling NaN, in which case the result is
215 also a quiet NaN, but with the original sign, and an optional
216 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000217 """
218 def handle(self, context, *args):
219 if args:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000220 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
221 return ans._fix_nan(context)
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000222 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000223
224class ConversionSyntax(InvalidOperation):
225 """Trying to convert badly formed string.
226
227 This occurs and signals invalid-operation if an string is being
228 converted to a number and it does not conform to the numeric string
Facundo Batista59c58842007-04-10 12:58:45 +0000229 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000231 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000232 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000233
234class DivisionByZero(DecimalException, ZeroDivisionError):
235 """Division by 0.
236
237 This occurs and signals division-by-zero if division of a finite number
238 by zero was attempted (during a divide-integer or divide operation, or a
239 power operation with negative right-hand operand), and the dividend was
240 not zero.
241
242 The result of the operation is [sign,inf], where sign is the exclusive
243 or of the signs of the operands for divide, or is 1 for an odd power of
244 -0, for power.
245 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000246
Facundo Batistacce8df22007-09-18 16:53:18 +0000247 def handle(self, context, sign, *args):
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000248 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000249
250class DivisionImpossible(InvalidOperation):
251 """Cannot perform the division adequately.
252
253 This occurs and signals invalid-operation if the integer result of a
254 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000255 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000256 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000257
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000258 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000259 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000260
261class DivisionUndefined(InvalidOperation, ZeroDivisionError):
262 """Undefined result of division.
263
264 This occurs and signals invalid-operation if division by zero was
265 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000266 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000267 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000268
Facundo Batistacce8df22007-09-18 16:53:18 +0000269 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000270 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000271
272class Inexact(DecimalException):
273 """Had to round, losing information.
274
275 This occurs and signals inexact whenever the result of an operation is
276 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000277 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000278 result in all cases is unchanged.
279
280 The inexact signal may be tested (or trapped) to determine if a given
281 operation (or sequence of operations) was inexact.
282 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000283
284class InvalidContext(InvalidOperation):
285 """Invalid context. Unknown rounding, for example.
286
287 This occurs and signals invalid-operation if an invalid context was
Facundo Batista59c58842007-04-10 12:58:45 +0000288 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000289 on creation and either the precision exceeds the capability of the
290 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista59c58842007-04-10 12:58:45 +0000291 was specified. These aspects of the context need only be checked when
292 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000293 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000294
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000295 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000296 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000297
298class Rounded(DecimalException):
299 """Number got rounded (not necessarily changed during rounding).
300
301 This occurs and signals rounded whenever the result of an operation is
302 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista59c58842007-04-10 12:58:45 +0000303 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000304 result in all cases is unchanged.
305
306 The rounded signal may be tested (or trapped) to determine if a given
307 operation (or sequence of operations) caused a loss of precision.
308 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000309
310class Subnormal(DecimalException):
311 """Exponent < Emin before rounding.
312
313 This occurs and signals subnormal whenever the result of a conversion or
314 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000315 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000316
317 The subnormal signal may be tested (or trapped) to determine if a given
318 or operation (or sequence of operations) yielded a subnormal result.
319 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000320
321class Overflow(Inexact, Rounded):
322 """Numerical overflow.
323
324 This occurs and signals overflow if the adjusted exponent of a result
325 (from a conversion or from an operation that is not an attempt to divide
326 by zero), after rounding, would be greater than the largest value that
327 can be handled by the implementation (the value Emax).
328
329 The result depends on the rounding mode:
330
331 For round-half-up and round-half-even (and for round-half-down and
332 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000333 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000334 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000335 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000336 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000337 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000338 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000339 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000340 will also be raised.
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000341 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000342
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000343 def handle(self, context, sign, *args):
344 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000345 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000346 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000347 if sign == 0:
348 if context.rounding == ROUND_CEILING:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000349 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000350 return _dec_from_triple(sign, '9'*context.prec,
351 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000352 if sign == 1:
353 if context.rounding == ROUND_FLOOR:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000354 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000355 return _dec_from_triple(sign, '9'*context.prec,
356 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000357
358
359class Underflow(Inexact, Rounded, Subnormal):
360 """Numerical underflow with result rounded to 0.
361
362 This occurs and signals underflow if a result is inexact and the
363 adjusted exponent of the result would be smaller (more negative) than
364 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000365 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000366
367 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000368 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000369 in 0 with the sign of the intermediate result and an exponent of Etiny.
370
371 In all cases, Inexact, Rounded, and Subnormal will also be raised.
372 """
373
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000374# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000375_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000376 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000377
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000378# Map conditions (per the spec) to signals
379_condition_map = {ConversionSyntax:InvalidOperation,
380 DivisionImpossible:InvalidOperation,
381 DivisionUndefined:InvalidOperation,
382 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000383
Facundo Batista59c58842007-04-10 12:58:45 +0000384##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000385
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000386# The getcontext() and setcontext() function manage access to a thread-local
387# current context. Py2.4 offers direct support for thread locals. If that
388# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000389# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000390# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000391
392try:
393 import threading
394except ImportError:
395 # Python was compiled without threads; create a mock object instead
396 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000397 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000398 def local(self, sys=sys):
399 return sys.modules[__name__]
400 threading = MockThreading()
401 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000402
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000403try:
404 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000406except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000407
Facundo Batista59c58842007-04-10 12:58:45 +0000408 # To fix reloading, force it to create a new context
409 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000410 if hasattr(threading.currentThread(), '__decimal_context__'):
411 del threading.currentThread().__decimal_context__
412
413 def setcontext(context):
414 """Set this thread's context to context."""
415 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000416 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000417 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000418 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000419
420 def getcontext():
421 """Returns this thread's context.
422
423 If this thread does not yet have a context, returns
424 a new context and sets this thread's context.
425 New contexts are copies of DefaultContext.
426 """
427 try:
428 return threading.currentThread().__decimal_context__
429 except AttributeError:
430 context = Context()
431 threading.currentThread().__decimal_context__ = context
432 return context
433
434else:
435
436 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000437 if hasattr(local, '__decimal_context__'):
438 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000439
440 def getcontext(_local=local):
441 """Returns this thread's context.
442
443 If this thread does not yet have a context, returns
444 a new context and sets this thread's context.
445 New contexts are copies of DefaultContext.
446 """
447 try:
448 return _local.__decimal_context__
449 except AttributeError:
450 context = Context()
451 _local.__decimal_context__ = context
452 return context
453
454 def setcontext(context, _local=local):
455 """Set this thread's context to context."""
456 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000457 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000458 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000459 _local.__decimal_context__ = context
460
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000461 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000462
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000463def localcontext(ctx=None):
464 """Return a context manager for a copy of the supplied context
465
466 Uses a copy of the current context if no context is specified
467 The returned context manager creates a local decimal context
468 in a with statement:
469 def sin(x):
470 with localcontext() as ctx:
471 ctx.prec += 2
472 # Rest of sin calculation algorithm
473 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000474 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000475
476 def sin(x):
477 with localcontext(ExtendedContext):
478 # Rest of sin calculation algorithm
479 # uses the Extended Context from the
480 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000481 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000482
Facundo Batistaee340e52008-05-02 17:39:00 +0000483 >>> setcontext(DefaultContext)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000484 >>> print getcontext().prec
485 28
486 >>> with localcontext():
487 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000488 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000489 ... print ctx.prec
490 ...
491 30
492 >>> with localcontext(ExtendedContext):
493 ... print getcontext().prec
494 ...
495 9
496 >>> print getcontext().prec
497 28
498 """
Nick Coghlanced12182006-09-02 03:54:17 +0000499 if ctx is None: ctx = getcontext()
500 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000501
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000502
Facundo Batista59c58842007-04-10 12:58:45 +0000503##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000504
505class Decimal(object):
506 """Floating point class for decimal arithmetic."""
507
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000508 __slots__ = ('_exp','_int','_sign', '_is_special')
509 # Generally, the value of the Decimal instance is given by
510 # (-1)**_sign * _int * 10**_exp
511 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000512
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000513 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000514 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000515 """Create a decimal point instance.
516
517 >>> Decimal('3.14') # string input
Raymond Hettingerabe32372008-02-14 02:41:22 +0000518 Decimal('3.14')
Facundo Batista59c58842007-04-10 12:58:45 +0000519 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000520 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000521 >>> Decimal(314) # int or long
Raymond Hettingerabe32372008-02-14 02:41:22 +0000522 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000523 >>> Decimal(Decimal(314)) # another decimal instance
Raymond Hettingerabe32372008-02-14 02:41:22 +0000524 Decimal('314')
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000525 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Raymond Hettingerabe32372008-02-14 02:41:22 +0000526 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000527 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000528
Facundo Batista72bc54f2007-11-23 17:59:00 +0000529 # Note that the coefficient, self._int, is actually stored as
530 # a string rather than as a tuple of digits. This speeds up
531 # the "digits to integer" and "integer to digits" conversions
532 # that are used in almost every arithmetic operation on
533 # Decimals. This is an internal detail: the as_tuple function
534 # and the Decimal constructor still deal with tuples of
535 # digits.
536
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000537 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000538
Facundo Batista0d157a02007-11-30 17:15:25 +0000539 # From a string
540 # REs insist on real strings, so we can too.
541 if isinstance(value, basestring):
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000542 m = _parser(value.strip())
Facundo Batista0d157a02007-11-30 17:15:25 +0000543 if m is None:
544 if context is None:
545 context = getcontext()
546 return context._raise_error(ConversionSyntax,
547 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000548
Facundo Batista0d157a02007-11-30 17:15:25 +0000549 if m.group('sign') == "-":
550 self._sign = 1
551 else:
552 self._sign = 0
553 intpart = m.group('int')
554 if intpart is not None:
555 # finite number
Mark Dickinson4326ad82009-08-02 10:59:36 +0000556 fracpart = m.group('frac') or ''
Facundo Batista0d157a02007-11-30 17:15:25 +0000557 exp = int(m.group('exp') or '0')
Mark Dickinson4326ad82009-08-02 10:59:36 +0000558 self._int = str(int(intpart+fracpart))
559 self._exp = exp - len(fracpart)
Facundo Batista0d157a02007-11-30 17:15:25 +0000560 self._is_special = False
561 else:
562 diag = m.group('diag')
563 if diag is not None:
564 # NaN
Mark Dickinson4326ad82009-08-02 10:59:36 +0000565 self._int = str(int(diag or '0')).lstrip('0')
Facundo Batista0d157a02007-11-30 17:15:25 +0000566 if m.group('signal'):
567 self._exp = 'N'
568 else:
569 self._exp = 'n'
570 else:
571 # infinity
572 self._int = '0'
573 self._exp = 'F'
574 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000575 return self
576
577 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000578 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000579 if value >= 0:
580 self._sign = 0
581 else:
582 self._sign = 1
583 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000584 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000585 self._is_special = False
586 return self
587
588 # From another decimal
589 if isinstance(value, Decimal):
590 self._exp = value._exp
591 self._sign = value._sign
592 self._int = value._int
593 self._is_special = value._is_special
594 return self
595
596 # From an internal working value
597 if isinstance(value, _WorkRep):
598 self._sign = value.sign
599 self._int = str(value.int)
600 self._exp = int(value.exp)
601 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000602 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000603
604 # tuple/list conversion (possibly from as_tuple())
605 if isinstance(value, (list,tuple)):
606 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000607 raise ValueError('Invalid tuple size in creation of Decimal '
608 'from list or tuple. The list or tuple '
609 'should have exactly three elements.')
610 # process sign. The isinstance test rejects floats
611 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
612 raise ValueError("Invalid sign. The first value in the tuple "
613 "should be an integer; either 0 for a "
614 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000615 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000616 if value[2] == 'F':
617 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000618 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000619 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000620 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000621 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000622 # process and validate the digits in value[1]
623 digits = []
624 for digit in value[1]:
625 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
626 # skip leading zeros
627 if digits or digit != 0:
628 digits.append(digit)
629 else:
630 raise ValueError("The second value in the tuple must "
631 "be composed of integers in the range "
632 "0 through 9.")
633 if value[2] in ('n', 'N'):
634 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000635 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000636 self._exp = value[2]
637 self._is_special = True
638 elif isinstance(value[2], (int, long)):
639 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000640 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000641 self._exp = value[2]
642 self._is_special = False
643 else:
644 raise ValueError("The third value in the tuple must "
645 "be an integer, or one of the "
646 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000647 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000648
Raymond Hettingerbf440692004-07-10 14:14:37 +0000649 if isinstance(value, float):
Raymond Hettingered171ab2010-04-02 18:39:24 +0000650 value = Decimal.from_float(value)
651 self._exp = value._exp
652 self._sign = value._sign
653 self._int = value._int
654 self._is_special = value._is_special
655 return self
Raymond Hettingerbf440692004-07-10 14:14:37 +0000656
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000657 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000658
Mark Dickinson6a961632009-01-04 21:10:56 +0000659 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
660 # don't use it (see notes on Py2.3 compatibility at top of file)
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000661 def from_float(cls, f):
662 """Converts a float to a decimal number, exactly.
663
664 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
665 Since 0.1 is not exactly representable in binary floating point, the
666 value is stored as the nearest representable value which is
667 0x1.999999999999ap-4. The exact equivalent of the value in decimal
668 is 0.1000000000000000055511151231257827021181583404541015625.
669
670 >>> Decimal.from_float(0.1)
671 Decimal('0.1000000000000000055511151231257827021181583404541015625')
672 >>> Decimal.from_float(float('nan'))
673 Decimal('NaN')
674 >>> Decimal.from_float(float('inf'))
675 Decimal('Infinity')
676 >>> Decimal.from_float(-float('inf'))
677 Decimal('-Infinity')
678 >>> Decimal.from_float(-0.0)
679 Decimal('-0')
680
681 """
682 if isinstance(f, (int, long)): # handle integer inputs
683 return cls(f)
684 if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
685 return cls(repr(f))
Mark Dickinson6a961632009-01-04 21:10:56 +0000686 if _math.copysign(1.0, f) == 1.0:
687 sign = 0
688 else:
689 sign = 1
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000690 n, d = abs(f).as_integer_ratio()
691 k = d.bit_length() - 1
692 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinson6a961632009-01-04 21:10:56 +0000693 if cls is Decimal:
694 return result
695 else:
696 return cls(result)
697 from_float = classmethod(from_float)
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000698
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000699 def _isnan(self):
700 """Returns whether the number is not actually one.
701
702 0 if a number
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000703 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000704 2 if sNaN
705 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000706 if self._is_special:
707 exp = self._exp
708 if exp == 'n':
709 return 1
710 elif exp == 'N':
711 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000712 return 0
713
714 def _isinfinity(self):
715 """Returns whether the number is infinite
716
717 0 if finite or not a number
718 1 if +INF
719 -1 if -INF
720 """
721 if self._exp == 'F':
722 if self._sign:
723 return -1
724 return 1
725 return 0
726
Facundo Batista353750c2007-09-13 18:13:15 +0000727 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000728 """Returns whether the number is not actually one.
729
730 if self, other are sNaN, signal
731 if self, other are NaN return nan
732 return 0
733
734 Done before operations.
735 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000736
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000737 self_is_nan = self._isnan()
738 if other is None:
739 other_is_nan = False
740 else:
741 other_is_nan = other._isnan()
742
743 if self_is_nan or other_is_nan:
744 if context is None:
745 context = getcontext()
746
747 if self_is_nan == 2:
748 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000749 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000750 if other_is_nan == 2:
751 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000752 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000753 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000754 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000755
Facundo Batista353750c2007-09-13 18:13:15 +0000756 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000757 return 0
758
Mark Dickinson2fc92632008-02-06 22:10:50 +0000759 def _compare_check_nans(self, other, context):
760 """Version of _check_nans used for the signaling comparisons
761 compare_signal, __le__, __lt__, __ge__, __gt__.
762
763 Signal InvalidOperation if either self or other is a (quiet
764 or signaling) NaN. Signaling NaNs take precedence over quiet
765 NaNs.
766
767 Return 0 if neither operand is a NaN.
768
769 """
770 if context is None:
771 context = getcontext()
772
773 if self._is_special or other._is_special:
774 if self.is_snan():
775 return context._raise_error(InvalidOperation,
776 'comparison involving sNaN',
777 self)
778 elif other.is_snan():
779 return context._raise_error(InvalidOperation,
780 'comparison involving sNaN',
781 other)
782 elif self.is_qnan():
783 return context._raise_error(InvalidOperation,
784 'comparison involving NaN',
785 self)
786 elif other.is_qnan():
787 return context._raise_error(InvalidOperation,
788 'comparison involving NaN',
789 other)
790 return 0
791
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000792 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000793 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000794
Facundo Batista1a191df2007-10-02 17:01:24 +0000795 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000796 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000797 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000798
Mark Dickinson2fc92632008-02-06 22:10:50 +0000799 def _cmp(self, other):
800 """Compare the two non-NaN decimal instances self and other.
801
802 Returns -1 if self < other, 0 if self == other and 1
803 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000804
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000805 if self._is_special or other._is_special:
Mark Dickinsone52c3142009-01-25 10:39:15 +0000806 self_inf = self._isinfinity()
807 other_inf = other._isinfinity()
808 if self_inf == other_inf:
809 return 0
810 elif self_inf < other_inf:
811 return -1
812 else:
813 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000814
Mark Dickinsone52c3142009-01-25 10:39:15 +0000815 # check for zeros; Decimal('0') == Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000816 if not self:
817 if not other:
818 return 0
819 else:
820 return -((-1)**other._sign)
821 if not other:
822 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000823
Facundo Batista59c58842007-04-10 12:58:45 +0000824 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000825 if other._sign < self._sign:
826 return -1
827 if self._sign < other._sign:
828 return 1
829
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000830 self_adjusted = self.adjusted()
831 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000832 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000833 self_padded = self._int + '0'*(self._exp - other._exp)
834 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone52c3142009-01-25 10:39:15 +0000835 if self_padded == other_padded:
836 return 0
837 elif self_padded < other_padded:
838 return -(-1)**self._sign
839 else:
840 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000841 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000842 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000843 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000844 return -((-1)**self._sign)
845
Mark Dickinson2fc92632008-02-06 22:10:50 +0000846 # Note: The Decimal standard doesn't cover rich comparisons for
847 # Decimals. In particular, the specification is silent on the
848 # subject of what should happen for a comparison involving a NaN.
849 # We take the following approach:
850 #
Mark Dickinsone096e822010-04-02 10:17:07 +0000851 # == comparisons involving a quiet NaN always return False
852 # != comparisons involving a quiet NaN always return True
853 # == or != comparisons involving a signaling NaN signal
854 # InvalidOperation, and return False or True as above if the
855 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000856 # <, >, <= and >= comparisons involving a (quiet or signaling)
857 # NaN signal InvalidOperation, and return False if the
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000858 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000859 #
860 # This behavior is designed to conform as closely as possible to
861 # that specified by IEEE 754.
862
Mark Dickinsone096e822010-04-02 10:17:07 +0000863 def __eq__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000864 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000865 if other is NotImplemented:
866 return other
Mark Dickinsone096e822010-04-02 10:17:07 +0000867 if self._check_nans(other, context):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000868 return False
869 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000870
Mark Dickinsone096e822010-04-02 10:17:07 +0000871 def __ne__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000872 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000873 if other is NotImplemented:
874 return other
Mark Dickinsone096e822010-04-02 10:17:07 +0000875 if self._check_nans(other, context):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000876 return True
877 return self._cmp(other) != 0
878
879 def __lt__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000880 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000881 if other is NotImplemented:
882 return other
883 ans = self._compare_check_nans(other, context)
884 if ans:
885 return False
886 return self._cmp(other) < 0
887
888 def __le__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000889 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000890 if other is NotImplemented:
891 return other
892 ans = self._compare_check_nans(other, context)
893 if ans:
894 return False
895 return self._cmp(other) <= 0
896
897 def __gt__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000898 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000899 if other is NotImplemented:
900 return other
901 ans = self._compare_check_nans(other, context)
902 if ans:
903 return False
904 return self._cmp(other) > 0
905
906 def __ge__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000907 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000908 if other is NotImplemented:
909 return other
910 ans = self._compare_check_nans(other, context)
911 if ans:
912 return False
913 return self._cmp(other) >= 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000914
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000915 def compare(self, other, context=None):
916 """Compares one to another.
917
918 -1 => a < b
919 0 => a = b
920 1 => a > b
921 NaN => one is NaN
922 Like __cmp__, but returns Decimal instances.
923 """
Facundo Batista353750c2007-09-13 18:13:15 +0000924 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000925
Facundo Batista59c58842007-04-10 12:58:45 +0000926 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000927 if (self._is_special or other and other._is_special):
928 ans = self._check_nans(other, context)
929 if ans:
930 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000931
Mark Dickinson2fc92632008-02-06 22:10:50 +0000932 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000933
934 def __hash__(self):
935 """x.__hash__() <==> hash(x)"""
936 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000937 #
938 # The hash of a nonspecial noninteger Decimal must depend only
939 # on the value of that Decimal, and not on its representation.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000940 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Mark Dickinsonf3eeca12010-04-02 10:35:12 +0000941
942 # Equality comparisons involving signaling nans can raise an
943 # exception; since equality checks are implicitly and
944 # unpredictably used when checking set and dict membership, we
945 # prevent signaling nans from being used as set elements or
946 # dict keys by making __hash__ raise an exception.
947 if self._is_special:
948 if self.is_snan():
949 raise TypeError('Cannot hash a signaling NaN value.')
950 elif self.is_nan():
951 # 0 to match hash(float('nan'))
952 return 0
953 else:
954 # values chosen to match hash(float('inf')) and
955 # hash(float('-inf')).
956 if self._sign:
957 return -271828
958 else:
959 return 314159
Mark Dickinson99d80962010-04-02 08:53:22 +0000960
961 # In Python 2.7, we're allowing comparisons (but not
962 # arithmetic operations) between floats and Decimals; so if
963 # a Decimal instance is exactly representable as a float then
Mark Dickinsonf3eeca12010-04-02 10:35:12 +0000964 # its hash should match that of the float.
Mark Dickinson99d80962010-04-02 08:53:22 +0000965 self_as_float = float(self)
966 if Decimal.from_float(self_as_float) == self:
967 return hash(self_as_float)
968
Facundo Batista8c202442007-09-19 17:53:25 +0000969 if self._isinteger():
970 op = _WorkRep(self.to_integral_value())
971 # to make computation feasible for Decimals with large
972 # exponent, we use the fact that hash(n) == hash(m) for
973 # any two nonzero integers n and m such that (i) n and m
974 # have the same sign, and (ii) n is congruent to m modulo
975 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
976 # hash((-1)**s*c*pow(10, e, 2**64-1).
977 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000978 # The value of a nonzero nonspecial Decimal instance is
979 # faithfully represented by the triple consisting of its sign,
980 # its adjusted exponent, and its coefficient with trailing
981 # zeros removed.
982 return hash((self._sign,
983 self._exp+len(self._int),
984 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000985
986 def as_tuple(self):
987 """Represents the number as a triple tuple.
988
989 To show the internals exactly as they are.
990 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000991 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000992
993 def __repr__(self):
994 """Represents the number as an instance of Decimal."""
995 # Invariant: eval(repr(d)) == d
Raymond Hettingerabe32372008-02-14 02:41:22 +0000996 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000997
Facundo Batista353750c2007-09-13 18:13:15 +0000998 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000999 """Return string representation of the number in scientific notation.
1000
1001 Captures all of the information in the underlying representation.
1002 """
1003
Facundo Batista62edb712007-12-03 16:29:52 +00001004 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +00001005 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +00001006 if self._exp == 'F':
1007 return sign + 'Infinity'
1008 elif self._exp == 'n':
1009 return sign + 'NaN' + self._int
1010 else: # self._exp == 'N'
1011 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012
Facundo Batista62edb712007-12-03 16:29:52 +00001013 # number of digits of self._int to left of decimal point
1014 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001015
Facundo Batista62edb712007-12-03 16:29:52 +00001016 # dotplace is number of digits of self._int to the left of the
1017 # decimal point in the mantissa of the output string (that is,
1018 # after adjusting the exponent)
1019 if self._exp <= 0 and leftdigits > -6:
1020 # no exponent required
1021 dotplace = leftdigits
1022 elif not eng:
1023 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001024 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +00001025 elif self._int == '0':
1026 # engineering notation, zero
1027 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001028 else:
Facundo Batista62edb712007-12-03 16:29:52 +00001029 # engineering notation, nonzero
1030 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001031
Facundo Batista62edb712007-12-03 16:29:52 +00001032 if dotplace <= 0:
1033 intpart = '0'
1034 fracpart = '.' + '0'*(-dotplace) + self._int
1035 elif dotplace >= len(self._int):
1036 intpart = self._int+'0'*(dotplace-len(self._int))
1037 fracpart = ''
1038 else:
1039 intpart = self._int[:dotplace]
1040 fracpart = '.' + self._int[dotplace:]
1041 if leftdigits == dotplace:
1042 exp = ''
1043 else:
1044 if context is None:
1045 context = getcontext()
1046 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1047
1048 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001049
1050 def to_eng_string(self, context=None):
1051 """Convert to engineering-type string.
1052
1053 Engineering notation has an exponent which is a multiple of 3, so there
1054 are up to 3 digits left of the decimal place.
1055
1056 Same rules for when in exponential and when as a value as in __str__.
1057 """
Facundo Batista353750c2007-09-13 18:13:15 +00001058 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001059
1060 def __neg__(self, context=None):
1061 """Returns a copy with the sign switched.
1062
1063 Rounds, if it has reason.
1064 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001065 if self._is_special:
1066 ans = self._check_nans(context=context)
1067 if ans:
1068 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069
Mark Dickinson2c8c62e2011-03-12 11:05:32 +00001070 if context is None:
1071 context = getcontext()
1072
1073 if not self and context.rounding != ROUND_FLOOR:
1074 # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
1075 # in ROUND_FLOOR rounding mode.
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001076 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001078 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001079
Facundo Batistae64acfa2007-12-17 14:18:42 +00001080 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
1082 def __pos__(self, context=None):
1083 """Returns a copy, unless it is a sNaN.
1084
1085 Rounds the number (if more then precision digits)
1086 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001087 if self._is_special:
1088 ans = self._check_nans(context=context)
1089 if ans:
1090 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001091
Mark Dickinson2c8c62e2011-03-12 11:05:32 +00001092 if context is None:
1093 context = getcontext()
1094
1095 if not self and context.rounding != ROUND_FLOOR:
1096 # + (-0) = 0, except in ROUND_FLOOR rounding mode.
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001097 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +00001098 else:
1099 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100
Facundo Batistae64acfa2007-12-17 14:18:42 +00001101 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001102
Facundo Batistae64acfa2007-12-17 14:18:42 +00001103 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001104 """Returns the absolute value of self.
1105
Facundo Batistae64acfa2007-12-17 14:18:42 +00001106 If the keyword argument 'round' is false, do not round. The
1107 expression self.__abs__(round=False) is equivalent to
1108 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109 """
Facundo Batistae64acfa2007-12-17 14:18:42 +00001110 if not round:
1111 return self.copy_abs()
1112
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001113 if self._is_special:
1114 ans = self._check_nans(context=context)
1115 if ans:
1116 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001117
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001118 if self._sign:
1119 ans = self.__neg__(context=context)
1120 else:
1121 ans = self.__pos__(context=context)
1122
1123 return ans
1124
1125 def __add__(self, other, context=None):
1126 """Returns self + other.
1127
1128 -INF + INF (or the reverse) cause InvalidOperation errors.
1129 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001130 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001131 if other is NotImplemented:
1132 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001133
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001134 if context is None:
1135 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001136
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001137 if self._is_special or other._is_special:
1138 ans = self._check_nans(other, context)
1139 if ans:
1140 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001142 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001143 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001144 if self._sign != other._sign and other._isinfinity():
1145 return context._raise_error(InvalidOperation, '-INF + INF')
1146 return Decimal(self)
1147 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001148 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001149
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001150 exp = min(self._exp, other._exp)
1151 negativezero = 0
1152 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001153 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001154 negativezero = 1
1155
1156 if not self and not other:
1157 sign = min(self._sign, other._sign)
1158 if negativezero:
1159 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001160 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001161 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001162 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001164 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001165 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001166 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001167 return ans
1168 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001169 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001170 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001171 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001172 return ans
1173
1174 op1 = _WorkRep(self)
1175 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001176 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001177
1178 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001179 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001180 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001181 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001182 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001183 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001184 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001185 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001187 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001188 if op1.sign == 1:
1189 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001190 op1.sign, op2.sign = op2.sign, op1.sign
1191 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001192 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001193 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001194 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001195 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001196 op1.sign, op2.sign = (0, 0)
1197 else:
1198 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001199 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200
Raymond Hettinger17931de2004-10-27 06:21:46 +00001201 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001202 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001203 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001204 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001205
1206 result.exp = op1.exp
1207 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001208 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001209 return ans
1210
1211 __radd__ = __add__
1212
1213 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001214 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001215 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001216 if other is NotImplemented:
1217 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001218
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001219 if self._is_special or other._is_special:
1220 ans = self._check_nans(other, context=context)
1221 if ans:
1222 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223
Facundo Batista353750c2007-09-13 18:13:15 +00001224 # self - other is computed as self + other.copy_negate()
1225 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001226
1227 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001228 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001229 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001230 if other is NotImplemented:
1231 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001232
Facundo Batista353750c2007-09-13 18:13:15 +00001233 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001234
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001235 def __mul__(self, other, context=None):
1236 """Return self * other.
1237
1238 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1239 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001240 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001241 if other is NotImplemented:
1242 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001243
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001244 if context is None:
1245 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001246
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001247 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001248
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001249 if self._is_special or other._is_special:
1250 ans = self._check_nans(other, context)
1251 if ans:
1252 return ans
1253
1254 if self._isinfinity():
1255 if not other:
1256 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001257 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001258
1259 if other._isinfinity():
1260 if not self:
1261 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001262 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001263
1264 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001265
1266 # Special case for multiplying by zero
1267 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001268 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001269 # Fixing in case the exponent is out of bounds
1270 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001271 return ans
1272
1273 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001274 if self._int == '1':
1275 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001276 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001277 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001278 if other._int == '1':
1279 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001280 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001281 return ans
1282
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001283 op1 = _WorkRep(self)
1284 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001285
Facundo Batista72bc54f2007-11-23 17:59:00 +00001286 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001287 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001288
1289 return ans
1290 __rmul__ = __mul__
1291
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001292 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001293 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001294 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001295 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001296 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001297
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001298 if context is None:
1299 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001300
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001301 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001302
1303 if self._is_special or other._is_special:
1304 ans = self._check_nans(other, context)
1305 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001306 return ans
1307
1308 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001309 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001310
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001311 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001312 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001313
1314 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001315 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001316 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001317
1318 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001319 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001320 if not self:
1321 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001322 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001323
Facundo Batistacce8df22007-09-18 16:53:18 +00001324 if not self:
1325 exp = self._exp - other._exp
1326 coeff = 0
1327 else:
1328 # OK, so neither = 0, INF or NaN
1329 shift = len(other._int) - len(self._int) + context.prec + 1
1330 exp = self._exp - other._exp - shift
1331 op1 = _WorkRep(self)
1332 op2 = _WorkRep(other)
1333 if shift >= 0:
1334 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1335 else:
1336 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1337 if remainder:
1338 # result is not exact; adjust to ensure correct rounding
1339 if coeff % 5 == 0:
1340 coeff += 1
1341 else:
1342 # result is exact; get as close to ideal exponent as possible
1343 ideal_exp = self._exp - other._exp
1344 while exp < ideal_exp and coeff % 10 == 0:
1345 coeff //= 10
1346 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001347
Facundo Batista72bc54f2007-11-23 17:59:00 +00001348 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001349 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001350
Facundo Batistacce8df22007-09-18 16:53:18 +00001351 def _divide(self, other, context):
1352 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001353
Facundo Batistacce8df22007-09-18 16:53:18 +00001354 Assumes that neither self nor other is a NaN, that self is not
1355 infinite and that other is nonzero.
1356 """
1357 sign = self._sign ^ other._sign
1358 if other._isinfinity():
1359 ideal_exp = self._exp
1360 else:
1361 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001362
Facundo Batistacce8df22007-09-18 16:53:18 +00001363 expdiff = self.adjusted() - other.adjusted()
1364 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001365 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001366 self._rescale(ideal_exp, context.rounding))
1367 if expdiff <= context.prec:
1368 op1 = _WorkRep(self)
1369 op2 = _WorkRep(other)
1370 if op1.exp >= op2.exp:
1371 op1.int *= 10**(op1.exp - op2.exp)
1372 else:
1373 op2.int *= 10**(op2.exp - op1.exp)
1374 q, r = divmod(op1.int, op2.int)
1375 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001376 return (_dec_from_triple(sign, str(q), 0),
1377 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001378
Facundo Batistacce8df22007-09-18 16:53:18 +00001379 # Here the quotient is too large to be representable
1380 ans = context._raise_error(DivisionImpossible,
1381 'quotient too large in //, % or divmod')
1382 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001383
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001384 def __rtruediv__(self, other, context=None):
1385 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001386 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001387 if other is NotImplemented:
1388 return other
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001389 return other.__truediv__(self, context=context)
1390
1391 __div__ = __truediv__
1392 __rdiv__ = __rtruediv__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001393
1394 def __divmod__(self, other, context=None):
1395 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001396 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001397 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001398 other = _convert_other(other)
1399 if other is NotImplemented:
1400 return other
1401
1402 if context is None:
1403 context = getcontext()
1404
1405 ans = self._check_nans(other, context)
1406 if ans:
1407 return (ans, ans)
1408
1409 sign = self._sign ^ other._sign
1410 if self._isinfinity():
1411 if other._isinfinity():
1412 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1413 return ans, ans
1414 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001415 return (_SignedInfinity[sign],
Facundo Batistacce8df22007-09-18 16:53:18 +00001416 context._raise_error(InvalidOperation, 'INF % x'))
1417
1418 if not other:
1419 if not self:
1420 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1421 return ans, ans
1422 else:
1423 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1424 context._raise_error(InvalidOperation, 'x % 0'))
1425
1426 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001427 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001428 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001429
1430 def __rdivmod__(self, other, context=None):
1431 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001432 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001433 if other is NotImplemented:
1434 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001435 return other.__divmod__(self, context=context)
1436
1437 def __mod__(self, other, context=None):
1438 """
1439 self % other
1440 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001441 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001442 if other is NotImplemented:
1443 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001444
Facundo Batistacce8df22007-09-18 16:53:18 +00001445 if context is None:
1446 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001447
Facundo Batistacce8df22007-09-18 16:53:18 +00001448 ans = self._check_nans(other, context)
1449 if ans:
1450 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001451
Facundo Batistacce8df22007-09-18 16:53:18 +00001452 if self._isinfinity():
1453 return context._raise_error(InvalidOperation, 'INF % x')
1454 elif not other:
1455 if self:
1456 return context._raise_error(InvalidOperation, 'x % 0')
1457 else:
1458 return context._raise_error(DivisionUndefined, '0 % 0')
1459
1460 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001461 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001462 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001463
1464 def __rmod__(self, other, context=None):
1465 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001466 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001467 if other is NotImplemented:
1468 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001469 return other.__mod__(self, context=context)
1470
1471 def remainder_near(self, other, context=None):
1472 """
1473 Remainder nearest to 0- abs(remainder-near) <= other/2
1474 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001475 if context is None:
1476 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001477
Facundo Batista353750c2007-09-13 18:13:15 +00001478 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001479
Facundo Batista353750c2007-09-13 18:13:15 +00001480 ans = self._check_nans(other, context)
1481 if ans:
1482 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001483
Facundo Batista353750c2007-09-13 18:13:15 +00001484 # self == +/-infinity -> InvalidOperation
1485 if self._isinfinity():
1486 return context._raise_error(InvalidOperation,
1487 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001488
Facundo Batista353750c2007-09-13 18:13:15 +00001489 # other == 0 -> either InvalidOperation or DivisionUndefined
1490 if not other:
1491 if self:
1492 return context._raise_error(InvalidOperation,
1493 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001494 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001495 return context._raise_error(DivisionUndefined,
1496 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001497
Facundo Batista353750c2007-09-13 18:13:15 +00001498 # other = +/-infinity -> remainder = self
1499 if other._isinfinity():
1500 ans = Decimal(self)
1501 return ans._fix(context)
1502
1503 # self = 0 -> remainder = self, with ideal exponent
1504 ideal_exponent = min(self._exp, other._exp)
1505 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001506 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001507 return ans._fix(context)
1508
1509 # catch most cases of large or small quotient
1510 expdiff = self.adjusted() - other.adjusted()
1511 if expdiff >= context.prec + 1:
1512 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001513 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001514 if expdiff <= -2:
1515 # expdiff <= -2 => abs(self/other) < 0.1
1516 ans = self._rescale(ideal_exponent, context.rounding)
1517 return ans._fix(context)
1518
1519 # adjust both arguments to have the same exponent, then divide
1520 op1 = _WorkRep(self)
1521 op2 = _WorkRep(other)
1522 if op1.exp >= op2.exp:
1523 op1.int *= 10**(op1.exp - op2.exp)
1524 else:
1525 op2.int *= 10**(op2.exp - op1.exp)
1526 q, r = divmod(op1.int, op2.int)
1527 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1528 # 10**ideal_exponent. Apply correction to ensure that
1529 # abs(remainder) <= abs(other)/2
1530 if 2*r + (q&1) > op2.int:
1531 r -= op2.int
1532 q += 1
1533
1534 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001535 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001536
1537 # result has same sign as self unless r is negative
1538 sign = self._sign
1539 if r < 0:
1540 sign = 1-sign
1541 r = -r
1542
Facundo Batista72bc54f2007-11-23 17:59:00 +00001543 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001544 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001545
1546 def __floordiv__(self, other, context=None):
1547 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001548 other = _convert_other(other)
1549 if other is NotImplemented:
1550 return other
1551
1552 if context is None:
1553 context = getcontext()
1554
1555 ans = self._check_nans(other, context)
1556 if ans:
1557 return ans
1558
1559 if self._isinfinity():
1560 if other._isinfinity():
1561 return context._raise_error(InvalidOperation, 'INF // INF')
1562 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001563 return _SignedInfinity[self._sign ^ other._sign]
Facundo Batistacce8df22007-09-18 16:53:18 +00001564
1565 if not other:
1566 if self:
1567 return context._raise_error(DivisionByZero, 'x // 0',
1568 self._sign ^ other._sign)
1569 else:
1570 return context._raise_error(DivisionUndefined, '0 // 0')
1571
1572 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001573
1574 def __rfloordiv__(self, other, context=None):
1575 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001576 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001577 if other is NotImplemented:
1578 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001579 return other.__floordiv__(self, context=context)
1580
1581 def __float__(self):
1582 """Float representation."""
Mark Dickinson088cec32012-08-24 20:06:30 +01001583 if self._isnan():
1584 if self.is_snan():
1585 raise ValueError("Cannot convert signaling NaN to float")
1586 s = "-nan" if self._sign else "nan"
1587 else:
1588 s = str(self)
1589 return float(s)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001590
1591 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001592 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001593 if self._is_special:
1594 if self._isnan():
Mark Dickinson968f1692009-09-07 18:04:58 +00001595 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001596 elif self._isinfinity():
Mark Dickinson968f1692009-09-07 18:04:58 +00001597 raise OverflowError("Cannot convert infinity to integer")
Facundo Batista353750c2007-09-13 18:13:15 +00001598 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001599 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001600 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001601 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001602 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001603
Raymond Hettinger5a053642008-01-24 19:05:29 +00001604 __trunc__ = __int__
1605
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001606 def real(self):
1607 return self
Mark Dickinson65808ff2009-01-04 21:22:02 +00001608 real = property(real)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001609
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001610 def imag(self):
1611 return Decimal(0)
Mark Dickinson65808ff2009-01-04 21:22:02 +00001612 imag = property(imag)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001613
1614 def conjugate(self):
1615 return self
1616
1617 def __complex__(self):
1618 return complex(float(self))
1619
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001620 def __long__(self):
1621 """Converts to a long.
1622
1623 Equivalent to long(int(self))
1624 """
1625 return long(self.__int__())
1626
Facundo Batista353750c2007-09-13 18:13:15 +00001627 def _fix_nan(self, context):
1628 """Decapitate the payload of a NaN to fit the context"""
1629 payload = self._int
1630
1631 # maximum length of payload is precision if _clamp=0,
1632 # precision-1 if _clamp=1.
1633 max_payload_len = context.prec - context._clamp
1634 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001635 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1636 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001637 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001638
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001639 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001640 """Round if it is necessary to keep self within prec precision.
1641
1642 Rounds and fixes the exponent. Does not raise on a sNaN.
1643
1644 Arguments:
1645 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001646 context - context used.
1647 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001648
Facundo Batista353750c2007-09-13 18:13:15 +00001649 if self._is_special:
1650 if self._isnan():
1651 # decapitate payload if necessary
1652 return self._fix_nan(context)
1653 else:
1654 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001655 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001656
Facundo Batista353750c2007-09-13 18:13:15 +00001657 # if self is zero then exponent should be between Etiny and
1658 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1659 Etiny = context.Etiny()
1660 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001661 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001662 exp_max = [context.Emax, Etop][context._clamp]
1663 new_exp = min(max(self._exp, Etiny), exp_max)
1664 if new_exp != self._exp:
1665 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001666 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001667 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001668 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001669
1670 # exp_min is the smallest allowable exponent of the result,
1671 # equal to max(self.adjusted()-context.prec+1, Etiny)
1672 exp_min = len(self._int) + self._exp - context.prec
1673 if exp_min > Etop:
1674 # overflow: exp_min > Etop iff self.adjusted() > Emax
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00001675 ans = context._raise_error(Overflow, 'above Emax', self._sign)
Facundo Batista353750c2007-09-13 18:13:15 +00001676 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001677 context._raise_error(Rounded)
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00001678 return ans
1679
Facundo Batista353750c2007-09-13 18:13:15 +00001680 self_is_subnormal = exp_min < Etiny
1681 if self_is_subnormal:
Facundo Batista353750c2007-09-13 18:13:15 +00001682 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001683
Facundo Batista353750c2007-09-13 18:13:15 +00001684 # round if self has too many digits
1685 if self._exp < exp_min:
Facundo Batista2ec74152007-12-03 17:55:00 +00001686 digits = len(self._int) + self._exp - exp_min
1687 if digits < 0:
1688 self = _dec_from_triple(self._sign, '1', exp_min-1)
1689 digits = 0
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00001690 rounding_method = self._pick_rounding_function[context.rounding]
Raymond Hettingerd9223292011-04-12 09:06:01 -07001691 changed = rounding_method(self, digits)
Facundo Batista2ec74152007-12-03 17:55:00 +00001692 coeff = self._int[:digits] or '0'
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00001693 if changed > 0:
Facundo Batista2ec74152007-12-03 17:55:00 +00001694 coeff = str(int(coeff)+1)
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00001695 if len(coeff) > context.prec:
1696 coeff = coeff[:-1]
1697 exp_min += 1
Facundo Batista2ec74152007-12-03 17:55:00 +00001698
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00001699 # check whether the rounding pushed the exponent out of range
1700 if exp_min > Etop:
1701 ans = context._raise_error(Overflow, 'above Emax', self._sign)
1702 else:
1703 ans = _dec_from_triple(self._sign, coeff, exp_min)
1704
1705 # raise the appropriate signals, taking care to respect
1706 # the precedence described in the specification
1707 if changed and self_is_subnormal:
1708 context._raise_error(Underflow)
1709 if self_is_subnormal:
1710 context._raise_error(Subnormal)
Facundo Batista2ec74152007-12-03 17:55:00 +00001711 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001712 context._raise_error(Inexact)
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00001713 context._raise_error(Rounded)
1714 if not ans:
1715 # raise Clamped on underflow to 0
1716 context._raise_error(Clamped)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001717 return ans
1718
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00001719 if self_is_subnormal:
1720 context._raise_error(Subnormal)
1721
Facundo Batista353750c2007-09-13 18:13:15 +00001722 # fold down if _clamp == 1 and self has too few digits
1723 if context._clamp == 1 and self._exp > Etop:
1724 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001725 self_padded = self._int + '0'*(self._exp - Etop)
1726 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001727
Facundo Batista353750c2007-09-13 18:13:15 +00001728 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001729 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001730
Facundo Batista353750c2007-09-13 18:13:15 +00001731 # for each of the rounding functions below:
1732 # self is a finite, nonzero Decimal
1733 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001734 #
1735 # each function returns either -1, 0, or 1, as follows:
1736 # 1 indicates that self should be rounded up (away from zero)
1737 # 0 indicates that self should be truncated, and that all the
1738 # digits to be truncated are zeros (so the value is unchanged)
1739 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001740
1741 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001742 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001743 if _all_zeros(self._int, prec):
1744 return 0
1745 else:
1746 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001747
Facundo Batista353750c2007-09-13 18:13:15 +00001748 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001749 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001750 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001751
Facundo Batista353750c2007-09-13 18:13:15 +00001752 def _round_half_up(self, prec):
1753 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001754 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001755 return 1
1756 elif _all_zeros(self._int, prec):
1757 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001758 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001759 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001760
1761 def _round_half_down(self, prec):
1762 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001763 if _exact_half(self._int, prec):
1764 return -1
1765 else:
1766 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001767
1768 def _round_half_even(self, prec):
1769 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001770 if _exact_half(self._int, prec) and \
1771 (prec == 0 or self._int[prec-1] in '02468'):
1772 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001773 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001774 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001775
1776 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001777 """Rounds up (not away from 0 if negative.)"""
1778 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001779 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001780 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001781 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001782
Facundo Batista353750c2007-09-13 18:13:15 +00001783 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001784 """Rounds down (not towards 0 if negative)"""
1785 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001786 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001787 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001788 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001789
Facundo Batista353750c2007-09-13 18:13:15 +00001790 def _round_05up(self, prec):
1791 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001792 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001793 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001794 else:
1795 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001796
Raymond Hettingere4579c32011-04-11 17:27:42 -07001797 _pick_rounding_function = dict(
Raymond Hettingerd9223292011-04-12 09:06:01 -07001798 ROUND_DOWN = _round_down,
1799 ROUND_UP = _round_up,
1800 ROUND_HALF_UP = _round_half_up,
1801 ROUND_HALF_DOWN = _round_half_down,
1802 ROUND_HALF_EVEN = _round_half_even,
1803 ROUND_CEILING = _round_ceiling,
1804 ROUND_FLOOR = _round_floor,
1805 ROUND_05UP = _round_05up,
Raymond Hettingere4579c32011-04-11 17:27:42 -07001806 )
1807
Facundo Batista353750c2007-09-13 18:13:15 +00001808 def fma(self, other, third, context=None):
1809 """Fused multiply-add.
1810
1811 Returns self*other+third with no rounding of the intermediate
1812 product self*other.
1813
1814 self and other are multiplied together, with no rounding of
1815 the result. The third operand is then added to the result,
1816 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001817 """
Facundo Batista353750c2007-09-13 18:13:15 +00001818
1819 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001820
1821 # compute product; raise InvalidOperation if either operand is
1822 # a signaling NaN or if the product is zero times infinity.
1823 if self._is_special or other._is_special:
1824 if context is None:
1825 context = getcontext()
1826 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001827 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001828 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001829 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001830 if self._exp == 'n':
1831 product = self
1832 elif other._exp == 'n':
1833 product = other
1834 elif self._exp == 'F':
1835 if not other:
1836 return context._raise_error(InvalidOperation,
1837 'INF * 0 in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001838 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001839 elif other._exp == 'F':
1840 if not self:
1841 return context._raise_error(InvalidOperation,
1842 '0 * INF in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001843 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001844 else:
1845 product = _dec_from_triple(self._sign ^ other._sign,
1846 str(int(self._int) * int(other._int)),
1847 self._exp + other._exp)
1848
Facundo Batista353750c2007-09-13 18:13:15 +00001849 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001850 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001851
Facundo Batista353750c2007-09-13 18:13:15 +00001852 def _power_modulo(self, other, modulo, context=None):
1853 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001854
Facundo Batista353750c2007-09-13 18:13:15 +00001855 # if can't convert other and modulo to Decimal, raise
1856 # TypeError; there's no point returning NotImplemented (no
1857 # equivalent of __rpow__ for three argument pow)
1858 other = _convert_other(other, raiseit=True)
1859 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001860
Facundo Batista353750c2007-09-13 18:13:15 +00001861 if context is None:
1862 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001863
Facundo Batista353750c2007-09-13 18:13:15 +00001864 # deal with NaNs: if there are any sNaNs then first one wins,
1865 # (i.e. behaviour for NaNs is identical to that of fma)
1866 self_is_nan = self._isnan()
1867 other_is_nan = other._isnan()
1868 modulo_is_nan = modulo._isnan()
1869 if self_is_nan or other_is_nan or modulo_is_nan:
1870 if self_is_nan == 2:
1871 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001872 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001873 if other_is_nan == 2:
1874 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001875 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001876 if modulo_is_nan == 2:
1877 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001878 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001879 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001880 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001881 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001882 return other._fix_nan(context)
1883 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001884
Facundo Batista353750c2007-09-13 18:13:15 +00001885 # check inputs: we apply same restrictions as Python's pow()
1886 if not (self._isinteger() and
1887 other._isinteger() and
1888 modulo._isinteger()):
1889 return context._raise_error(InvalidOperation,
1890 'pow() 3rd argument not allowed '
1891 'unless all arguments are integers')
1892 if other < 0:
1893 return context._raise_error(InvalidOperation,
1894 'pow() 2nd argument cannot be '
1895 'negative when 3rd argument specified')
1896 if not modulo:
1897 return context._raise_error(InvalidOperation,
1898 'pow() 3rd argument cannot be 0')
1899
1900 # additional restriction for decimal: the modulus must be less
1901 # than 10**prec in absolute value
1902 if modulo.adjusted() >= context.prec:
1903 return context._raise_error(InvalidOperation,
1904 'insufficient precision: pow() 3rd '
1905 'argument must not have more than '
1906 'precision digits')
1907
1908 # define 0**0 == NaN, for consistency with two-argument pow
1909 # (even though it hurts!)
1910 if not other and not self:
1911 return context._raise_error(InvalidOperation,
1912 'at least one of pow() 1st argument '
1913 'and 2nd argument must be nonzero ;'
1914 '0**0 is not defined')
1915
1916 # compute sign of result
1917 if other._iseven():
1918 sign = 0
1919 else:
1920 sign = self._sign
1921
1922 # convert modulo to a Python integer, and self and other to
1923 # Decimal integers (i.e. force their exponents to be >= 0)
1924 modulo = abs(int(modulo))
1925 base = _WorkRep(self.to_integral_value())
1926 exponent = _WorkRep(other.to_integral_value())
1927
1928 # compute result using integer pow()
1929 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1930 for i in xrange(exponent.exp):
1931 base = pow(base, 10, modulo)
1932 base = pow(base, exponent.int, modulo)
1933
Facundo Batista72bc54f2007-11-23 17:59:00 +00001934 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001935
1936 def _power_exact(self, other, p):
1937 """Attempt to compute self**other exactly.
1938
1939 Given Decimals self and other and an integer p, attempt to
1940 compute an exact result for the power self**other, with p
1941 digits of precision. Return None if self**other is not
1942 exactly representable in p digits.
1943
1944 Assumes that elimination of special cases has already been
1945 performed: self and other must both be nonspecial; self must
1946 be positive and not numerically equal to 1; other must be
1947 nonzero. For efficiency, other._exp should not be too large,
1948 so that 10**abs(other._exp) is a feasible calculation."""
1949
Mark Dickinsona493ca32011-06-04 18:24:15 +01001950 # In the comments below, we write x for the value of self and y for the
1951 # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
1952 # and yc positive integers not divisible by 10.
Facundo Batista353750c2007-09-13 18:13:15 +00001953
1954 # The main purpose of this method is to identify the *failure*
1955 # of x**y to be exactly representable with as little effort as
1956 # possible. So we look for cheap and easy tests that
1957 # eliminate the possibility of x**y being exact. Only if all
1958 # these tests are passed do we go on to actually compute x**y.
1959
Mark Dickinsona493ca32011-06-04 18:24:15 +01001960 # Here's the main idea. Express y as a rational number m/n, with m and
1961 # n relatively prime and n>0. Then for x**y to be exactly
1962 # representable (at *any* precision), xc must be the nth power of a
1963 # positive integer and xe must be divisible by n. If y is negative
1964 # then additionally xc must be a power of either 2 or 5, hence a power
1965 # of 2**n or 5**n.
Facundo Batista353750c2007-09-13 18:13:15 +00001966 #
1967 # There's a limit to how small |y| can be: if y=m/n as above
1968 # then:
1969 #
1970 # (1) if xc != 1 then for the result to be representable we
1971 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1972 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1973 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1974 # representable.
1975 #
1976 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1977 # |y| < 1/|xe| then the result is not representable.
1978 #
1979 # Note that since x is not equal to 1, at least one of (1) and
1980 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1981 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1982 #
1983 # There's also a limit to how large y can be, at least if it's
1984 # positive: the normalized result will have coefficient xc**y,
1985 # so if it's representable then xc**y < 10**p, and y <
1986 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1987 # not exactly representable.
1988
1989 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1990 # so |y| < 1/xe and the result is not representable.
1991 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1992 # < 1/nbits(xc).
1993
1994 x = _WorkRep(self)
1995 xc, xe = x.int, x.exp
1996 while xc % 10 == 0:
1997 xc //= 10
1998 xe += 1
1999
2000 y = _WorkRep(other)
2001 yc, ye = y.int, y.exp
2002 while yc % 10 == 0:
2003 yc //= 10
2004 ye += 1
2005
2006 # case where xc == 1: result is 10**(xe*y), with xe*y
2007 # required to be an integer
2008 if xc == 1:
Mark Dickinsone85aa732010-07-08 19:24:40 +00002009 xe *= yc
2010 # result is now 10**(xe * 10**ye); xe * 10**ye must be integral
2011 while xe % 10 == 0:
2012 xe //= 10
2013 ye += 1
2014 if ye < 0:
2015 return None
2016 exponent = xe * 10**ye
Facundo Batista353750c2007-09-13 18:13:15 +00002017 if y.sign == 1:
2018 exponent = -exponent
2019 # if other is a nonnegative integer, use ideal exponent
2020 if other._isinteger() and other._sign == 0:
2021 ideal_exponent = self._exp*int(other)
2022 zeros = min(exponent-ideal_exponent, p-1)
2023 else:
2024 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002025 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002026
2027 # case where y is negative: xc must be either a power
2028 # of 2 or a power of 5.
2029 if y.sign == 1:
2030 last_digit = xc % 10
2031 if last_digit in (2,4,6,8):
2032 # quick test for power of 2
2033 if xc & -xc != xc:
2034 return None
2035 # now xc is a power of 2; e is its exponent
2036 e = _nbits(xc)-1
Facundo Batista353750c2007-09-13 18:13:15 +00002037
Mark Dickinsona493ca32011-06-04 18:24:15 +01002038 # We now have:
2039 #
2040 # x = 2**e * 10**xe, e > 0, and y < 0.
2041 #
2042 # The exact result is:
2043 #
2044 # x**y = 5**(-e*y) * 10**(e*y + xe*y)
2045 #
2046 # provided that both e*y and xe*y are integers. Note that if
2047 # 5**(-e*y) >= 10**p, then the result can't be expressed
2048 # exactly with p digits of precision.
2049 #
2050 # Using the above, we can guard against large values of ye.
2051 # 93/65 is an upper bound for log(10)/log(5), so if
2052 #
2053 # ye >= len(str(93*p//65))
2054 #
2055 # then
2056 #
2057 # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
2058 #
2059 # so 5**(-e*y) >= 10**p, and the coefficient of the result
2060 # can't be expressed in p digits.
2061
2062 # emax >= largest e such that 5**e < 10**p.
2063 emax = p*93//65
2064 if ye >= len(str(emax)):
2065 return None
2066
2067 # Find -e*y and -xe*y; both must be integers
2068 e = _decimal_lshift_exact(e * yc, ye)
2069 xe = _decimal_lshift_exact(xe * yc, ye)
2070 if e is None or xe is None:
2071 return None
2072
2073 if e > emax:
Facundo Batista353750c2007-09-13 18:13:15 +00002074 return None
2075 xc = 5**e
2076
2077 elif last_digit == 5:
2078 # e >= log_5(xc) if xc is a power of 5; we have
2079 # equality all the way up to xc=5**2658
2080 e = _nbits(xc)*28//65
2081 xc, remainder = divmod(5**e, xc)
2082 if remainder:
2083 return None
2084 while xc % 5 == 0:
2085 xc //= 5
2086 e -= 1
Mark Dickinsona493ca32011-06-04 18:24:15 +01002087
2088 # Guard against large values of ye, using the same logic as in
2089 # the 'xc is a power of 2' branch. 10/3 is an upper bound for
2090 # log(10)/log(2).
2091 emax = p*10//3
2092 if ye >= len(str(emax)):
2093 return None
2094
2095 e = _decimal_lshift_exact(e * yc, ye)
2096 xe = _decimal_lshift_exact(xe * yc, ye)
2097 if e is None or xe is None:
2098 return None
2099
2100 if e > emax:
Facundo Batista353750c2007-09-13 18:13:15 +00002101 return None
2102 xc = 2**e
2103 else:
2104 return None
2105
2106 if xc >= 10**p:
2107 return None
2108 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00002109 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00002110
2111 # now y is positive; find m and n such that y = m/n
2112 if ye >= 0:
2113 m, n = yc*10**ye, 1
2114 else:
2115 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2116 return None
2117 xc_bits = _nbits(xc)
2118 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2119 return None
2120 m, n = yc, 10**(-ye)
2121 while m % 2 == n % 2 == 0:
2122 m //= 2
2123 n //= 2
2124 while m % 5 == n % 5 == 0:
2125 m //= 5
2126 n //= 5
2127
2128 # compute nth root of xc*10**xe
2129 if n > 1:
2130 # if 1 < xc < 2**n then xc isn't an nth power
2131 if xc != 1 and xc_bits <= n:
2132 return None
2133
2134 xe, rem = divmod(xe, n)
2135 if rem != 0:
2136 return None
2137
2138 # compute nth root of xc using Newton's method
2139 a = 1L << -(-_nbits(xc)//n) # initial estimate
2140 while True:
2141 q, r = divmod(xc, a**(n-1))
2142 if a <= q:
2143 break
2144 else:
2145 a = (a*(n-1) + q)//n
2146 if not (a == q and r == 0):
2147 return None
2148 xc = a
2149
2150 # now xc*10**xe is the nth root of the original xc*10**xe
2151 # compute mth power of xc*10**xe
2152
2153 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2154 # 10**p and the result is not representable.
2155 if xc > 1 and m > p*100//_log10_lb(xc):
2156 return None
2157 xc = xc**m
2158 xe *= m
2159 if xc > 10**p:
2160 return None
2161
2162 # by this point the result *is* exactly representable
2163 # adjust the exponent to get as close as possible to the ideal
2164 # exponent, if necessary
2165 str_xc = str(xc)
2166 if other._isinteger() and other._sign == 0:
2167 ideal_exponent = self._exp*int(other)
2168 zeros = min(xe-ideal_exponent, p-len(str_xc))
2169 else:
2170 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002171 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002172
2173 def __pow__(self, other, modulo=None, context=None):
2174 """Return self ** other [ % modulo].
2175
2176 With two arguments, compute self**other.
2177
2178 With three arguments, compute (self**other) % modulo. For the
2179 three argument form, the following restrictions on the
2180 arguments hold:
2181
2182 - all three arguments must be integral
2183 - other must be nonnegative
2184 - either self or other (or both) must be nonzero
2185 - modulo must be nonzero and must have at most p digits,
2186 where p is the context precision.
2187
2188 If any of these restrictions is violated the InvalidOperation
2189 flag is raised.
2190
2191 The result of pow(self, other, modulo) is identical to the
2192 result that would be obtained by computing (self**other) %
2193 modulo with unbounded precision, but is computed more
2194 efficiently. It is always exact.
2195 """
2196
2197 if modulo is not None:
2198 return self._power_modulo(other, modulo, context)
2199
2200 other = _convert_other(other)
2201 if other is NotImplemented:
2202 return other
2203
2204 if context is None:
2205 context = getcontext()
2206
2207 # either argument is a NaN => result is NaN
2208 ans = self._check_nans(other, context)
2209 if ans:
2210 return ans
2211
2212 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2213 if not other:
2214 if not self:
2215 return context._raise_error(InvalidOperation, '0 ** 0')
2216 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002217 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002218
2219 # result has sign 1 iff self._sign is 1 and other is an odd integer
2220 result_sign = 0
2221 if self._sign == 1:
2222 if other._isinteger():
2223 if not other._iseven():
2224 result_sign = 1
2225 else:
2226 # -ve**noninteger = NaN
2227 # (-0)**noninteger = 0**noninteger
2228 if self:
2229 return context._raise_error(InvalidOperation,
2230 'x ** y with x negative and y not an integer')
2231 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002232 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002233
2234 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2235 if not self:
2236 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002237 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002238 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002239 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002240
2241 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002242 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002243 if other._sign == 0:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002244 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002245 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002246 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002247
Facundo Batista353750c2007-09-13 18:13:15 +00002248 # 1**other = 1, but the choice of exponent and the flags
2249 # depend on the exponent of self, and on whether other is a
2250 # positive integer, a negative integer, or neither
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002251 if self == _One:
Facundo Batista353750c2007-09-13 18:13:15 +00002252 if other._isinteger():
2253 # exp = max(self._exp*max(int(other), 0),
2254 # 1-context.prec) but evaluating int(other) directly
2255 # is dangerous until we know other is small (other
2256 # could be 1e999999999)
2257 if other._sign == 1:
2258 multiplier = 0
2259 elif other > context.prec:
2260 multiplier = context.prec
2261 else:
2262 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002263
Facundo Batista353750c2007-09-13 18:13:15 +00002264 exp = self._exp * multiplier
2265 if exp < 1-context.prec:
2266 exp = 1-context.prec
2267 context._raise_error(Rounded)
2268 else:
2269 context._raise_error(Inexact)
2270 context._raise_error(Rounded)
2271 exp = 1-context.prec
2272
Facundo Batista72bc54f2007-11-23 17:59:00 +00002273 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002274
2275 # compute adjusted exponent of self
2276 self_adj = self.adjusted()
2277
2278 # self ** infinity is infinity if self > 1, 0 if self < 1
2279 # self ** -infinity is infinity if self < 1, 0 if self > 1
2280 if other._isinfinity():
2281 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002282 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002283 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002284 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002285
2286 # from here on, the result always goes through the call
2287 # to _fix at the end of this function.
2288 ans = None
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00002289 exact = False
Facundo Batista353750c2007-09-13 18:13:15 +00002290
2291 # crude test to catch cases of extreme overflow/underflow. If
2292 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2293 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2294 # self**other >= 10**(Emax+1), so overflow occurs. The test
2295 # for underflow is similar.
2296 bound = self._log10_exp_bound() + other.adjusted()
2297 if (self_adj >= 0) == (other._sign == 0):
2298 # self > 1 and other +ve, or self < 1 and other -ve
2299 # possibility of overflow
2300 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002301 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002302 else:
2303 # self > 1 and other -ve, or self < 1 and other +ve
2304 # possibility of underflow to 0
2305 Etiny = context.Etiny()
2306 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002307 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002308
2309 # try for an exact result with precision +1
2310 if ans is None:
2311 ans = self._power_exact(other, context.prec + 1)
Mark Dickinsone85aa732010-07-08 19:24:40 +00002312 if ans is not None:
2313 if result_sign == 1:
2314 ans = _dec_from_triple(1, ans._int, ans._exp)
2315 exact = True
Facundo Batista353750c2007-09-13 18:13:15 +00002316
2317 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2318 if ans is None:
2319 p = context.prec
2320 x = _WorkRep(self)
2321 xc, xe = x.int, x.exp
2322 y = _WorkRep(other)
2323 yc, ye = y.int, y.exp
2324 if y.sign == 1:
2325 yc = -yc
2326
2327 # compute correctly rounded result: start with precision +3,
2328 # then increase precision until result is unambiguously roundable
2329 extra = 3
2330 while True:
2331 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2332 if coeff % (5*10**(len(str(coeff))-p-1)):
2333 break
2334 extra += 3
2335
Facundo Batista72bc54f2007-11-23 17:59:00 +00002336 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002337
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00002338 # unlike exp, ln and log10, the power function respects the
2339 # rounding mode; no need to switch to ROUND_HALF_EVEN here
2340
2341 # There's a difficulty here when 'other' is not an integer and
2342 # the result is exact. In this case, the specification
2343 # requires that the Inexact flag be raised (in spite of
2344 # exactness), but since the result is exact _fix won't do this
2345 # for us. (Correspondingly, the Underflow signal should also
2346 # be raised for subnormal results.) We can't directly raise
2347 # these signals either before or after calling _fix, since
2348 # that would violate the precedence for signals. So we wrap
2349 # the ._fix call in a temporary context, and reraise
2350 # afterwards.
2351 if exact and not other._isinteger():
2352 # pad with zeros up to length context.prec+1 if necessary; this
2353 # ensures that the Rounded signal will be raised.
Facundo Batista353750c2007-09-13 18:13:15 +00002354 if len(ans._int) <= context.prec:
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00002355 expdiff = context.prec + 1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002356 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2357 ans._exp-expdiff)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002358
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00002359 # create a copy of the current context, with cleared flags/traps
2360 newcontext = context.copy()
2361 newcontext.clear_flags()
2362 for exception in _signals:
2363 newcontext.traps[exception] = 0
2364
2365 # round in the new context
2366 ans = ans._fix(newcontext)
2367
2368 # raise Inexact, and if necessary, Underflow
2369 newcontext._raise_error(Inexact)
2370 if newcontext.flags[Subnormal]:
2371 newcontext._raise_error(Underflow)
2372
2373 # propagate signals to the original context; _fix could
2374 # have raised any of Overflow, Underflow, Subnormal,
2375 # Inexact, Rounded, Clamped. Overflow needs the correct
2376 # arguments. Note that the order of the exceptions is
2377 # important here.
2378 if newcontext.flags[Overflow]:
2379 context._raise_error(Overflow, 'above Emax', ans._sign)
2380 for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
2381 if newcontext.flags[exception]:
2382 context._raise_error(exception)
2383
2384 else:
2385 ans = ans._fix(context)
2386
Facundo Batista353750c2007-09-13 18:13:15 +00002387 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002388
2389 def __rpow__(self, other, context=None):
2390 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002391 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002392 if other is NotImplemented:
2393 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002394 return other.__pow__(self, context=context)
2395
2396 def normalize(self, context=None):
2397 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002398
Facundo Batista353750c2007-09-13 18:13:15 +00002399 if context is None:
2400 context = getcontext()
2401
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002402 if self._is_special:
2403 ans = self._check_nans(context=context)
2404 if ans:
2405 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002406
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002407 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002408 if dup._isinfinity():
2409 return dup
2410
2411 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002412 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002413 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002414 end = len(dup._int)
2415 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002416 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002417 exp += 1
2418 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002419 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002420
Facundo Batistabd2fe832007-09-13 18:42:09 +00002421 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002422 """Quantize self so its exponent is the same as that of exp.
2423
2424 Similar to self._rescale(exp._exp) but with error checking.
2425 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002426 exp = _convert_other(exp, raiseit=True)
2427
Facundo Batista353750c2007-09-13 18:13:15 +00002428 if context is None:
2429 context = getcontext()
2430 if rounding is None:
2431 rounding = context.rounding
2432
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002433 if self._is_special or exp._is_special:
2434 ans = self._check_nans(exp, context)
2435 if ans:
2436 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002437
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002438 if exp._isinfinity() or self._isinfinity():
2439 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002440 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002441 return context._raise_error(InvalidOperation,
2442 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002443
Facundo Batistabd2fe832007-09-13 18:42:09 +00002444 # if we're not watching exponents, do a simple rescale
2445 if not watchexp:
2446 ans = self._rescale(exp._exp, rounding)
2447 # raise Inexact and Rounded where appropriate
2448 if ans._exp > self._exp:
2449 context._raise_error(Rounded)
2450 if ans != self:
2451 context._raise_error(Inexact)
2452 return ans
2453
Facundo Batista353750c2007-09-13 18:13:15 +00002454 # exp._exp should be between Etiny and Emax
2455 if not (context.Etiny() <= exp._exp <= context.Emax):
2456 return context._raise_error(InvalidOperation,
2457 'target exponent out of bounds in quantize')
2458
2459 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002460 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002461 return ans._fix(context)
2462
2463 self_adjusted = self.adjusted()
2464 if self_adjusted > context.Emax:
2465 return context._raise_error(InvalidOperation,
2466 'exponent of quantize result too large for current context')
2467 if self_adjusted - exp._exp + 1 > context.prec:
2468 return context._raise_error(InvalidOperation,
2469 'quantize result has too many digits for current context')
2470
2471 ans = self._rescale(exp._exp, rounding)
2472 if ans.adjusted() > context.Emax:
2473 return context._raise_error(InvalidOperation,
2474 'exponent of quantize result too large for current context')
2475 if len(ans._int) > context.prec:
2476 return context._raise_error(InvalidOperation,
2477 'quantize result has too many digits for current context')
2478
2479 # raise appropriate flags
Facundo Batista353750c2007-09-13 18:13:15 +00002480 if ans and ans.adjusted() < context.Emin:
2481 context._raise_error(Subnormal)
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00002482 if ans._exp > self._exp:
2483 if ans != self:
2484 context._raise_error(Inexact)
2485 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00002486
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00002487 # call to fix takes care of any necessary folddown, and
2488 # signals Clamped if necessary
Facundo Batista353750c2007-09-13 18:13:15 +00002489 ans = ans._fix(context)
2490 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002491
2492 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002493 """Return True if self and other have the same exponent; otherwise
2494 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002495
Facundo Batista1a191df2007-10-02 17:01:24 +00002496 If either operand is a special value, the following rules are used:
2497 * return True if both operands are infinities
2498 * return True if both operands are NaNs
2499 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002500 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002501 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002502 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002503 return (self.is_nan() and other.is_nan() or
2504 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505 return self._exp == other._exp
2506
Facundo Batista353750c2007-09-13 18:13:15 +00002507 def _rescale(self, exp, rounding):
2508 """Rescale self so that the exponent is exp, either by padding with zeros
2509 or by truncating digits, using the given rounding mode.
2510
2511 Specials are returned without change. This operation is
2512 quiet: it raises no flags, and uses no information from the
2513 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002514
2515 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002516 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002517 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002518 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002519 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002520 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002521 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002522
Facundo Batista353750c2007-09-13 18:13:15 +00002523 if self._exp >= exp:
2524 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002525 return _dec_from_triple(self._sign,
2526 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002527
Facundo Batista353750c2007-09-13 18:13:15 +00002528 # too many digits; round and lose data. If self.adjusted() <
2529 # exp-1, replace self by 10**(exp-1) before rounding
2530 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002531 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002532 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002533 digits = 0
Raymond Hettingerd9223292011-04-12 09:06:01 -07002534 this_function = self._pick_rounding_function[rounding]
2535 changed = this_function(self, digits)
Facundo Batista2ec74152007-12-03 17:55:00 +00002536 coeff = self._int[:digits] or '0'
2537 if changed == 1:
2538 coeff = str(int(coeff)+1)
2539 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002540
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00002541 def _round(self, places, rounding):
2542 """Round a nonzero, nonspecial Decimal to a fixed number of
2543 significant figures, using the given rounding mode.
2544
2545 Infinities, NaNs and zeros are returned unaltered.
2546
2547 This operation is quiet: it raises no flags, and uses no
2548 information from the context.
2549
2550 """
2551 if places <= 0:
2552 raise ValueError("argument should be at least 1 in _round")
2553 if self._is_special or not self:
2554 return Decimal(self)
2555 ans = self._rescale(self.adjusted()+1-places, rounding)
2556 # it can happen that the rescale alters the adjusted exponent;
2557 # for example when rounding 99.97 to 3 significant figures.
2558 # When this happens we end up with an extra 0 at the end of
2559 # the number; a second rescale fixes this.
2560 if ans.adjusted() != self.adjusted():
2561 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2562 return ans
2563
Facundo Batista353750c2007-09-13 18:13:15 +00002564 def to_integral_exact(self, rounding=None, context=None):
2565 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002566
Facundo Batista353750c2007-09-13 18:13:15 +00002567 If no rounding mode is specified, take the rounding mode from
2568 the context. This method raises the Rounded and Inexact flags
2569 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002570
Facundo Batista353750c2007-09-13 18:13:15 +00002571 See also: to_integral_value, which does exactly the same as
2572 this method except that it doesn't raise Inexact or Rounded.
2573 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002574 if self._is_special:
2575 ans = self._check_nans(context=context)
2576 if ans:
2577 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002578 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002579 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002580 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002581 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002582 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002583 if context is None:
2584 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002585 if rounding is None:
2586 rounding = context.rounding
Facundo Batista353750c2007-09-13 18:13:15 +00002587 ans = self._rescale(0, rounding)
2588 if ans != self:
2589 context._raise_error(Inexact)
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00002590 context._raise_error(Rounded)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002591 return ans
2592
Facundo Batista353750c2007-09-13 18:13:15 +00002593 def to_integral_value(self, rounding=None, context=None):
2594 """Rounds to the nearest integer, without raising inexact, rounded."""
2595 if context is None:
2596 context = getcontext()
2597 if rounding is None:
2598 rounding = context.rounding
2599 if self._is_special:
2600 ans = self._check_nans(context=context)
2601 if ans:
2602 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002603 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002604 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002605 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002606 else:
2607 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002608
Facundo Batista353750c2007-09-13 18:13:15 +00002609 # the method name changed, but we provide also the old one, for compatibility
2610 to_integral = to_integral_value
2611
2612 def sqrt(self, context=None):
2613 """Return the square root of self."""
Mark Dickinson3b24ccb2008-03-25 14:33:23 +00002614 if context is None:
2615 context = getcontext()
2616
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002617 if self._is_special:
2618 ans = self._check_nans(context=context)
2619 if ans:
2620 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002621
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002622 if self._isinfinity() and self._sign == 0:
2623 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002624
2625 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002626 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002627 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002628 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002629
2630 if self._sign == 1:
2631 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2632
Facundo Batista353750c2007-09-13 18:13:15 +00002633 # At this point self represents a positive number. Let p be
2634 # the desired precision and express self in the form c*100**e
2635 # with c a positive real number and e an integer, c and e
2636 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2637 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2638 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2639 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2640 # the closest integer to sqrt(c) with the even integer chosen
2641 # in the case of a tie.
2642 #
2643 # To ensure correct rounding in all cases, we use the
2644 # following trick: we compute the square root to an extra
2645 # place (precision p+1 instead of precision p), rounding down.
2646 # Then, if the result is inexact and its last digit is 0 or 5,
2647 # we increase the last digit to 1 or 6 respectively; if it's
2648 # exact we leave the last digit alone. Now the final round to
2649 # p places (or fewer in the case of underflow) will round
2650 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002651
Facundo Batista353750c2007-09-13 18:13:15 +00002652 # use an extra digit of precision
2653 prec = context.prec+1
2654
2655 # write argument in the form c*100**e where e = self._exp//2
2656 # is the 'ideal' exponent, to be used if the square root is
2657 # exactly representable. l is the number of 'digits' of c in
2658 # base 100, so that 100**(l-1) <= c < 100**l.
2659 op = _WorkRep(self)
2660 e = op.exp >> 1
2661 if op.exp & 1:
2662 c = op.int * 10
2663 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002664 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002665 c = op.int
2666 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002667
Facundo Batista353750c2007-09-13 18:13:15 +00002668 # rescale so that c has exactly prec base 100 'digits'
2669 shift = prec-l
2670 if shift >= 0:
2671 c *= 100**shift
2672 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002673 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002674 c, remainder = divmod(c, 100**-shift)
2675 exact = not remainder
2676 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002677
Facundo Batista353750c2007-09-13 18:13:15 +00002678 # find n = floor(sqrt(c)) using Newton's method
2679 n = 10**prec
2680 while True:
2681 q = c//n
2682 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002683 break
Facundo Batista353750c2007-09-13 18:13:15 +00002684 else:
2685 n = n + q >> 1
2686 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002687
Facundo Batista353750c2007-09-13 18:13:15 +00002688 if exact:
2689 # result is exact; rescale to use ideal exponent e
2690 if shift >= 0:
2691 # assert n % 10**shift == 0
2692 n //= 10**shift
2693 else:
2694 n *= 10**-shift
2695 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002696 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002697 # result is not exact; fix last digit as described above
2698 if n % 5 == 0:
2699 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002700
Facundo Batista72bc54f2007-11-23 17:59:00 +00002701 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002702
Facundo Batista353750c2007-09-13 18:13:15 +00002703 # round, and fit to current context
2704 context = context._shallow_copy()
2705 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002706 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002707 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002708
Facundo Batista353750c2007-09-13 18:13:15 +00002709 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002710
2711 def max(self, other, context=None):
2712 """Returns the larger value.
2713
Facundo Batista353750c2007-09-13 18:13:15 +00002714 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002715 NaN (and signals if one is sNaN). Also rounds.
2716 """
Facundo Batista353750c2007-09-13 18:13:15 +00002717 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002718
Facundo Batista6c398da2007-09-17 17:30:13 +00002719 if context is None:
2720 context = getcontext()
2721
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002722 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002723 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002724 # number is always returned
2725 sn = self._isnan()
2726 on = other._isnan()
2727 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002728 if on == 1 and sn == 0:
2729 return self._fix(context)
2730 if sn == 1 and on == 0:
2731 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002732 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002733
Mark Dickinson2fc92632008-02-06 22:10:50 +00002734 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002735 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002736 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002737 # then an ordering is applied:
2738 #
Facundo Batista59c58842007-04-10 12:58:45 +00002739 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002740 # positive sign and min returns the operand with the negative sign
2741 #
Facundo Batista59c58842007-04-10 12:58:45 +00002742 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002743 # the result. This is exactly the ordering used in compare_total.
2744 c = self.compare_total(other)
2745
2746 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002747 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002748 else:
2749 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002750
Facundo Batistae64acfa2007-12-17 14:18:42 +00002751 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002752
2753 def min(self, other, context=None):
2754 """Returns the smaller value.
2755
Facundo Batista59c58842007-04-10 12:58:45 +00002756 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002757 NaN (and signals if one is sNaN). Also rounds.
2758 """
Facundo Batista353750c2007-09-13 18:13:15 +00002759 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002760
Facundo Batista6c398da2007-09-17 17:30:13 +00002761 if context is None:
2762 context = getcontext()
2763
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002764 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002765 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002766 # number is always returned
2767 sn = self._isnan()
2768 on = other._isnan()
2769 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002770 if on == 1 and sn == 0:
2771 return self._fix(context)
2772 if sn == 1 and on == 0:
2773 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002774 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002775
Mark Dickinson2fc92632008-02-06 22:10:50 +00002776 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002777 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002778 c = self.compare_total(other)
2779
2780 if c == -1:
2781 ans = self
2782 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002783 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002784
Facundo Batistae64acfa2007-12-17 14:18:42 +00002785 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002786
2787 def _isinteger(self):
2788 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002789 if self._is_special:
2790 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002791 if self._exp >= 0:
2792 return True
2793 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002794 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002795
2796 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002797 """Returns True if self is even. Assumes self is an integer."""
2798 if not self or self._exp > 0:
2799 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002800 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002801
2802 def adjusted(self):
2803 """Return the adjusted exponent of self"""
2804 try:
2805 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002806 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002807 except TypeError:
2808 return 0
2809
Facundo Batista353750c2007-09-13 18:13:15 +00002810 def canonical(self, context=None):
2811 """Returns the same Decimal object.
2812
2813 As we do not have different encodings for the same number, the
2814 received object already is in its canonical form.
2815 """
2816 return self
2817
2818 def compare_signal(self, other, context=None):
2819 """Compares self to the other operand numerically.
2820
2821 It's pretty much like compare(), but all NaNs signal, with signaling
2822 NaNs taking precedence over quiet NaNs.
2823 """
Mark Dickinson2fc92632008-02-06 22:10:50 +00002824 other = _convert_other(other, raiseit = True)
2825 ans = self._compare_check_nans(other, context)
2826 if ans:
2827 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002828 return self.compare(other, context=context)
2829
2830 def compare_total(self, other):
2831 """Compares self to other using the abstract representations.
2832
2833 This is not like the standard compare, which use their numerical
2834 value. Note that a total ordering is defined for all possible abstract
2835 representations.
2836 """
Mark Dickinson0c673122009-10-29 12:04:00 +00002837 other = _convert_other(other, raiseit=True)
2838
Facundo Batista353750c2007-09-13 18:13:15 +00002839 # if one is negative and the other is positive, it's easy
2840 if self._sign and not other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002841 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002842 if not self._sign and other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002843 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002844 sign = self._sign
2845
2846 # let's handle both NaN types
2847 self_nan = self._isnan()
2848 other_nan = other._isnan()
2849 if self_nan or other_nan:
2850 if self_nan == other_nan:
Mark Dickinson7a7739d2009-08-28 13:25:02 +00002851 # compare payloads as though they're integers
2852 self_key = len(self._int), self._int
2853 other_key = len(other._int), other._int
2854 if self_key < other_key:
Facundo Batista353750c2007-09-13 18:13:15 +00002855 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002856 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002857 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002858 return _NegativeOne
Mark Dickinson7a7739d2009-08-28 13:25:02 +00002859 if self_key > other_key:
Facundo Batista353750c2007-09-13 18:13:15 +00002860 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002861 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002862 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002863 return _One
2864 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002865
2866 if sign:
2867 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002868 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002869 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002870 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002871 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002872 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002873 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002874 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002875 else:
2876 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002877 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002878 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002879 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002880 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002881 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002882 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002883 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002884
2885 if self < other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002886 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002887 if self > other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002888 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002889
2890 if self._exp < other._exp:
2891 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002892 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002893 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002894 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002895 if self._exp > other._exp:
2896 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002897 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002898 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002899 return _One
2900 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002901
2902
2903 def compare_total_mag(self, other):
2904 """Compares self to other using abstract repr., ignoring sign.
2905
2906 Like compare_total, but with operand's sign ignored and assumed to be 0.
2907 """
Mark Dickinson0c673122009-10-29 12:04:00 +00002908 other = _convert_other(other, raiseit=True)
2909
Facundo Batista353750c2007-09-13 18:13:15 +00002910 s = self.copy_abs()
2911 o = other.copy_abs()
2912 return s.compare_total(o)
2913
2914 def copy_abs(self):
2915 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002916 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002917
2918 def copy_negate(self):
2919 """Returns a copy with the sign inverted."""
2920 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002921 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002922 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002923 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002924
2925 def copy_sign(self, other):
2926 """Returns self with the sign of other."""
Mark Dickinson6d8effb2010-02-18 14:27:02 +00002927 other = _convert_other(other, raiseit=True)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002928 return _dec_from_triple(other._sign, self._int,
2929 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002930
2931 def exp(self, context=None):
2932 """Returns e ** self."""
2933
2934 if context is None:
2935 context = getcontext()
2936
2937 # exp(NaN) = NaN
2938 ans = self._check_nans(context=context)
2939 if ans:
2940 return ans
2941
2942 # exp(-Infinity) = 0
2943 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002944 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002945
2946 # exp(0) = 1
2947 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002948 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002949
2950 # exp(Infinity) = Infinity
2951 if self._isinfinity() == 1:
2952 return Decimal(self)
2953
2954 # the result is now guaranteed to be inexact (the true
2955 # mathematical result is transcendental). There's no need to
2956 # raise Rounded and Inexact here---they'll always be raised as
2957 # a result of the call to _fix.
2958 p = context.prec
2959 adj = self.adjusted()
2960
2961 # we only need to do any computation for quite a small range
2962 # of adjusted exponents---for example, -29 <= adj <= 10 for
2963 # the default context. For smaller exponent the result is
2964 # indistinguishable from 1 at the given precision, while for
2965 # larger exponent the result either overflows or underflows.
2966 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2967 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002968 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002969 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2970 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002971 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002972 elif self._sign == 0 and adj < -p:
2973 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002974 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002975 elif self._sign == 1 and adj < -p-1:
2976 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002977 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002978 # general case
2979 else:
2980 op = _WorkRep(self)
2981 c, e = op.int, op.exp
2982 if op.sign == 1:
2983 c = -c
2984
2985 # compute correctly rounded result: increase precision by
2986 # 3 digits at a time until we get an unambiguously
2987 # roundable result
2988 extra = 3
2989 while True:
2990 coeff, exp = _dexp(c, e, p+extra)
2991 if coeff % (5*10**(len(str(coeff))-p-1)):
2992 break
2993 extra += 3
2994
Facundo Batista72bc54f2007-11-23 17:59:00 +00002995 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002996
2997 # at this stage, ans should round correctly with *any*
2998 # rounding mode, not just with ROUND_HALF_EVEN
2999 context = context._shallow_copy()
3000 rounding = context._set_rounding(ROUND_HALF_EVEN)
3001 ans = ans._fix(context)
3002 context.rounding = rounding
3003
3004 return ans
3005
3006 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00003007 """Return True if self is canonical; otherwise return False.
3008
3009 Currently, the encoding of a Decimal instance is always
3010 canonical, so this method returns True for any Decimal.
3011 """
3012 return True
Facundo Batista353750c2007-09-13 18:13:15 +00003013
3014 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00003015 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00003016
Facundo Batista1a191df2007-10-02 17:01:24 +00003017 A Decimal instance is considered finite if it is neither
3018 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00003019 """
Facundo Batista1a191df2007-10-02 17:01:24 +00003020 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00003021
3022 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00003023 """Return True if self is infinite; otherwise return False."""
3024 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00003025
3026 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00003027 """Return True if self is a qNaN or sNaN; otherwise return False."""
3028 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00003029
3030 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00003031 """Return True if self is a normal number; otherwise return False."""
3032 if self._is_special or not self:
3033 return False
Facundo Batista353750c2007-09-13 18:13:15 +00003034 if context is None:
3035 context = getcontext()
Mark Dickinsona7a52ab2009-10-20 13:33:03 +00003036 return context.Emin <= self.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +00003037
3038 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00003039 """Return True if self is a quiet NaN; otherwise return False."""
3040 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00003041
3042 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00003043 """Return True if self is negative; otherwise return False."""
3044 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00003045
3046 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00003047 """Return True if self is a signaling NaN; otherwise return False."""
3048 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00003049
3050 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00003051 """Return True if self is subnormal; otherwise return False."""
3052 if self._is_special or not self:
3053 return False
Facundo Batista353750c2007-09-13 18:13:15 +00003054 if context is None:
3055 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00003056 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00003057
3058 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00003059 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00003060 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00003061
3062 def _ln_exp_bound(self):
3063 """Compute a lower bound for the adjusted exponent of self.ln().
3064 In other words, compute r such that self.ln() >= 10**r. Assumes
3065 that self is finite and positive and that self != 1.
3066 """
3067
3068 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3069 adj = self._exp + len(self._int) - 1
3070 if adj >= 1:
3071 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3072 return len(str(adj*23//10)) - 1
3073 if adj <= -2:
3074 # argument <= 0.1
3075 return len(str((-1-adj)*23//10)) - 1
3076 op = _WorkRep(self)
3077 c, e = op.int, op.exp
3078 if adj == 0:
3079 # 1 < self < 10
3080 num = str(c-10**-e)
3081 den = str(c)
3082 return len(num) - len(den) - (num < den)
3083 # adj == -1, 0.1 <= self < 1
3084 return e + len(str(10**-e - c)) - 1
3085
3086
3087 def ln(self, context=None):
3088 """Returns the natural (base e) logarithm of self."""
3089
3090 if context is None:
3091 context = getcontext()
3092
3093 # ln(NaN) = NaN
3094 ans = self._check_nans(context=context)
3095 if ans:
3096 return ans
3097
3098 # ln(0.0) == -Infinity
3099 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003100 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003101
3102 # ln(Infinity) = Infinity
3103 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003104 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003105
3106 # ln(1.0) == 0.0
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003107 if self == _One:
3108 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00003109
3110 # ln(negative) raises InvalidOperation
3111 if self._sign == 1:
3112 return context._raise_error(InvalidOperation,
3113 'ln of a negative value')
3114
3115 # result is irrational, so necessarily inexact
3116 op = _WorkRep(self)
3117 c, e = op.int, op.exp
3118 p = context.prec
3119
3120 # correctly rounded result: repeatedly increase precision by 3
3121 # until we get an unambiguously roundable result
3122 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3123 while True:
3124 coeff = _dlog(c, e, places)
3125 # assert len(str(abs(coeff)))-p >= 1
3126 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3127 break
3128 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003129 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003130
3131 context = context._shallow_copy()
3132 rounding = context._set_rounding(ROUND_HALF_EVEN)
3133 ans = ans._fix(context)
3134 context.rounding = rounding
3135 return ans
3136
3137 def _log10_exp_bound(self):
3138 """Compute a lower bound for the adjusted exponent of self.log10().
3139 In other words, find r such that self.log10() >= 10**r.
3140 Assumes that self is finite and positive and that self != 1.
3141 """
3142
3143 # For x >= 10 or x < 0.1 we only need a bound on the integer
3144 # part of log10(self), and this comes directly from the
3145 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3146 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3147 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3148
3149 adj = self._exp + len(self._int) - 1
3150 if adj >= 1:
3151 # self >= 10
3152 return len(str(adj))-1
3153 if adj <= -2:
3154 # self < 0.1
3155 return len(str(-1-adj))-1
3156 op = _WorkRep(self)
3157 c, e = op.int, op.exp
3158 if adj == 0:
3159 # 1 < self < 10
3160 num = str(c-10**-e)
3161 den = str(231*c)
3162 return len(num) - len(den) - (num < den) + 2
3163 # adj == -1, 0.1 <= self < 1
3164 num = str(10**-e-c)
3165 return len(num) + e - (num < "231") - 1
3166
3167 def log10(self, context=None):
3168 """Returns the base 10 logarithm of self."""
3169
3170 if context is None:
3171 context = getcontext()
3172
3173 # log10(NaN) = NaN
3174 ans = self._check_nans(context=context)
3175 if ans:
3176 return ans
3177
3178 # log10(0.0) == -Infinity
3179 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003180 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003181
3182 # log10(Infinity) = Infinity
3183 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003184 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003185
3186 # log10(negative or -Infinity) raises InvalidOperation
3187 if self._sign == 1:
3188 return context._raise_error(InvalidOperation,
3189 'log10 of a negative value')
3190
3191 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00003192 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00003193 # answer may need rounding
3194 ans = Decimal(self._exp + len(self._int) - 1)
3195 else:
3196 # result is irrational, so necessarily inexact
3197 op = _WorkRep(self)
3198 c, e = op.int, op.exp
3199 p = context.prec
3200
3201 # correctly rounded result: repeatedly increase precision
3202 # until result is unambiguously roundable
3203 places = p-self._log10_exp_bound()+2
3204 while True:
3205 coeff = _dlog10(c, e, places)
3206 # assert len(str(abs(coeff)))-p >= 1
3207 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3208 break
3209 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003210 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003211
3212 context = context._shallow_copy()
3213 rounding = context._set_rounding(ROUND_HALF_EVEN)
3214 ans = ans._fix(context)
3215 context.rounding = rounding
3216 return ans
3217
3218 def logb(self, context=None):
3219 """ Returns the exponent of the magnitude of self's MSD.
3220
3221 The result is the integer which is the exponent of the magnitude
3222 of the most significant digit of self (as though it were truncated
3223 to a single digit while maintaining the value of that digit and
3224 without limiting the resulting exponent).
3225 """
3226 # logb(NaN) = NaN
3227 ans = self._check_nans(context=context)
3228 if ans:
3229 return ans
3230
3231 if context is None:
3232 context = getcontext()
3233
3234 # logb(+/-Inf) = +Inf
3235 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003236 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003237
3238 # logb(0) = -Inf, DivisionByZero
3239 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003240 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003241
3242 # otherwise, simply return the adjusted exponent of self, as a
3243 # Decimal. Note that no attempt is made to fit the result
3244 # into the current context.
Mark Dickinson15ae41c2009-10-07 19:22:05 +00003245 ans = Decimal(self.adjusted())
3246 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003247
3248 def _islogical(self):
3249 """Return True if self is a logical operand.
3250
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00003251 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00003252 an exponent of 0, and a coefficient whose digits must all be
3253 either 0 or 1.
3254 """
3255 if self._sign != 0 or self._exp != 0:
3256 return False
3257 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003258 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003259 return False
3260 return True
3261
3262 def _fill_logical(self, context, opa, opb):
3263 dif = context.prec - len(opa)
3264 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003265 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003266 elif dif < 0:
3267 opa = opa[-context.prec:]
3268 dif = context.prec - len(opb)
3269 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003270 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003271 elif dif < 0:
3272 opb = opb[-context.prec:]
3273 return opa, opb
3274
3275 def logical_and(self, other, context=None):
3276 """Applies an 'and' operation between self and other's digits."""
3277 if context is None:
3278 context = getcontext()
Mark Dickinson0c673122009-10-29 12:04:00 +00003279
3280 other = _convert_other(other, raiseit=True)
3281
Facundo Batista353750c2007-09-13 18:13:15 +00003282 if not self._islogical() or not other._islogical():
3283 return context._raise_error(InvalidOperation)
3284
3285 # fill to context.prec
3286 (opa, opb) = self._fill_logical(context, self._int, other._int)
3287
3288 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003289 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3290 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003291
3292 def logical_invert(self, context=None):
3293 """Invert all its digits."""
3294 if context is None:
3295 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003296 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3297 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003298
3299 def logical_or(self, other, context=None):
3300 """Applies an 'or' operation between self and other's digits."""
3301 if context is None:
3302 context = getcontext()
Mark Dickinson0c673122009-10-29 12:04:00 +00003303
3304 other = _convert_other(other, raiseit=True)
3305
Facundo Batista353750c2007-09-13 18:13:15 +00003306 if not self._islogical() or not other._islogical():
3307 return context._raise_error(InvalidOperation)
3308
3309 # fill to context.prec
3310 (opa, opb) = self._fill_logical(context, self._int, other._int)
3311
3312 # make the operation, and clean starting zeroes
Mark Dickinson65808ff2009-01-04 21:22:02 +00003313 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003314 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003315
3316 def logical_xor(self, other, context=None):
3317 """Applies an 'xor' operation between self and other's digits."""
3318 if context is None:
3319 context = getcontext()
Mark Dickinson0c673122009-10-29 12:04:00 +00003320
3321 other = _convert_other(other, raiseit=True)
3322
Facundo Batista353750c2007-09-13 18:13:15 +00003323 if not self._islogical() or not other._islogical():
3324 return context._raise_error(InvalidOperation)
3325
3326 # fill to context.prec
3327 (opa, opb) = self._fill_logical(context, self._int, other._int)
3328
3329 # make the operation, and clean starting zeroes
Mark Dickinson65808ff2009-01-04 21:22:02 +00003330 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003331 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003332
3333 def max_mag(self, other, context=None):
3334 """Compares the values numerically with their sign ignored."""
3335 other = _convert_other(other, raiseit=True)
3336
Facundo Batista6c398da2007-09-17 17:30:13 +00003337 if context is None:
3338 context = getcontext()
3339
Facundo Batista353750c2007-09-13 18:13:15 +00003340 if self._is_special or other._is_special:
3341 # If one operand is a quiet NaN and the other is number, then the
3342 # number is always returned
3343 sn = self._isnan()
3344 on = other._isnan()
3345 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003346 if on == 1 and sn == 0:
3347 return self._fix(context)
3348 if sn == 1 and on == 0:
3349 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003350 return self._check_nans(other, context)
3351
Mark Dickinson2fc92632008-02-06 22:10:50 +00003352 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003353 if c == 0:
3354 c = self.compare_total(other)
3355
3356 if c == -1:
3357 ans = other
3358 else:
3359 ans = self
3360
Facundo Batistae64acfa2007-12-17 14:18:42 +00003361 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003362
3363 def min_mag(self, other, context=None):
3364 """Compares the values numerically with their sign ignored."""
3365 other = _convert_other(other, raiseit=True)
3366
Facundo Batista6c398da2007-09-17 17:30:13 +00003367 if context is None:
3368 context = getcontext()
3369
Facundo Batista353750c2007-09-13 18:13:15 +00003370 if self._is_special or other._is_special:
3371 # If one operand is a quiet NaN and the other is number, then the
3372 # number is always returned
3373 sn = self._isnan()
3374 on = other._isnan()
3375 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003376 if on == 1 and sn == 0:
3377 return self._fix(context)
3378 if sn == 1 and on == 0:
3379 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003380 return self._check_nans(other, context)
3381
Mark Dickinson2fc92632008-02-06 22:10:50 +00003382 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003383 if c == 0:
3384 c = self.compare_total(other)
3385
3386 if c == -1:
3387 ans = self
3388 else:
3389 ans = other
3390
Facundo Batistae64acfa2007-12-17 14:18:42 +00003391 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003392
3393 def next_minus(self, context=None):
3394 """Returns the largest representable number smaller than itself."""
3395 if context is None:
3396 context = getcontext()
3397
3398 ans = self._check_nans(context=context)
3399 if ans:
3400 return ans
3401
3402 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003403 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003404 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003405 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003406
3407 context = context.copy()
3408 context._set_rounding(ROUND_FLOOR)
3409 context._ignore_all_flags()
3410 new_self = self._fix(context)
3411 if new_self != self:
3412 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003413 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3414 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003415
3416 def next_plus(self, context=None):
3417 """Returns the smallest representable number larger than itself."""
3418 if context is None:
3419 context = getcontext()
3420
3421 ans = self._check_nans(context=context)
3422 if ans:
3423 return ans
3424
3425 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003426 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003427 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003428 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003429
3430 context = context.copy()
3431 context._set_rounding(ROUND_CEILING)
3432 context._ignore_all_flags()
3433 new_self = self._fix(context)
3434 if new_self != self:
3435 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003436 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3437 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003438
3439 def next_toward(self, other, context=None):
3440 """Returns the number closest to self, in the direction towards other.
3441
3442 The result is the closest representable number to self
3443 (excluding self) that is in the direction towards other,
3444 unless both have the same value. If the two operands are
3445 numerically equal, then the result is a copy of self with the
3446 sign set to be the same as the sign of other.
3447 """
3448 other = _convert_other(other, raiseit=True)
3449
3450 if context is None:
3451 context = getcontext()
3452
3453 ans = self._check_nans(other, context)
3454 if ans:
3455 return ans
3456
Mark Dickinson2fc92632008-02-06 22:10:50 +00003457 comparison = self._cmp(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003458 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003459 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003460
3461 if comparison == -1:
3462 ans = self.next_plus(context)
3463 else: # comparison == 1
3464 ans = self.next_minus(context)
3465
3466 # decide which flags to raise using value of ans
3467 if ans._isinfinity():
3468 context._raise_error(Overflow,
3469 'Infinite result from next_toward',
3470 ans._sign)
Facundo Batista353750c2007-09-13 18:13:15 +00003471 context._raise_error(Inexact)
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00003472 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00003473 elif ans.adjusted() < context.Emin:
3474 context._raise_error(Underflow)
3475 context._raise_error(Subnormal)
Facundo Batista353750c2007-09-13 18:13:15 +00003476 context._raise_error(Inexact)
Mark Dickinson4f96f5f2010-05-04 14:25:50 +00003477 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00003478 # if precision == 1 then we don't raise Clamped for a
3479 # result 0E-Etiny.
3480 if not ans:
3481 context._raise_error(Clamped)
3482
3483 return ans
3484
3485 def number_class(self, context=None):
3486 """Returns an indication of the class of self.
3487
3488 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003489 sNaN
3490 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003491 -Infinity
3492 -Normal
3493 -Subnormal
3494 -Zero
3495 +Zero
3496 +Subnormal
3497 +Normal
3498 +Infinity
3499 """
3500 if self.is_snan():
3501 return "sNaN"
3502 if self.is_qnan():
3503 return "NaN"
3504 inf = self._isinfinity()
3505 if inf == 1:
3506 return "+Infinity"
3507 if inf == -1:
3508 return "-Infinity"
3509 if self.is_zero():
3510 if self._sign:
3511 return "-Zero"
3512 else:
3513 return "+Zero"
3514 if context is None:
3515 context = getcontext()
3516 if self.is_subnormal(context=context):
3517 if self._sign:
3518 return "-Subnormal"
3519 else:
3520 return "+Subnormal"
3521 # just a normal, regular, boring number, :)
3522 if self._sign:
3523 return "-Normal"
3524 else:
3525 return "+Normal"
3526
3527 def radix(self):
3528 """Just returns 10, as this is Decimal, :)"""
3529 return Decimal(10)
3530
3531 def rotate(self, other, context=None):
3532 """Returns a rotated copy of self, value-of-other times."""
3533 if context is None:
3534 context = getcontext()
3535
Mark Dickinson0c673122009-10-29 12:04:00 +00003536 other = _convert_other(other, raiseit=True)
3537
Facundo Batista353750c2007-09-13 18:13:15 +00003538 ans = self._check_nans(other, context)
3539 if ans:
3540 return ans
3541
3542 if other._exp != 0:
3543 return context._raise_error(InvalidOperation)
3544 if not (-context.prec <= int(other) <= context.prec):
3545 return context._raise_error(InvalidOperation)
3546
3547 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003548 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003549
3550 # get values, pad if necessary
3551 torot = int(other)
3552 rotdig = self._int
3553 topad = context.prec - len(rotdig)
Mark Dickinson6f390012009-10-29 12:11:18 +00003554 if topad > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003555 rotdig = '0'*topad + rotdig
Mark Dickinson6f390012009-10-29 12:11:18 +00003556 elif topad < 0:
3557 rotdig = rotdig[-topad:]
Facundo Batista353750c2007-09-13 18:13:15 +00003558
3559 # let's rotate!
3560 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003561 return _dec_from_triple(self._sign,
3562 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003563
Mark Dickinson0c673122009-10-29 12:04:00 +00003564 def scaleb(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00003565 """Returns self operand after adding the second value to its exp."""
3566 if context is None:
3567 context = getcontext()
3568
Mark Dickinson0c673122009-10-29 12:04:00 +00003569 other = _convert_other(other, raiseit=True)
3570
Facundo Batista353750c2007-09-13 18:13:15 +00003571 ans = self._check_nans(other, context)
3572 if ans:
3573 return ans
3574
3575 if other._exp != 0:
3576 return context._raise_error(InvalidOperation)
3577 liminf = -2 * (context.Emax + context.prec)
3578 limsup = 2 * (context.Emax + context.prec)
3579 if not (liminf <= int(other) <= limsup):
3580 return context._raise_error(InvalidOperation)
3581
3582 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003583 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003584
Facundo Batista72bc54f2007-11-23 17:59:00 +00003585 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003586 d = d._fix(context)
3587 return d
3588
3589 def shift(self, other, context=None):
3590 """Returns a shifted copy of self, value-of-other times."""
3591 if context is None:
3592 context = getcontext()
3593
Mark Dickinson0c673122009-10-29 12:04:00 +00003594 other = _convert_other(other, raiseit=True)
3595
Facundo Batista353750c2007-09-13 18:13:15 +00003596 ans = self._check_nans(other, context)
3597 if ans:
3598 return ans
3599
3600 if other._exp != 0:
3601 return context._raise_error(InvalidOperation)
3602 if not (-context.prec <= int(other) <= context.prec):
3603 return context._raise_error(InvalidOperation)
3604
3605 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003606 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003607
3608 # get values, pad if necessary
3609 torot = int(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003610 rotdig = self._int
3611 topad = context.prec - len(rotdig)
Mark Dickinson6f390012009-10-29 12:11:18 +00003612 if topad > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003613 rotdig = '0'*topad + rotdig
Mark Dickinson6f390012009-10-29 12:11:18 +00003614 elif topad < 0:
3615 rotdig = rotdig[-topad:]
Facundo Batista353750c2007-09-13 18:13:15 +00003616
3617 # let's shift!
3618 if torot < 0:
Mark Dickinson6f390012009-10-29 12:11:18 +00003619 shifted = rotdig[:torot]
Facundo Batista353750c2007-09-13 18:13:15 +00003620 else:
Mark Dickinson6f390012009-10-29 12:11:18 +00003621 shifted = rotdig + '0'*torot
3622 shifted = shifted[-context.prec:]
Facundo Batista353750c2007-09-13 18:13:15 +00003623
Facundo Batista72bc54f2007-11-23 17:59:00 +00003624 return _dec_from_triple(self._sign,
Mark Dickinson6f390012009-10-29 12:11:18 +00003625 shifted.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003626
Facundo Batista59c58842007-04-10 12:58:45 +00003627 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003628 def __reduce__(self):
3629 return (self.__class__, (str(self),))
3630
3631 def __copy__(self):
Benjamin Peterson28e369a2010-01-25 03:58:21 +00003632 if type(self) is Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003633 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003634 return self.__class__(str(self))
3635
3636 def __deepcopy__(self, memo):
Benjamin Peterson28e369a2010-01-25 03:58:21 +00003637 if type(self) is Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003638 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003639 return self.__class__(str(self))
3640
Mark Dickinson277859d2009-03-17 23:03:46 +00003641 # PEP 3101 support. the _localeconv keyword argument should be
3642 # considered private: it's provided for ease of testing only.
3643 def __format__(self, specifier, context=None, _localeconv=None):
Mark Dickinsonf4da7772008-02-29 03:29:17 +00003644 """Format a Decimal instance according to the given specifier.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003645
3646 The specifier should be a standard format specifier, with the
3647 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson277859d2009-03-17 23:03:46 +00003648 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3649 type is omitted it defaults to 'g' or 'G', depending on the
3650 value of context.capitals.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003651 """
3652
3653 # Note: PEP 3101 says that if the type is not present then
3654 # there should be at least one digit after the decimal point.
3655 # We take the liberty of ignoring this requirement for
3656 # Decimal---it's presumably there to make sure that
3657 # format(float, '') behaves similarly to str(float).
3658 if context is None:
3659 context = getcontext()
3660
Mark Dickinson277859d2009-03-17 23:03:46 +00003661 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003662
Mark Dickinson277859d2009-03-17 23:03:46 +00003663 # special values don't care about the type or precision
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003664 if self._is_special:
Mark Dickinson277859d2009-03-17 23:03:46 +00003665 sign = _format_sign(self._sign, spec)
3666 body = str(self.copy_abs())
Stefan Krahce2ec492014-08-26 20:49:57 +02003667 if spec['type'] == '%':
3668 body += '%'
Mark Dickinson277859d2009-03-17 23:03:46 +00003669 return _format_align(sign, body, spec)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003670
3671 # a type of None defaults to 'g' or 'G', depending on context
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003672 if spec['type'] is None:
3673 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson277859d2009-03-17 23:03:46 +00003674
3675 # if type is '%', adjust exponent of self accordingly
3676 if spec['type'] == '%':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003677 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3678
3679 # round if necessary, taking rounding mode from the context
3680 rounding = context.rounding
3681 precision = spec['precision']
3682 if precision is not None:
3683 if spec['type'] in 'eE':
3684 self = self._round(precision+1, rounding)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003685 elif spec['type'] in 'fF%':
3686 self = self._rescale(-precision, rounding)
Mark Dickinson277859d2009-03-17 23:03:46 +00003687 elif spec['type'] in 'gG' and len(self._int) > precision:
3688 self = self._round(precision, rounding)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003689 # special case: zeros with a positive exponent can't be
3690 # represented in fixed point; rescale them to 0e0.
Mark Dickinson277859d2009-03-17 23:03:46 +00003691 if not self and self._exp > 0 and spec['type'] in 'fF%':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003692 self = self._rescale(0, rounding)
3693
3694 # figure out placement of the decimal point
3695 leftdigits = self._exp + len(self._int)
Mark Dickinson277859d2009-03-17 23:03:46 +00003696 if spec['type'] in 'eE':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003697 if not self and precision is not None:
3698 dotplace = 1 - precision
3699 else:
3700 dotplace = 1
Mark Dickinson277859d2009-03-17 23:03:46 +00003701 elif spec['type'] in 'fF%':
3702 dotplace = leftdigits
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003703 elif spec['type'] in 'gG':
3704 if self._exp <= 0 and leftdigits > -6:
3705 dotplace = leftdigits
3706 else:
3707 dotplace = 1
3708
Mark Dickinson277859d2009-03-17 23:03:46 +00003709 # find digits before and after decimal point, and get exponent
3710 if dotplace < 0:
3711 intpart = '0'
3712 fracpart = '0'*(-dotplace) + self._int
3713 elif dotplace > len(self._int):
3714 intpart = self._int + '0'*(dotplace-len(self._int))
3715 fracpart = ''
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003716 else:
Mark Dickinson277859d2009-03-17 23:03:46 +00003717 intpart = self._int[:dotplace] or '0'
3718 fracpart = self._int[dotplace:]
3719 exp = leftdigits-dotplace
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003720
Mark Dickinson277859d2009-03-17 23:03:46 +00003721 # done with the decimal-specific stuff; hand over the rest
3722 # of the formatting to the _format_number function
3723 return _format_number(self._sign, intpart, fracpart, exp, spec)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003724
Facundo Batista72bc54f2007-11-23 17:59:00 +00003725def _dec_from_triple(sign, coefficient, exponent, special=False):
3726 """Create a decimal instance directly, without any validation,
3727 normalization (e.g. removal of leading zeros) or argument
3728 conversion.
3729
3730 This function is for *internal use only*.
3731 """
3732
3733 self = object.__new__(Decimal)
3734 self._sign = sign
3735 self._int = coefficient
3736 self._exp = exponent
3737 self._is_special = special
3738
3739 return self
3740
Raymond Hettinger2c8585b2009-02-03 03:37:03 +00003741# Register Decimal as a kind of Number (an abstract base class).
3742# However, do not register it as Real (because Decimals are not
3743# interoperable with floats).
3744_numbers.Number.register(Decimal)
3745
3746
Facundo Batista59c58842007-04-10 12:58:45 +00003747##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003748
Nick Coghlanced12182006-09-02 03:54:17 +00003749class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003750 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003751
Nick Coghlanced12182006-09-02 03:54:17 +00003752 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003753 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003754 """
3755 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003756 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003757 def __enter__(self):
3758 self.saved_context = getcontext()
3759 setcontext(self.new_context)
3760 return self.new_context
3761 def __exit__(self, t, v, tb):
3762 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003763
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003764class Context(object):
3765 """Contains the context for a Decimal instance.
3766
3767 Contains:
3768 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003769 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003770 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003771 raised when it is caused. Otherwise, a value is
3772 substituted in.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003773 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003774 (Whether or not the trap_enabler is set)
3775 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003776 Emin - Minimum exponent
3777 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003778 capitals - If 1, 1*10^1 is printed as 1E+1.
3779 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003780 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003781 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003782
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003783 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003784 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003785 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003786 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003787 _ignored_flags=None):
Mark Dickinson9b9e1252010-07-08 21:22:54 +00003788 # Set defaults; for everything except flags and _ignored_flags,
3789 # inherit from DefaultContext.
3790 try:
3791 dc = DefaultContext
3792 except NameError:
3793 pass
3794
3795 self.prec = prec if prec is not None else dc.prec
3796 self.rounding = rounding if rounding is not None else dc.rounding
3797 self.Emin = Emin if Emin is not None else dc.Emin
3798 self.Emax = Emax if Emax is not None else dc.Emax
3799 self.capitals = capitals if capitals is not None else dc.capitals
3800 self._clamp = _clamp if _clamp is not None else dc._clamp
3801
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003802 if _ignored_flags is None:
Mark Dickinson9b9e1252010-07-08 21:22:54 +00003803 self._ignored_flags = []
3804 else:
3805 self._ignored_flags = _ignored_flags
3806
3807 if traps is None:
3808 self.traps = dc.traps.copy()
3809 elif not isinstance(traps, dict):
3810 self.traps = dict((s, int(s in traps)) for s in _signals)
3811 else:
3812 self.traps = traps
3813
3814 if flags is None:
3815 self.flags = dict.fromkeys(_signals, 0)
3816 elif not isinstance(flags, dict):
3817 self.flags = dict((s, int(s in flags)) for s in _signals)
3818 else:
3819 self.flags = flags
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003820
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003821 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003822 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003823 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003824 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3825 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3826 % vars(self))
3827 names = [f.__name__ for f, v in self.flags.items() if v]
3828 s.append('flags=[' + ', '.join(names) + ']')
3829 names = [t.__name__ for t, v in self.traps.items() if v]
3830 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003831 return ', '.join(s) + ')'
3832
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003833 def clear_flags(self):
3834 """Reset all flags to zero"""
3835 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003836 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003837
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003838 def _shallow_copy(self):
3839 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003840 nc = Context(self.prec, self.rounding, self.traps,
3841 self.flags, self.Emin, self.Emax,
3842 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003843 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003844
3845 def copy(self):
3846 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003847 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003848 self.flags.copy(), self.Emin, self.Emax,
3849 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003850 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003851 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003852
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003853 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003854 """Handles an error
3855
3856 If the flag is in _ignored_flags, returns the default response.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003857 Otherwise, it sets the flag, then, if the corresponding
Stefan Krah8a6f3fe2010-05-19 15:46:39 +00003858 trap_enabler is set, it reraises the exception. Otherwise, it returns
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003859 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003860 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003861 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003862 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003863 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003864 return error().handle(self, *args)
3865
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003866 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003867 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003868 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003869 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003870
3871 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003872 # self._ignored_flags = []
Mark Dickinson8aca9d02008-05-04 02:05:06 +00003873 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003874
3875 def _ignore_all_flags(self):
3876 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003877 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003878
3879 def _ignore_flags(self, *flags):
3880 """Ignore the flags, if they are raised"""
3881 # Do not mutate-- This way, copies of a context leave the original
3882 # alone.
3883 self._ignored_flags = (self._ignored_flags + list(flags))
3884 return list(flags)
3885
3886 def _regard_flags(self, *flags):
3887 """Stop ignoring the flags, if they are raised"""
3888 if flags and isinstance(flags[0], (tuple,list)):
3889 flags = flags[0]
3890 for flag in flags:
3891 self._ignored_flags.remove(flag)
3892
Nick Coghlan53663a62008-07-15 14:27:37 +00003893 # We inherit object.__hash__, so we must deny this explicitly
3894 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003895
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003896 def Etiny(self):
3897 """Returns Etiny (= Emin - prec + 1)"""
3898 return int(self.Emin - self.prec + 1)
3899
3900 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003901 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003902 return int(self.Emax - self.prec + 1)
3903
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003904 def _set_rounding(self, type):
3905 """Sets the rounding type.
3906
3907 Sets the rounding type, and returns the current (previous)
3908 rounding type. Often used like:
3909
3910 context = context.copy()
3911 # so you don't change the calling context
3912 # if an error occurs in the middle.
3913 rounding = context._set_rounding(ROUND_UP)
3914 val = self.__sub__(other, context=context)
3915 context._set_rounding(rounding)
3916
3917 This will make it round up for that operation.
3918 """
3919 rounding = self.rounding
3920 self.rounding= type
3921 return rounding
3922
Raymond Hettingerfed52962004-07-14 15:41:57 +00003923 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003924 """Creates a new Decimal instance but using self as context.
3925
3926 This method implements the to-number operation of the
3927 IBM Decimal specification."""
3928
3929 if isinstance(num, basestring) and num != num.strip():
3930 return self._raise_error(ConversionSyntax,
3931 "no trailing or leading whitespace is "
3932 "permitted.")
3933
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003934 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003935 if d._isnan() and len(d._int) > self.prec - self._clamp:
3936 return self._raise_error(ConversionSyntax,
3937 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003938 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003939
Raymond Hettingerf4d85972009-01-03 19:02:23 +00003940 def create_decimal_from_float(self, f):
3941 """Creates a new Decimal instance from a float but rounding using self
3942 as the context.
3943
3944 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3945 >>> context.create_decimal_from_float(3.1415926535897932)
3946 Decimal('3.1415')
3947 >>> context = Context(prec=5, traps=[Inexact])
3948 >>> context.create_decimal_from_float(3.1415926535897932)
3949 Traceback (most recent call last):
3950 ...
3951 Inexact: None
3952
3953 """
3954 d = Decimal.from_float(f) # An exact conversion
3955 return d._fix(self) # Apply the context rounding
3956
Facundo Batista59c58842007-04-10 12:58:45 +00003957 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003958 def abs(self, a):
3959 """Returns the absolute value of the operand.
3960
3961 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003962 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003963 the plus operation on the operand.
3964
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003965 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003966 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003967 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003968 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003969 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003970 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003971 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003972 Decimal('101.5')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003973 >>> ExtendedContext.abs(-1)
3974 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003975 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003976 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003977 return a.__abs__(context=self)
3978
3979 def add(self, a, b):
3980 """Return the sum of the two operands.
3981
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003982 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003983 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003984 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003985 Decimal('1.02E+4')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003986 >>> ExtendedContext.add(1, Decimal(2))
3987 Decimal('3')
3988 >>> ExtendedContext.add(Decimal(8), 5)
3989 Decimal('13')
3990 >>> ExtendedContext.add(5, 5)
3991 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003992 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003993 a = _convert_other(a, raiseit=True)
3994 r = a.__add__(b, context=self)
3995 if r is NotImplemented:
3996 raise TypeError("Unable to convert %s to Decimal" % b)
3997 else:
3998 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003999
4000 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00004001 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004002
Facundo Batista353750c2007-09-13 18:13:15 +00004003 def canonical(self, a):
4004 """Returns the same Decimal object.
4005
4006 As we do not have different encodings for the same number, the
4007 received object already is in its canonical form.
4008
4009 >>> ExtendedContext.canonical(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004010 Decimal('2.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004011 """
4012 return a.canonical(context=self)
4013
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004014 def compare(self, a, b):
4015 """Compares values numerically.
4016
4017 If the signs of the operands differ, a value representing each operand
4018 ('-1' if the operand is less than zero, '0' if the operand is zero or
4019 negative zero, or '1' if the operand is greater than zero) is used in
4020 place of that operand for the comparison instead of the actual
4021 operand.
4022
4023 The comparison is then effected by subtracting the second operand from
4024 the first and then returning a value according to the result of the
4025 subtraction: '-1' if the result is less than zero, '0' if the result is
4026 zero or negative zero, or '1' if the result is greater than zero.
4027
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004028 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004029 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004030 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004031 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004032 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004033 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004034 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004035 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004036 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004037 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004038 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004039 Decimal('-1')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004040 >>> ExtendedContext.compare(1, 2)
4041 Decimal('-1')
4042 >>> ExtendedContext.compare(Decimal(1), 2)
4043 Decimal('-1')
4044 >>> ExtendedContext.compare(1, Decimal(2))
4045 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004046 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004047 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004048 return a.compare(b, context=self)
4049
Facundo Batista353750c2007-09-13 18:13:15 +00004050 def compare_signal(self, a, b):
4051 """Compares the values of the two operands numerically.
4052
4053 It's pretty much like compare(), but all NaNs signal, with signaling
4054 NaNs taking precedence over quiet NaNs.
4055
4056 >>> c = ExtendedContext
4057 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004058 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004059 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004060 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004061 >>> c.flags[InvalidOperation] = 0
4062 >>> print c.flags[InvalidOperation]
4063 0
4064 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004065 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00004066 >>> print c.flags[InvalidOperation]
4067 1
4068 >>> c.flags[InvalidOperation] = 0
4069 >>> print c.flags[InvalidOperation]
4070 0
4071 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004072 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00004073 >>> print c.flags[InvalidOperation]
4074 1
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004075 >>> c.compare_signal(-1, 2)
4076 Decimal('-1')
4077 >>> c.compare_signal(Decimal(-1), 2)
4078 Decimal('-1')
4079 >>> c.compare_signal(-1, Decimal(2))
4080 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004081 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004082 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004083 return a.compare_signal(b, context=self)
4084
4085 def compare_total(self, a, b):
4086 """Compares two operands using their abstract representation.
4087
4088 This is not like the standard compare, which use their numerical
4089 value. Note that a total ordering is defined for all possible abstract
4090 representations.
4091
4092 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004093 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004094 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004095 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004096 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004097 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004098 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004099 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004100 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004101 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004102 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004103 Decimal('-1')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004104 >>> ExtendedContext.compare_total(1, 2)
4105 Decimal('-1')
4106 >>> ExtendedContext.compare_total(Decimal(1), 2)
4107 Decimal('-1')
4108 >>> ExtendedContext.compare_total(1, Decimal(2))
4109 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004110 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004111 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004112 return a.compare_total(b)
4113
4114 def compare_total_mag(self, a, b):
4115 """Compares two operands using their abstract representation ignoring sign.
4116
4117 Like compare_total, but with operand's sign ignored and assumed to be 0.
4118 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004119 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004120 return a.compare_total_mag(b)
4121
4122 def copy_abs(self, a):
4123 """Returns a copy of the operand with the sign set to 0.
4124
4125 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004126 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00004127 >>> ExtendedContext.copy_abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004128 Decimal('100')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004129 >>> ExtendedContext.copy_abs(-1)
4130 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004131 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004132 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004133 return a.copy_abs()
4134
4135 def copy_decimal(self, a):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004136 """Returns a copy of the decimal object.
Facundo Batista353750c2007-09-13 18:13:15 +00004137
4138 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004139 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00004140 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004141 Decimal('-1.00')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004142 >>> ExtendedContext.copy_decimal(1)
4143 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004144 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004145 a = _convert_other(a, raiseit=True)
Facundo Batista6c398da2007-09-17 17:30:13 +00004146 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00004147
4148 def copy_negate(self, a):
4149 """Returns a copy of the operand with the sign inverted.
4150
4151 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004152 Decimal('-101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00004153 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004154 Decimal('101.5')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004155 >>> ExtendedContext.copy_negate(1)
4156 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004157 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004158 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004159 return a.copy_negate()
4160
4161 def copy_sign(self, a, b):
4162 """Copies the second operand's sign to the first one.
4163
4164 In detail, it returns a copy of the first operand with the sign
4165 equal to the sign of the second operand.
4166
4167 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004168 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004169 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004170 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004171 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004172 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004173 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004174 Decimal('-1.50')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004175 >>> ExtendedContext.copy_sign(1, -2)
4176 Decimal('-1')
4177 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4178 Decimal('-1')
4179 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4180 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004181 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004182 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004183 return a.copy_sign(b)
4184
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004185 def divide(self, a, b):
4186 """Decimal division in a specified context.
4187
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004188 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004189 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004190 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004191 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004192 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004193 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004194 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004195 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004196 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004197 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004198 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004199 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004200 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004201 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004202 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004203 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004204 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004205 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004206 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004207 Decimal('1.20E+6')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004208 >>> ExtendedContext.divide(5, 5)
4209 Decimal('1')
4210 >>> ExtendedContext.divide(Decimal(5), 5)
4211 Decimal('1')
4212 >>> ExtendedContext.divide(5, Decimal(5))
4213 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004214 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004215 a = _convert_other(a, raiseit=True)
4216 r = a.__div__(b, context=self)
4217 if r is NotImplemented:
4218 raise TypeError("Unable to convert %s to Decimal" % b)
4219 else:
4220 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004221
4222 def divide_int(self, a, b):
4223 """Divides two numbers and returns the integer part of the result.
4224
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004225 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004226 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004227 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004228 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004229 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004230 Decimal('3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004231 >>> ExtendedContext.divide_int(10, 3)
4232 Decimal('3')
4233 >>> ExtendedContext.divide_int(Decimal(10), 3)
4234 Decimal('3')
4235 >>> ExtendedContext.divide_int(10, Decimal(3))
4236 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004237 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004238 a = _convert_other(a, raiseit=True)
4239 r = a.__floordiv__(b, context=self)
4240 if r is NotImplemented:
4241 raise TypeError("Unable to convert %s to Decimal" % b)
4242 else:
4243 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004244
4245 def divmod(self, a, b):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004246 """Return (a // b, a % b).
Mark Dickinson202eb902010-01-06 16:20:22 +00004247
4248 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4249 (Decimal('2'), Decimal('2'))
4250 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4251 (Decimal('2'), Decimal('0'))
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004252 >>> ExtendedContext.divmod(8, 4)
4253 (Decimal('2'), Decimal('0'))
4254 >>> ExtendedContext.divmod(Decimal(8), 4)
4255 (Decimal('2'), Decimal('0'))
4256 >>> ExtendedContext.divmod(8, Decimal(4))
4257 (Decimal('2'), Decimal('0'))
Mark Dickinson202eb902010-01-06 16:20:22 +00004258 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004259 a = _convert_other(a, raiseit=True)
4260 r = a.__divmod__(b, context=self)
4261 if r is NotImplemented:
4262 raise TypeError("Unable to convert %s to Decimal" % b)
4263 else:
4264 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004265
Facundo Batista353750c2007-09-13 18:13:15 +00004266 def exp(self, a):
4267 """Returns e ** a.
4268
4269 >>> c = ExtendedContext.copy()
4270 >>> c.Emin = -999
4271 >>> c.Emax = 999
4272 >>> c.exp(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004273 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004274 >>> c.exp(Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004275 Decimal('0.367879441')
Facundo Batista353750c2007-09-13 18:13:15 +00004276 >>> c.exp(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004277 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004278 >>> c.exp(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004279 Decimal('2.71828183')
Facundo Batista353750c2007-09-13 18:13:15 +00004280 >>> c.exp(Decimal('0.693147181'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004281 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004282 >>> c.exp(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004283 Decimal('Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004284 >>> c.exp(10)
4285 Decimal('22026.4658')
Facundo Batista353750c2007-09-13 18:13:15 +00004286 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004287 a =_convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004288 return a.exp(context=self)
4289
4290 def fma(self, a, b, c):
4291 """Returns a multiplied by b, plus c.
4292
4293 The first two operands are multiplied together, using multiply,
4294 the third operand is then added to the result of that
4295 multiplication, using add, all with only one final rounding.
4296
4297 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004298 Decimal('22')
Facundo Batista353750c2007-09-13 18:13:15 +00004299 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004300 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004301 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004302 Decimal('1.38435736E+12')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004303 >>> ExtendedContext.fma(1, 3, 4)
4304 Decimal('7')
4305 >>> ExtendedContext.fma(1, Decimal(3), 4)
4306 Decimal('7')
4307 >>> ExtendedContext.fma(1, 3, Decimal(4))
4308 Decimal('7')
Facundo Batista353750c2007-09-13 18:13:15 +00004309 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004310 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004311 return a.fma(b, c, context=self)
4312
4313 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004314 """Return True if the operand is canonical; otherwise return False.
4315
4316 Currently, the encoding of a Decimal instance is always
4317 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00004318
4319 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004320 True
Facundo Batista353750c2007-09-13 18:13:15 +00004321 """
Facundo Batista1a191df2007-10-02 17:01:24 +00004322 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00004323
4324 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004325 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004326
Facundo Batista1a191df2007-10-02 17:01:24 +00004327 A Decimal instance is considered finite if it is neither
4328 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00004329
4330 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004331 True
Facundo Batista353750c2007-09-13 18:13:15 +00004332 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004333 True
Facundo Batista353750c2007-09-13 18:13:15 +00004334 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004335 True
Facundo Batista353750c2007-09-13 18:13:15 +00004336 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004337 False
Facundo Batista353750c2007-09-13 18:13:15 +00004338 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004339 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004340 >>> ExtendedContext.is_finite(1)
4341 True
Facundo Batista353750c2007-09-13 18:13:15 +00004342 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004343 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004344 return a.is_finite()
4345
4346 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004347 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004348
4349 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004350 False
Facundo Batista353750c2007-09-13 18:13:15 +00004351 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004352 True
Facundo Batista353750c2007-09-13 18:13:15 +00004353 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004354 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004355 >>> ExtendedContext.is_infinite(1)
4356 False
Facundo Batista353750c2007-09-13 18:13:15 +00004357 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004358 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004359 return a.is_infinite()
4360
4361 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004362 """Return True if the operand is a qNaN or sNaN;
4363 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004364
4365 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004366 False
Facundo Batista353750c2007-09-13 18:13:15 +00004367 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004368 True
Facundo Batista353750c2007-09-13 18:13:15 +00004369 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004370 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004371 >>> ExtendedContext.is_nan(1)
4372 False
Facundo Batista353750c2007-09-13 18:13:15 +00004373 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004374 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004375 return a.is_nan()
4376
4377 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004378 """Return True if the operand is a normal number;
4379 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004380
4381 >>> c = ExtendedContext.copy()
4382 >>> c.Emin = -999
4383 >>> c.Emax = 999
4384 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004385 True
Facundo Batista353750c2007-09-13 18:13:15 +00004386 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004387 False
Facundo Batista353750c2007-09-13 18:13:15 +00004388 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004389 False
Facundo Batista353750c2007-09-13 18:13:15 +00004390 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004391 False
Facundo Batista353750c2007-09-13 18:13:15 +00004392 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004393 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004394 >>> c.is_normal(1)
4395 True
Facundo Batista353750c2007-09-13 18:13:15 +00004396 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004397 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004398 return a.is_normal(context=self)
4399
4400 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004401 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004402
4403 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004404 False
Facundo Batista353750c2007-09-13 18:13:15 +00004405 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004406 True
Facundo Batista353750c2007-09-13 18:13:15 +00004407 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004408 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004409 >>> ExtendedContext.is_qnan(1)
4410 False
Facundo Batista353750c2007-09-13 18:13:15 +00004411 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004412 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004413 return a.is_qnan()
4414
4415 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004416 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004417
4418 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004419 False
Facundo Batista353750c2007-09-13 18:13:15 +00004420 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004421 True
Facundo Batista353750c2007-09-13 18:13:15 +00004422 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004423 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004424 >>> ExtendedContext.is_signed(8)
4425 False
4426 >>> ExtendedContext.is_signed(-8)
4427 True
Facundo Batista353750c2007-09-13 18:13:15 +00004428 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004429 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004430 return a.is_signed()
4431
4432 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004433 """Return True if the operand is a signaling NaN;
4434 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004435
4436 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004437 False
Facundo Batista353750c2007-09-13 18:13:15 +00004438 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004439 False
Facundo Batista353750c2007-09-13 18:13:15 +00004440 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004441 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004442 >>> ExtendedContext.is_snan(1)
4443 False
Facundo Batista353750c2007-09-13 18:13:15 +00004444 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004445 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004446 return a.is_snan()
4447
4448 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004449 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004450
4451 >>> c = ExtendedContext.copy()
4452 >>> c.Emin = -999
4453 >>> c.Emax = 999
4454 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004455 False
Facundo Batista353750c2007-09-13 18:13:15 +00004456 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004457 True
Facundo Batista353750c2007-09-13 18:13:15 +00004458 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004459 False
Facundo Batista353750c2007-09-13 18:13:15 +00004460 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004461 False
Facundo Batista353750c2007-09-13 18:13:15 +00004462 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004463 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004464 >>> c.is_subnormal(1)
4465 False
Facundo Batista353750c2007-09-13 18:13:15 +00004466 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004467 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004468 return a.is_subnormal(context=self)
4469
4470 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004471 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004472
4473 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004474 True
Facundo Batista353750c2007-09-13 18:13:15 +00004475 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004476 False
Facundo Batista353750c2007-09-13 18:13:15 +00004477 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004478 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004479 >>> ExtendedContext.is_zero(1)
4480 False
4481 >>> ExtendedContext.is_zero(0)
4482 True
Facundo Batista353750c2007-09-13 18:13:15 +00004483 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004484 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004485 return a.is_zero()
4486
4487 def ln(self, a):
4488 """Returns the natural (base e) logarithm of the operand.
4489
4490 >>> c = ExtendedContext.copy()
4491 >>> c.Emin = -999
4492 >>> c.Emax = 999
4493 >>> c.ln(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004494 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004495 >>> c.ln(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004496 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004497 >>> c.ln(Decimal('2.71828183'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004498 Decimal('1.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004499 >>> c.ln(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004500 Decimal('2.30258509')
Facundo Batista353750c2007-09-13 18:13:15 +00004501 >>> c.ln(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004502 Decimal('Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004503 >>> c.ln(1)
4504 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004505 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004506 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004507 return a.ln(context=self)
4508
4509 def log10(self, a):
4510 """Returns the base 10 logarithm of the operand.
4511
4512 >>> c = ExtendedContext.copy()
4513 >>> c.Emin = -999
4514 >>> c.Emax = 999
4515 >>> c.log10(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004516 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004517 >>> c.log10(Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004518 Decimal('-3')
Facundo Batista353750c2007-09-13 18:13:15 +00004519 >>> c.log10(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004520 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004521 >>> c.log10(Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004522 Decimal('0.301029996')
Facundo Batista353750c2007-09-13 18:13:15 +00004523 >>> c.log10(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004524 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004525 >>> c.log10(Decimal('70'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004526 Decimal('1.84509804')
Facundo Batista353750c2007-09-13 18:13:15 +00004527 >>> c.log10(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004528 Decimal('Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004529 >>> c.log10(0)
4530 Decimal('-Infinity')
4531 >>> c.log10(1)
4532 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004533 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004534 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004535 return a.log10(context=self)
4536
4537 def logb(self, a):
4538 """ Returns the exponent of the magnitude of the operand's MSD.
4539
4540 The result is the integer which is the exponent of the magnitude
4541 of the most significant digit of the operand (as though the
4542 operand were truncated to a single digit while maintaining the
4543 value of that digit and without limiting the resulting exponent).
4544
4545 >>> ExtendedContext.logb(Decimal('250'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004546 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004547 >>> ExtendedContext.logb(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004548 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004549 >>> ExtendedContext.logb(Decimal('0.03'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004550 Decimal('-2')
Facundo Batista353750c2007-09-13 18:13:15 +00004551 >>> ExtendedContext.logb(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004552 Decimal('-Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004553 >>> ExtendedContext.logb(1)
4554 Decimal('0')
4555 >>> ExtendedContext.logb(10)
4556 Decimal('1')
4557 >>> ExtendedContext.logb(100)
4558 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004559 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004560 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004561 return a.logb(context=self)
4562
4563 def logical_and(self, a, b):
4564 """Applies the logical operation 'and' between each operand's digits.
4565
4566 The operands must be both logical numbers.
4567
4568 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004569 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004570 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004571 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004572 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004573 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004574 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004575 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004576 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004577 Decimal('1000')
Facundo Batista353750c2007-09-13 18:13:15 +00004578 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004579 Decimal('10')
Mark Dickinson456e1652010-02-18 14:45:33 +00004580 >>> ExtendedContext.logical_and(110, 1101)
4581 Decimal('100')
4582 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4583 Decimal('100')
4584 >>> ExtendedContext.logical_and(110, Decimal(1101))
4585 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004586 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004587 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004588 return a.logical_and(b, context=self)
4589
4590 def logical_invert(self, a):
4591 """Invert all the digits in the operand.
4592
4593 The operand must be a logical number.
4594
4595 >>> ExtendedContext.logical_invert(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004596 Decimal('111111111')
Facundo Batista353750c2007-09-13 18:13:15 +00004597 >>> ExtendedContext.logical_invert(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004598 Decimal('111111110')
Facundo Batista353750c2007-09-13 18:13:15 +00004599 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004600 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004601 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004602 Decimal('10101010')
Mark Dickinson456e1652010-02-18 14:45:33 +00004603 >>> ExtendedContext.logical_invert(1101)
4604 Decimal('111110010')
Facundo Batista353750c2007-09-13 18:13:15 +00004605 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004606 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004607 return a.logical_invert(context=self)
4608
4609 def logical_or(self, a, b):
4610 """Applies the logical operation 'or' between each operand's digits.
4611
4612 The operands must be both logical numbers.
4613
4614 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004615 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004616 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004617 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004618 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004619 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004620 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004621 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004622 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004623 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004624 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004625 Decimal('1110')
Mark Dickinson456e1652010-02-18 14:45:33 +00004626 >>> ExtendedContext.logical_or(110, 1101)
4627 Decimal('1111')
4628 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4629 Decimal('1111')
4630 >>> ExtendedContext.logical_or(110, Decimal(1101))
4631 Decimal('1111')
Facundo Batista353750c2007-09-13 18:13:15 +00004632 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004633 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004634 return a.logical_or(b, context=self)
4635
4636 def logical_xor(self, a, b):
4637 """Applies the logical operation 'xor' between each operand's digits.
4638
4639 The operands must be both logical numbers.
4640
4641 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004642 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004643 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004644 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004645 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004646 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004647 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004648 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004649 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004650 Decimal('110')
Facundo Batista353750c2007-09-13 18:13:15 +00004651 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004652 Decimal('1101')
Mark Dickinson456e1652010-02-18 14:45:33 +00004653 >>> ExtendedContext.logical_xor(110, 1101)
4654 Decimal('1011')
4655 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4656 Decimal('1011')
4657 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4658 Decimal('1011')
Facundo Batista353750c2007-09-13 18:13:15 +00004659 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004660 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004661 return a.logical_xor(b, context=self)
4662
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004663 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004664 """max compares two values numerically and returns the maximum.
4665
4666 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004667 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004668 operation. If they are numerically equal then the left-hand operand
4669 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004670 infinity) of the two operands is chosen as the result.
4671
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004672 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004673 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004674 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004675 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004676 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004677 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004678 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004679 Decimal('7')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004680 >>> ExtendedContext.max(1, 2)
4681 Decimal('2')
4682 >>> ExtendedContext.max(Decimal(1), 2)
4683 Decimal('2')
4684 >>> ExtendedContext.max(1, Decimal(2))
4685 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004686 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004687 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004688 return a.max(b, context=self)
4689
Facundo Batista353750c2007-09-13 18:13:15 +00004690 def max_mag(self, a, b):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004691 """Compares the values numerically with their sign ignored.
4692
4693 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4694 Decimal('7')
4695 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4696 Decimal('-10')
4697 >>> ExtendedContext.max_mag(1, -2)
4698 Decimal('-2')
4699 >>> ExtendedContext.max_mag(Decimal(1), -2)
4700 Decimal('-2')
4701 >>> ExtendedContext.max_mag(1, Decimal(-2))
4702 Decimal('-2')
4703 """
4704 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004705 return a.max_mag(b, context=self)
4706
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004707 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004708 """min compares two values numerically and returns the minimum.
4709
4710 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004711 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004712 operation. If they are numerically equal then the left-hand operand
4713 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004714 infinity) of the two operands is chosen as the result.
4715
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004716 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004717 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004718 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004719 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004720 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004721 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004722 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004723 Decimal('7')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004724 >>> ExtendedContext.min(1, 2)
4725 Decimal('1')
4726 >>> ExtendedContext.min(Decimal(1), 2)
4727 Decimal('1')
4728 >>> ExtendedContext.min(1, Decimal(29))
4729 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004730 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004731 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004732 return a.min(b, context=self)
4733
Facundo Batista353750c2007-09-13 18:13:15 +00004734 def min_mag(self, a, b):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004735 """Compares the values numerically with their sign ignored.
4736
4737 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4738 Decimal('-2')
4739 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4740 Decimal('-3')
4741 >>> ExtendedContext.min_mag(1, -2)
4742 Decimal('1')
4743 >>> ExtendedContext.min_mag(Decimal(1), -2)
4744 Decimal('1')
4745 >>> ExtendedContext.min_mag(1, Decimal(-2))
4746 Decimal('1')
4747 """
4748 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004749 return a.min_mag(b, context=self)
4750
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004751 def minus(self, a):
4752 """Minus corresponds to unary prefix minus in Python.
4753
4754 The operation is evaluated using the same rules as subtract; the
4755 operation minus(a) is calculated as subtract('0', a) where the '0'
4756 has the same exponent as the operand.
4757
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004758 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004759 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004760 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004761 Decimal('1.3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004762 >>> ExtendedContext.minus(1)
4763 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004764 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004765 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004766 return a.__neg__(context=self)
4767
4768 def multiply(self, a, b):
4769 """multiply multiplies two operands.
4770
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004771 If either operand is a special value then the general rules apply.
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004772 Otherwise, the operands are multiplied together
4773 ('long multiplication'), resulting in a number which may be as long as
4774 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004775
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004776 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004777 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004778 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004779 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004780 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004781 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004782 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004783 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004784 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004785 Decimal('4.28135971E+11')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004786 >>> ExtendedContext.multiply(7, 7)
4787 Decimal('49')
4788 >>> ExtendedContext.multiply(Decimal(7), 7)
4789 Decimal('49')
4790 >>> ExtendedContext.multiply(7, Decimal(7))
4791 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004792 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004793 a = _convert_other(a, raiseit=True)
4794 r = a.__mul__(b, context=self)
4795 if r is NotImplemented:
4796 raise TypeError("Unable to convert %s to Decimal" % b)
4797 else:
4798 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004799
Facundo Batista353750c2007-09-13 18:13:15 +00004800 def next_minus(self, a):
4801 """Returns the largest representable number smaller than a.
4802
4803 >>> c = ExtendedContext.copy()
4804 >>> c.Emin = -999
4805 >>> c.Emax = 999
4806 >>> ExtendedContext.next_minus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004807 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004808 >>> c.next_minus(Decimal('1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004809 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004810 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004811 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004812 >>> c.next_minus(Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004813 Decimal('9.99999999E+999')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004814 >>> c.next_minus(1)
4815 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004816 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004817 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004818 return a.next_minus(context=self)
4819
4820 def next_plus(self, a):
4821 """Returns the smallest representable number larger than a.
4822
4823 >>> c = ExtendedContext.copy()
4824 >>> c.Emin = -999
4825 >>> c.Emax = 999
4826 >>> ExtendedContext.next_plus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004827 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004828 >>> c.next_plus(Decimal('-1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004829 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004830 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004831 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004832 >>> c.next_plus(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004833 Decimal('-9.99999999E+999')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004834 >>> c.next_plus(1)
4835 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004836 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004837 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004838 return a.next_plus(context=self)
4839
4840 def next_toward(self, a, b):
4841 """Returns the number closest to a, in direction towards b.
4842
4843 The result is the closest representable number from the first
4844 operand (but not the first operand) that is in the direction
4845 towards the second operand, unless the operands have the same
4846 value.
4847
4848 >>> c = ExtendedContext.copy()
4849 >>> c.Emin = -999
4850 >>> c.Emax = 999
4851 >>> c.next_toward(Decimal('1'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004852 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004853 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004854 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004855 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004856 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004857 >>> c.next_toward(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004858 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004859 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004860 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004861 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004862 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004863 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004864 Decimal('-0.00')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004865 >>> c.next_toward(0, 1)
4866 Decimal('1E-1007')
4867 >>> c.next_toward(Decimal(0), 1)
4868 Decimal('1E-1007')
4869 >>> c.next_toward(0, Decimal(1))
4870 Decimal('1E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004871 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004872 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004873 return a.next_toward(b, context=self)
4874
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004875 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004876 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004877
4878 Essentially a plus operation with all trailing zeros removed from the
4879 result.
4880
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004881 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004882 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004883 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004884 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004885 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004886 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004887 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004888 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004889 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004890 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004891 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004892 Decimal('0')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004893 >>> ExtendedContext.normalize(6)
4894 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004895 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004896 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004897 return a.normalize(context=self)
4898
Facundo Batista353750c2007-09-13 18:13:15 +00004899 def number_class(self, a):
4900 """Returns an indication of the class of the operand.
4901
4902 The class is one of the following strings:
4903 -sNaN
4904 -NaN
4905 -Infinity
4906 -Normal
4907 -Subnormal
4908 -Zero
4909 +Zero
4910 +Subnormal
4911 +Normal
4912 +Infinity
4913
4914 >>> c = Context(ExtendedContext)
4915 >>> c.Emin = -999
4916 >>> c.Emax = 999
4917 >>> c.number_class(Decimal('Infinity'))
4918 '+Infinity'
4919 >>> c.number_class(Decimal('1E-10'))
4920 '+Normal'
4921 >>> c.number_class(Decimal('2.50'))
4922 '+Normal'
4923 >>> c.number_class(Decimal('0.1E-999'))
4924 '+Subnormal'
4925 >>> c.number_class(Decimal('0'))
4926 '+Zero'
4927 >>> c.number_class(Decimal('-0'))
4928 '-Zero'
4929 >>> c.number_class(Decimal('-0.1E-999'))
4930 '-Subnormal'
4931 >>> c.number_class(Decimal('-1E-10'))
4932 '-Normal'
4933 >>> c.number_class(Decimal('-2.50'))
4934 '-Normal'
4935 >>> c.number_class(Decimal('-Infinity'))
4936 '-Infinity'
4937 >>> c.number_class(Decimal('NaN'))
4938 'NaN'
4939 >>> c.number_class(Decimal('-NaN'))
4940 'NaN'
4941 >>> c.number_class(Decimal('sNaN'))
4942 'sNaN'
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004943 >>> c.number_class(123)
4944 '+Normal'
Facundo Batista353750c2007-09-13 18:13:15 +00004945 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004946 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004947 return a.number_class(context=self)
4948
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004949 def plus(self, a):
4950 """Plus corresponds to unary prefix plus in Python.
4951
4952 The operation is evaluated using the same rules as add; the
4953 operation plus(a) is calculated as add('0', a) where the '0'
4954 has the same exponent as the operand.
4955
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004956 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004957 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004958 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004959 Decimal('-1.3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004960 >>> ExtendedContext.plus(-1)
4961 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004962 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004963 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004964 return a.__pos__(context=self)
4965
4966 def power(self, a, b, modulo=None):
4967 """Raises a to the power of b, to modulo if given.
4968
Facundo Batista353750c2007-09-13 18:13:15 +00004969 With two arguments, compute a**b. If a is negative then b
4970 must be integral. The result will be inexact unless b is
4971 integral and the result is finite and can be expressed exactly
4972 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004973
Facundo Batista353750c2007-09-13 18:13:15 +00004974 With three arguments, compute (a**b) % modulo. For the
4975 three argument form, the following restrictions on the
4976 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004977
Facundo Batista353750c2007-09-13 18:13:15 +00004978 - all three arguments must be integral
4979 - b must be nonnegative
4980 - at least one of a or b must be nonzero
4981 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004982
Facundo Batista353750c2007-09-13 18:13:15 +00004983 The result of pow(a, b, modulo) is identical to the result
4984 that would be obtained by computing (a**b) % modulo with
4985 unbounded precision, but is computed more efficiently. It is
4986 always exact.
4987
4988 >>> c = ExtendedContext.copy()
4989 >>> c.Emin = -999
4990 >>> c.Emax = 999
4991 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004992 Decimal('8')
Facundo Batista353750c2007-09-13 18:13:15 +00004993 >>> c.power(Decimal('-2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004994 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004995 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004996 Decimal('0.125')
Facundo Batista353750c2007-09-13 18:13:15 +00004997 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004998 Decimal('69.7575744')
Facundo Batista353750c2007-09-13 18:13:15 +00004999 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005000 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00005001 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005002 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00005003 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005004 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00005005 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005006 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00005007 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005008 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00005009 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005010 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00005011 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005012 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00005013 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005014 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00005015 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005016 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00005017
5018 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005019 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00005020 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005021 Decimal('-11')
Facundo Batista353750c2007-09-13 18:13:15 +00005022 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005023 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00005024 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005025 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00005026 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005027 Decimal('11729830')
Facundo Batista353750c2007-09-13 18:13:15 +00005028 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005029 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00005030 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005031 Decimal('1')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005032 >>> ExtendedContext.power(7, 7)
5033 Decimal('823543')
5034 >>> ExtendedContext.power(Decimal(7), 7)
5035 Decimal('823543')
5036 >>> ExtendedContext.power(7, Decimal(7), 2)
5037 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005038 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005039 a = _convert_other(a, raiseit=True)
5040 r = a.__pow__(b, modulo, context=self)
5041 if r is NotImplemented:
5042 raise TypeError("Unable to convert %s to Decimal" % b)
5043 else:
5044 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005045
5046 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00005047 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005048
5049 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00005050 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005051 exponent is being increased), multiplied by a positive power of ten (if
5052 the exponent is being decreased), or is unchanged (if the exponent is
5053 already equal to that of the right-hand operand).
5054
5055 Unlike other operations, if the length of the coefficient after the
5056 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00005057 operation condition is raised. This guarantees that, unless there is
5058 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005059 equal to that of the right-hand operand.
5060
5061 Also unlike other operations, quantize will never raise Underflow, even
5062 if the result is subnormal and inexact.
5063
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005064 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005065 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005066 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005067 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005068 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005069 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005070 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005071 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005072 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005073 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005074 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005075 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005076 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005077 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005078 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005079 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005080 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005081 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005082 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005083 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005084 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005085 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005086 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005087 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005088 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005089 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005090 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005091 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005092 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005093 Decimal('2E+2')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005094 >>> ExtendedContext.quantize(1, 2)
5095 Decimal('1')
5096 >>> ExtendedContext.quantize(Decimal(1), 2)
5097 Decimal('1')
5098 >>> ExtendedContext.quantize(1, Decimal(2))
5099 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005100 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005101 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005102 return a.quantize(b, context=self)
5103
Facundo Batista353750c2007-09-13 18:13:15 +00005104 def radix(self):
5105 """Just returns 10, as this is Decimal, :)
5106
5107 >>> ExtendedContext.radix()
Raymond Hettingerabe32372008-02-14 02:41:22 +00005108 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00005109 """
5110 return Decimal(10)
5111
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005112 def remainder(self, a, b):
5113 """Returns the remainder from integer division.
5114
5115 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00005116 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00005117 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00005118 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005119
5120 This operation will fail under the same conditions as integer division
5121 (that is, if integer division on the same two operands would fail, the
5122 remainder cannot be calculated).
5123
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005124 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005125 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005126 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005127 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005128 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005129 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005130 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005131 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005132 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005133 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005134 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005135 Decimal('1.0')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005136 >>> ExtendedContext.remainder(22, 6)
5137 Decimal('4')
5138 >>> ExtendedContext.remainder(Decimal(22), 6)
5139 Decimal('4')
5140 >>> ExtendedContext.remainder(22, Decimal(6))
5141 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005142 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005143 a = _convert_other(a, raiseit=True)
5144 r = a.__mod__(b, context=self)
5145 if r is NotImplemented:
5146 raise TypeError("Unable to convert %s to Decimal" % b)
5147 else:
5148 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005149
5150 def remainder_near(self, a, b):
5151 """Returns to be "a - b * n", where n is the integer nearest the exact
5152 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00005153 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005154 sign of a.
5155
5156 This operation will fail under the same conditions as integer division
5157 (that is, if integer division on the same two operands would fail, the
5158 remainder cannot be calculated).
5159
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005160 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005161 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005162 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005163 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005164 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005165 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005166 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005167 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005168 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005169 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005170 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005171 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005172 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005173 Decimal('-0.3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005174 >>> ExtendedContext.remainder_near(3, 11)
5175 Decimal('3')
5176 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5177 Decimal('3')
5178 >>> ExtendedContext.remainder_near(3, Decimal(11))
5179 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005180 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005181 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005182 return a.remainder_near(b, context=self)
5183
Facundo Batista353750c2007-09-13 18:13:15 +00005184 def rotate(self, a, b):
5185 """Returns a rotated copy of a, b times.
5186
5187 The coefficient of the result is a rotated copy of the digits in
5188 the coefficient of the first operand. The number of places of
5189 rotation is taken from the absolute value of the second operand,
5190 with the rotation being to the left if the second operand is
5191 positive or to the right otherwise.
5192
5193 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005194 Decimal('400000003')
Facundo Batista353750c2007-09-13 18:13:15 +00005195 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005196 Decimal('12')
Facundo Batista353750c2007-09-13 18:13:15 +00005197 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005198 Decimal('891234567')
Facundo Batista353750c2007-09-13 18:13:15 +00005199 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005200 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00005201 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005202 Decimal('345678912')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005203 >>> ExtendedContext.rotate(1333333, 1)
5204 Decimal('13333330')
5205 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5206 Decimal('13333330')
5207 >>> ExtendedContext.rotate(1333333, Decimal(1))
5208 Decimal('13333330')
Facundo Batista353750c2007-09-13 18:13:15 +00005209 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005210 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005211 return a.rotate(b, context=self)
5212
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005213 def same_quantum(self, a, b):
5214 """Returns True if the two operands have the same exponent.
5215
5216 The result is never affected by either the sign or the coefficient of
5217 either operand.
5218
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005219 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005220 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005221 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005222 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005223 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005224 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005225 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005226 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005227 >>> ExtendedContext.same_quantum(10000, -1)
5228 True
5229 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5230 True
5231 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5232 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005233 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005234 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005235 return a.same_quantum(b)
5236
Facundo Batista353750c2007-09-13 18:13:15 +00005237 def scaleb (self, a, b):
5238 """Returns the first operand after adding the second value its exp.
5239
5240 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005241 Decimal('0.0750')
Facundo Batista353750c2007-09-13 18:13:15 +00005242 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005243 Decimal('7.50')
Facundo Batista353750c2007-09-13 18:13:15 +00005244 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005245 Decimal('7.50E+3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005246 >>> ExtendedContext.scaleb(1, 4)
5247 Decimal('1E+4')
5248 >>> ExtendedContext.scaleb(Decimal(1), 4)
5249 Decimal('1E+4')
5250 >>> ExtendedContext.scaleb(1, Decimal(4))
5251 Decimal('1E+4')
Facundo Batista353750c2007-09-13 18:13:15 +00005252 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005253 a = _convert_other(a, raiseit=True)
5254 return a.scaleb(b, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00005255
5256 def shift(self, a, b):
5257 """Returns a shifted copy of a, b times.
5258
5259 The coefficient of the result is a shifted copy of the digits
5260 in the coefficient of the first operand. The number of places
5261 to shift is taken from the absolute value of the second operand,
5262 with the shift being to the left if the second operand is
5263 positive or to the right otherwise. Digits shifted into the
5264 coefficient are zeros.
5265
5266 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005267 Decimal('400000000')
Facundo Batista353750c2007-09-13 18:13:15 +00005268 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005269 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00005270 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005271 Decimal('1234567')
Facundo Batista353750c2007-09-13 18:13:15 +00005272 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005273 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00005274 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005275 Decimal('345678900')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005276 >>> ExtendedContext.shift(88888888, 2)
5277 Decimal('888888800')
5278 >>> ExtendedContext.shift(Decimal(88888888), 2)
5279 Decimal('888888800')
5280 >>> ExtendedContext.shift(88888888, Decimal(2))
5281 Decimal('888888800')
Facundo Batista353750c2007-09-13 18:13:15 +00005282 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005283 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005284 return a.shift(b, context=self)
5285
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005286 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00005287 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005288
5289 If the result must be inexact, it is rounded using the round-half-even
5290 algorithm.
5291
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005292 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005293 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005294 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005295 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005296 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005297 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005298 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005299 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005300 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005301 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005302 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005303 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005304 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005305 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005306 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005307 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005308 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005309 Decimal('3.16227766')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005310 >>> ExtendedContext.sqrt(2)
5311 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005312 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005313 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005314 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005315 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005316 return a.sqrt(context=self)
5317
5318 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005319 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005320
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005321 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005322 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005323 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005324 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005325 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005326 Decimal('-0.77')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005327 >>> ExtendedContext.subtract(8, 5)
5328 Decimal('3')
5329 >>> ExtendedContext.subtract(Decimal(8), 5)
5330 Decimal('3')
5331 >>> ExtendedContext.subtract(8, Decimal(5))
5332 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005333 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005334 a = _convert_other(a, raiseit=True)
5335 r = a.__sub__(b, context=self)
5336 if r is NotImplemented:
5337 raise TypeError("Unable to convert %s to Decimal" % b)
5338 else:
5339 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005340
5341 def to_eng_string(self, a):
5342 """Converts a number to a string, using scientific notation.
5343
5344 The operation is not affected by the context.
5345 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005346 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005347 return a.to_eng_string(context=self)
5348
5349 def to_sci_string(self, a):
5350 """Converts a number to a string, using scientific notation.
5351
5352 The operation is not affected by the context.
5353 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005354 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005355 return a.__str__(context=self)
5356
Facundo Batista353750c2007-09-13 18:13:15 +00005357 def to_integral_exact(self, a):
5358 """Rounds to an integer.
5359
5360 When the operand has a negative exponent, the result is the same
5361 as using the quantize() operation using the given operand as the
5362 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5363 of the operand as the precision setting; Inexact and Rounded flags
5364 are allowed in this operation. The rounding mode is taken from the
5365 context.
5366
5367 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005368 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00005369 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005370 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005371 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005372 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005373 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005374 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00005375 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005376 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00005377 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005378 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00005379 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005380 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00005381 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005382 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00005383 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005384 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005385 return a.to_integral_exact(context=self)
5386
5387 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005388 """Rounds to an integer.
5389
5390 When the operand has a negative exponent, the result is the same
5391 as using the quantize() operation using the given operand as the
5392 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5393 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00005394 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005395
Facundo Batista353750c2007-09-13 18:13:15 +00005396 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005397 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00005398 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005399 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005400 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005401 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005402 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005403 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00005404 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005405 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00005406 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005407 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00005408 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005409 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00005410 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005411 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005412 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005413 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005414 return a.to_integral_value(context=self)
5415
5416 # the method name changed, but we provide also the old one, for compatibility
5417 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005418
5419class _WorkRep(object):
5420 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005421 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005422 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005423 # exp: None, int, or string
5424
5425 def __init__(self, value=None):
5426 if value is None:
5427 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005428 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005429 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005430 elif isinstance(value, Decimal):
5431 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00005432 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005433 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005434 else:
5435 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005436 self.sign = value[0]
5437 self.int = value[1]
5438 self.exp = value[2]
5439
5440 def __repr__(self):
5441 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5442
5443 __str__ = __repr__
5444
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005445
5446
Facundo Batistae64acfa2007-12-17 14:18:42 +00005447def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005448 """Normalizes op1, op2 to have the same exp and length of coefficient.
5449
5450 Done during addition.
5451 """
Facundo Batista353750c2007-09-13 18:13:15 +00005452 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005453 tmp = op2
5454 other = op1
5455 else:
5456 tmp = op1
5457 other = op2
5458
Facundo Batista353750c2007-09-13 18:13:15 +00005459 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5460 # Then adding 10**exp to tmp has the same effect (after rounding)
5461 # as adding any positive quantity smaller than 10**exp; similarly
5462 # for subtraction. So if other is smaller than 10**exp we replace
5463 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00005464 tmp_len = len(str(tmp.int))
5465 other_len = len(str(other.int))
5466 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5467 if other_len + other.exp - 1 < exp:
5468 other.int = 1
5469 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005470
Facundo Batista353750c2007-09-13 18:13:15 +00005471 tmp.int *= 10 ** (tmp.exp - other.exp)
5472 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005473 return op1, op2
5474
Facundo Batista353750c2007-09-13 18:13:15 +00005475##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
5476
5477# This function from Tim Peters was taken from here:
5478# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5479# The correction being in the function definition is for speed, and
5480# the whole function is not resolved with math.log because of avoiding
5481# the use of floats.
5482def _nbits(n, correction = {
5483 '0': 4, '1': 3, '2': 2, '3': 2,
5484 '4': 1, '5': 1, '6': 1, '7': 1,
5485 '8': 0, '9': 0, 'a': 0, 'b': 0,
5486 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5487 """Number of bits in binary representation of the positive integer n,
5488 or 0 if n == 0.
5489 """
5490 if n < 0:
5491 raise ValueError("The argument to _nbits should be nonnegative.")
5492 hex_n = "%x" % n
5493 return 4*len(hex_n) - correction[hex_n[0]]
5494
Mark Dickinsona493ca32011-06-04 18:24:15 +01005495def _decimal_lshift_exact(n, e):
5496 """ Given integers n and e, return n * 10**e if it's an integer, else None.
5497
5498 The computation is designed to avoid computing large powers of 10
5499 unnecessarily.
5500
5501 >>> _decimal_lshift_exact(3, 4)
5502 30000
5503 >>> _decimal_lshift_exact(300, -999999999) # returns None
5504
5505 """
5506 if n == 0:
5507 return 0
5508 elif e >= 0:
5509 return n * 10**e
5510 else:
5511 # val_n = largest power of 10 dividing n.
5512 str_n = str(abs(n))
5513 val_n = len(str_n) - len(str_n.rstrip('0'))
5514 return None if val_n < -e else n // 10**-e
5515
Facundo Batista353750c2007-09-13 18:13:15 +00005516def _sqrt_nearest(n, a):
5517 """Closest integer to the square root of the positive integer n. a is
5518 an initial approximation to the square root. Any positive integer
5519 will do for a, but the closer a is to the square root of n the
5520 faster convergence will be.
5521
5522 """
5523 if n <= 0 or a <= 0:
5524 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5525
5526 b=0
5527 while a != b:
5528 b, a = a, a--n//a>>1
5529 return a
5530
5531def _rshift_nearest(x, shift):
5532 """Given an integer x and a nonnegative integer shift, return closest
5533 integer to x / 2**shift; use round-to-even in case of a tie.
5534
5535 """
5536 b, q = 1L << shift, x >> shift
5537 return q + (2*(x & (b-1)) + (q&1) > b)
5538
5539def _div_nearest(a, b):
5540 """Closest integer to a/b, a and b positive integers; rounds to even
5541 in the case of a tie.
5542
5543 """
5544 q, r = divmod(a, b)
5545 return q + (2*r + (q&1) > b)
5546
5547def _ilog(x, M, L = 8):
5548 """Integer approximation to M*log(x/M), with absolute error boundable
5549 in terms only of x/M.
5550
5551 Given positive integers x and M, return an integer approximation to
5552 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5553 between the approximation and the exact result is at most 22. For
5554 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5555 both cases these are upper bounds on the error; it will usually be
5556 much smaller."""
5557
5558 # The basic algorithm is the following: let log1p be the function
5559 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5560 # the reduction
5561 #
5562 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5563 #
5564 # repeatedly until the argument to log1p is small (< 2**-L in
5565 # absolute value). For small y we can use the Taylor series
5566 # expansion
5567 #
5568 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5569 #
5570 # truncating at T such that y**T is small enough. The whole
5571 # computation is carried out in a form of fixed-point arithmetic,
5572 # with a real number z being represented by an integer
5573 # approximation to z*M. To avoid loss of precision, the y below
5574 # is actually an integer approximation to 2**R*y*M, where R is the
5575 # number of reductions performed so far.
5576
5577 y = x-M
5578 # argument reduction; R = number of reductions performed
5579 R = 0
5580 while (R <= L and long(abs(y)) << L-R >= M or
5581 R > L and abs(y) >> R-L >= M):
5582 y = _div_nearest(long(M*y) << 1,
5583 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5584 R += 1
5585
5586 # Taylor series with T terms
5587 T = -int(-10*len(str(M))//(3*L))
5588 yshift = _rshift_nearest(y, R)
5589 w = _div_nearest(M, T)
5590 for k in xrange(T-1, 0, -1):
5591 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5592
5593 return _div_nearest(w*y, M)
5594
5595def _dlog10(c, e, p):
5596 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5597 approximation to 10**p * log10(c*10**e), with an absolute error of
5598 at most 1. Assumes that c*10**e is not exactly 1."""
5599
5600 # increase precision by 2; compensate for this by dividing
5601 # final result by 100
5602 p += 2
5603
5604 # write c*10**e as d*10**f with either:
5605 # f >= 0 and 1 <= d <= 10, or
5606 # f <= 0 and 0.1 <= d <= 1.
5607 # Thus for c*10**e close to 1, f = 0
5608 l = len(str(c))
5609 f = e+l - (e+l >= 1)
5610
5611 if p > 0:
5612 M = 10**p
5613 k = e+p-f
5614 if k >= 0:
5615 c *= 10**k
5616 else:
5617 c = _div_nearest(c, 10**-k)
5618
5619 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005620 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005621 log_d = _div_nearest(log_d*M, log_10)
5622 log_tenpower = f*M # exact
5623 else:
5624 log_d = 0 # error < 2.31
Neal Norwitz18aa3882008-08-24 05:04:52 +00005625 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Facundo Batista353750c2007-09-13 18:13:15 +00005626
5627 return _div_nearest(log_tenpower+log_d, 100)
5628
5629def _dlog(c, e, p):
5630 """Given integers c, e and p with c > 0, compute an integer
5631 approximation to 10**p * log(c*10**e), with an absolute error of
5632 at most 1. Assumes that c*10**e is not exactly 1."""
5633
5634 # Increase precision by 2. The precision increase is compensated
5635 # for at the end with a division by 100.
5636 p += 2
5637
5638 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5639 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5640 # as 10**p * log(d) + 10**p*f * log(10).
5641 l = len(str(c))
5642 f = e+l - (e+l >= 1)
5643
5644 # compute approximation to 10**p*log(d), with error < 27
5645 if p > 0:
5646 k = e+p-f
5647 if k >= 0:
5648 c *= 10**k
5649 else:
5650 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5651
5652 # _ilog magnifies existing error in c by a factor of at most 10
5653 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5654 else:
5655 # p <= 0: just approximate the whole thing by 0; error < 2.31
5656 log_d = 0
5657
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005658 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00005659 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005660 extra = len(str(abs(f)))-1
5661 if p + extra >= 0:
5662 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5663 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5664 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00005665 else:
5666 f_log_ten = 0
5667 else:
5668 f_log_ten = 0
5669
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005670 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005671 return _div_nearest(f_log_ten + log_d, 100)
5672
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005673class _Log10Memoize(object):
5674 """Class to compute, store, and allow retrieval of, digits of the
5675 constant log(10) = 2.302585.... This constant is needed by
5676 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5677 def __init__(self):
5678 self.digits = "23025850929940456840179914546843642076011014886"
5679
5680 def getdigits(self, p):
5681 """Given an integer p >= 0, return floor(10**p)*log(10).
5682
5683 For example, self.getdigits(3) returns 2302.
5684 """
5685 # digits are stored as a string, for quick conversion to
5686 # integer in the case that we've already computed enough
5687 # digits; the stored digits should always be correct
5688 # (truncated, not rounded to nearest).
5689 if p < 0:
5690 raise ValueError("p should be nonnegative")
5691
5692 if p >= len(self.digits):
5693 # compute p+3, p+6, p+9, ... digits; continue until at
5694 # least one of the extra digits is nonzero
5695 extra = 3
5696 while True:
5697 # compute p+extra digits, correct to within 1ulp
5698 M = 10**(p+extra+2)
5699 digits = str(_div_nearest(_ilog(10*M, M), 100))
5700 if digits[-extra:] != '0'*extra:
5701 break
5702 extra += 3
5703 # keep all reliable digits so far; remove trailing zeros
5704 # and next nonzero digit
5705 self.digits = digits.rstrip('0')[:-1]
5706 return int(self.digits[:p+1])
5707
5708_log10_digits = _Log10Memoize().getdigits
5709
Facundo Batista353750c2007-09-13 18:13:15 +00005710def _iexp(x, M, L=8):
5711 """Given integers x and M, M > 0, such that x/M is small in absolute
5712 value, compute an integer approximation to M*exp(x/M). For 0 <=
5713 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5714 is usually much smaller)."""
5715
5716 # Algorithm: to compute exp(z) for a real number z, first divide z
5717 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5718 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5719 # series
5720 #
5721 # expm1(x) = x + x**2/2! + x**3/3! + ...
5722 #
5723 # Now use the identity
5724 #
5725 # expm1(2x) = expm1(x)*(expm1(x)+2)
5726 #
5727 # R times to compute the sequence expm1(z/2**R),
5728 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5729
5730 # Find R such that x/2**R/M <= 2**-L
5731 R = _nbits((long(x)<<L)//M)
5732
5733 # Taylor series. (2**L)**T > M
5734 T = -int(-10*len(str(M))//(3*L))
5735 y = _div_nearest(x, T)
5736 Mshift = long(M)<<R
5737 for i in xrange(T-1, 0, -1):
5738 y = _div_nearest(x*(Mshift + y), Mshift * i)
5739
5740 # Expansion
5741 for k in xrange(R-1, -1, -1):
5742 Mshift = long(M)<<(k+2)
5743 y = _div_nearest(y*(y+Mshift), Mshift)
5744
5745 return M+y
5746
5747def _dexp(c, e, p):
5748 """Compute an approximation to exp(c*10**e), with p decimal places of
5749 precision.
5750
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005751 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005752
5753 10**(p-1) <= d <= 10**p, and
5754 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5755
5756 In other words, d*10**f is an approximation to exp(c*10**e) with p
5757 digits of precision, and with an error in d of at most 1. This is
5758 almost, but not quite, the same as the error being < 1ulp: when d
5759 = 10**(p-1) the error could be up to 10 ulp."""
5760
5761 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5762 p += 2
5763
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005764 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005765 extra = max(0, e + len(str(c)) - 1)
5766 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005767
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005768 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005769 # rounding down
5770 shift = e+q
5771 if shift >= 0:
5772 cshift = c*10**shift
5773 else:
5774 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005775 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005776
5777 # reduce remainder back to original precision
5778 rem = _div_nearest(rem, 10**extra)
5779
5780 # error in result of _iexp < 120; error after division < 0.62
5781 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5782
5783def _dpower(xc, xe, yc, ye, p):
5784 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5785 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5786
5787 10**(p-1) <= c <= 10**p, and
5788 (c-1)*10**e < x**y < (c+1)*10**e
5789
5790 in other words, c*10**e is an approximation to x**y with p digits
5791 of precision, and with an error in c of at most 1. (This is
5792 almost, but not quite, the same as the error being < 1ulp: when c
5793 == 10**(p-1) we can only guarantee error < 10ulp.)
5794
5795 We assume that: x is positive and not equal to 1, and y is nonzero.
5796 """
5797
5798 # Find b such that 10**(b-1) <= |y| <= 10**b
5799 b = len(str(abs(yc))) + ye
5800
5801 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5802 lxc = _dlog(xc, xe, p+b+1)
5803
5804 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5805 shift = ye-b
5806 if shift >= 0:
5807 pc = lxc*yc*10**shift
5808 else:
5809 pc = _div_nearest(lxc*yc, 10**-shift)
5810
5811 if pc == 0:
5812 # we prefer a result that isn't exactly 1; this makes it
5813 # easier to compute a correctly rounded result in __pow__
5814 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5815 coeff, exp = 10**(p-1)+1, 1-p
5816 else:
5817 coeff, exp = 10**p-1, -p
5818 else:
5819 coeff, exp = _dexp(pc, -(p+1), p+1)
5820 coeff = _div_nearest(coeff, 10)
5821 exp += 1
5822
5823 return coeff, exp
5824
5825def _log10_lb(c, correction = {
5826 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5827 '6': 23, '7': 16, '8': 10, '9': 5}):
5828 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5829 if c <= 0:
5830 raise ValueError("The argument to _log10_lb should be nonnegative.")
5831 str_c = str(c)
5832 return 100*len(str_c) - correction[str_c[0]]
5833
Facundo Batista59c58842007-04-10 12:58:45 +00005834##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005835
Mark Dickinson99d80962010-04-02 08:53:22 +00005836def _convert_other(other, raiseit=False, allow_float=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005837 """Convert other to Decimal.
5838
5839 Verifies that it's ok to use in an implicit construction.
Mark Dickinson99d80962010-04-02 08:53:22 +00005840 If allow_float is true, allow conversion from float; this
5841 is used in the comparison methods (__eq__ and friends).
5842
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005843 """
5844 if isinstance(other, Decimal):
5845 return other
5846 if isinstance(other, (int, long)):
5847 return Decimal(other)
Mark Dickinson99d80962010-04-02 08:53:22 +00005848 if allow_float and isinstance(other, float):
5849 return Decimal.from_float(other)
5850
Facundo Batista353750c2007-09-13 18:13:15 +00005851 if raiseit:
5852 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005853 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005854
Facundo Batista59c58842007-04-10 12:58:45 +00005855##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005856
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005857# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005858# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005859
5860DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005861 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005862 traps=[DivisionByZero, Overflow, InvalidOperation],
5863 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005864 Emax=999999999,
5865 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005866 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005867)
5868
5869# Pre-made alternate contexts offered by the specification
5870# Don't change these; the user should be able to select these
5871# contexts and be able to reproduce results from other implementations
5872# of the spec.
5873
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005874BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005875 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005876 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5877 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005878)
5879
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005880ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005881 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005882 traps=[],
5883 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005884)
5885
5886
Facundo Batista72bc54f2007-11-23 17:59:00 +00005887##### crud for parsing strings #############################################
Mark Dickinson6a123cb2008-02-24 18:12:36 +00005888#
Facundo Batista72bc54f2007-11-23 17:59:00 +00005889# Regular expression used for parsing numeric strings. Additional
5890# comments:
5891#
5892# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5893# whitespace. But note that the specification disallows whitespace in
5894# a numeric string.
5895#
5896# 2. For finite numbers (not infinities and NaNs) the body of the
5897# number between the optional sign and the optional exponent must have
5898# at least one decimal digit, possibly after the decimal point. The
5899# lookahead expression '(?=\d|\.\d)' checks this.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005900
5901import re
Mark Dickinson70c32892008-07-02 09:37:01 +00005902_parser = re.compile(r""" # A numeric string consists of:
Facundo Batista72bc54f2007-11-23 17:59:00 +00005903# \s*
Mark Dickinson70c32892008-07-02 09:37:01 +00005904 (?P<sign>[-+])? # an optional sign, followed by either...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005905 (
Mark Dickinson4326ad82009-08-02 10:59:36 +00005906 (?=\d|\.\d) # ...a number (with at least one digit)
5907 (?P<int>\d*) # having a (possibly empty) integer part
5908 (\.(?P<frac>\d*))? # followed by an optional fractional part
5909 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005910 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005911 Inf(inity)? # ...an infinity, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005912 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005913 (?P<signal>s)? # ...an (optionally signaling)
5914 NaN # NaN
Mark Dickinson4326ad82009-08-02 10:59:36 +00005915 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005916 )
5917# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005918 \Z
Mark Dickinson4326ad82009-08-02 10:59:36 +00005919""", re.VERBOSE | re.IGNORECASE | re.UNICODE).match
Facundo Batista72bc54f2007-11-23 17:59:00 +00005920
Facundo Batista2ec74152007-12-03 17:55:00 +00005921_all_zeros = re.compile('0*$').match
5922_exact_half = re.compile('50*$').match
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005923
5924##### PEP3101 support functions ##############################################
Mark Dickinson277859d2009-03-17 23:03:46 +00005925# The functions in this section have little to do with the Decimal
5926# class, and could potentially be reused or adapted for other pure
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005927# Python numeric classes that want to implement __format__
5928#
5929# A format specifier for Decimal looks like:
5930#
Mark Dickinson277859d2009-03-17 23:03:46 +00005931# [[fill]align][sign][0][minimumwidth][,][.precision][type]
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005932
5933_parse_format_specifier_regex = re.compile(r"""\A
5934(?:
5935 (?P<fill>.)?
5936 (?P<align>[<>=^])
5937)?
5938(?P<sign>[-+ ])?
5939(?P<zeropad>0)?
5940(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson277859d2009-03-17 23:03:46 +00005941(?P<thousands_sep>,)?
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005942(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson277859d2009-03-17 23:03:46 +00005943(?P<type>[eEfFgGn%])?
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005944\Z
5945""", re.VERBOSE)
5946
Facundo Batista72bc54f2007-11-23 17:59:00 +00005947del re
5948
Mark Dickinson277859d2009-03-17 23:03:46 +00005949# The locale module is only needed for the 'n' format specifier. The
5950# rest of the PEP 3101 code functions quite happily without it, so we
5951# don't care too much if locale isn't present.
5952try:
5953 import locale as _locale
5954except ImportError:
5955 pass
5956
5957def _parse_format_specifier(format_spec, _localeconv=None):
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005958 """Parse and validate a format specifier.
5959
5960 Turns a standard numeric format specifier into a dict, with the
5961 following entries:
5962
5963 fill: fill character to pad field to minimum width
5964 align: alignment type, either '<', '>', '=' or '^'
5965 sign: either '+', '-' or ' '
5966 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson277859d2009-03-17 23:03:46 +00005967 zeropad: boolean, indicating whether to pad with zeros
5968 thousands_sep: string to use as thousands separator, or ''
5969 grouping: grouping for thousands separators, in format
5970 used by localeconv
5971 decimal_point: string to use for decimal point
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005972 precision: nonnegative integer giving precision, or None
5973 type: one of the characters 'eEfFgG%', or None
Mark Dickinson277859d2009-03-17 23:03:46 +00005974 unicode: boolean (always True for Python 3.x)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005975
5976 """
5977 m = _parse_format_specifier_regex.match(format_spec)
5978 if m is None:
5979 raise ValueError("Invalid format specifier: " + format_spec)
5980
5981 # get the dictionary
5982 format_dict = m.groupdict()
5983
Mark Dickinson277859d2009-03-17 23:03:46 +00005984 # zeropad; defaults for fill and alignment. If zero padding
5985 # is requested, the fill and align fields should be absent.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005986 fill = format_dict['fill']
5987 align = format_dict['align']
Mark Dickinson277859d2009-03-17 23:03:46 +00005988 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
5989 if format_dict['zeropad']:
5990 if fill is not None:
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005991 raise ValueError("Fill character conflicts with '0'"
5992 " in format specifier: " + format_spec)
Mark Dickinson277859d2009-03-17 23:03:46 +00005993 if align is not None:
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005994 raise ValueError("Alignment conflicts with '0' in "
5995 "format specifier: " + format_spec)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005996 format_dict['fill'] = fill or ' '
Mark Dickinson5cfa8042009-09-08 20:20:19 +00005997 # PEP 3101 originally specified that the default alignment should
5998 # be left; it was later agreed that right-aligned makes more sense
5999 # for numeric types. See http://bugs.python.org/issue6857.
6000 format_dict['align'] = align or '>'
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006001
Mark Dickinson277859d2009-03-17 23:03:46 +00006002 # default sign handling: '-' for negative, '' for positive
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006003 if format_dict['sign'] is None:
6004 format_dict['sign'] = '-'
6005
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006006 # minimumwidth defaults to 0; precision remains None if not given
6007 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
6008 if format_dict['precision'] is not None:
6009 format_dict['precision'] = int(format_dict['precision'])
6010
6011 # if format type is 'g' or 'G' then a precision of 0 makes little
6012 # sense; convert it to 1. Same if format type is unspecified.
6013 if format_dict['precision'] == 0:
Mark Dickinson491ea552009-09-07 16:17:41 +00006014 if format_dict['type'] is None or format_dict['type'] in 'gG':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006015 format_dict['precision'] = 1
6016
Mark Dickinson277859d2009-03-17 23:03:46 +00006017 # determine thousands separator, grouping, and decimal separator, and
6018 # add appropriate entries to format_dict
6019 if format_dict['type'] == 'n':
6020 # apart from separators, 'n' behaves just like 'g'
6021 format_dict['type'] = 'g'
6022 if _localeconv is None:
6023 _localeconv = _locale.localeconv()
6024 if format_dict['thousands_sep'] is not None:
6025 raise ValueError("Explicit thousands separator conflicts with "
6026 "'n' type in format specifier: " + format_spec)
6027 format_dict['thousands_sep'] = _localeconv['thousands_sep']
6028 format_dict['grouping'] = _localeconv['grouping']
6029 format_dict['decimal_point'] = _localeconv['decimal_point']
6030 else:
6031 if format_dict['thousands_sep'] is None:
6032 format_dict['thousands_sep'] = ''
6033 format_dict['grouping'] = [3, 0]
6034 format_dict['decimal_point'] = '.'
6035
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006036 # record whether return type should be str or unicode
Serhiy Storchaka20c049d2014-10-14 21:10:56 +03006037 try:
6038 format_dict['unicode'] = isinstance(format_spec, unicode)
6039 except NameError:
6040 format_dict['unicode'] = False
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006041
6042 return format_dict
6043
Mark Dickinson277859d2009-03-17 23:03:46 +00006044def _format_align(sign, body, spec):
6045 """Given an unpadded, non-aligned numeric string 'body' and sign
Ezio Melotti24b07bc2011-03-15 18:55:01 +02006046 string 'sign', add padding and alignment conforming to the given
Mark Dickinson277859d2009-03-17 23:03:46 +00006047 format specifier dictionary 'spec' (as produced by
6048 parse_format_specifier).
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006049
Mark Dickinson277859d2009-03-17 23:03:46 +00006050 Also converts result to unicode if necessary.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006051
6052 """
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006053 # how much extra space do we have to play with?
Mark Dickinson277859d2009-03-17 23:03:46 +00006054 minimumwidth = spec['minimumwidth']
6055 fill = spec['fill']
6056 padding = fill*(minimumwidth - len(sign) - len(body))
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006057
Mark Dickinson277859d2009-03-17 23:03:46 +00006058 align = spec['align']
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006059 if align == '<':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006060 result = sign + body + padding
Mark Dickinsonb065e522009-03-17 18:01:03 +00006061 elif align == '>':
6062 result = padding + sign + body
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006063 elif align == '=':
6064 result = sign + padding + body
Mark Dickinson277859d2009-03-17 23:03:46 +00006065 elif align == '^':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006066 half = len(padding)//2
6067 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson277859d2009-03-17 23:03:46 +00006068 else:
6069 raise ValueError('Unrecognised alignment field')
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006070
6071 # make sure that result is unicode if necessary
Mark Dickinson277859d2009-03-17 23:03:46 +00006072 if spec['unicode']:
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00006073 result = unicode(result)
6074
6075 return result
Facundo Batista72bc54f2007-11-23 17:59:00 +00006076
Mark Dickinson277859d2009-03-17 23:03:46 +00006077def _group_lengths(grouping):
6078 """Convert a localeconv-style grouping into a (possibly infinite)
6079 iterable of integers representing group lengths.
6080
6081 """
6082 # The result from localeconv()['grouping'], and the input to this
6083 # function, should be a list of integers in one of the
6084 # following three forms:
6085 #
6086 # (1) an empty list, or
6087 # (2) nonempty list of positive integers + [0]
6088 # (3) list of positive integers + [locale.CHAR_MAX], or
6089
6090 from itertools import chain, repeat
6091 if not grouping:
6092 return []
6093 elif grouping[-1] == 0 and len(grouping) >= 2:
6094 return chain(grouping[:-1], repeat(grouping[-2]))
6095 elif grouping[-1] == _locale.CHAR_MAX:
6096 return grouping[:-1]
6097 else:
6098 raise ValueError('unrecognised format for grouping')
6099
6100def _insert_thousands_sep(digits, spec, min_width=1):
6101 """Insert thousands separators into a digit string.
6102
6103 spec is a dictionary whose keys should include 'thousands_sep' and
6104 'grouping'; typically it's the result of parsing the format
6105 specifier using _parse_format_specifier.
6106
6107 The min_width keyword argument gives the minimum length of the
6108 result, which will be padded on the left with zeros if necessary.
6109
6110 If necessary, the zero padding adds an extra '0' on the left to
6111 avoid a leading thousands separator. For example, inserting
6112 commas every three digits in '123456', with min_width=8, gives
6113 '0,123,456', even though that has length 9.
6114
6115 """
6116
6117 sep = spec['thousands_sep']
6118 grouping = spec['grouping']
6119
6120 groups = []
6121 for l in _group_lengths(grouping):
Mark Dickinson277859d2009-03-17 23:03:46 +00006122 if l <= 0:
6123 raise ValueError("group length should be positive")
6124 # max(..., 1) forces at least 1 digit to the left of a separator
6125 l = min(max(len(digits), min_width, 1), l)
6126 groups.append('0'*(l - len(digits)) + digits[-l:])
6127 digits = digits[:-l]
6128 min_width -= l
6129 if not digits and min_width <= 0:
6130 break
Mark Dickinsonb14514a2009-03-18 08:22:51 +00006131 min_width -= len(sep)
Mark Dickinson277859d2009-03-17 23:03:46 +00006132 else:
6133 l = max(len(digits), min_width, 1)
6134 groups.append('0'*(l - len(digits)) + digits[-l:])
6135 return sep.join(reversed(groups))
6136
6137def _format_sign(is_negative, spec):
6138 """Determine sign character."""
6139
6140 if is_negative:
6141 return '-'
6142 elif spec['sign'] in ' +':
6143 return spec['sign']
6144 else:
6145 return ''
6146
6147def _format_number(is_negative, intpart, fracpart, exp, spec):
6148 """Format a number, given the following data:
6149
6150 is_negative: true if the number is negative, else false
6151 intpart: string of digits that must appear before the decimal point
6152 fracpart: string of digits that must come after the point
6153 exp: exponent, as an integer
6154 spec: dictionary resulting from parsing the format specifier
6155
6156 This function uses the information in spec to:
6157 insert separators (decimal separator and thousands separators)
6158 format the sign
6159 format the exponent
6160 add trailing '%' for the '%' type
6161 zero-pad if necessary
6162 fill and align if necessary
6163 """
6164
6165 sign = _format_sign(is_negative, spec)
6166
6167 if fracpart:
6168 fracpart = spec['decimal_point'] + fracpart
6169
6170 if exp != 0 or spec['type'] in 'eE':
6171 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6172 fracpart += "{0}{1:+}".format(echar, exp)
6173 if spec['type'] == '%':
6174 fracpart += '%'
6175
6176 if spec['zeropad']:
6177 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6178 else:
6179 min_width = 0
6180 intpart = _insert_thousands_sep(intpart, spec, min_width)
6181
6182 return _format_align(sign, intpart+fracpart, spec)
6183
6184
Facundo Batista59c58842007-04-10 12:58:45 +00006185##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006186
Facundo Batista59c58842007-04-10 12:58:45 +00006187# Reusable defaults
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00006188_Infinity = Decimal('Inf')
6189_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonc5de0962009-01-02 23:07:08 +00006190_NaN = Decimal('NaN')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00006191_Zero = Decimal(0)
6192_One = Decimal(1)
6193_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006194
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00006195# _SignedInfinity[sign] is infinity w/ that sign
6196_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006197
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006198
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006199
6200if __name__ == '__main__':
6201 import doctest, sys
6202 doctest.testmod(sys.modules[__name__])