blob: 52ac7a8b8be6e68f33558a453c260b9d9fd398c4 [file] [log] [blame]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001# Copyright (c) 2004 Python Software Foundation.
2# All rights reserved.
3
4# Written by Eric Price <eprice at tjhsst.edu>
5# and Facundo Batista <facundo at taniquetil.com.ar>
6# and Raymond Hettinger <python at rcn.com>
Fred Drake1f34eb12004-07-01 14:28:36 +00007# and Aahz <aahz at pobox.com>
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00008# and Tim Peters
9
Raymond Hettinger27dbcf22004-08-19 22:39:55 +000010# This module is currently Py2.3 compatible and should be kept that way
11# unless a major compelling advantage arises. IOW, 2.3 compatibility is
12# strongly preferred, but not guaranteed.
13
14# Also, this module should be kept in sync with the latest updates of
15# the IBM specification as it evolves. Those updates will be treated
16# as bug fixes (deviation from the spec is a compatibility, usability
17# bug) and will be backported. At this point the spec is stabilizing
18# and the updates are becoming fewer, smaller, and less significant.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000019
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000020"""
21This is a Py2.3 implementation of decimal floating point arithmetic based on
22the General Decimal Arithmetic Specification:
23
24 www2.hursley.ibm.com/decimal/decarith.html
25
Raymond Hettinger0ea241e2004-07-04 13:53:24 +000026and IEEE standard 854-1987:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000027
28 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
29
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030Decimal floating point has finite precision with arbitrarily large bounds.
31
Facundo Batista59c58842007-04-10 12:58:45 +000032The purpose of this module is to support arithmetic using familiar
33"schoolhouse" rules and to avoid some of the tricky representation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000034issues associated with binary floating point. The package is especially
35useful for financial applications or for contexts where users have
36expectations that are at odds with binary floating point (for instance,
37in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
Raymond Hettingerabe32372008-02-14 02:41:22 +000038of the expected Decimal('0.00') returned by decimal floating point).
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000039
40Here are some examples of using the decimal module:
41
42>>> from decimal import *
Raymond Hettingerbd7f76d2004-07-08 00:49:18 +000043>>> setcontext(ExtendedContext)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000044>>> Decimal(0)
Raymond Hettingerabe32372008-02-14 02:41:22 +000045Decimal('0')
46>>> Decimal('1')
47Decimal('1')
48>>> Decimal('-.0123')
49Decimal('-0.0123')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000050>>> Decimal(123456)
Raymond Hettingerabe32372008-02-14 02:41:22 +000051Decimal('123456')
52>>> Decimal('123.45e12345678901234567890')
53Decimal('1.2345E+12345678901234567892')
54>>> Decimal('1.33') + Decimal('1.27')
55Decimal('2.60')
56>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
57Decimal('-2.20')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000058>>> dig = Decimal(1)
59>>> print dig / Decimal(3)
600.333333333
61>>> getcontext().prec = 18
62>>> print dig / Decimal(3)
630.333333333333333333
64>>> print dig.sqrt()
651
66>>> print Decimal(3).sqrt()
671.73205080756887729
68>>> print Decimal(3) ** 123
694.85192780976896427E+58
70>>> inf = Decimal(1) / Decimal(0)
71>>> print inf
72Infinity
73>>> neginf = Decimal(-1) / Decimal(0)
74>>> print neginf
75-Infinity
76>>> print neginf + inf
77NaN
78>>> print neginf * inf
79-Infinity
80>>> print dig / 0
81Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000082>>> getcontext().traps[DivisionByZero] = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000083>>> print dig / 0
84Traceback (most recent call last):
85 ...
86 ...
87 ...
88DivisionByZero: x / 0
89>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000090>>> c.traps[InvalidOperation] = 0
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000091>>> print c.flags[InvalidOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000920
93>>> c.divide(Decimal(0), Decimal(0))
Raymond Hettingerabe32372008-02-14 02:41:22 +000094Decimal('NaN')
Raymond Hettingerbf440692004-07-10 14:14:37 +000095>>> c.traps[InvalidOperation] = 1
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000096>>> print c.flags[InvalidOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000098>>> c.flags[InvalidOperation] = 0
99>>> print c.flags[InvalidOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
101>>> print c.divide(Decimal(0), Decimal(0))
102Traceback (most recent call last):
103 ...
104 ...
105 ...
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000106InvalidOperation: 0 / 0
107>>> print c.flags[InvalidOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001081
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000109>>> c.flags[InvalidOperation] = 0
Raymond Hettingerbf440692004-07-10 14:14:37 +0000110>>> c.traps[InvalidOperation] = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000111>>> print c.divide(Decimal(0), Decimal(0))
112NaN
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000113>>> print c.flags[InvalidOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141
115>>>
116"""
117
118__all__ = [
119 # Two major classes
120 'Decimal', 'Context',
121
122 # Contexts
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +0000123 'DefaultContext', 'BasicContext', 'ExtendedContext',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000124
125 # Exceptions
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000128
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000129 # Constants for use in setting up contexts
130 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
Facundo Batista353750c2007-09-13 18:13:15 +0000131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000132
133 # Functions for manipulating contexts
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000134 'setcontext', 'getcontext', 'localcontext'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000135]
136
Raymond Hettingera016deb2009-04-27 21:12:27 +0000137__version__ = '1.70' # Highest version of the spec this complies with
Raymond Hettingerdaeceb22009-03-10 04:49:21 +0000138
Raymond Hettingereb260842005-06-07 18:52:34 +0000139import copy as _copy
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000140import math as _math
Raymond Hettinger2c8585b2009-02-03 03:37:03 +0000141import numbers as _numbers
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000142
Raymond Hettinger097a1902008-01-11 02:24:13 +0000143try:
144 from collections import namedtuple as _namedtuple
145 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
146except ImportError:
147 DecimalTuple = lambda *args: args
148
Facundo Batista59c58842007-04-10 12:58:45 +0000149# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000150ROUND_DOWN = 'ROUND_DOWN'
151ROUND_HALF_UP = 'ROUND_HALF_UP'
152ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
153ROUND_CEILING = 'ROUND_CEILING'
154ROUND_FLOOR = 'ROUND_FLOOR'
155ROUND_UP = 'ROUND_UP'
156ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Facundo Batista353750c2007-09-13 18:13:15 +0000157ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000158
Facundo Batista59c58842007-04-10 12:58:45 +0000159# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000160
161class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000162 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000163
164 Used exceptions derive from this.
165 If an exception derives from another exception besides this (such as
166 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
167 called if the others are present. This isn't actually used for
168 anything, though.
169
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000170 handle -- Called when context._raise_error is called and the
171 trap_enabler is set. First argument is self, second is the
172 context. More arguments can be given, those being after
173 the explanation in _raise_error (For example,
174 context._raise_error(NewError, '(-x)!', self._sign) would
175 call NewError().handle(context, self._sign).)
176
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000177 To define a new exception, it should be sufficient to have it derive
178 from DecimalException.
179 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000180 def handle(self, context, *args):
181 pass
182
183
184class Clamped(DecimalException):
185 """Exponent of a 0 changed to fit bounds.
186
187 This occurs and signals clamped if the exponent of a result has been
188 altered in order to fit the constraints of a specific concrete
Facundo Batista59c58842007-04-10 12:58:45 +0000189 representation. This may occur when the exponent of a zero result would
190 be outside the bounds of a representation, or when a large normal
191 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000192 this latter case, the exponent is reduced to fit and the corresponding
193 number of zero digits are appended to the coefficient ("fold-down").
194 """
195
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000196class InvalidOperation(DecimalException):
197 """An invalid operation was performed.
198
199 Various bad things cause this:
200
201 Something creates a signaling NaN
202 -INF + INF
Facundo Batista59c58842007-04-10 12:58:45 +0000203 0 * (+-)INF
204 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000205 x % 0
206 (+-)INF % x
207 x._rescale( non-integer )
208 sqrt(-x) , x > 0
209 0 ** 0
210 x ** (non-integer)
211 x ** (+-)INF
212 An operand is invalid
Facundo Batista353750c2007-09-13 18:13:15 +0000213
214 The result of the operation after these is a quiet positive NaN,
215 except when the cause is a signaling NaN, in which case the result is
216 also a quiet NaN, but with the original sign, and an optional
217 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000218 """
219 def handle(self, context, *args):
220 if args:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000221 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
222 return ans._fix_nan(context)
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000223 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000224
225class ConversionSyntax(InvalidOperation):
226 """Trying to convert badly formed string.
227
228 This occurs and signals invalid-operation if an string is being
229 converted to a number and it does not conform to the numeric string
Facundo Batista59c58842007-04-10 12:58:45 +0000230 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000231 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000232 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000233 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000234
235class DivisionByZero(DecimalException, ZeroDivisionError):
236 """Division by 0.
237
238 This occurs and signals division-by-zero if division of a finite number
239 by zero was attempted (during a divide-integer or divide operation, or a
240 power operation with negative right-hand operand), and the dividend was
241 not zero.
242
243 The result of the operation is [sign,inf], where sign is the exclusive
244 or of the signs of the operands for divide, or is 1 for an odd power of
245 -0, for power.
246 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000247
Facundo Batistacce8df22007-09-18 16:53:18 +0000248 def handle(self, context, sign, *args):
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000249 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000250
251class DivisionImpossible(InvalidOperation):
252 """Cannot perform the division adequately.
253
254 This occurs and signals invalid-operation if the integer result of a
255 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000256 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000257 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000258
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000259 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000260 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000261
262class DivisionUndefined(InvalidOperation, ZeroDivisionError):
263 """Undefined result of division.
264
265 This occurs and signals invalid-operation if division by zero was
266 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000267 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000268 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000269
Facundo Batistacce8df22007-09-18 16:53:18 +0000270 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000271 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000272
273class Inexact(DecimalException):
274 """Had to round, losing information.
275
276 This occurs and signals inexact whenever the result of an operation is
277 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000278 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000279 result in all cases is unchanged.
280
281 The inexact signal may be tested (or trapped) to determine if a given
282 operation (or sequence of operations) was inexact.
283 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000284
285class InvalidContext(InvalidOperation):
286 """Invalid context. Unknown rounding, for example.
287
288 This occurs and signals invalid-operation if an invalid context was
Facundo Batista59c58842007-04-10 12:58:45 +0000289 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000290 on creation and either the precision exceeds the capability of the
291 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista59c58842007-04-10 12:58:45 +0000292 was specified. These aspects of the context need only be checked when
293 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000294 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000295
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000296 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000297 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000298
299class Rounded(DecimalException):
300 """Number got rounded (not necessarily changed during rounding).
301
302 This occurs and signals rounded whenever the result of an operation is
303 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista59c58842007-04-10 12:58:45 +0000304 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000305 result in all cases is unchanged.
306
307 The rounded signal may be tested (or trapped) to determine if a given
308 operation (or sequence of operations) caused a loss of precision.
309 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000310
311class Subnormal(DecimalException):
312 """Exponent < Emin before rounding.
313
314 This occurs and signals subnormal whenever the result of a conversion or
315 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000316 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000317
318 The subnormal signal may be tested (or trapped) to determine if a given
319 or operation (or sequence of operations) yielded a subnormal result.
320 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000321
322class Overflow(Inexact, Rounded):
323 """Numerical overflow.
324
325 This occurs and signals overflow if the adjusted exponent of a result
326 (from a conversion or from an operation that is not an attempt to divide
327 by zero), after rounding, would be greater than the largest value that
328 can be handled by the implementation (the value Emax).
329
330 The result depends on the rounding mode:
331
332 For round-half-up and round-half-even (and for round-half-down and
333 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000334 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000335 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000336 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000338 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000340 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 will also be raised.
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000342 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000343
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000344 def handle(self, context, sign, *args):
345 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000346 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000347 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000348 if sign == 0:
349 if context.rounding == ROUND_CEILING:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000350 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000351 return _dec_from_triple(sign, '9'*context.prec,
352 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000353 if sign == 1:
354 if context.rounding == ROUND_FLOOR:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000355 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000356 return _dec_from_triple(sign, '9'*context.prec,
357 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000358
359
360class Underflow(Inexact, Rounded, Subnormal):
361 """Numerical underflow with result rounded to 0.
362
363 This occurs and signals underflow if a result is inexact and the
364 adjusted exponent of the result would be smaller (more negative) than
365 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000366 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000367
368 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000369 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000370 in 0 with the sign of the intermediate result and an exponent of Etiny.
371
372 In all cases, Inexact, Rounded, and Subnormal will also be raised.
373 """
374
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000375# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000376_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000377 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000378
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000379# Map conditions (per the spec) to signals
380_condition_map = {ConversionSyntax:InvalidOperation,
381 DivisionImpossible:InvalidOperation,
382 DivisionUndefined:InvalidOperation,
383 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000384
Facundo Batista59c58842007-04-10 12:58:45 +0000385##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000386
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000387# The getcontext() and setcontext() function manage access to a thread-local
388# current context. Py2.4 offers direct support for thread locals. If that
389# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000390# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000391# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000392
393try:
394 import threading
395except ImportError:
396 # Python was compiled without threads; create a mock object instead
397 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000398 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000399 def local(self, sys=sys):
400 return sys.modules[__name__]
401 threading = MockThreading()
402 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000403
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000404try:
405 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000406
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000407except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000408
Facundo Batista59c58842007-04-10 12:58:45 +0000409 # To fix reloading, force it to create a new context
410 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000411 if hasattr(threading.currentThread(), '__decimal_context__'):
412 del threading.currentThread().__decimal_context__
413
414 def setcontext(context):
415 """Set this thread's context to context."""
416 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000417 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000418 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000419 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000420
421 def getcontext():
422 """Returns this thread's context.
423
424 If this thread does not yet have a context, returns
425 a new context and sets this thread's context.
426 New contexts are copies of DefaultContext.
427 """
428 try:
429 return threading.currentThread().__decimal_context__
430 except AttributeError:
431 context = Context()
432 threading.currentThread().__decimal_context__ = context
433 return context
434
435else:
436
437 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000438 if hasattr(local, '__decimal_context__'):
439 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000440
441 def getcontext(_local=local):
442 """Returns this thread's context.
443
444 If this thread does not yet have a context, returns
445 a new context and sets this thread's context.
446 New contexts are copies of DefaultContext.
447 """
448 try:
449 return _local.__decimal_context__
450 except AttributeError:
451 context = Context()
452 _local.__decimal_context__ = context
453 return context
454
455 def setcontext(context, _local=local):
456 """Set this thread's context to context."""
457 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000458 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000459 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000460 _local.__decimal_context__ = context
461
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000462 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000463
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000464def localcontext(ctx=None):
465 """Return a context manager for a copy of the supplied context
466
467 Uses a copy of the current context if no context is specified
468 The returned context manager creates a local decimal context
469 in a with statement:
470 def sin(x):
471 with localcontext() as ctx:
472 ctx.prec += 2
473 # Rest of sin calculation algorithm
474 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000475 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000476
477 def sin(x):
478 with localcontext(ExtendedContext):
479 # Rest of sin calculation algorithm
480 # uses the Extended Context from the
481 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000482 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000483
Facundo Batistaee340e52008-05-02 17:39:00 +0000484 >>> setcontext(DefaultContext)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000485 >>> print getcontext().prec
486 28
487 >>> with localcontext():
488 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000489 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000490 ... print ctx.prec
491 ...
492 30
493 >>> with localcontext(ExtendedContext):
494 ... print getcontext().prec
495 ...
496 9
497 >>> print getcontext().prec
498 28
499 """
Nick Coghlanced12182006-09-02 03:54:17 +0000500 if ctx is None: ctx = getcontext()
501 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000502
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000503
Facundo Batista59c58842007-04-10 12:58:45 +0000504##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000505
506class Decimal(object):
507 """Floating point class for decimal arithmetic."""
508
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000509 __slots__ = ('_exp','_int','_sign', '_is_special')
510 # Generally, the value of the Decimal instance is given by
511 # (-1)**_sign * _int * 10**_exp
512 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000513
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000514 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000515 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000516 """Create a decimal point instance.
517
518 >>> Decimal('3.14') # string input
Raymond Hettingerabe32372008-02-14 02:41:22 +0000519 Decimal('3.14')
Facundo Batista59c58842007-04-10 12:58:45 +0000520 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000521 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 >>> Decimal(314) # int or long
Raymond Hettingerabe32372008-02-14 02:41:22 +0000523 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000524 >>> Decimal(Decimal(314)) # another decimal instance
Raymond Hettingerabe32372008-02-14 02:41:22 +0000525 Decimal('314')
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000526 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Raymond Hettingerabe32372008-02-14 02:41:22 +0000527 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000528 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529
Facundo Batista72bc54f2007-11-23 17:59:00 +0000530 # Note that the coefficient, self._int, is actually stored as
531 # a string rather than as a tuple of digits. This speeds up
532 # the "digits to integer" and "integer to digits" conversions
533 # that are used in almost every arithmetic operation on
534 # Decimals. This is an internal detail: the as_tuple function
535 # and the Decimal constructor still deal with tuples of
536 # digits.
537
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000538 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000539
Facundo Batista0d157a02007-11-30 17:15:25 +0000540 # From a string
541 # REs insist on real strings, so we can too.
542 if isinstance(value, basestring):
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000543 m = _parser(value.strip())
Facundo Batista0d157a02007-11-30 17:15:25 +0000544 if m is None:
545 if context is None:
546 context = getcontext()
547 return context._raise_error(ConversionSyntax,
548 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000549
Facundo Batista0d157a02007-11-30 17:15:25 +0000550 if m.group('sign') == "-":
551 self._sign = 1
552 else:
553 self._sign = 0
554 intpart = m.group('int')
555 if intpart is not None:
556 # finite number
Mark Dickinson4326ad82009-08-02 10:59:36 +0000557 fracpart = m.group('frac') or ''
Facundo Batista0d157a02007-11-30 17:15:25 +0000558 exp = int(m.group('exp') or '0')
Mark Dickinson4326ad82009-08-02 10:59:36 +0000559 self._int = str(int(intpart+fracpart))
560 self._exp = exp - len(fracpart)
Facundo Batista0d157a02007-11-30 17:15:25 +0000561 self._is_special = False
562 else:
563 diag = m.group('diag')
564 if diag is not None:
565 # NaN
Mark Dickinson4326ad82009-08-02 10:59:36 +0000566 self._int = str(int(diag or '0')).lstrip('0')
Facundo Batista0d157a02007-11-30 17:15:25 +0000567 if m.group('signal'):
568 self._exp = 'N'
569 else:
570 self._exp = 'n'
571 else:
572 # infinity
573 self._int = '0'
574 self._exp = 'F'
575 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000576 return self
577
578 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000579 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580 if value >= 0:
581 self._sign = 0
582 else:
583 self._sign = 1
584 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000585 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000586 self._is_special = False
587 return self
588
589 # From another decimal
590 if isinstance(value, Decimal):
591 self._exp = value._exp
592 self._sign = value._sign
593 self._int = value._int
594 self._is_special = value._is_special
595 return self
596
597 # From an internal working value
598 if isinstance(value, _WorkRep):
599 self._sign = value.sign
600 self._int = str(value.int)
601 self._exp = int(value.exp)
602 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000603 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000604
605 # tuple/list conversion (possibly from as_tuple())
606 if isinstance(value, (list,tuple)):
607 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000608 raise ValueError('Invalid tuple size in creation of Decimal '
609 'from list or tuple. The list or tuple '
610 'should have exactly three elements.')
611 # process sign. The isinstance test rejects floats
612 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
613 raise ValueError("Invalid sign. The first value in the tuple "
614 "should be an integer; either 0 for a "
615 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000616 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000617 if value[2] == 'F':
618 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000619 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000620 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000621 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000622 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000623 # process and validate the digits in value[1]
624 digits = []
625 for digit in value[1]:
626 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
627 # skip leading zeros
628 if digits or digit != 0:
629 digits.append(digit)
630 else:
631 raise ValueError("The second value in the tuple must "
632 "be composed of integers in the range "
633 "0 through 9.")
634 if value[2] in ('n', 'N'):
635 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000636 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000637 self._exp = value[2]
638 self._is_special = True
639 elif isinstance(value[2], (int, long)):
640 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000641 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000642 self._exp = value[2]
643 self._is_special = False
644 else:
645 raise ValueError("The third value in the tuple must "
646 "be an integer, or one of the "
647 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000648 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000649
Raymond Hettingerbf440692004-07-10 14:14:37 +0000650 if isinstance(value, float):
Benjamin Petersona617e202010-01-25 03:52:52 +0000651 raise TypeError("Cannot convert float in Decimal constructor. "
652 "Use from_float class method.")
Raymond Hettingerbf440692004-07-10 14:14:37 +0000653
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000654 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000655
Mark Dickinson6a961632009-01-04 21:10:56 +0000656 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
657 # don't use it (see notes on Py2.3 compatibility at top of file)
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000658 def from_float(cls, f):
659 """Converts a float to a decimal number, exactly.
660
661 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
662 Since 0.1 is not exactly representable in binary floating point, the
663 value is stored as the nearest representable value which is
664 0x1.999999999999ap-4. The exact equivalent of the value in decimal
665 is 0.1000000000000000055511151231257827021181583404541015625.
666
667 >>> Decimal.from_float(0.1)
668 Decimal('0.1000000000000000055511151231257827021181583404541015625')
669 >>> Decimal.from_float(float('nan'))
670 Decimal('NaN')
671 >>> Decimal.from_float(float('inf'))
672 Decimal('Infinity')
673 >>> Decimal.from_float(-float('inf'))
674 Decimal('-Infinity')
675 >>> Decimal.from_float(-0.0)
676 Decimal('-0')
677
678 """
679 if isinstance(f, (int, long)): # handle integer inputs
680 return cls(f)
681 if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
682 return cls(repr(f))
Mark Dickinson6a961632009-01-04 21:10:56 +0000683 if _math.copysign(1.0, f) == 1.0:
684 sign = 0
685 else:
686 sign = 1
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000687 n, d = abs(f).as_integer_ratio()
688 k = d.bit_length() - 1
689 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinson6a961632009-01-04 21:10:56 +0000690 if cls is Decimal:
691 return result
692 else:
693 return cls(result)
694 from_float = classmethod(from_float)
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000695
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000696 def _isnan(self):
697 """Returns whether the number is not actually one.
698
699 0 if a number
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000700 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000701 2 if sNaN
702 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000703 if self._is_special:
704 exp = self._exp
705 if exp == 'n':
706 return 1
707 elif exp == 'N':
708 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000709 return 0
710
711 def _isinfinity(self):
712 """Returns whether the number is infinite
713
714 0 if finite or not a number
715 1 if +INF
716 -1 if -INF
717 """
718 if self._exp == 'F':
719 if self._sign:
720 return -1
721 return 1
722 return 0
723
Facundo Batista353750c2007-09-13 18:13:15 +0000724 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000725 """Returns whether the number is not actually one.
726
727 if self, other are sNaN, signal
728 if self, other are NaN return nan
729 return 0
730
731 Done before operations.
732 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000733
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000734 self_is_nan = self._isnan()
735 if other is None:
736 other_is_nan = False
737 else:
738 other_is_nan = other._isnan()
739
740 if self_is_nan or other_is_nan:
741 if context is None:
742 context = getcontext()
743
744 if self_is_nan == 2:
745 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000746 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000747 if other_is_nan == 2:
748 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000749 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000750 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000751 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000752
Facundo Batista353750c2007-09-13 18:13:15 +0000753 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000754 return 0
755
Mark Dickinson2fc92632008-02-06 22:10:50 +0000756 def _compare_check_nans(self, other, context):
757 """Version of _check_nans used for the signaling comparisons
758 compare_signal, __le__, __lt__, __ge__, __gt__.
759
760 Signal InvalidOperation if either self or other is a (quiet
761 or signaling) NaN. Signaling NaNs take precedence over quiet
762 NaNs.
763
764 Return 0 if neither operand is a NaN.
765
766 """
767 if context is None:
768 context = getcontext()
769
770 if self._is_special or other._is_special:
771 if self.is_snan():
772 return context._raise_error(InvalidOperation,
773 'comparison involving sNaN',
774 self)
775 elif other.is_snan():
776 return context._raise_error(InvalidOperation,
777 'comparison involving sNaN',
778 other)
779 elif self.is_qnan():
780 return context._raise_error(InvalidOperation,
781 'comparison involving NaN',
782 self)
783 elif other.is_qnan():
784 return context._raise_error(InvalidOperation,
785 'comparison involving NaN',
786 other)
787 return 0
788
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000789 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000790 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000791
Facundo Batista1a191df2007-10-02 17:01:24 +0000792 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000793 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000794 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000795
Mark Dickinson2fc92632008-02-06 22:10:50 +0000796 def _cmp(self, other):
797 """Compare the two non-NaN decimal instances self and other.
798
799 Returns -1 if self < other, 0 if self == other and 1
800 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000801
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000802 if self._is_special or other._is_special:
Mark Dickinsone52c3142009-01-25 10:39:15 +0000803 self_inf = self._isinfinity()
804 other_inf = other._isinfinity()
805 if self_inf == other_inf:
806 return 0
807 elif self_inf < other_inf:
808 return -1
809 else:
810 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000811
Mark Dickinsone52c3142009-01-25 10:39:15 +0000812 # check for zeros; Decimal('0') == Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000813 if not self:
814 if not other:
815 return 0
816 else:
817 return -((-1)**other._sign)
818 if not other:
819 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000820
Facundo Batista59c58842007-04-10 12:58:45 +0000821 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000822 if other._sign < self._sign:
823 return -1
824 if self._sign < other._sign:
825 return 1
826
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000827 self_adjusted = self.adjusted()
828 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000829 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000830 self_padded = self._int + '0'*(self._exp - other._exp)
831 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone52c3142009-01-25 10:39:15 +0000832 if self_padded == other_padded:
833 return 0
834 elif self_padded < other_padded:
835 return -(-1)**self._sign
836 else:
837 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000838 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000839 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000840 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000841 return -((-1)**self._sign)
842
Mark Dickinson2fc92632008-02-06 22:10:50 +0000843 # Note: The Decimal standard doesn't cover rich comparisons for
844 # Decimals. In particular, the specification is silent on the
845 # subject of what should happen for a comparison involving a NaN.
846 # We take the following approach:
847 #
Mark Dickinsone096e822010-04-02 10:17:07 +0000848 # == comparisons involving a quiet NaN always return False
849 # != comparisons involving a quiet NaN always return True
850 # == or != comparisons involving a signaling NaN signal
851 # InvalidOperation, and return False or True as above if the
852 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000853 # <, >, <= and >= comparisons involving a (quiet or signaling)
854 # NaN signal InvalidOperation, and return False if the
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000855 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000856 #
857 # This behavior is designed to conform as closely as possible to
858 # that specified by IEEE 754.
859
Mark Dickinsone096e822010-04-02 10:17:07 +0000860 def __eq__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000861 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000862 if other is NotImplemented:
863 return other
Mark Dickinsone096e822010-04-02 10:17:07 +0000864 if self._check_nans(other, context):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000865 return False
866 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000867
Mark Dickinsone096e822010-04-02 10:17:07 +0000868 def __ne__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000869 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000870 if other is NotImplemented:
871 return other
Mark Dickinsone096e822010-04-02 10:17:07 +0000872 if self._check_nans(other, context):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000873 return True
874 return self._cmp(other) != 0
875
876 def __lt__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000877 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000878 if other is NotImplemented:
879 return other
880 ans = self._compare_check_nans(other, context)
881 if ans:
882 return False
883 return self._cmp(other) < 0
884
885 def __le__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000886 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000887 if other is NotImplemented:
888 return other
889 ans = self._compare_check_nans(other, context)
890 if ans:
891 return False
892 return self._cmp(other) <= 0
893
894 def __gt__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000895 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000896 if other is NotImplemented:
897 return other
898 ans = self._compare_check_nans(other, context)
899 if ans:
900 return False
901 return self._cmp(other) > 0
902
903 def __ge__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000904 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000905 if other is NotImplemented:
906 return other
907 ans = self._compare_check_nans(other, context)
908 if ans:
909 return False
910 return self._cmp(other) >= 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000911
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000912 def compare(self, other, context=None):
913 """Compares one to another.
914
915 -1 => a < b
916 0 => a = b
917 1 => a > b
918 NaN => one is NaN
919 Like __cmp__, but returns Decimal instances.
920 """
Facundo Batista353750c2007-09-13 18:13:15 +0000921 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000922
Facundo Batista59c58842007-04-10 12:58:45 +0000923 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000924 if (self._is_special or other and other._is_special):
925 ans = self._check_nans(other, context)
926 if ans:
927 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000928
Mark Dickinson2fc92632008-02-06 22:10:50 +0000929 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000930
931 def __hash__(self):
932 """x.__hash__() <==> hash(x)"""
933 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000934 #
935 # The hash of a nonspecial noninteger Decimal must depend only
936 # on the value of that Decimal, and not on its representation.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000937 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Mark Dickinson99d80962010-04-02 08:53:22 +0000938 if self._is_special and self._isnan():
939 raise TypeError('Cannot hash a NaN value.')
940
941 # In Python 2.7, we're allowing comparisons (but not
942 # arithmetic operations) between floats and Decimals; so if
943 # a Decimal instance is exactly representable as a float then
944 # its hash should match that of the float. Note that this takes care
945 # of zeros and infinities, as well as small integers.
946 self_as_float = float(self)
947 if Decimal.from_float(self_as_float) == self:
948 return hash(self_as_float)
949
Facundo Batista8c202442007-09-19 17:53:25 +0000950 if self._isinteger():
951 op = _WorkRep(self.to_integral_value())
952 # to make computation feasible for Decimals with large
953 # exponent, we use the fact that hash(n) == hash(m) for
954 # any two nonzero integers n and m such that (i) n and m
955 # have the same sign, and (ii) n is congruent to m modulo
956 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
957 # hash((-1)**s*c*pow(10, e, 2**64-1).
958 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000959 # The value of a nonzero nonspecial Decimal instance is
960 # faithfully represented by the triple consisting of its sign,
961 # its adjusted exponent, and its coefficient with trailing
962 # zeros removed.
963 return hash((self._sign,
964 self._exp+len(self._int),
965 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000966
967 def as_tuple(self):
968 """Represents the number as a triple tuple.
969
970 To show the internals exactly as they are.
971 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000972 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000973
974 def __repr__(self):
975 """Represents the number as an instance of Decimal."""
976 # Invariant: eval(repr(d)) == d
Raymond Hettingerabe32372008-02-14 02:41:22 +0000977 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000978
Facundo Batista353750c2007-09-13 18:13:15 +0000979 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000980 """Return string representation of the number in scientific notation.
981
982 Captures all of the information in the underlying representation.
983 """
984
Facundo Batista62edb712007-12-03 16:29:52 +0000985 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000986 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000987 if self._exp == 'F':
988 return sign + 'Infinity'
989 elif self._exp == 'n':
990 return sign + 'NaN' + self._int
991 else: # self._exp == 'N'
992 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000993
Facundo Batista62edb712007-12-03 16:29:52 +0000994 # number of digits of self._int to left of decimal point
995 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000996
Facundo Batista62edb712007-12-03 16:29:52 +0000997 # dotplace is number of digits of self._int to the left of the
998 # decimal point in the mantissa of the output string (that is,
999 # after adjusting the exponent)
1000 if self._exp <= 0 and leftdigits > -6:
1001 # no exponent required
1002 dotplace = leftdigits
1003 elif not eng:
1004 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001005 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +00001006 elif self._int == '0':
1007 # engineering notation, zero
1008 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009 else:
Facundo Batista62edb712007-12-03 16:29:52 +00001010 # engineering notation, nonzero
1011 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012
Facundo Batista62edb712007-12-03 16:29:52 +00001013 if dotplace <= 0:
1014 intpart = '0'
1015 fracpart = '.' + '0'*(-dotplace) + self._int
1016 elif dotplace >= len(self._int):
1017 intpart = self._int+'0'*(dotplace-len(self._int))
1018 fracpart = ''
1019 else:
1020 intpart = self._int[:dotplace]
1021 fracpart = '.' + self._int[dotplace:]
1022 if leftdigits == dotplace:
1023 exp = ''
1024 else:
1025 if context is None:
1026 context = getcontext()
1027 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1028
1029 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030
1031 def to_eng_string(self, context=None):
1032 """Convert to engineering-type string.
1033
1034 Engineering notation has an exponent which is a multiple of 3, so there
1035 are up to 3 digits left of the decimal place.
1036
1037 Same rules for when in exponential and when as a value as in __str__.
1038 """
Facundo Batista353750c2007-09-13 18:13:15 +00001039 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001040
1041 def __neg__(self, context=None):
1042 """Returns a copy with the sign switched.
1043
1044 Rounds, if it has reason.
1045 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001046 if self._is_special:
1047 ans = self._check_nans(context=context)
1048 if ans:
1049 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001050
1051 if not self:
1052 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001053 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001054 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001055 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001056
1057 if context is None:
1058 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001059 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001060
1061 def __pos__(self, context=None):
1062 """Returns a copy, unless it is a sNaN.
1063
1064 Rounds the number (if more then precision digits)
1065 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001066 if self._is_special:
1067 ans = self._check_nans(context=context)
1068 if ans:
1069 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001070
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071 if not self:
1072 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001073 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +00001074 else:
1075 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001076
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001077 if context is None:
1078 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001079 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001080
Facundo Batistae64acfa2007-12-17 14:18:42 +00001081 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001082 """Returns the absolute value of self.
1083
Facundo Batistae64acfa2007-12-17 14:18:42 +00001084 If the keyword argument 'round' is false, do not round. The
1085 expression self.__abs__(round=False) is equivalent to
1086 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001087 """
Facundo Batistae64acfa2007-12-17 14:18:42 +00001088 if not round:
1089 return self.copy_abs()
1090
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001091 if self._is_special:
1092 ans = self._check_nans(context=context)
1093 if ans:
1094 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001095
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001096 if self._sign:
1097 ans = self.__neg__(context=context)
1098 else:
1099 ans = self.__pos__(context=context)
1100
1101 return ans
1102
1103 def __add__(self, other, context=None):
1104 """Returns self + other.
1105
1106 -INF + INF (or the reverse) cause InvalidOperation errors.
1107 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001108 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001109 if other is NotImplemented:
1110 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001111
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001112 if context is None:
1113 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001114
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001115 if self._is_special or other._is_special:
1116 ans = self._check_nans(other, context)
1117 if ans:
1118 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001119
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001120 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001121 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001122 if self._sign != other._sign and other._isinfinity():
1123 return context._raise_error(InvalidOperation, '-INF + INF')
1124 return Decimal(self)
1125 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001126 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001127
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001128 exp = min(self._exp, other._exp)
1129 negativezero = 0
1130 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001131 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001132 negativezero = 1
1133
1134 if not self and not other:
1135 sign = min(self._sign, other._sign)
1136 if negativezero:
1137 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001138 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001139 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001140 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001141 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001142 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001143 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001144 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001145 return ans
1146 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001147 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001148 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001149 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001150 return ans
1151
1152 op1 = _WorkRep(self)
1153 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001154 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001155
1156 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001157 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001159 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001160 ans = _dec_from_triple(negativezero, '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 Hettinger17931de2004-10-27 06:21:46 +00001163 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001164 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001165 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001166 if op1.sign == 1:
1167 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001168 op1.sign, op2.sign = op2.sign, op1.sign
1169 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001170 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001171 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001172 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001174 op1.sign, op2.sign = (0, 0)
1175 else:
1176 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001177 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178
Raymond Hettinger17931de2004-10-27 06:21:46 +00001179 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001180 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001181 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001182 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001183
1184 result.exp = op1.exp
1185 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001186 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001187 return ans
1188
1189 __radd__ = __add__
1190
1191 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001192 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001193 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001194 if other is NotImplemented:
1195 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001196
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001197 if self._is_special or other._is_special:
1198 ans = self._check_nans(other, context=context)
1199 if ans:
1200 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201
Facundo Batista353750c2007-09-13 18:13:15 +00001202 # self - other is computed as self + other.copy_negate()
1203 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001204
1205 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001206 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001207 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001208 if other is NotImplemented:
1209 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001210
Facundo Batista353750c2007-09-13 18:13:15 +00001211 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001212
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001213 def __mul__(self, other, context=None):
1214 """Return self * other.
1215
1216 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1217 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001218 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001219 if other is NotImplemented:
1220 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001221
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001222 if context is None:
1223 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001224
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001225 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001226
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001227 if self._is_special or other._is_special:
1228 ans = self._check_nans(other, context)
1229 if ans:
1230 return ans
1231
1232 if self._isinfinity():
1233 if not other:
1234 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001235 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001236
1237 if other._isinfinity():
1238 if not self:
1239 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001240 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001241
1242 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001243
1244 # Special case for multiplying by zero
1245 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001246 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001247 # Fixing in case the exponent is out of bounds
1248 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001249 return ans
1250
1251 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001252 if self._int == '1':
1253 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001254 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001255 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001256 if other._int == '1':
1257 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001258 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001259 return ans
1260
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001261 op1 = _WorkRep(self)
1262 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001263
Facundo Batista72bc54f2007-11-23 17:59:00 +00001264 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001265 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001266
1267 return ans
1268 __rmul__ = __mul__
1269
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001270 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001271 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001272 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001273 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001274 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001275
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276 if context is None:
1277 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001278
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001279 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001280
1281 if self._is_special or other._is_special:
1282 ans = self._check_nans(other, context)
1283 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001284 return ans
1285
1286 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001287 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001288
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001289 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001290 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001291
1292 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001293 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001294 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001295
1296 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001297 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001298 if not self:
1299 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001300 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001301
Facundo Batistacce8df22007-09-18 16:53:18 +00001302 if not self:
1303 exp = self._exp - other._exp
1304 coeff = 0
1305 else:
1306 # OK, so neither = 0, INF or NaN
1307 shift = len(other._int) - len(self._int) + context.prec + 1
1308 exp = self._exp - other._exp - shift
1309 op1 = _WorkRep(self)
1310 op2 = _WorkRep(other)
1311 if shift >= 0:
1312 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1313 else:
1314 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1315 if remainder:
1316 # result is not exact; adjust to ensure correct rounding
1317 if coeff % 5 == 0:
1318 coeff += 1
1319 else:
1320 # result is exact; get as close to ideal exponent as possible
1321 ideal_exp = self._exp - other._exp
1322 while exp < ideal_exp and coeff % 10 == 0:
1323 coeff //= 10
1324 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001325
Facundo Batista72bc54f2007-11-23 17:59:00 +00001326 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001327 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001328
Facundo Batistacce8df22007-09-18 16:53:18 +00001329 def _divide(self, other, context):
1330 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001331
Facundo Batistacce8df22007-09-18 16:53:18 +00001332 Assumes that neither self nor other is a NaN, that self is not
1333 infinite and that other is nonzero.
1334 """
1335 sign = self._sign ^ other._sign
1336 if other._isinfinity():
1337 ideal_exp = self._exp
1338 else:
1339 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001340
Facundo Batistacce8df22007-09-18 16:53:18 +00001341 expdiff = self.adjusted() - other.adjusted()
1342 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001343 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001344 self._rescale(ideal_exp, context.rounding))
1345 if expdiff <= context.prec:
1346 op1 = _WorkRep(self)
1347 op2 = _WorkRep(other)
1348 if op1.exp >= op2.exp:
1349 op1.int *= 10**(op1.exp - op2.exp)
1350 else:
1351 op2.int *= 10**(op2.exp - op1.exp)
1352 q, r = divmod(op1.int, op2.int)
1353 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001354 return (_dec_from_triple(sign, str(q), 0),
1355 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001356
Facundo Batistacce8df22007-09-18 16:53:18 +00001357 # Here the quotient is too large to be representable
1358 ans = context._raise_error(DivisionImpossible,
1359 'quotient too large in //, % or divmod')
1360 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001361
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001362 def __rtruediv__(self, other, context=None):
1363 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001364 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001365 if other is NotImplemented:
1366 return other
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001367 return other.__truediv__(self, context=context)
1368
1369 __div__ = __truediv__
1370 __rdiv__ = __rtruediv__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001371
1372 def __divmod__(self, other, context=None):
1373 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001374 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001375 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001376 other = _convert_other(other)
1377 if other is NotImplemented:
1378 return other
1379
1380 if context is None:
1381 context = getcontext()
1382
1383 ans = self._check_nans(other, context)
1384 if ans:
1385 return (ans, ans)
1386
1387 sign = self._sign ^ other._sign
1388 if self._isinfinity():
1389 if other._isinfinity():
1390 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1391 return ans, ans
1392 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001393 return (_SignedInfinity[sign],
Facundo Batistacce8df22007-09-18 16:53:18 +00001394 context._raise_error(InvalidOperation, 'INF % x'))
1395
1396 if not other:
1397 if not self:
1398 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1399 return ans, ans
1400 else:
1401 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1402 context._raise_error(InvalidOperation, 'x % 0'))
1403
1404 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001405 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001406 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001407
1408 def __rdivmod__(self, other, context=None):
1409 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001410 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001411 if other is NotImplemented:
1412 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001413 return other.__divmod__(self, context=context)
1414
1415 def __mod__(self, other, context=None):
1416 """
1417 self % other
1418 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001419 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001420 if other is NotImplemented:
1421 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001422
Facundo Batistacce8df22007-09-18 16:53:18 +00001423 if context is None:
1424 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001425
Facundo Batistacce8df22007-09-18 16:53:18 +00001426 ans = self._check_nans(other, context)
1427 if ans:
1428 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001429
Facundo Batistacce8df22007-09-18 16:53:18 +00001430 if self._isinfinity():
1431 return context._raise_error(InvalidOperation, 'INF % x')
1432 elif not other:
1433 if self:
1434 return context._raise_error(InvalidOperation, 'x % 0')
1435 else:
1436 return context._raise_error(DivisionUndefined, '0 % 0')
1437
1438 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001439 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001440 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001441
1442 def __rmod__(self, other, context=None):
1443 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001444 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001445 if other is NotImplemented:
1446 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001447 return other.__mod__(self, context=context)
1448
1449 def remainder_near(self, other, context=None):
1450 """
1451 Remainder nearest to 0- abs(remainder-near) <= other/2
1452 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001453 if context is None:
1454 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001455
Facundo Batista353750c2007-09-13 18:13:15 +00001456 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001457
Facundo Batista353750c2007-09-13 18:13:15 +00001458 ans = self._check_nans(other, context)
1459 if ans:
1460 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001461
Facundo Batista353750c2007-09-13 18:13:15 +00001462 # self == +/-infinity -> InvalidOperation
1463 if self._isinfinity():
1464 return context._raise_error(InvalidOperation,
1465 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001466
Facundo Batista353750c2007-09-13 18:13:15 +00001467 # other == 0 -> either InvalidOperation or DivisionUndefined
1468 if not other:
1469 if self:
1470 return context._raise_error(InvalidOperation,
1471 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001472 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001473 return context._raise_error(DivisionUndefined,
1474 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001475
Facundo Batista353750c2007-09-13 18:13:15 +00001476 # other = +/-infinity -> remainder = self
1477 if other._isinfinity():
1478 ans = Decimal(self)
1479 return ans._fix(context)
1480
1481 # self = 0 -> remainder = self, with ideal exponent
1482 ideal_exponent = min(self._exp, other._exp)
1483 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001484 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001485 return ans._fix(context)
1486
1487 # catch most cases of large or small quotient
1488 expdiff = self.adjusted() - other.adjusted()
1489 if expdiff >= context.prec + 1:
1490 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001491 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001492 if expdiff <= -2:
1493 # expdiff <= -2 => abs(self/other) < 0.1
1494 ans = self._rescale(ideal_exponent, context.rounding)
1495 return ans._fix(context)
1496
1497 # adjust both arguments to have the same exponent, then divide
1498 op1 = _WorkRep(self)
1499 op2 = _WorkRep(other)
1500 if op1.exp >= op2.exp:
1501 op1.int *= 10**(op1.exp - op2.exp)
1502 else:
1503 op2.int *= 10**(op2.exp - op1.exp)
1504 q, r = divmod(op1.int, op2.int)
1505 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1506 # 10**ideal_exponent. Apply correction to ensure that
1507 # abs(remainder) <= abs(other)/2
1508 if 2*r + (q&1) > op2.int:
1509 r -= op2.int
1510 q += 1
1511
1512 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001513 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001514
1515 # result has same sign as self unless r is negative
1516 sign = self._sign
1517 if r < 0:
1518 sign = 1-sign
1519 r = -r
1520
Facundo Batista72bc54f2007-11-23 17:59:00 +00001521 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001522 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001523
1524 def __floordiv__(self, other, context=None):
1525 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001526 other = _convert_other(other)
1527 if other is NotImplemented:
1528 return other
1529
1530 if context is None:
1531 context = getcontext()
1532
1533 ans = self._check_nans(other, context)
1534 if ans:
1535 return ans
1536
1537 if self._isinfinity():
1538 if other._isinfinity():
1539 return context._raise_error(InvalidOperation, 'INF // INF')
1540 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001541 return _SignedInfinity[self._sign ^ other._sign]
Facundo Batistacce8df22007-09-18 16:53:18 +00001542
1543 if not other:
1544 if self:
1545 return context._raise_error(DivisionByZero, 'x // 0',
1546 self._sign ^ other._sign)
1547 else:
1548 return context._raise_error(DivisionUndefined, '0 // 0')
1549
1550 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001551
1552 def __rfloordiv__(self, other, context=None):
1553 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001554 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001555 if other is NotImplemented:
1556 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001557 return other.__floordiv__(self, context=context)
1558
1559 def __float__(self):
1560 """Float representation."""
1561 return float(str(self))
1562
1563 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001564 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001565 if self._is_special:
1566 if self._isnan():
Mark Dickinson968f1692009-09-07 18:04:58 +00001567 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001568 elif self._isinfinity():
Mark Dickinson968f1692009-09-07 18:04:58 +00001569 raise OverflowError("Cannot convert infinity to integer")
Facundo Batista353750c2007-09-13 18:13:15 +00001570 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001571 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001572 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001573 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001574 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001575
Raymond Hettinger5a053642008-01-24 19:05:29 +00001576 __trunc__ = __int__
1577
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001578 def real(self):
1579 return self
Mark Dickinson65808ff2009-01-04 21:22:02 +00001580 real = property(real)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001581
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001582 def imag(self):
1583 return Decimal(0)
Mark Dickinson65808ff2009-01-04 21:22:02 +00001584 imag = property(imag)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001585
1586 def conjugate(self):
1587 return self
1588
1589 def __complex__(self):
1590 return complex(float(self))
1591
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001592 def __long__(self):
1593 """Converts to a long.
1594
1595 Equivalent to long(int(self))
1596 """
1597 return long(self.__int__())
1598
Facundo Batista353750c2007-09-13 18:13:15 +00001599 def _fix_nan(self, context):
1600 """Decapitate the payload of a NaN to fit the context"""
1601 payload = self._int
1602
1603 # maximum length of payload is precision if _clamp=0,
1604 # precision-1 if _clamp=1.
1605 max_payload_len = context.prec - context._clamp
1606 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001607 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1608 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001609 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001610
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001611 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001612 """Round if it is necessary to keep self within prec precision.
1613
1614 Rounds and fixes the exponent. Does not raise on a sNaN.
1615
1616 Arguments:
1617 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001618 context - context used.
1619 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001620
Facundo Batista353750c2007-09-13 18:13:15 +00001621 if self._is_special:
1622 if self._isnan():
1623 # decapitate payload if necessary
1624 return self._fix_nan(context)
1625 else:
1626 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001627 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001628
Facundo Batista353750c2007-09-13 18:13:15 +00001629 # if self is zero then exponent should be between Etiny and
1630 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1631 Etiny = context.Etiny()
1632 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001633 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001634 exp_max = [context.Emax, Etop][context._clamp]
1635 new_exp = min(max(self._exp, Etiny), exp_max)
1636 if new_exp != self._exp:
1637 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001638 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001639 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001640 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001641
1642 # exp_min is the smallest allowable exponent of the result,
1643 # equal to max(self.adjusted()-context.prec+1, Etiny)
1644 exp_min = len(self._int) + self._exp - context.prec
1645 if exp_min > Etop:
1646 # overflow: exp_min > Etop iff self.adjusted() > Emax
1647 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001648 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001649 return context._raise_error(Overflow, 'above Emax', self._sign)
1650 self_is_subnormal = exp_min < Etiny
1651 if self_is_subnormal:
1652 context._raise_error(Subnormal)
1653 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001654
Facundo Batista353750c2007-09-13 18:13:15 +00001655 # round if self has too many digits
1656 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001657 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001658 digits = len(self._int) + self._exp - exp_min
1659 if digits < 0:
1660 self = _dec_from_triple(self._sign, '1', exp_min-1)
1661 digits = 0
1662 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1663 changed = this_function(digits)
1664 coeff = self._int[:digits] or '0'
1665 if changed == 1:
1666 coeff = str(int(coeff)+1)
1667 ans = _dec_from_triple(self._sign, coeff, exp_min)
1668
1669 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001670 context._raise_error(Inexact)
1671 if self_is_subnormal:
1672 context._raise_error(Underflow)
1673 if not ans:
1674 # raise Clamped on underflow to 0
1675 context._raise_error(Clamped)
1676 elif len(ans._int) == context.prec+1:
1677 # we get here only if rescaling rounds the
1678 # cofficient up to exactly 10**context.prec
1679 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001680 ans = _dec_from_triple(ans._sign,
1681 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001682 else:
1683 # Inexact and Rounded have already been raised
1684 ans = context._raise_error(Overflow, 'above Emax',
1685 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001686 return ans
1687
Facundo Batista353750c2007-09-13 18:13:15 +00001688 # fold down if _clamp == 1 and self has too few digits
1689 if context._clamp == 1 and self._exp > Etop:
1690 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001691 self_padded = self._int + '0'*(self._exp - Etop)
1692 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001693
Facundo Batista353750c2007-09-13 18:13:15 +00001694 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001695 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001696
1697 _pick_rounding_function = {}
1698
Facundo Batista353750c2007-09-13 18:13:15 +00001699 # for each of the rounding functions below:
1700 # self is a finite, nonzero Decimal
1701 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001702 #
1703 # each function returns either -1, 0, or 1, as follows:
1704 # 1 indicates that self should be rounded up (away from zero)
1705 # 0 indicates that self should be truncated, and that all the
1706 # digits to be truncated are zeros (so the value is unchanged)
1707 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001708
1709 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001710 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001711 if _all_zeros(self._int, prec):
1712 return 0
1713 else:
1714 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001715
Facundo Batista353750c2007-09-13 18:13:15 +00001716 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001717 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001718 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001719
Facundo Batista353750c2007-09-13 18:13:15 +00001720 def _round_half_up(self, prec):
1721 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001722 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001723 return 1
1724 elif _all_zeros(self._int, prec):
1725 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001726 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001727 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001728
1729 def _round_half_down(self, prec):
1730 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001731 if _exact_half(self._int, prec):
1732 return -1
1733 else:
1734 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001735
1736 def _round_half_even(self, prec):
1737 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001738 if _exact_half(self._int, prec) and \
1739 (prec == 0 or self._int[prec-1] in '02468'):
1740 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001741 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001742 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001743
1744 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001745 """Rounds up (not away from 0 if negative.)"""
1746 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001747 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001748 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001749 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001750
Facundo Batista353750c2007-09-13 18:13:15 +00001751 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001752 """Rounds down (not towards 0 if negative)"""
1753 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001754 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001755 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001756 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001757
Facundo Batista353750c2007-09-13 18:13:15 +00001758 def _round_05up(self, prec):
1759 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001760 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001761 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001762 else:
1763 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001764
Facundo Batista353750c2007-09-13 18:13:15 +00001765 def fma(self, other, third, context=None):
1766 """Fused multiply-add.
1767
1768 Returns self*other+third with no rounding of the intermediate
1769 product self*other.
1770
1771 self and other are multiplied together, with no rounding of
1772 the result. The third operand is then added to the result,
1773 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001774 """
Facundo Batista353750c2007-09-13 18:13:15 +00001775
1776 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001777
1778 # compute product; raise InvalidOperation if either operand is
1779 # a signaling NaN or if the product is zero times infinity.
1780 if self._is_special or other._is_special:
1781 if context is None:
1782 context = getcontext()
1783 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001784 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001785 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001786 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001787 if self._exp == 'n':
1788 product = self
1789 elif other._exp == 'n':
1790 product = other
1791 elif self._exp == 'F':
1792 if not other:
1793 return context._raise_error(InvalidOperation,
1794 'INF * 0 in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001795 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001796 elif other._exp == 'F':
1797 if not self:
1798 return context._raise_error(InvalidOperation,
1799 '0 * INF in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001800 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001801 else:
1802 product = _dec_from_triple(self._sign ^ other._sign,
1803 str(int(self._int) * int(other._int)),
1804 self._exp + other._exp)
1805
Facundo Batista353750c2007-09-13 18:13:15 +00001806 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001807 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001808
Facundo Batista353750c2007-09-13 18:13:15 +00001809 def _power_modulo(self, other, modulo, context=None):
1810 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001811
Facundo Batista353750c2007-09-13 18:13:15 +00001812 # if can't convert other and modulo to Decimal, raise
1813 # TypeError; there's no point returning NotImplemented (no
1814 # equivalent of __rpow__ for three argument pow)
1815 other = _convert_other(other, raiseit=True)
1816 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001817
Facundo Batista353750c2007-09-13 18:13:15 +00001818 if context is None:
1819 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001820
Facundo Batista353750c2007-09-13 18:13:15 +00001821 # deal with NaNs: if there are any sNaNs then first one wins,
1822 # (i.e. behaviour for NaNs is identical to that of fma)
1823 self_is_nan = self._isnan()
1824 other_is_nan = other._isnan()
1825 modulo_is_nan = modulo._isnan()
1826 if self_is_nan or other_is_nan or modulo_is_nan:
1827 if self_is_nan == 2:
1828 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001829 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001830 if other_is_nan == 2:
1831 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001832 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001833 if modulo_is_nan == 2:
1834 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001835 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001836 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001837 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001838 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001839 return other._fix_nan(context)
1840 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001841
Facundo Batista353750c2007-09-13 18:13:15 +00001842 # check inputs: we apply same restrictions as Python's pow()
1843 if not (self._isinteger() and
1844 other._isinteger() and
1845 modulo._isinteger()):
1846 return context._raise_error(InvalidOperation,
1847 'pow() 3rd argument not allowed '
1848 'unless all arguments are integers')
1849 if other < 0:
1850 return context._raise_error(InvalidOperation,
1851 'pow() 2nd argument cannot be '
1852 'negative when 3rd argument specified')
1853 if not modulo:
1854 return context._raise_error(InvalidOperation,
1855 'pow() 3rd argument cannot be 0')
1856
1857 # additional restriction for decimal: the modulus must be less
1858 # than 10**prec in absolute value
1859 if modulo.adjusted() >= context.prec:
1860 return context._raise_error(InvalidOperation,
1861 'insufficient precision: pow() 3rd '
1862 'argument must not have more than '
1863 'precision digits')
1864
1865 # define 0**0 == NaN, for consistency with two-argument pow
1866 # (even though it hurts!)
1867 if not other and not self:
1868 return context._raise_error(InvalidOperation,
1869 'at least one of pow() 1st argument '
1870 'and 2nd argument must be nonzero ;'
1871 '0**0 is not defined')
1872
1873 # compute sign of result
1874 if other._iseven():
1875 sign = 0
1876 else:
1877 sign = self._sign
1878
1879 # convert modulo to a Python integer, and self and other to
1880 # Decimal integers (i.e. force their exponents to be >= 0)
1881 modulo = abs(int(modulo))
1882 base = _WorkRep(self.to_integral_value())
1883 exponent = _WorkRep(other.to_integral_value())
1884
1885 # compute result using integer pow()
1886 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1887 for i in xrange(exponent.exp):
1888 base = pow(base, 10, modulo)
1889 base = pow(base, exponent.int, modulo)
1890
Facundo Batista72bc54f2007-11-23 17:59:00 +00001891 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001892
1893 def _power_exact(self, other, p):
1894 """Attempt to compute self**other exactly.
1895
1896 Given Decimals self and other and an integer p, attempt to
1897 compute an exact result for the power self**other, with p
1898 digits of precision. Return None if self**other is not
1899 exactly representable in p digits.
1900
1901 Assumes that elimination of special cases has already been
1902 performed: self and other must both be nonspecial; self must
1903 be positive and not numerically equal to 1; other must be
1904 nonzero. For efficiency, other._exp should not be too large,
1905 so that 10**abs(other._exp) is a feasible calculation."""
1906
1907 # In the comments below, we write x for the value of self and
1908 # y for the value of other. Write x = xc*10**xe and y =
1909 # yc*10**ye.
1910
1911 # The main purpose of this method is to identify the *failure*
1912 # of x**y to be exactly representable with as little effort as
1913 # possible. So we look for cheap and easy tests that
1914 # eliminate the possibility of x**y being exact. Only if all
1915 # these tests are passed do we go on to actually compute x**y.
1916
1917 # Here's the main idea. First normalize both x and y. We
1918 # express y as a rational m/n, with m and n relatively prime
1919 # and n>0. Then for x**y to be exactly representable (at
1920 # *any* precision), xc must be the nth power of a positive
1921 # integer and xe must be divisible by n. If m is negative
1922 # then additionally xc must be a power of either 2 or 5, hence
1923 # a power of 2**n or 5**n.
1924 #
1925 # There's a limit to how small |y| can be: if y=m/n as above
1926 # then:
1927 #
1928 # (1) if xc != 1 then for the result to be representable we
1929 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1930 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1931 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1932 # representable.
1933 #
1934 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1935 # |y| < 1/|xe| then the result is not representable.
1936 #
1937 # Note that since x is not equal to 1, at least one of (1) and
1938 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1939 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1940 #
1941 # There's also a limit to how large y can be, at least if it's
1942 # positive: the normalized result will have coefficient xc**y,
1943 # so if it's representable then xc**y < 10**p, and y <
1944 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1945 # not exactly representable.
1946
1947 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1948 # so |y| < 1/xe and the result is not representable.
1949 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1950 # < 1/nbits(xc).
1951
1952 x = _WorkRep(self)
1953 xc, xe = x.int, x.exp
1954 while xc % 10 == 0:
1955 xc //= 10
1956 xe += 1
1957
1958 y = _WorkRep(other)
1959 yc, ye = y.int, y.exp
1960 while yc % 10 == 0:
1961 yc //= 10
1962 ye += 1
1963
1964 # case where xc == 1: result is 10**(xe*y), with xe*y
1965 # required to be an integer
1966 if xc == 1:
1967 if ye >= 0:
1968 exponent = xe*yc*10**ye
1969 else:
1970 exponent, remainder = divmod(xe*yc, 10**-ye)
1971 if remainder:
1972 return None
1973 if y.sign == 1:
1974 exponent = -exponent
1975 # if other is a nonnegative integer, use ideal exponent
1976 if other._isinteger() and other._sign == 0:
1977 ideal_exponent = self._exp*int(other)
1978 zeros = min(exponent-ideal_exponent, p-1)
1979 else:
1980 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001981 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001982
1983 # case where y is negative: xc must be either a power
1984 # of 2 or a power of 5.
1985 if y.sign == 1:
1986 last_digit = xc % 10
1987 if last_digit in (2,4,6,8):
1988 # quick test for power of 2
1989 if xc & -xc != xc:
1990 return None
1991 # now xc is a power of 2; e is its exponent
1992 e = _nbits(xc)-1
1993 # find e*y and xe*y; both must be integers
1994 if ye >= 0:
1995 y_as_int = yc*10**ye
1996 e = e*y_as_int
1997 xe = xe*y_as_int
1998 else:
1999 ten_pow = 10**-ye
2000 e, remainder = divmod(e*yc, ten_pow)
2001 if remainder:
2002 return None
2003 xe, remainder = divmod(xe*yc, ten_pow)
2004 if remainder:
2005 return None
2006
2007 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2008 return None
2009 xc = 5**e
2010
2011 elif last_digit == 5:
2012 # e >= log_5(xc) if xc is a power of 5; we have
2013 # equality all the way up to xc=5**2658
2014 e = _nbits(xc)*28//65
2015 xc, remainder = divmod(5**e, xc)
2016 if remainder:
2017 return None
2018 while xc % 5 == 0:
2019 xc //= 5
2020 e -= 1
2021 if ye >= 0:
2022 y_as_integer = yc*10**ye
2023 e = e*y_as_integer
2024 xe = xe*y_as_integer
2025 else:
2026 ten_pow = 10**-ye
2027 e, remainder = divmod(e*yc, ten_pow)
2028 if remainder:
2029 return None
2030 xe, remainder = divmod(xe*yc, ten_pow)
2031 if remainder:
2032 return None
2033 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2034 return None
2035 xc = 2**e
2036 else:
2037 return None
2038
2039 if xc >= 10**p:
2040 return None
2041 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00002042 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00002043
2044 # now y is positive; find m and n such that y = m/n
2045 if ye >= 0:
2046 m, n = yc*10**ye, 1
2047 else:
2048 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2049 return None
2050 xc_bits = _nbits(xc)
2051 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2052 return None
2053 m, n = yc, 10**(-ye)
2054 while m % 2 == n % 2 == 0:
2055 m //= 2
2056 n //= 2
2057 while m % 5 == n % 5 == 0:
2058 m //= 5
2059 n //= 5
2060
2061 # compute nth root of xc*10**xe
2062 if n > 1:
2063 # if 1 < xc < 2**n then xc isn't an nth power
2064 if xc != 1 and xc_bits <= n:
2065 return None
2066
2067 xe, rem = divmod(xe, n)
2068 if rem != 0:
2069 return None
2070
2071 # compute nth root of xc using Newton's method
2072 a = 1L << -(-_nbits(xc)//n) # initial estimate
2073 while True:
2074 q, r = divmod(xc, a**(n-1))
2075 if a <= q:
2076 break
2077 else:
2078 a = (a*(n-1) + q)//n
2079 if not (a == q and r == 0):
2080 return None
2081 xc = a
2082
2083 # now xc*10**xe is the nth root of the original xc*10**xe
2084 # compute mth power of xc*10**xe
2085
2086 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2087 # 10**p and the result is not representable.
2088 if xc > 1 and m > p*100//_log10_lb(xc):
2089 return None
2090 xc = xc**m
2091 xe *= m
2092 if xc > 10**p:
2093 return None
2094
2095 # by this point the result *is* exactly representable
2096 # adjust the exponent to get as close as possible to the ideal
2097 # exponent, if necessary
2098 str_xc = str(xc)
2099 if other._isinteger() and other._sign == 0:
2100 ideal_exponent = self._exp*int(other)
2101 zeros = min(xe-ideal_exponent, p-len(str_xc))
2102 else:
2103 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002104 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002105
2106 def __pow__(self, other, modulo=None, context=None):
2107 """Return self ** other [ % modulo].
2108
2109 With two arguments, compute self**other.
2110
2111 With three arguments, compute (self**other) % modulo. For the
2112 three argument form, the following restrictions on the
2113 arguments hold:
2114
2115 - all three arguments must be integral
2116 - other must be nonnegative
2117 - either self or other (or both) must be nonzero
2118 - modulo must be nonzero and must have at most p digits,
2119 where p is the context precision.
2120
2121 If any of these restrictions is violated the InvalidOperation
2122 flag is raised.
2123
2124 The result of pow(self, other, modulo) is identical to the
2125 result that would be obtained by computing (self**other) %
2126 modulo with unbounded precision, but is computed more
2127 efficiently. It is always exact.
2128 """
2129
2130 if modulo is not None:
2131 return self._power_modulo(other, modulo, context)
2132
2133 other = _convert_other(other)
2134 if other is NotImplemented:
2135 return other
2136
2137 if context is None:
2138 context = getcontext()
2139
2140 # either argument is a NaN => result is NaN
2141 ans = self._check_nans(other, context)
2142 if ans:
2143 return ans
2144
2145 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2146 if not other:
2147 if not self:
2148 return context._raise_error(InvalidOperation, '0 ** 0')
2149 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002150 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002151
2152 # result has sign 1 iff self._sign is 1 and other is an odd integer
2153 result_sign = 0
2154 if self._sign == 1:
2155 if other._isinteger():
2156 if not other._iseven():
2157 result_sign = 1
2158 else:
2159 # -ve**noninteger = NaN
2160 # (-0)**noninteger = 0**noninteger
2161 if self:
2162 return context._raise_error(InvalidOperation,
2163 'x ** y with x negative and y not an integer')
2164 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002165 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002166
2167 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2168 if not self:
2169 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002170 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002171 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002172 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002173
2174 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002175 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002176 if other._sign == 0:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002177 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002178 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002179 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002180
Facundo Batista353750c2007-09-13 18:13:15 +00002181 # 1**other = 1, but the choice of exponent and the flags
2182 # depend on the exponent of self, and on whether other is a
2183 # positive integer, a negative integer, or neither
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002184 if self == _One:
Facundo Batista353750c2007-09-13 18:13:15 +00002185 if other._isinteger():
2186 # exp = max(self._exp*max(int(other), 0),
2187 # 1-context.prec) but evaluating int(other) directly
2188 # is dangerous until we know other is small (other
2189 # could be 1e999999999)
2190 if other._sign == 1:
2191 multiplier = 0
2192 elif other > context.prec:
2193 multiplier = context.prec
2194 else:
2195 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002196
Facundo Batista353750c2007-09-13 18:13:15 +00002197 exp = self._exp * multiplier
2198 if exp < 1-context.prec:
2199 exp = 1-context.prec
2200 context._raise_error(Rounded)
2201 else:
2202 context._raise_error(Inexact)
2203 context._raise_error(Rounded)
2204 exp = 1-context.prec
2205
Facundo Batista72bc54f2007-11-23 17:59:00 +00002206 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002207
2208 # compute adjusted exponent of self
2209 self_adj = self.adjusted()
2210
2211 # self ** infinity is infinity if self > 1, 0 if self < 1
2212 # self ** -infinity is infinity if self < 1, 0 if self > 1
2213 if other._isinfinity():
2214 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002215 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002216 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002217 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002218
2219 # from here on, the result always goes through the call
2220 # to _fix at the end of this function.
2221 ans = None
2222
2223 # crude test to catch cases of extreme overflow/underflow. If
2224 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2225 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2226 # self**other >= 10**(Emax+1), so overflow occurs. The test
2227 # for underflow is similar.
2228 bound = self._log10_exp_bound() + other.adjusted()
2229 if (self_adj >= 0) == (other._sign == 0):
2230 # self > 1 and other +ve, or self < 1 and other -ve
2231 # possibility of overflow
2232 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002233 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002234 else:
2235 # self > 1 and other -ve, or self < 1 and other +ve
2236 # possibility of underflow to 0
2237 Etiny = context.Etiny()
2238 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002239 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002240
2241 # try for an exact result with precision +1
2242 if ans is None:
2243 ans = self._power_exact(other, context.prec + 1)
2244 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002245 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002246
2247 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2248 if ans is None:
2249 p = context.prec
2250 x = _WorkRep(self)
2251 xc, xe = x.int, x.exp
2252 y = _WorkRep(other)
2253 yc, ye = y.int, y.exp
2254 if y.sign == 1:
2255 yc = -yc
2256
2257 # compute correctly rounded result: start with precision +3,
2258 # then increase precision until result is unambiguously roundable
2259 extra = 3
2260 while True:
2261 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2262 if coeff % (5*10**(len(str(coeff))-p-1)):
2263 break
2264 extra += 3
2265
Facundo Batista72bc54f2007-11-23 17:59:00 +00002266 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002267
2268 # the specification says that for non-integer other we need to
2269 # raise Inexact, even when the result is actually exact. In
2270 # the same way, we need to raise Underflow here if the result
2271 # is subnormal. (The call to _fix will take care of raising
2272 # Rounded and Subnormal, as usual.)
2273 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002274 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002275 # pad with zeros up to length context.prec+1 if necessary
2276 if len(ans._int) <= context.prec:
2277 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002278 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2279 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002280 if ans.adjusted() < context.Emin:
2281 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002282
Facundo Batista353750c2007-09-13 18:13:15 +00002283 # unlike exp, ln and log10, the power function respects the
2284 # rounding mode; no need to use ROUND_HALF_EVEN here
2285 ans = ans._fix(context)
2286 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002287
2288 def __rpow__(self, other, context=None):
2289 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002290 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002291 if other is NotImplemented:
2292 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002293 return other.__pow__(self, context=context)
2294
2295 def normalize(self, context=None):
2296 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002297
Facundo Batista353750c2007-09-13 18:13:15 +00002298 if context is None:
2299 context = getcontext()
2300
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002301 if self._is_special:
2302 ans = self._check_nans(context=context)
2303 if ans:
2304 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002305
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002306 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002307 if dup._isinfinity():
2308 return dup
2309
2310 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002311 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002312 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002313 end = len(dup._int)
2314 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002315 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002316 exp += 1
2317 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002318 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002319
Facundo Batistabd2fe832007-09-13 18:42:09 +00002320 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002321 """Quantize self so its exponent is the same as that of exp.
2322
2323 Similar to self._rescale(exp._exp) but with error checking.
2324 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002325 exp = _convert_other(exp, raiseit=True)
2326
Facundo Batista353750c2007-09-13 18:13:15 +00002327 if context is None:
2328 context = getcontext()
2329 if rounding is None:
2330 rounding = context.rounding
2331
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002332 if self._is_special or exp._is_special:
2333 ans = self._check_nans(exp, context)
2334 if ans:
2335 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002336
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002337 if exp._isinfinity() or self._isinfinity():
2338 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002339 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002340 return context._raise_error(InvalidOperation,
2341 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002342
Facundo Batistabd2fe832007-09-13 18:42:09 +00002343 # if we're not watching exponents, do a simple rescale
2344 if not watchexp:
2345 ans = self._rescale(exp._exp, rounding)
2346 # raise Inexact and Rounded where appropriate
2347 if ans._exp > self._exp:
2348 context._raise_error(Rounded)
2349 if ans != self:
2350 context._raise_error(Inexact)
2351 return ans
2352
Facundo Batista353750c2007-09-13 18:13:15 +00002353 # exp._exp should be between Etiny and Emax
2354 if not (context.Etiny() <= exp._exp <= context.Emax):
2355 return context._raise_error(InvalidOperation,
2356 'target exponent out of bounds in quantize')
2357
2358 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002359 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002360 return ans._fix(context)
2361
2362 self_adjusted = self.adjusted()
2363 if self_adjusted > context.Emax:
2364 return context._raise_error(InvalidOperation,
2365 'exponent of quantize result too large for current context')
2366 if self_adjusted - exp._exp + 1 > context.prec:
2367 return context._raise_error(InvalidOperation,
2368 'quantize result has too many digits for current context')
2369
2370 ans = self._rescale(exp._exp, rounding)
2371 if ans.adjusted() > context.Emax:
2372 return context._raise_error(InvalidOperation,
2373 'exponent of quantize result too large for current context')
2374 if len(ans._int) > context.prec:
2375 return context._raise_error(InvalidOperation,
2376 'quantize result has too many digits for current context')
2377
2378 # raise appropriate flags
2379 if ans._exp > self._exp:
2380 context._raise_error(Rounded)
2381 if ans != self:
2382 context._raise_error(Inexact)
2383 if ans and ans.adjusted() < context.Emin:
2384 context._raise_error(Subnormal)
2385
2386 # call to fix takes care of any necessary folddown
2387 ans = ans._fix(context)
2388 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002389
2390 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002391 """Return True if self and other have the same exponent; otherwise
2392 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002393
Facundo Batista1a191df2007-10-02 17:01:24 +00002394 If either operand is a special value, the following rules are used:
2395 * return True if both operands are infinities
2396 * return True if both operands are NaNs
2397 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002398 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002399 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002400 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002401 return (self.is_nan() and other.is_nan() or
2402 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002403 return self._exp == other._exp
2404
Facundo Batista353750c2007-09-13 18:13:15 +00002405 def _rescale(self, exp, rounding):
2406 """Rescale self so that the exponent is exp, either by padding with zeros
2407 or by truncating digits, using the given rounding mode.
2408
2409 Specials are returned without change. This operation is
2410 quiet: it raises no flags, and uses no information from the
2411 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002412
2413 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002414 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002415 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002416 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002417 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002418 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002419 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002420
Facundo Batista353750c2007-09-13 18:13:15 +00002421 if self._exp >= exp:
2422 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002423 return _dec_from_triple(self._sign,
2424 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002425
Facundo Batista353750c2007-09-13 18:13:15 +00002426 # too many digits; round and lose data. If self.adjusted() <
2427 # exp-1, replace self by 10**(exp-1) before rounding
2428 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002429 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002430 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002431 digits = 0
2432 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002433 changed = this_function(digits)
2434 coeff = self._int[:digits] or '0'
2435 if changed == 1:
2436 coeff = str(int(coeff)+1)
2437 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002438
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00002439 def _round(self, places, rounding):
2440 """Round a nonzero, nonspecial Decimal to a fixed number of
2441 significant figures, using the given rounding mode.
2442
2443 Infinities, NaNs and zeros are returned unaltered.
2444
2445 This operation is quiet: it raises no flags, and uses no
2446 information from the context.
2447
2448 """
2449 if places <= 0:
2450 raise ValueError("argument should be at least 1 in _round")
2451 if self._is_special or not self:
2452 return Decimal(self)
2453 ans = self._rescale(self.adjusted()+1-places, rounding)
2454 # it can happen that the rescale alters the adjusted exponent;
2455 # for example when rounding 99.97 to 3 significant figures.
2456 # When this happens we end up with an extra 0 at the end of
2457 # the number; a second rescale fixes this.
2458 if ans.adjusted() != self.adjusted():
2459 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2460 return ans
2461
Facundo Batista353750c2007-09-13 18:13:15 +00002462 def to_integral_exact(self, rounding=None, context=None):
2463 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002464
Facundo Batista353750c2007-09-13 18:13:15 +00002465 If no rounding mode is specified, take the rounding mode from
2466 the context. This method raises the Rounded and Inexact flags
2467 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002468
Facundo Batista353750c2007-09-13 18:13:15 +00002469 See also: to_integral_value, which does exactly the same as
2470 this method except that it doesn't raise Inexact or Rounded.
2471 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002472 if self._is_special:
2473 ans = self._check_nans(context=context)
2474 if ans:
2475 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002476 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002477 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002478 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002479 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002480 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002481 if context is None:
2482 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002483 if rounding is None:
2484 rounding = context.rounding
2485 context._raise_error(Rounded)
2486 ans = self._rescale(0, rounding)
2487 if ans != self:
2488 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002489 return ans
2490
Facundo Batista353750c2007-09-13 18:13:15 +00002491 def to_integral_value(self, rounding=None, context=None):
2492 """Rounds to the nearest integer, without raising inexact, rounded."""
2493 if context is None:
2494 context = getcontext()
2495 if rounding is None:
2496 rounding = context.rounding
2497 if self._is_special:
2498 ans = self._check_nans(context=context)
2499 if ans:
2500 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002501 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002502 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002503 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002504 else:
2505 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002506
Facundo Batista353750c2007-09-13 18:13:15 +00002507 # the method name changed, but we provide also the old one, for compatibility
2508 to_integral = to_integral_value
2509
2510 def sqrt(self, context=None):
2511 """Return the square root of self."""
Mark Dickinson3b24ccb2008-03-25 14:33:23 +00002512 if context is None:
2513 context = getcontext()
2514
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002515 if self._is_special:
2516 ans = self._check_nans(context=context)
2517 if ans:
2518 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002519
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002520 if self._isinfinity() and self._sign == 0:
2521 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002522
2523 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002524 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002525 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002526 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002527
2528 if self._sign == 1:
2529 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2530
Facundo Batista353750c2007-09-13 18:13:15 +00002531 # At this point self represents a positive number. Let p be
2532 # the desired precision and express self in the form c*100**e
2533 # with c a positive real number and e an integer, c and e
2534 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2535 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2536 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2537 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2538 # the closest integer to sqrt(c) with the even integer chosen
2539 # in the case of a tie.
2540 #
2541 # To ensure correct rounding in all cases, we use the
2542 # following trick: we compute the square root to an extra
2543 # place (precision p+1 instead of precision p), rounding down.
2544 # Then, if the result is inexact and its last digit is 0 or 5,
2545 # we increase the last digit to 1 or 6 respectively; if it's
2546 # exact we leave the last digit alone. Now the final round to
2547 # p places (or fewer in the case of underflow) will round
2548 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002549
Facundo Batista353750c2007-09-13 18:13:15 +00002550 # use an extra digit of precision
2551 prec = context.prec+1
2552
2553 # write argument in the form c*100**e where e = self._exp//2
2554 # is the 'ideal' exponent, to be used if the square root is
2555 # exactly representable. l is the number of 'digits' of c in
2556 # base 100, so that 100**(l-1) <= c < 100**l.
2557 op = _WorkRep(self)
2558 e = op.exp >> 1
2559 if op.exp & 1:
2560 c = op.int * 10
2561 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002562 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002563 c = op.int
2564 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002565
Facundo Batista353750c2007-09-13 18:13:15 +00002566 # rescale so that c has exactly prec base 100 'digits'
2567 shift = prec-l
2568 if shift >= 0:
2569 c *= 100**shift
2570 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002571 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002572 c, remainder = divmod(c, 100**-shift)
2573 exact = not remainder
2574 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002575
Facundo Batista353750c2007-09-13 18:13:15 +00002576 # find n = floor(sqrt(c)) using Newton's method
2577 n = 10**prec
2578 while True:
2579 q = c//n
2580 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002581 break
Facundo Batista353750c2007-09-13 18:13:15 +00002582 else:
2583 n = n + q >> 1
2584 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002585
Facundo Batista353750c2007-09-13 18:13:15 +00002586 if exact:
2587 # result is exact; rescale to use ideal exponent e
2588 if shift >= 0:
2589 # assert n % 10**shift == 0
2590 n //= 10**shift
2591 else:
2592 n *= 10**-shift
2593 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002594 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002595 # result is not exact; fix last digit as described above
2596 if n % 5 == 0:
2597 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002598
Facundo Batista72bc54f2007-11-23 17:59:00 +00002599 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002600
Facundo Batista353750c2007-09-13 18:13:15 +00002601 # round, and fit to current context
2602 context = context._shallow_copy()
2603 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002604 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002605 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002606
Facundo Batista353750c2007-09-13 18:13:15 +00002607 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002608
2609 def max(self, other, context=None):
2610 """Returns the larger value.
2611
Facundo Batista353750c2007-09-13 18:13:15 +00002612 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002613 NaN (and signals if one is sNaN). Also rounds.
2614 """
Facundo Batista353750c2007-09-13 18:13:15 +00002615 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002616
Facundo Batista6c398da2007-09-17 17:30:13 +00002617 if context is None:
2618 context = getcontext()
2619
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002620 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002621 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002622 # number is always returned
2623 sn = self._isnan()
2624 on = other._isnan()
2625 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002626 if on == 1 and sn == 0:
2627 return self._fix(context)
2628 if sn == 1 and on == 0:
2629 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002630 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002631
Mark Dickinson2fc92632008-02-06 22:10:50 +00002632 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002633 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002634 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002635 # then an ordering is applied:
2636 #
Facundo Batista59c58842007-04-10 12:58:45 +00002637 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002638 # positive sign and min returns the operand with the negative sign
2639 #
Facundo Batista59c58842007-04-10 12:58:45 +00002640 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002641 # the result. This is exactly the ordering used in compare_total.
2642 c = self.compare_total(other)
2643
2644 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002645 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002646 else:
2647 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002648
Facundo Batistae64acfa2007-12-17 14:18:42 +00002649 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002650
2651 def min(self, other, context=None):
2652 """Returns the smaller value.
2653
Facundo Batista59c58842007-04-10 12:58:45 +00002654 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002655 NaN (and signals if one is sNaN). Also rounds.
2656 """
Facundo Batista353750c2007-09-13 18:13:15 +00002657 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002658
Facundo Batista6c398da2007-09-17 17:30:13 +00002659 if context is None:
2660 context = getcontext()
2661
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002662 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002663 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002664 # number is always returned
2665 sn = self._isnan()
2666 on = other._isnan()
2667 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002668 if on == 1 and sn == 0:
2669 return self._fix(context)
2670 if sn == 1 and on == 0:
2671 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002672 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002673
Mark Dickinson2fc92632008-02-06 22:10:50 +00002674 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002675 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002676 c = self.compare_total(other)
2677
2678 if c == -1:
2679 ans = self
2680 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002681 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002682
Facundo Batistae64acfa2007-12-17 14:18:42 +00002683 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002684
2685 def _isinteger(self):
2686 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002687 if self._is_special:
2688 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002689 if self._exp >= 0:
2690 return True
2691 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002692 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002693
2694 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002695 """Returns True if self is even. Assumes self is an integer."""
2696 if not self or self._exp > 0:
2697 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002698 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002699
2700 def adjusted(self):
2701 """Return the adjusted exponent of self"""
2702 try:
2703 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002704 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002705 except TypeError:
2706 return 0
2707
Facundo Batista353750c2007-09-13 18:13:15 +00002708 def canonical(self, context=None):
2709 """Returns the same Decimal object.
2710
2711 As we do not have different encodings for the same number, the
2712 received object already is in its canonical form.
2713 """
2714 return self
2715
2716 def compare_signal(self, other, context=None):
2717 """Compares self to the other operand numerically.
2718
2719 It's pretty much like compare(), but all NaNs signal, with signaling
2720 NaNs taking precedence over quiet NaNs.
2721 """
Mark Dickinson2fc92632008-02-06 22:10:50 +00002722 other = _convert_other(other, raiseit = True)
2723 ans = self._compare_check_nans(other, context)
2724 if ans:
2725 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002726 return self.compare(other, context=context)
2727
2728 def compare_total(self, other):
2729 """Compares self to other using the abstract representations.
2730
2731 This is not like the standard compare, which use their numerical
2732 value. Note that a total ordering is defined for all possible abstract
2733 representations.
2734 """
Mark Dickinson0c673122009-10-29 12:04:00 +00002735 other = _convert_other(other, raiseit=True)
2736
Facundo Batista353750c2007-09-13 18:13:15 +00002737 # if one is negative and the other is positive, it's easy
2738 if self._sign and not other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002739 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002740 if not self._sign and other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002741 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002742 sign = self._sign
2743
2744 # let's handle both NaN types
2745 self_nan = self._isnan()
2746 other_nan = other._isnan()
2747 if self_nan or other_nan:
2748 if self_nan == other_nan:
Mark Dickinson7a7739d2009-08-28 13:25:02 +00002749 # compare payloads as though they're integers
2750 self_key = len(self._int), self._int
2751 other_key = len(other._int), other._int
2752 if self_key < other_key:
Facundo Batista353750c2007-09-13 18:13:15 +00002753 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002754 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002755 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002756 return _NegativeOne
Mark Dickinson7a7739d2009-08-28 13:25:02 +00002757 if self_key > other_key:
Facundo Batista353750c2007-09-13 18:13:15 +00002758 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002759 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002760 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002761 return _One
2762 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002763
2764 if sign:
2765 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002766 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002767 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002768 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002769 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002770 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002771 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002772 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002773 else:
2774 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002775 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002776 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002777 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002778 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002779 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002780 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002781 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002782
2783 if self < other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002784 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002785 if self > other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002786 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002787
2788 if self._exp < other._exp:
2789 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002790 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002791 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002792 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002793 if self._exp > other._exp:
2794 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002795 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002796 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002797 return _One
2798 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002799
2800
2801 def compare_total_mag(self, other):
2802 """Compares self to other using abstract repr., ignoring sign.
2803
2804 Like compare_total, but with operand's sign ignored and assumed to be 0.
2805 """
Mark Dickinson0c673122009-10-29 12:04:00 +00002806 other = _convert_other(other, raiseit=True)
2807
Facundo Batista353750c2007-09-13 18:13:15 +00002808 s = self.copy_abs()
2809 o = other.copy_abs()
2810 return s.compare_total(o)
2811
2812 def copy_abs(self):
2813 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002814 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002815
2816 def copy_negate(self):
2817 """Returns a copy with the sign inverted."""
2818 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002819 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002820 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002821 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002822
2823 def copy_sign(self, other):
2824 """Returns self with the sign of other."""
Mark Dickinson6d8effb2010-02-18 14:27:02 +00002825 other = _convert_other(other, raiseit=True)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002826 return _dec_from_triple(other._sign, self._int,
2827 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002828
2829 def exp(self, context=None):
2830 """Returns e ** self."""
2831
2832 if context is None:
2833 context = getcontext()
2834
2835 # exp(NaN) = NaN
2836 ans = self._check_nans(context=context)
2837 if ans:
2838 return ans
2839
2840 # exp(-Infinity) = 0
2841 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002842 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002843
2844 # exp(0) = 1
2845 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002846 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002847
2848 # exp(Infinity) = Infinity
2849 if self._isinfinity() == 1:
2850 return Decimal(self)
2851
2852 # the result is now guaranteed to be inexact (the true
2853 # mathematical result is transcendental). There's no need to
2854 # raise Rounded and Inexact here---they'll always be raised as
2855 # a result of the call to _fix.
2856 p = context.prec
2857 adj = self.adjusted()
2858
2859 # we only need to do any computation for quite a small range
2860 # of adjusted exponents---for example, -29 <= adj <= 10 for
2861 # the default context. For smaller exponent the result is
2862 # indistinguishable from 1 at the given precision, while for
2863 # larger exponent the result either overflows or underflows.
2864 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2865 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002866 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002867 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2868 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002869 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002870 elif self._sign == 0 and adj < -p:
2871 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002872 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002873 elif self._sign == 1 and adj < -p-1:
2874 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002875 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002876 # general case
2877 else:
2878 op = _WorkRep(self)
2879 c, e = op.int, op.exp
2880 if op.sign == 1:
2881 c = -c
2882
2883 # compute correctly rounded result: increase precision by
2884 # 3 digits at a time until we get an unambiguously
2885 # roundable result
2886 extra = 3
2887 while True:
2888 coeff, exp = _dexp(c, e, p+extra)
2889 if coeff % (5*10**(len(str(coeff))-p-1)):
2890 break
2891 extra += 3
2892
Facundo Batista72bc54f2007-11-23 17:59:00 +00002893 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002894
2895 # at this stage, ans should round correctly with *any*
2896 # rounding mode, not just with ROUND_HALF_EVEN
2897 context = context._shallow_copy()
2898 rounding = context._set_rounding(ROUND_HALF_EVEN)
2899 ans = ans._fix(context)
2900 context.rounding = rounding
2901
2902 return ans
2903
2904 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002905 """Return True if self is canonical; otherwise return False.
2906
2907 Currently, the encoding of a Decimal instance is always
2908 canonical, so this method returns True for any Decimal.
2909 """
2910 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002911
2912 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002913 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002914
Facundo Batista1a191df2007-10-02 17:01:24 +00002915 A Decimal instance is considered finite if it is neither
2916 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002917 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002918 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002919
2920 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002921 """Return True if self is infinite; otherwise return False."""
2922 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002923
2924 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002925 """Return True if self is a qNaN or sNaN; otherwise return False."""
2926 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002927
2928 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002929 """Return True if self is a normal number; otherwise return False."""
2930 if self._is_special or not self:
2931 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002932 if context is None:
2933 context = getcontext()
Mark Dickinsona7a52ab2009-10-20 13:33:03 +00002934 return context.Emin <= self.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +00002935
2936 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002937 """Return True if self is a quiet NaN; otherwise return False."""
2938 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002939
2940 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002941 """Return True if self is negative; otherwise return False."""
2942 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002943
2944 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002945 """Return True if self is a signaling NaN; otherwise return False."""
2946 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002947
2948 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002949 """Return True if self is subnormal; otherwise return False."""
2950 if self._is_special or not self:
2951 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002952 if context is None:
2953 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002954 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002955
2956 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002957 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002958 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002959
2960 def _ln_exp_bound(self):
2961 """Compute a lower bound for the adjusted exponent of self.ln().
2962 In other words, compute r such that self.ln() >= 10**r. Assumes
2963 that self is finite and positive and that self != 1.
2964 """
2965
2966 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2967 adj = self._exp + len(self._int) - 1
2968 if adj >= 1:
2969 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2970 return len(str(adj*23//10)) - 1
2971 if adj <= -2:
2972 # argument <= 0.1
2973 return len(str((-1-adj)*23//10)) - 1
2974 op = _WorkRep(self)
2975 c, e = op.int, op.exp
2976 if adj == 0:
2977 # 1 < self < 10
2978 num = str(c-10**-e)
2979 den = str(c)
2980 return len(num) - len(den) - (num < den)
2981 # adj == -1, 0.1 <= self < 1
2982 return e + len(str(10**-e - c)) - 1
2983
2984
2985 def ln(self, context=None):
2986 """Returns the natural (base e) logarithm of self."""
2987
2988 if context is None:
2989 context = getcontext()
2990
2991 # ln(NaN) = NaN
2992 ans = self._check_nans(context=context)
2993 if ans:
2994 return ans
2995
2996 # ln(0.0) == -Infinity
2997 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002998 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00002999
3000 # ln(Infinity) = Infinity
3001 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003002 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003003
3004 # ln(1.0) == 0.0
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003005 if self == _One:
3006 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00003007
3008 # ln(negative) raises InvalidOperation
3009 if self._sign == 1:
3010 return context._raise_error(InvalidOperation,
3011 'ln of a negative value')
3012
3013 # result is irrational, so necessarily inexact
3014 op = _WorkRep(self)
3015 c, e = op.int, op.exp
3016 p = context.prec
3017
3018 # correctly rounded result: repeatedly increase precision by 3
3019 # until we get an unambiguously roundable result
3020 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3021 while True:
3022 coeff = _dlog(c, e, places)
3023 # assert len(str(abs(coeff)))-p >= 1
3024 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3025 break
3026 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003027 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003028
3029 context = context._shallow_copy()
3030 rounding = context._set_rounding(ROUND_HALF_EVEN)
3031 ans = ans._fix(context)
3032 context.rounding = rounding
3033 return ans
3034
3035 def _log10_exp_bound(self):
3036 """Compute a lower bound for the adjusted exponent of self.log10().
3037 In other words, find r such that self.log10() >= 10**r.
3038 Assumes that self is finite and positive and that self != 1.
3039 """
3040
3041 # For x >= 10 or x < 0.1 we only need a bound on the integer
3042 # part of log10(self), and this comes directly from the
3043 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3044 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3045 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3046
3047 adj = self._exp + len(self._int) - 1
3048 if adj >= 1:
3049 # self >= 10
3050 return len(str(adj))-1
3051 if adj <= -2:
3052 # self < 0.1
3053 return len(str(-1-adj))-1
3054 op = _WorkRep(self)
3055 c, e = op.int, op.exp
3056 if adj == 0:
3057 # 1 < self < 10
3058 num = str(c-10**-e)
3059 den = str(231*c)
3060 return len(num) - len(den) - (num < den) + 2
3061 # adj == -1, 0.1 <= self < 1
3062 num = str(10**-e-c)
3063 return len(num) + e - (num < "231") - 1
3064
3065 def log10(self, context=None):
3066 """Returns the base 10 logarithm of self."""
3067
3068 if context is None:
3069 context = getcontext()
3070
3071 # log10(NaN) = NaN
3072 ans = self._check_nans(context=context)
3073 if ans:
3074 return ans
3075
3076 # log10(0.0) == -Infinity
3077 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003078 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003079
3080 # log10(Infinity) = Infinity
3081 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003082 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003083
3084 # log10(negative or -Infinity) raises InvalidOperation
3085 if self._sign == 1:
3086 return context._raise_error(InvalidOperation,
3087 'log10 of a negative value')
3088
3089 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00003090 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00003091 # answer may need rounding
3092 ans = Decimal(self._exp + len(self._int) - 1)
3093 else:
3094 # result is irrational, so necessarily inexact
3095 op = _WorkRep(self)
3096 c, e = op.int, op.exp
3097 p = context.prec
3098
3099 # correctly rounded result: repeatedly increase precision
3100 # until result is unambiguously roundable
3101 places = p-self._log10_exp_bound()+2
3102 while True:
3103 coeff = _dlog10(c, e, places)
3104 # assert len(str(abs(coeff)))-p >= 1
3105 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3106 break
3107 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003108 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003109
3110 context = context._shallow_copy()
3111 rounding = context._set_rounding(ROUND_HALF_EVEN)
3112 ans = ans._fix(context)
3113 context.rounding = rounding
3114 return ans
3115
3116 def logb(self, context=None):
3117 """ Returns the exponent of the magnitude of self's MSD.
3118
3119 The result is the integer which is the exponent of the magnitude
3120 of the most significant digit of self (as though it were truncated
3121 to a single digit while maintaining the value of that digit and
3122 without limiting the resulting exponent).
3123 """
3124 # logb(NaN) = NaN
3125 ans = self._check_nans(context=context)
3126 if ans:
3127 return ans
3128
3129 if context is None:
3130 context = getcontext()
3131
3132 # logb(+/-Inf) = +Inf
3133 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003134 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003135
3136 # logb(0) = -Inf, DivisionByZero
3137 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003138 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003139
3140 # otherwise, simply return the adjusted exponent of self, as a
3141 # Decimal. Note that no attempt is made to fit the result
3142 # into the current context.
Mark Dickinson15ae41c2009-10-07 19:22:05 +00003143 ans = Decimal(self.adjusted())
3144 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003145
3146 def _islogical(self):
3147 """Return True if self is a logical operand.
3148
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00003149 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00003150 an exponent of 0, and a coefficient whose digits must all be
3151 either 0 or 1.
3152 """
3153 if self._sign != 0 or self._exp != 0:
3154 return False
3155 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003156 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003157 return False
3158 return True
3159
3160 def _fill_logical(self, context, opa, opb):
3161 dif = context.prec - len(opa)
3162 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003163 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003164 elif dif < 0:
3165 opa = opa[-context.prec:]
3166 dif = context.prec - len(opb)
3167 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003168 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003169 elif dif < 0:
3170 opb = opb[-context.prec:]
3171 return opa, opb
3172
3173 def logical_and(self, other, context=None):
3174 """Applies an 'and' operation between self and other's digits."""
3175 if context is None:
3176 context = getcontext()
Mark Dickinson0c673122009-10-29 12:04:00 +00003177
3178 other = _convert_other(other, raiseit=True)
3179
Facundo Batista353750c2007-09-13 18:13:15 +00003180 if not self._islogical() or not other._islogical():
3181 return context._raise_error(InvalidOperation)
3182
3183 # fill to context.prec
3184 (opa, opb) = self._fill_logical(context, self._int, other._int)
3185
3186 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003187 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3188 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003189
3190 def logical_invert(self, context=None):
3191 """Invert all its digits."""
3192 if context is None:
3193 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003194 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3195 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003196
3197 def logical_or(self, other, context=None):
3198 """Applies an 'or' operation between self and other's digits."""
3199 if context is None:
3200 context = getcontext()
Mark Dickinson0c673122009-10-29 12:04:00 +00003201
3202 other = _convert_other(other, raiseit=True)
3203
Facundo Batista353750c2007-09-13 18:13:15 +00003204 if not self._islogical() or not other._islogical():
3205 return context._raise_error(InvalidOperation)
3206
3207 # fill to context.prec
3208 (opa, opb) = self._fill_logical(context, self._int, other._int)
3209
3210 # make the operation, and clean starting zeroes
Mark Dickinson65808ff2009-01-04 21:22:02 +00003211 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003212 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003213
3214 def logical_xor(self, other, context=None):
3215 """Applies an 'xor' operation between self and other's digits."""
3216 if context is None:
3217 context = getcontext()
Mark Dickinson0c673122009-10-29 12:04:00 +00003218
3219 other = _convert_other(other, raiseit=True)
3220
Facundo Batista353750c2007-09-13 18:13:15 +00003221 if not self._islogical() or not other._islogical():
3222 return context._raise_error(InvalidOperation)
3223
3224 # fill to context.prec
3225 (opa, opb) = self._fill_logical(context, self._int, other._int)
3226
3227 # make the operation, and clean starting zeroes
Mark Dickinson65808ff2009-01-04 21:22:02 +00003228 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003229 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003230
3231 def max_mag(self, other, context=None):
3232 """Compares the values numerically with their sign ignored."""
3233 other = _convert_other(other, raiseit=True)
3234
Facundo Batista6c398da2007-09-17 17:30:13 +00003235 if context is None:
3236 context = getcontext()
3237
Facundo Batista353750c2007-09-13 18:13:15 +00003238 if self._is_special or other._is_special:
3239 # If one operand is a quiet NaN and the other is number, then the
3240 # number is always returned
3241 sn = self._isnan()
3242 on = other._isnan()
3243 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003244 if on == 1 and sn == 0:
3245 return self._fix(context)
3246 if sn == 1 and on == 0:
3247 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003248 return self._check_nans(other, context)
3249
Mark Dickinson2fc92632008-02-06 22:10:50 +00003250 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003251 if c == 0:
3252 c = self.compare_total(other)
3253
3254 if c == -1:
3255 ans = other
3256 else:
3257 ans = self
3258
Facundo Batistae64acfa2007-12-17 14:18:42 +00003259 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003260
3261 def min_mag(self, other, context=None):
3262 """Compares the values numerically with their sign ignored."""
3263 other = _convert_other(other, raiseit=True)
3264
Facundo Batista6c398da2007-09-17 17:30:13 +00003265 if context is None:
3266 context = getcontext()
3267
Facundo Batista353750c2007-09-13 18:13:15 +00003268 if self._is_special or other._is_special:
3269 # If one operand is a quiet NaN and the other is number, then the
3270 # number is always returned
3271 sn = self._isnan()
3272 on = other._isnan()
3273 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003274 if on == 1 and sn == 0:
3275 return self._fix(context)
3276 if sn == 1 and on == 0:
3277 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003278 return self._check_nans(other, context)
3279
Mark Dickinson2fc92632008-02-06 22:10:50 +00003280 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003281 if c == 0:
3282 c = self.compare_total(other)
3283
3284 if c == -1:
3285 ans = self
3286 else:
3287 ans = other
3288
Facundo Batistae64acfa2007-12-17 14:18:42 +00003289 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003290
3291 def next_minus(self, context=None):
3292 """Returns the largest representable number smaller than itself."""
3293 if context is None:
3294 context = getcontext()
3295
3296 ans = self._check_nans(context=context)
3297 if ans:
3298 return ans
3299
3300 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003301 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003302 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003303 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003304
3305 context = context.copy()
3306 context._set_rounding(ROUND_FLOOR)
3307 context._ignore_all_flags()
3308 new_self = self._fix(context)
3309 if new_self != self:
3310 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003311 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3312 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003313
3314 def next_plus(self, context=None):
3315 """Returns the smallest representable number larger than itself."""
3316 if context is None:
3317 context = getcontext()
3318
3319 ans = self._check_nans(context=context)
3320 if ans:
3321 return ans
3322
3323 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003324 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003325 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003326 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003327
3328 context = context.copy()
3329 context._set_rounding(ROUND_CEILING)
3330 context._ignore_all_flags()
3331 new_self = self._fix(context)
3332 if new_self != self:
3333 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003334 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3335 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003336
3337 def next_toward(self, other, context=None):
3338 """Returns the number closest to self, in the direction towards other.
3339
3340 The result is the closest representable number to self
3341 (excluding self) that is in the direction towards other,
3342 unless both have the same value. If the two operands are
3343 numerically equal, then the result is a copy of self with the
3344 sign set to be the same as the sign of other.
3345 """
3346 other = _convert_other(other, raiseit=True)
3347
3348 if context is None:
3349 context = getcontext()
3350
3351 ans = self._check_nans(other, context)
3352 if ans:
3353 return ans
3354
Mark Dickinson2fc92632008-02-06 22:10:50 +00003355 comparison = self._cmp(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003356 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003357 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003358
3359 if comparison == -1:
3360 ans = self.next_plus(context)
3361 else: # comparison == 1
3362 ans = self.next_minus(context)
3363
3364 # decide which flags to raise using value of ans
3365 if ans._isinfinity():
3366 context._raise_error(Overflow,
3367 'Infinite result from next_toward',
3368 ans._sign)
3369 context._raise_error(Rounded)
3370 context._raise_error(Inexact)
3371 elif ans.adjusted() < context.Emin:
3372 context._raise_error(Underflow)
3373 context._raise_error(Subnormal)
3374 context._raise_error(Rounded)
3375 context._raise_error(Inexact)
3376 # if precision == 1 then we don't raise Clamped for a
3377 # result 0E-Etiny.
3378 if not ans:
3379 context._raise_error(Clamped)
3380
3381 return ans
3382
3383 def number_class(self, context=None):
3384 """Returns an indication of the class of self.
3385
3386 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003387 sNaN
3388 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003389 -Infinity
3390 -Normal
3391 -Subnormal
3392 -Zero
3393 +Zero
3394 +Subnormal
3395 +Normal
3396 +Infinity
3397 """
3398 if self.is_snan():
3399 return "sNaN"
3400 if self.is_qnan():
3401 return "NaN"
3402 inf = self._isinfinity()
3403 if inf == 1:
3404 return "+Infinity"
3405 if inf == -1:
3406 return "-Infinity"
3407 if self.is_zero():
3408 if self._sign:
3409 return "-Zero"
3410 else:
3411 return "+Zero"
3412 if context is None:
3413 context = getcontext()
3414 if self.is_subnormal(context=context):
3415 if self._sign:
3416 return "-Subnormal"
3417 else:
3418 return "+Subnormal"
3419 # just a normal, regular, boring number, :)
3420 if self._sign:
3421 return "-Normal"
3422 else:
3423 return "+Normal"
3424
3425 def radix(self):
3426 """Just returns 10, as this is Decimal, :)"""
3427 return Decimal(10)
3428
3429 def rotate(self, other, context=None):
3430 """Returns a rotated copy of self, value-of-other times."""
3431 if context is None:
3432 context = getcontext()
3433
Mark Dickinson0c673122009-10-29 12:04:00 +00003434 other = _convert_other(other, raiseit=True)
3435
Facundo Batista353750c2007-09-13 18:13:15 +00003436 ans = self._check_nans(other, context)
3437 if ans:
3438 return ans
3439
3440 if other._exp != 0:
3441 return context._raise_error(InvalidOperation)
3442 if not (-context.prec <= int(other) <= context.prec):
3443 return context._raise_error(InvalidOperation)
3444
3445 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003446 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003447
3448 # get values, pad if necessary
3449 torot = int(other)
3450 rotdig = self._int
3451 topad = context.prec - len(rotdig)
Mark Dickinson6f390012009-10-29 12:11:18 +00003452 if topad > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003453 rotdig = '0'*topad + rotdig
Mark Dickinson6f390012009-10-29 12:11:18 +00003454 elif topad < 0:
3455 rotdig = rotdig[-topad:]
Facundo Batista353750c2007-09-13 18:13:15 +00003456
3457 # let's rotate!
3458 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003459 return _dec_from_triple(self._sign,
3460 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003461
Mark Dickinson0c673122009-10-29 12:04:00 +00003462 def scaleb(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00003463 """Returns self operand after adding the second value to its exp."""
3464 if context is None:
3465 context = getcontext()
3466
Mark Dickinson0c673122009-10-29 12:04:00 +00003467 other = _convert_other(other, raiseit=True)
3468
Facundo Batista353750c2007-09-13 18:13:15 +00003469 ans = self._check_nans(other, context)
3470 if ans:
3471 return ans
3472
3473 if other._exp != 0:
3474 return context._raise_error(InvalidOperation)
3475 liminf = -2 * (context.Emax + context.prec)
3476 limsup = 2 * (context.Emax + context.prec)
3477 if not (liminf <= int(other) <= limsup):
3478 return context._raise_error(InvalidOperation)
3479
3480 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003481 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003482
Facundo Batista72bc54f2007-11-23 17:59:00 +00003483 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003484 d = d._fix(context)
3485 return d
3486
3487 def shift(self, other, context=None):
3488 """Returns a shifted copy of self, value-of-other times."""
3489 if context is None:
3490 context = getcontext()
3491
Mark Dickinson0c673122009-10-29 12:04:00 +00003492 other = _convert_other(other, raiseit=True)
3493
Facundo Batista353750c2007-09-13 18:13:15 +00003494 ans = self._check_nans(other, context)
3495 if ans:
3496 return ans
3497
3498 if other._exp != 0:
3499 return context._raise_error(InvalidOperation)
3500 if not (-context.prec <= int(other) <= context.prec):
3501 return context._raise_error(InvalidOperation)
3502
3503 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003504 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003505
3506 # get values, pad if necessary
3507 torot = int(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003508 rotdig = self._int
3509 topad = context.prec - len(rotdig)
Mark Dickinson6f390012009-10-29 12:11:18 +00003510 if topad > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003511 rotdig = '0'*topad + rotdig
Mark Dickinson6f390012009-10-29 12:11:18 +00003512 elif topad < 0:
3513 rotdig = rotdig[-topad:]
Facundo Batista353750c2007-09-13 18:13:15 +00003514
3515 # let's shift!
3516 if torot < 0:
Mark Dickinson6f390012009-10-29 12:11:18 +00003517 shifted = rotdig[:torot]
Facundo Batista353750c2007-09-13 18:13:15 +00003518 else:
Mark Dickinson6f390012009-10-29 12:11:18 +00003519 shifted = rotdig + '0'*torot
3520 shifted = shifted[-context.prec:]
Facundo Batista353750c2007-09-13 18:13:15 +00003521
Facundo Batista72bc54f2007-11-23 17:59:00 +00003522 return _dec_from_triple(self._sign,
Mark Dickinson6f390012009-10-29 12:11:18 +00003523 shifted.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003524
Facundo Batista59c58842007-04-10 12:58:45 +00003525 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003526 def __reduce__(self):
3527 return (self.__class__, (str(self),))
3528
3529 def __copy__(self):
Benjamin Peterson28e369a2010-01-25 03:58:21 +00003530 if type(self) is Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003531 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003532 return self.__class__(str(self))
3533
3534 def __deepcopy__(self, memo):
Benjamin Peterson28e369a2010-01-25 03:58:21 +00003535 if type(self) is Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003536 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003537 return self.__class__(str(self))
3538
Mark Dickinson277859d2009-03-17 23:03:46 +00003539 # PEP 3101 support. the _localeconv keyword argument should be
3540 # considered private: it's provided for ease of testing only.
3541 def __format__(self, specifier, context=None, _localeconv=None):
Mark Dickinsonf4da7772008-02-29 03:29:17 +00003542 """Format a Decimal instance according to the given specifier.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003543
3544 The specifier should be a standard format specifier, with the
3545 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson277859d2009-03-17 23:03:46 +00003546 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3547 type is omitted it defaults to 'g' or 'G', depending on the
3548 value of context.capitals.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003549 """
3550
3551 # Note: PEP 3101 says that if the type is not present then
3552 # there should be at least one digit after the decimal point.
3553 # We take the liberty of ignoring this requirement for
3554 # Decimal---it's presumably there to make sure that
3555 # format(float, '') behaves similarly to str(float).
3556 if context is None:
3557 context = getcontext()
3558
Mark Dickinson277859d2009-03-17 23:03:46 +00003559 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003560
Mark Dickinson277859d2009-03-17 23:03:46 +00003561 # special values don't care about the type or precision
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003562 if self._is_special:
Mark Dickinson277859d2009-03-17 23:03:46 +00003563 sign = _format_sign(self._sign, spec)
3564 body = str(self.copy_abs())
3565 return _format_align(sign, body, spec)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003566
3567 # a type of None defaults to 'g' or 'G', depending on context
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003568 if spec['type'] is None:
3569 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson277859d2009-03-17 23:03:46 +00003570
3571 # if type is '%', adjust exponent of self accordingly
3572 if spec['type'] == '%':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003573 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3574
3575 # round if necessary, taking rounding mode from the context
3576 rounding = context.rounding
3577 precision = spec['precision']
3578 if precision is not None:
3579 if spec['type'] in 'eE':
3580 self = self._round(precision+1, rounding)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003581 elif spec['type'] in 'fF%':
3582 self = self._rescale(-precision, rounding)
Mark Dickinson277859d2009-03-17 23:03:46 +00003583 elif spec['type'] in 'gG' and len(self._int) > precision:
3584 self = self._round(precision, rounding)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003585 # special case: zeros with a positive exponent can't be
3586 # represented in fixed point; rescale them to 0e0.
Mark Dickinson277859d2009-03-17 23:03:46 +00003587 if not self and self._exp > 0 and spec['type'] in 'fF%':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003588 self = self._rescale(0, rounding)
3589
3590 # figure out placement of the decimal point
3591 leftdigits = self._exp + len(self._int)
Mark Dickinson277859d2009-03-17 23:03:46 +00003592 if spec['type'] in 'eE':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003593 if not self and precision is not None:
3594 dotplace = 1 - precision
3595 else:
3596 dotplace = 1
Mark Dickinson277859d2009-03-17 23:03:46 +00003597 elif spec['type'] in 'fF%':
3598 dotplace = leftdigits
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003599 elif spec['type'] in 'gG':
3600 if self._exp <= 0 and leftdigits > -6:
3601 dotplace = leftdigits
3602 else:
3603 dotplace = 1
3604
Mark Dickinson277859d2009-03-17 23:03:46 +00003605 # find digits before and after decimal point, and get exponent
3606 if dotplace < 0:
3607 intpart = '0'
3608 fracpart = '0'*(-dotplace) + self._int
3609 elif dotplace > len(self._int):
3610 intpart = self._int + '0'*(dotplace-len(self._int))
3611 fracpart = ''
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003612 else:
Mark Dickinson277859d2009-03-17 23:03:46 +00003613 intpart = self._int[:dotplace] or '0'
3614 fracpart = self._int[dotplace:]
3615 exp = leftdigits-dotplace
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003616
Mark Dickinson277859d2009-03-17 23:03:46 +00003617 # done with the decimal-specific stuff; hand over the rest
3618 # of the formatting to the _format_number function
3619 return _format_number(self._sign, intpart, fracpart, exp, spec)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003620
Facundo Batista72bc54f2007-11-23 17:59:00 +00003621def _dec_from_triple(sign, coefficient, exponent, special=False):
3622 """Create a decimal instance directly, without any validation,
3623 normalization (e.g. removal of leading zeros) or argument
3624 conversion.
3625
3626 This function is for *internal use only*.
3627 """
3628
3629 self = object.__new__(Decimal)
3630 self._sign = sign
3631 self._int = coefficient
3632 self._exp = exponent
3633 self._is_special = special
3634
3635 return self
3636
Raymond Hettinger2c8585b2009-02-03 03:37:03 +00003637# Register Decimal as a kind of Number (an abstract base class).
3638# However, do not register it as Real (because Decimals are not
3639# interoperable with floats).
3640_numbers.Number.register(Decimal)
3641
3642
Facundo Batista59c58842007-04-10 12:58:45 +00003643##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003644
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003645
3646# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003647rounding_functions = [name for name in Decimal.__dict__.keys()
3648 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003649for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003650 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003651 globalname = name[1:].upper()
3652 val = globals()[globalname]
3653 Decimal._pick_rounding_function[val] = name
3654
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003655del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003656
Nick Coghlanced12182006-09-02 03:54:17 +00003657class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003658 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003659
Nick Coghlanced12182006-09-02 03:54:17 +00003660 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003661 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003662 """
3663 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003664 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003665 def __enter__(self):
3666 self.saved_context = getcontext()
3667 setcontext(self.new_context)
3668 return self.new_context
3669 def __exit__(self, t, v, tb):
3670 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003671
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003672class Context(object):
3673 """Contains the context for a Decimal instance.
3674
3675 Contains:
3676 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003677 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003678 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003679 raised when it is caused. Otherwise, a value is
3680 substituted in.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003681 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003682 (Whether or not the trap_enabler is set)
3683 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003684 Emin - Minimum exponent
3685 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003686 capitals - If 1, 1*10^1 is printed as 1E+1.
3687 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003688 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003689 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003690
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003691 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003692 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003693 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003694 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003695 _ignored_flags=None):
3696 if flags is None:
3697 flags = []
3698 if _ignored_flags is None:
3699 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003700 if not isinstance(flags, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003701 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003702 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003703 if traps is not None and not isinstance(traps, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003704 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003705 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003706 for name, val in locals().items():
3707 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003708 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003709 else:
3710 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003711 del self.self
3712
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003713 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003714 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003715 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003716 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3717 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3718 % vars(self))
3719 names = [f.__name__ for f, v in self.flags.items() if v]
3720 s.append('flags=[' + ', '.join(names) + ']')
3721 names = [t.__name__ for t, v in self.traps.items() if v]
3722 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003723 return ', '.join(s) + ')'
3724
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003725 def clear_flags(self):
3726 """Reset all flags to zero"""
3727 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003728 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003729
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003730 def _shallow_copy(self):
3731 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003732 nc = Context(self.prec, self.rounding, self.traps,
3733 self.flags, self.Emin, self.Emax,
3734 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003735 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003736
3737 def copy(self):
3738 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003739 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003740 self.flags.copy(), self.Emin, self.Emax,
3741 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003742 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003743 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003744
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003745 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003746 """Handles an error
3747
3748 If the flag is in _ignored_flags, returns the default response.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003749 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003750 trap_enabler is set, it reaises the exception. Otherwise, it returns
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003751 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003752 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003753 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003754 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003755 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003756 return error().handle(self, *args)
3757
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003758 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003759 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003760 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003761 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003762
3763 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003764 # self._ignored_flags = []
Mark Dickinson8aca9d02008-05-04 02:05:06 +00003765 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003766
3767 def _ignore_all_flags(self):
3768 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003769 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003770
3771 def _ignore_flags(self, *flags):
3772 """Ignore the flags, if they are raised"""
3773 # Do not mutate-- This way, copies of a context leave the original
3774 # alone.
3775 self._ignored_flags = (self._ignored_flags + list(flags))
3776 return list(flags)
3777
3778 def _regard_flags(self, *flags):
3779 """Stop ignoring the flags, if they are raised"""
3780 if flags and isinstance(flags[0], (tuple,list)):
3781 flags = flags[0]
3782 for flag in flags:
3783 self._ignored_flags.remove(flag)
3784
Nick Coghlan53663a62008-07-15 14:27:37 +00003785 # We inherit object.__hash__, so we must deny this explicitly
3786 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003787
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003788 def Etiny(self):
3789 """Returns Etiny (= Emin - prec + 1)"""
3790 return int(self.Emin - self.prec + 1)
3791
3792 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003793 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003794 return int(self.Emax - self.prec + 1)
3795
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003796 def _set_rounding(self, type):
3797 """Sets the rounding type.
3798
3799 Sets the rounding type, and returns the current (previous)
3800 rounding type. Often used like:
3801
3802 context = context.copy()
3803 # so you don't change the calling context
3804 # if an error occurs in the middle.
3805 rounding = context._set_rounding(ROUND_UP)
3806 val = self.__sub__(other, context=context)
3807 context._set_rounding(rounding)
3808
3809 This will make it round up for that operation.
3810 """
3811 rounding = self.rounding
3812 self.rounding= type
3813 return rounding
3814
Raymond Hettingerfed52962004-07-14 15:41:57 +00003815 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003816 """Creates a new Decimal instance but using self as context.
3817
3818 This method implements the to-number operation of the
3819 IBM Decimal specification."""
3820
3821 if isinstance(num, basestring) and num != num.strip():
3822 return self._raise_error(ConversionSyntax,
3823 "no trailing or leading whitespace is "
3824 "permitted.")
3825
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003826 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003827 if d._isnan() and len(d._int) > self.prec - self._clamp:
3828 return self._raise_error(ConversionSyntax,
3829 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003830 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003831
Raymond Hettingerf4d85972009-01-03 19:02:23 +00003832 def create_decimal_from_float(self, f):
3833 """Creates a new Decimal instance from a float but rounding using self
3834 as the context.
3835
3836 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3837 >>> context.create_decimal_from_float(3.1415926535897932)
3838 Decimal('3.1415')
3839 >>> context = Context(prec=5, traps=[Inexact])
3840 >>> context.create_decimal_from_float(3.1415926535897932)
3841 Traceback (most recent call last):
3842 ...
3843 Inexact: None
3844
3845 """
3846 d = Decimal.from_float(f) # An exact conversion
3847 return d._fix(self) # Apply the context rounding
3848
Facundo Batista59c58842007-04-10 12:58:45 +00003849 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003850 def abs(self, a):
3851 """Returns the absolute value of the operand.
3852
3853 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003854 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003855 the plus operation on the operand.
3856
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003857 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003858 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003859 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003860 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003861 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003862 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003863 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003864 Decimal('101.5')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003865 >>> ExtendedContext.abs(-1)
3866 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003867 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003868 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003869 return a.__abs__(context=self)
3870
3871 def add(self, a, b):
3872 """Return the sum of the two operands.
3873
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003874 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003875 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003876 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003877 Decimal('1.02E+4')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003878 >>> ExtendedContext.add(1, Decimal(2))
3879 Decimal('3')
3880 >>> ExtendedContext.add(Decimal(8), 5)
3881 Decimal('13')
3882 >>> ExtendedContext.add(5, 5)
3883 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003884 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003885 a = _convert_other(a, raiseit=True)
3886 r = a.__add__(b, context=self)
3887 if r is NotImplemented:
3888 raise TypeError("Unable to convert %s to Decimal" % b)
3889 else:
3890 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003891
3892 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003893 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003894
Facundo Batista353750c2007-09-13 18:13:15 +00003895 def canonical(self, a):
3896 """Returns the same Decimal object.
3897
3898 As we do not have different encodings for the same number, the
3899 received object already is in its canonical form.
3900
3901 >>> ExtendedContext.canonical(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003902 Decimal('2.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003903 """
3904 return a.canonical(context=self)
3905
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003906 def compare(self, a, b):
3907 """Compares values numerically.
3908
3909 If the signs of the operands differ, a value representing each operand
3910 ('-1' if the operand is less than zero, '0' if the operand is zero or
3911 negative zero, or '1' if the operand is greater than zero) is used in
3912 place of that operand for the comparison instead of the actual
3913 operand.
3914
3915 The comparison is then effected by subtracting the second operand from
3916 the first and then returning a value according to the result of the
3917 subtraction: '-1' if the result is less than zero, '0' if the result is
3918 zero or negative zero, or '1' if the result is greater than zero.
3919
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003920 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003921 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003922 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003923 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003924 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003925 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003926 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003927 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003928 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003929 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003930 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003931 Decimal('-1')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003932 >>> ExtendedContext.compare(1, 2)
3933 Decimal('-1')
3934 >>> ExtendedContext.compare(Decimal(1), 2)
3935 Decimal('-1')
3936 >>> ExtendedContext.compare(1, Decimal(2))
3937 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003938 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003939 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003940 return a.compare(b, context=self)
3941
Facundo Batista353750c2007-09-13 18:13:15 +00003942 def compare_signal(self, a, b):
3943 """Compares the values of the two operands numerically.
3944
3945 It's pretty much like compare(), but all NaNs signal, with signaling
3946 NaNs taking precedence over quiet NaNs.
3947
3948 >>> c = ExtendedContext
3949 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003950 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003951 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003952 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003953 >>> c.flags[InvalidOperation] = 0
3954 >>> print c.flags[InvalidOperation]
3955 0
3956 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003957 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003958 >>> print c.flags[InvalidOperation]
3959 1
3960 >>> c.flags[InvalidOperation] = 0
3961 >>> print c.flags[InvalidOperation]
3962 0
3963 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003964 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003965 >>> print c.flags[InvalidOperation]
3966 1
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003967 >>> c.compare_signal(-1, 2)
3968 Decimal('-1')
3969 >>> c.compare_signal(Decimal(-1), 2)
3970 Decimal('-1')
3971 >>> c.compare_signal(-1, Decimal(2))
3972 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003973 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003974 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00003975 return a.compare_signal(b, context=self)
3976
3977 def compare_total(self, a, b):
3978 """Compares two operands using their abstract representation.
3979
3980 This is not like the standard compare, which use their numerical
3981 value. Note that a total ordering is defined for all possible abstract
3982 representations.
3983
3984 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003985 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003986 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003987 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003988 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003989 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003990 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003991 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003992 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003993 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00003994 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003995 Decimal('-1')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003996 >>> ExtendedContext.compare_total(1, 2)
3997 Decimal('-1')
3998 >>> ExtendedContext.compare_total(Decimal(1), 2)
3999 Decimal('-1')
4000 >>> ExtendedContext.compare_total(1, Decimal(2))
4001 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004002 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004003 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004004 return a.compare_total(b)
4005
4006 def compare_total_mag(self, a, b):
4007 """Compares two operands using their abstract representation ignoring sign.
4008
4009 Like compare_total, but with operand's sign ignored and assumed to be 0.
4010 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004011 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004012 return a.compare_total_mag(b)
4013
4014 def copy_abs(self, a):
4015 """Returns a copy of the operand with the sign set to 0.
4016
4017 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004018 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00004019 >>> ExtendedContext.copy_abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004020 Decimal('100')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004021 >>> ExtendedContext.copy_abs(-1)
4022 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004023 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004024 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004025 return a.copy_abs()
4026
4027 def copy_decimal(self, a):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004028 """Returns a copy of the decimal object.
Facundo Batista353750c2007-09-13 18:13:15 +00004029
4030 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004031 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00004032 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004033 Decimal('-1.00')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004034 >>> ExtendedContext.copy_decimal(1)
4035 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004036 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004037 a = _convert_other(a, raiseit=True)
Facundo Batista6c398da2007-09-17 17:30:13 +00004038 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00004039
4040 def copy_negate(self, a):
4041 """Returns a copy of the operand with the sign inverted.
4042
4043 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004044 Decimal('-101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00004045 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004046 Decimal('101.5')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004047 >>> ExtendedContext.copy_negate(1)
4048 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004049 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004050 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004051 return a.copy_negate()
4052
4053 def copy_sign(self, a, b):
4054 """Copies the second operand's sign to the first one.
4055
4056 In detail, it returns a copy of the first operand with the sign
4057 equal to the sign of the second operand.
4058
4059 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004060 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004061 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004062 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004063 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004064 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004065 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004066 Decimal('-1.50')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004067 >>> ExtendedContext.copy_sign(1, -2)
4068 Decimal('-1')
4069 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4070 Decimal('-1')
4071 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4072 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004073 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004074 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004075 return a.copy_sign(b)
4076
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004077 def divide(self, a, b):
4078 """Decimal division in a specified context.
4079
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004080 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004081 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004082 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004083 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004084 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004085 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004086 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004087 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004088 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004089 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004090 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004091 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004092 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004093 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004094 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004095 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004096 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004097 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004098 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004099 Decimal('1.20E+6')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004100 >>> ExtendedContext.divide(5, 5)
4101 Decimal('1')
4102 >>> ExtendedContext.divide(Decimal(5), 5)
4103 Decimal('1')
4104 >>> ExtendedContext.divide(5, Decimal(5))
4105 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004106 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004107 a = _convert_other(a, raiseit=True)
4108 r = a.__div__(b, context=self)
4109 if r is NotImplemented:
4110 raise TypeError("Unable to convert %s to Decimal" % b)
4111 else:
4112 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004113
4114 def divide_int(self, a, b):
4115 """Divides two numbers and returns the integer part of the result.
4116
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004117 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004118 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004119 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004120 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004121 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004122 Decimal('3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004123 >>> ExtendedContext.divide_int(10, 3)
4124 Decimal('3')
4125 >>> ExtendedContext.divide_int(Decimal(10), 3)
4126 Decimal('3')
4127 >>> ExtendedContext.divide_int(10, Decimal(3))
4128 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004129 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004130 a = _convert_other(a, raiseit=True)
4131 r = a.__floordiv__(b, context=self)
4132 if r is NotImplemented:
4133 raise TypeError("Unable to convert %s to Decimal" % b)
4134 else:
4135 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004136
4137 def divmod(self, a, b):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004138 """Return (a // b, a % b).
Mark Dickinson202eb902010-01-06 16:20:22 +00004139
4140 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4141 (Decimal('2'), Decimal('2'))
4142 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4143 (Decimal('2'), Decimal('0'))
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004144 >>> ExtendedContext.divmod(8, 4)
4145 (Decimal('2'), Decimal('0'))
4146 >>> ExtendedContext.divmod(Decimal(8), 4)
4147 (Decimal('2'), Decimal('0'))
4148 >>> ExtendedContext.divmod(8, Decimal(4))
4149 (Decimal('2'), Decimal('0'))
Mark Dickinson202eb902010-01-06 16:20:22 +00004150 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004151 a = _convert_other(a, raiseit=True)
4152 r = a.__divmod__(b, context=self)
4153 if r is NotImplemented:
4154 raise TypeError("Unable to convert %s to Decimal" % b)
4155 else:
4156 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004157
Facundo Batista353750c2007-09-13 18:13:15 +00004158 def exp(self, a):
4159 """Returns e ** a.
4160
4161 >>> c = ExtendedContext.copy()
4162 >>> c.Emin = -999
4163 >>> c.Emax = 999
4164 >>> c.exp(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004165 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004166 >>> c.exp(Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004167 Decimal('0.367879441')
Facundo Batista353750c2007-09-13 18:13:15 +00004168 >>> c.exp(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004169 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004170 >>> c.exp(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004171 Decimal('2.71828183')
Facundo Batista353750c2007-09-13 18:13:15 +00004172 >>> c.exp(Decimal('0.693147181'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004173 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004174 >>> c.exp(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004175 Decimal('Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004176 >>> c.exp(10)
4177 Decimal('22026.4658')
Facundo Batista353750c2007-09-13 18:13:15 +00004178 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004179 a =_convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004180 return a.exp(context=self)
4181
4182 def fma(self, a, b, c):
4183 """Returns a multiplied by b, plus c.
4184
4185 The first two operands are multiplied together, using multiply,
4186 the third operand is then added to the result of that
4187 multiplication, using add, all with only one final rounding.
4188
4189 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004190 Decimal('22')
Facundo Batista353750c2007-09-13 18:13:15 +00004191 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004192 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004193 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004194 Decimal('1.38435736E+12')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004195 >>> ExtendedContext.fma(1, 3, 4)
4196 Decimal('7')
4197 >>> ExtendedContext.fma(1, Decimal(3), 4)
4198 Decimal('7')
4199 >>> ExtendedContext.fma(1, 3, Decimal(4))
4200 Decimal('7')
Facundo Batista353750c2007-09-13 18:13:15 +00004201 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004202 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004203 return a.fma(b, c, context=self)
4204
4205 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004206 """Return True if the operand is canonical; otherwise return False.
4207
4208 Currently, the encoding of a Decimal instance is always
4209 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00004210
4211 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004212 True
Facundo Batista353750c2007-09-13 18:13:15 +00004213 """
Facundo Batista1a191df2007-10-02 17:01:24 +00004214 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00004215
4216 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004217 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004218
Facundo Batista1a191df2007-10-02 17:01:24 +00004219 A Decimal instance is considered finite if it is neither
4220 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00004221
4222 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004223 True
Facundo Batista353750c2007-09-13 18:13:15 +00004224 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004225 True
Facundo Batista353750c2007-09-13 18:13:15 +00004226 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004227 True
Facundo Batista353750c2007-09-13 18:13:15 +00004228 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004229 False
Facundo Batista353750c2007-09-13 18:13:15 +00004230 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004231 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004232 >>> ExtendedContext.is_finite(1)
4233 True
Facundo Batista353750c2007-09-13 18:13:15 +00004234 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004235 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004236 return a.is_finite()
4237
4238 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004239 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004240
4241 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004242 False
Facundo Batista353750c2007-09-13 18:13:15 +00004243 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004244 True
Facundo Batista353750c2007-09-13 18:13:15 +00004245 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004246 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004247 >>> ExtendedContext.is_infinite(1)
4248 False
Facundo Batista353750c2007-09-13 18:13:15 +00004249 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004250 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004251 return a.is_infinite()
4252
4253 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004254 """Return True if the operand is a qNaN or sNaN;
4255 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004256
4257 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004258 False
Facundo Batista353750c2007-09-13 18:13:15 +00004259 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004260 True
Facundo Batista353750c2007-09-13 18:13:15 +00004261 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004262 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004263 >>> ExtendedContext.is_nan(1)
4264 False
Facundo Batista353750c2007-09-13 18:13:15 +00004265 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004266 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004267 return a.is_nan()
4268
4269 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004270 """Return True if the operand is a normal number;
4271 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004272
4273 >>> c = ExtendedContext.copy()
4274 >>> c.Emin = -999
4275 >>> c.Emax = 999
4276 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004277 True
Facundo Batista353750c2007-09-13 18:13:15 +00004278 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004279 False
Facundo Batista353750c2007-09-13 18:13:15 +00004280 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004281 False
Facundo Batista353750c2007-09-13 18:13:15 +00004282 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004283 False
Facundo Batista353750c2007-09-13 18:13:15 +00004284 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004285 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004286 >>> c.is_normal(1)
4287 True
Facundo Batista353750c2007-09-13 18:13:15 +00004288 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004289 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004290 return a.is_normal(context=self)
4291
4292 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004293 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004294
4295 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004296 False
Facundo Batista353750c2007-09-13 18:13:15 +00004297 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004298 True
Facundo Batista353750c2007-09-13 18:13:15 +00004299 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004300 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004301 >>> ExtendedContext.is_qnan(1)
4302 False
Facundo Batista353750c2007-09-13 18:13:15 +00004303 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004304 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004305 return a.is_qnan()
4306
4307 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004308 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004309
4310 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004311 False
Facundo Batista353750c2007-09-13 18:13:15 +00004312 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004313 True
Facundo Batista353750c2007-09-13 18:13:15 +00004314 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004315 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004316 >>> ExtendedContext.is_signed(8)
4317 False
4318 >>> ExtendedContext.is_signed(-8)
4319 True
Facundo Batista353750c2007-09-13 18:13:15 +00004320 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004321 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004322 return a.is_signed()
4323
4324 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004325 """Return True if the operand is a signaling NaN;
4326 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004327
4328 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004329 False
Facundo Batista353750c2007-09-13 18:13:15 +00004330 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004331 False
Facundo Batista353750c2007-09-13 18:13:15 +00004332 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004333 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004334 >>> ExtendedContext.is_snan(1)
4335 False
Facundo Batista353750c2007-09-13 18:13:15 +00004336 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004337 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004338 return a.is_snan()
4339
4340 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004341 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004342
4343 >>> c = ExtendedContext.copy()
4344 >>> c.Emin = -999
4345 >>> c.Emax = 999
4346 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004347 False
Facundo Batista353750c2007-09-13 18:13:15 +00004348 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004349 True
Facundo Batista353750c2007-09-13 18:13:15 +00004350 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004351 False
Facundo Batista353750c2007-09-13 18:13:15 +00004352 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004353 False
Facundo Batista353750c2007-09-13 18:13:15 +00004354 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004355 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004356 >>> c.is_subnormal(1)
4357 False
Facundo Batista353750c2007-09-13 18:13:15 +00004358 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004359 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004360 return a.is_subnormal(context=self)
4361
4362 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004363 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004364
4365 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004366 True
Facundo Batista353750c2007-09-13 18:13:15 +00004367 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004368 False
Facundo Batista353750c2007-09-13 18:13:15 +00004369 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004370 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004371 >>> ExtendedContext.is_zero(1)
4372 False
4373 >>> ExtendedContext.is_zero(0)
4374 True
Facundo Batista353750c2007-09-13 18:13:15 +00004375 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004376 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004377 return a.is_zero()
4378
4379 def ln(self, a):
4380 """Returns the natural (base e) logarithm of the operand.
4381
4382 >>> c = ExtendedContext.copy()
4383 >>> c.Emin = -999
4384 >>> c.Emax = 999
4385 >>> c.ln(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004386 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004387 >>> c.ln(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004388 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004389 >>> c.ln(Decimal('2.71828183'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004390 Decimal('1.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004391 >>> c.ln(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004392 Decimal('2.30258509')
Facundo Batista353750c2007-09-13 18:13:15 +00004393 >>> c.ln(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004394 Decimal('Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004395 >>> c.ln(1)
4396 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004397 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004398 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004399 return a.ln(context=self)
4400
4401 def log10(self, a):
4402 """Returns the base 10 logarithm of the operand.
4403
4404 >>> c = ExtendedContext.copy()
4405 >>> c.Emin = -999
4406 >>> c.Emax = 999
4407 >>> c.log10(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004408 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004409 >>> c.log10(Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004410 Decimal('-3')
Facundo Batista353750c2007-09-13 18:13:15 +00004411 >>> c.log10(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004412 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004413 >>> c.log10(Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004414 Decimal('0.301029996')
Facundo Batista353750c2007-09-13 18:13:15 +00004415 >>> c.log10(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004416 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004417 >>> c.log10(Decimal('70'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004418 Decimal('1.84509804')
Facundo Batista353750c2007-09-13 18:13:15 +00004419 >>> c.log10(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004420 Decimal('Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004421 >>> c.log10(0)
4422 Decimal('-Infinity')
4423 >>> c.log10(1)
4424 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004425 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004426 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004427 return a.log10(context=self)
4428
4429 def logb(self, a):
4430 """ Returns the exponent of the magnitude of the operand's MSD.
4431
4432 The result is the integer which is the exponent of the magnitude
4433 of the most significant digit of the operand (as though the
4434 operand were truncated to a single digit while maintaining the
4435 value of that digit and without limiting the resulting exponent).
4436
4437 >>> ExtendedContext.logb(Decimal('250'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004438 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004439 >>> ExtendedContext.logb(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004440 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004441 >>> ExtendedContext.logb(Decimal('0.03'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004442 Decimal('-2')
Facundo Batista353750c2007-09-13 18:13:15 +00004443 >>> ExtendedContext.logb(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004444 Decimal('-Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004445 >>> ExtendedContext.logb(1)
4446 Decimal('0')
4447 >>> ExtendedContext.logb(10)
4448 Decimal('1')
4449 >>> ExtendedContext.logb(100)
4450 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004451 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004452 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004453 return a.logb(context=self)
4454
4455 def logical_and(self, a, b):
4456 """Applies the logical operation 'and' between each operand's digits.
4457
4458 The operands must be both logical numbers.
4459
4460 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004461 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004462 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004463 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004464 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004465 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004466 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004467 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004468 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004469 Decimal('1000')
Facundo Batista353750c2007-09-13 18:13:15 +00004470 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004471 Decimal('10')
Mark Dickinson456e1652010-02-18 14:45:33 +00004472 >>> ExtendedContext.logical_and(110, 1101)
4473 Decimal('100')
4474 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4475 Decimal('100')
4476 >>> ExtendedContext.logical_and(110, Decimal(1101))
4477 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004478 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004479 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004480 return a.logical_and(b, context=self)
4481
4482 def logical_invert(self, a):
4483 """Invert all the digits in the operand.
4484
4485 The operand must be a logical number.
4486
4487 >>> ExtendedContext.logical_invert(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004488 Decimal('111111111')
Facundo Batista353750c2007-09-13 18:13:15 +00004489 >>> ExtendedContext.logical_invert(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004490 Decimal('111111110')
Facundo Batista353750c2007-09-13 18:13:15 +00004491 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004492 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004493 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004494 Decimal('10101010')
Mark Dickinson456e1652010-02-18 14:45:33 +00004495 >>> ExtendedContext.logical_invert(1101)
4496 Decimal('111110010')
Facundo Batista353750c2007-09-13 18:13:15 +00004497 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004498 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004499 return a.logical_invert(context=self)
4500
4501 def logical_or(self, a, b):
4502 """Applies the logical operation 'or' between each operand's digits.
4503
4504 The operands must be both logical numbers.
4505
4506 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004507 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004508 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004509 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004510 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004511 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004512 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004513 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004514 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004515 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004516 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004517 Decimal('1110')
Mark Dickinson456e1652010-02-18 14:45:33 +00004518 >>> ExtendedContext.logical_or(110, 1101)
4519 Decimal('1111')
4520 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4521 Decimal('1111')
4522 >>> ExtendedContext.logical_or(110, Decimal(1101))
4523 Decimal('1111')
Facundo Batista353750c2007-09-13 18:13:15 +00004524 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004525 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004526 return a.logical_or(b, context=self)
4527
4528 def logical_xor(self, a, b):
4529 """Applies the logical operation 'xor' between each operand's digits.
4530
4531 The operands must be both logical numbers.
4532
4533 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004534 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004535 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004536 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004537 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004538 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004539 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004540 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004541 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004542 Decimal('110')
Facundo Batista353750c2007-09-13 18:13:15 +00004543 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004544 Decimal('1101')
Mark Dickinson456e1652010-02-18 14:45:33 +00004545 >>> ExtendedContext.logical_xor(110, 1101)
4546 Decimal('1011')
4547 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4548 Decimal('1011')
4549 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4550 Decimal('1011')
Facundo Batista353750c2007-09-13 18:13:15 +00004551 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004552 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004553 return a.logical_xor(b, context=self)
4554
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004555 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004556 """max compares two values numerically and returns the maximum.
4557
4558 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004559 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004560 operation. If they are numerically equal then the left-hand operand
4561 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004562 infinity) of the two operands is chosen as the result.
4563
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004564 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004565 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004566 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004567 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004568 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004569 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004570 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004571 Decimal('7')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004572 >>> ExtendedContext.max(1, 2)
4573 Decimal('2')
4574 >>> ExtendedContext.max(Decimal(1), 2)
4575 Decimal('2')
4576 >>> ExtendedContext.max(1, Decimal(2))
4577 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004578 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004579 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004580 return a.max(b, context=self)
4581
Facundo Batista353750c2007-09-13 18:13:15 +00004582 def max_mag(self, a, b):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004583 """Compares the values numerically with their sign ignored.
4584
4585 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4586 Decimal('7')
4587 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4588 Decimal('-10')
4589 >>> ExtendedContext.max_mag(1, -2)
4590 Decimal('-2')
4591 >>> ExtendedContext.max_mag(Decimal(1), -2)
4592 Decimal('-2')
4593 >>> ExtendedContext.max_mag(1, Decimal(-2))
4594 Decimal('-2')
4595 """
4596 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004597 return a.max_mag(b, context=self)
4598
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004599 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004600 """min compares two values numerically and returns the minimum.
4601
4602 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004603 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004604 operation. If they are numerically equal then the left-hand operand
4605 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004606 infinity) of the two operands is chosen as the result.
4607
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004608 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004609 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004610 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004611 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004612 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004613 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004614 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004615 Decimal('7')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004616 >>> ExtendedContext.min(1, 2)
4617 Decimal('1')
4618 >>> ExtendedContext.min(Decimal(1), 2)
4619 Decimal('1')
4620 >>> ExtendedContext.min(1, Decimal(29))
4621 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004622 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004623 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004624 return a.min(b, context=self)
4625
Facundo Batista353750c2007-09-13 18:13:15 +00004626 def min_mag(self, a, b):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004627 """Compares the values numerically with their sign ignored.
4628
4629 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4630 Decimal('-2')
4631 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4632 Decimal('-3')
4633 >>> ExtendedContext.min_mag(1, -2)
4634 Decimal('1')
4635 >>> ExtendedContext.min_mag(Decimal(1), -2)
4636 Decimal('1')
4637 >>> ExtendedContext.min_mag(1, Decimal(-2))
4638 Decimal('1')
4639 """
4640 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004641 return a.min_mag(b, context=self)
4642
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004643 def minus(self, a):
4644 """Minus corresponds to unary prefix minus in Python.
4645
4646 The operation is evaluated using the same rules as subtract; the
4647 operation minus(a) is calculated as subtract('0', a) where the '0'
4648 has the same exponent as the operand.
4649
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004650 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004651 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004652 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004653 Decimal('1.3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004654 >>> ExtendedContext.minus(1)
4655 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004656 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004657 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004658 return a.__neg__(context=self)
4659
4660 def multiply(self, a, b):
4661 """multiply multiplies two operands.
4662
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004663 If either operand is a special value then the general rules apply.
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004664 Otherwise, the operands are multiplied together
4665 ('long multiplication'), resulting in a number which may be as long as
4666 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004668 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004669 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004670 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004671 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004672 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004673 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004674 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004675 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004676 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004677 Decimal('4.28135971E+11')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004678 >>> ExtendedContext.multiply(7, 7)
4679 Decimal('49')
4680 >>> ExtendedContext.multiply(Decimal(7), 7)
4681 Decimal('49')
4682 >>> ExtendedContext.multiply(7, Decimal(7))
4683 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004684 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004685 a = _convert_other(a, raiseit=True)
4686 r = a.__mul__(b, context=self)
4687 if r is NotImplemented:
4688 raise TypeError("Unable to convert %s to Decimal" % b)
4689 else:
4690 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004691
Facundo Batista353750c2007-09-13 18:13:15 +00004692 def next_minus(self, a):
4693 """Returns the largest representable number smaller than a.
4694
4695 >>> c = ExtendedContext.copy()
4696 >>> c.Emin = -999
4697 >>> c.Emax = 999
4698 >>> ExtendedContext.next_minus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004699 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004700 >>> c.next_minus(Decimal('1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004701 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004702 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004703 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004704 >>> c.next_minus(Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004705 Decimal('9.99999999E+999')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004706 >>> c.next_minus(1)
4707 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004708 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004709 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004710 return a.next_minus(context=self)
4711
4712 def next_plus(self, a):
4713 """Returns the smallest representable number larger than a.
4714
4715 >>> c = ExtendedContext.copy()
4716 >>> c.Emin = -999
4717 >>> c.Emax = 999
4718 >>> ExtendedContext.next_plus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004719 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004720 >>> c.next_plus(Decimal('-1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004721 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004722 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004723 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004724 >>> c.next_plus(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004725 Decimal('-9.99999999E+999')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004726 >>> c.next_plus(1)
4727 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004728 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004729 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004730 return a.next_plus(context=self)
4731
4732 def next_toward(self, a, b):
4733 """Returns the number closest to a, in direction towards b.
4734
4735 The result is the closest representable number from the first
4736 operand (but not the first operand) that is in the direction
4737 towards the second operand, unless the operands have the same
4738 value.
4739
4740 >>> c = ExtendedContext.copy()
4741 >>> c.Emin = -999
4742 >>> c.Emax = 999
4743 >>> c.next_toward(Decimal('1'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004744 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004745 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004746 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004747 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004748 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004749 >>> c.next_toward(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004750 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004751 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004752 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004753 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004754 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004755 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004756 Decimal('-0.00')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004757 >>> c.next_toward(0, 1)
4758 Decimal('1E-1007')
4759 >>> c.next_toward(Decimal(0), 1)
4760 Decimal('1E-1007')
4761 >>> c.next_toward(0, Decimal(1))
4762 Decimal('1E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004763 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004764 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004765 return a.next_toward(b, context=self)
4766
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004767 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004768 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004769
4770 Essentially a plus operation with all trailing zeros removed from the
4771 result.
4772
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004773 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004774 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004775 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004776 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004777 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004778 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004779 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004780 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004781 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004782 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004783 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004784 Decimal('0')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004785 >>> ExtendedContext.normalize(6)
4786 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004787 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004788 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004789 return a.normalize(context=self)
4790
Facundo Batista353750c2007-09-13 18:13:15 +00004791 def number_class(self, a):
4792 """Returns an indication of the class of the operand.
4793
4794 The class is one of the following strings:
4795 -sNaN
4796 -NaN
4797 -Infinity
4798 -Normal
4799 -Subnormal
4800 -Zero
4801 +Zero
4802 +Subnormal
4803 +Normal
4804 +Infinity
4805
4806 >>> c = Context(ExtendedContext)
4807 >>> c.Emin = -999
4808 >>> c.Emax = 999
4809 >>> c.number_class(Decimal('Infinity'))
4810 '+Infinity'
4811 >>> c.number_class(Decimal('1E-10'))
4812 '+Normal'
4813 >>> c.number_class(Decimal('2.50'))
4814 '+Normal'
4815 >>> c.number_class(Decimal('0.1E-999'))
4816 '+Subnormal'
4817 >>> c.number_class(Decimal('0'))
4818 '+Zero'
4819 >>> c.number_class(Decimal('-0'))
4820 '-Zero'
4821 >>> c.number_class(Decimal('-0.1E-999'))
4822 '-Subnormal'
4823 >>> c.number_class(Decimal('-1E-10'))
4824 '-Normal'
4825 >>> c.number_class(Decimal('-2.50'))
4826 '-Normal'
4827 >>> c.number_class(Decimal('-Infinity'))
4828 '-Infinity'
4829 >>> c.number_class(Decimal('NaN'))
4830 'NaN'
4831 >>> c.number_class(Decimal('-NaN'))
4832 'NaN'
4833 >>> c.number_class(Decimal('sNaN'))
4834 'sNaN'
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004835 >>> c.number_class(123)
4836 '+Normal'
Facundo Batista353750c2007-09-13 18:13:15 +00004837 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004838 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004839 return a.number_class(context=self)
4840
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004841 def plus(self, a):
4842 """Plus corresponds to unary prefix plus in Python.
4843
4844 The operation is evaluated using the same rules as add; the
4845 operation plus(a) is calculated as add('0', a) where the '0'
4846 has the same exponent as the operand.
4847
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004848 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004849 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004850 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004851 Decimal('-1.3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004852 >>> ExtendedContext.plus(-1)
4853 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004854 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004855 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004856 return a.__pos__(context=self)
4857
4858 def power(self, a, b, modulo=None):
4859 """Raises a to the power of b, to modulo if given.
4860
Facundo Batista353750c2007-09-13 18:13:15 +00004861 With two arguments, compute a**b. If a is negative then b
4862 must be integral. The result will be inexact unless b is
4863 integral and the result is finite and can be expressed exactly
4864 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004865
Facundo Batista353750c2007-09-13 18:13:15 +00004866 With three arguments, compute (a**b) % modulo. For the
4867 three argument form, the following restrictions on the
4868 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004869
Facundo Batista353750c2007-09-13 18:13:15 +00004870 - all three arguments must be integral
4871 - b must be nonnegative
4872 - at least one of a or b must be nonzero
4873 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004874
Facundo Batista353750c2007-09-13 18:13:15 +00004875 The result of pow(a, b, modulo) is identical to the result
4876 that would be obtained by computing (a**b) % modulo with
4877 unbounded precision, but is computed more efficiently. It is
4878 always exact.
4879
4880 >>> c = ExtendedContext.copy()
4881 >>> c.Emin = -999
4882 >>> c.Emax = 999
4883 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004884 Decimal('8')
Facundo Batista353750c2007-09-13 18:13:15 +00004885 >>> c.power(Decimal('-2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004886 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004887 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004888 Decimal('0.125')
Facundo Batista353750c2007-09-13 18:13:15 +00004889 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004890 Decimal('69.7575744')
Facundo Batista353750c2007-09-13 18:13:15 +00004891 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004892 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004893 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004894 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004895 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004896 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004897 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004898 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004899 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004900 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004901 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004902 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004903 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004904 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004905 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004906 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004907 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004908 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00004909
4910 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004911 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004912 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004913 Decimal('-11')
Facundo Batista353750c2007-09-13 18:13:15 +00004914 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004915 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004916 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004917 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004918 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004919 Decimal('11729830')
Facundo Batista353750c2007-09-13 18:13:15 +00004920 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004921 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004922 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004923 Decimal('1')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004924 >>> ExtendedContext.power(7, 7)
4925 Decimal('823543')
4926 >>> ExtendedContext.power(Decimal(7), 7)
4927 Decimal('823543')
4928 >>> ExtendedContext.power(7, Decimal(7), 2)
4929 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004930 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004931 a = _convert_other(a, raiseit=True)
4932 r = a.__pow__(b, modulo, context=self)
4933 if r is NotImplemented:
4934 raise TypeError("Unable to convert %s to Decimal" % b)
4935 else:
4936 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004937
4938 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004939 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004940
4941 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004942 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004943 exponent is being increased), multiplied by a positive power of ten (if
4944 the exponent is being decreased), or is unchanged (if the exponent is
4945 already equal to that of the right-hand operand).
4946
4947 Unlike other operations, if the length of the coefficient after the
4948 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004949 operation condition is raised. This guarantees that, unless there is
4950 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004951 equal to that of the right-hand operand.
4952
4953 Also unlike other operations, quantize will never raise Underflow, even
4954 if the result is subnormal and inexact.
4955
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004956 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004957 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004958 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004959 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004960 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004961 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004962 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004963 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004964 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004965 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004966 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004967 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004968 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004969 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004970 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004971 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004972 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004973 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004974 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004975 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004976 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004977 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004978 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004979 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004980 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004981 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004982 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004983 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004984 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004985 Decimal('2E+2')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004986 >>> ExtendedContext.quantize(1, 2)
4987 Decimal('1')
4988 >>> ExtendedContext.quantize(Decimal(1), 2)
4989 Decimal('1')
4990 >>> ExtendedContext.quantize(1, Decimal(2))
4991 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004992 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004993 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004994 return a.quantize(b, context=self)
4995
Facundo Batista353750c2007-09-13 18:13:15 +00004996 def radix(self):
4997 """Just returns 10, as this is Decimal, :)
4998
4999 >>> ExtendedContext.radix()
Raymond Hettingerabe32372008-02-14 02:41:22 +00005000 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00005001 """
5002 return Decimal(10)
5003
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005004 def remainder(self, a, b):
5005 """Returns the remainder from integer division.
5006
5007 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00005008 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00005009 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00005010 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005011
5012 This operation will fail under the same conditions as integer division
5013 (that is, if integer division on the same two operands would fail, the
5014 remainder cannot be calculated).
5015
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005016 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005017 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005018 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005019 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005020 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005021 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005022 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005023 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005024 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005025 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005026 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005027 Decimal('1.0')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005028 >>> ExtendedContext.remainder(22, 6)
5029 Decimal('4')
5030 >>> ExtendedContext.remainder(Decimal(22), 6)
5031 Decimal('4')
5032 >>> ExtendedContext.remainder(22, Decimal(6))
5033 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005034 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005035 a = _convert_other(a, raiseit=True)
5036 r = a.__mod__(b, context=self)
5037 if r is NotImplemented:
5038 raise TypeError("Unable to convert %s to Decimal" % b)
5039 else:
5040 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005041
5042 def remainder_near(self, a, b):
5043 """Returns to be "a - b * n", where n is the integer nearest the exact
5044 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00005045 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005046 sign of a.
5047
5048 This operation will fail under the same conditions as integer division
5049 (that is, if integer division on the same two operands would fail, the
5050 remainder cannot be calculated).
5051
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005052 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005053 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005054 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005055 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005056 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005057 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005058 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005059 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005060 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005061 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005062 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005063 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005064 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005065 Decimal('-0.3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005066 >>> ExtendedContext.remainder_near(3, 11)
5067 Decimal('3')
5068 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5069 Decimal('3')
5070 >>> ExtendedContext.remainder_near(3, Decimal(11))
5071 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005072 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005073 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005074 return a.remainder_near(b, context=self)
5075
Facundo Batista353750c2007-09-13 18:13:15 +00005076 def rotate(self, a, b):
5077 """Returns a rotated copy of a, b times.
5078
5079 The coefficient of the result is a rotated copy of the digits in
5080 the coefficient of the first operand. The number of places of
5081 rotation is taken from the absolute value of the second operand,
5082 with the rotation being to the left if the second operand is
5083 positive or to the right otherwise.
5084
5085 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005086 Decimal('400000003')
Facundo Batista353750c2007-09-13 18:13:15 +00005087 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005088 Decimal('12')
Facundo Batista353750c2007-09-13 18:13:15 +00005089 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005090 Decimal('891234567')
Facundo Batista353750c2007-09-13 18:13:15 +00005091 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005092 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00005093 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005094 Decimal('345678912')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005095 >>> ExtendedContext.rotate(1333333, 1)
5096 Decimal('13333330')
5097 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5098 Decimal('13333330')
5099 >>> ExtendedContext.rotate(1333333, Decimal(1))
5100 Decimal('13333330')
Facundo Batista353750c2007-09-13 18:13:15 +00005101 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005102 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005103 return a.rotate(b, context=self)
5104
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005105 def same_quantum(self, a, b):
5106 """Returns True if the two operands have the same exponent.
5107
5108 The result is never affected by either the sign or the coefficient of
5109 either operand.
5110
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005111 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005112 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005113 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005114 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005115 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005116 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005117 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005118 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005119 >>> ExtendedContext.same_quantum(10000, -1)
5120 True
5121 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5122 True
5123 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5124 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005125 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005126 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005127 return a.same_quantum(b)
5128
Facundo Batista353750c2007-09-13 18:13:15 +00005129 def scaleb (self, a, b):
5130 """Returns the first operand after adding the second value its exp.
5131
5132 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005133 Decimal('0.0750')
Facundo Batista353750c2007-09-13 18:13:15 +00005134 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005135 Decimal('7.50')
Facundo Batista353750c2007-09-13 18:13:15 +00005136 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005137 Decimal('7.50E+3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005138 >>> ExtendedContext.scaleb(1, 4)
5139 Decimal('1E+4')
5140 >>> ExtendedContext.scaleb(Decimal(1), 4)
5141 Decimal('1E+4')
5142 >>> ExtendedContext.scaleb(1, Decimal(4))
5143 Decimal('1E+4')
Facundo Batista353750c2007-09-13 18:13:15 +00005144 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005145 a = _convert_other(a, raiseit=True)
5146 return a.scaleb(b, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00005147
5148 def shift(self, a, b):
5149 """Returns a shifted copy of a, b times.
5150
5151 The coefficient of the result is a shifted copy of the digits
5152 in the coefficient of the first operand. The number of places
5153 to shift is taken from the absolute value of the second operand,
5154 with the shift being to the left if the second operand is
5155 positive or to the right otherwise. Digits shifted into the
5156 coefficient are zeros.
5157
5158 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005159 Decimal('400000000')
Facundo Batista353750c2007-09-13 18:13:15 +00005160 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005161 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00005162 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005163 Decimal('1234567')
Facundo Batista353750c2007-09-13 18:13:15 +00005164 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005165 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00005166 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005167 Decimal('345678900')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005168 >>> ExtendedContext.shift(88888888, 2)
5169 Decimal('888888800')
5170 >>> ExtendedContext.shift(Decimal(88888888), 2)
5171 Decimal('888888800')
5172 >>> ExtendedContext.shift(88888888, Decimal(2))
5173 Decimal('888888800')
Facundo Batista353750c2007-09-13 18:13:15 +00005174 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005175 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005176 return a.shift(b, context=self)
5177
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005178 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00005179 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005180
5181 If the result must be inexact, it is rounded using the round-half-even
5182 algorithm.
5183
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005184 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005185 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005186 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005187 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005188 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005189 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005190 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005191 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005192 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005193 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005194 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005195 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005196 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005197 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005198 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005199 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005200 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005201 Decimal('3.16227766')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005202 >>> ExtendedContext.sqrt(2)
5203 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005204 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005205 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005206 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005207 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005208 return a.sqrt(context=self)
5209
5210 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005211 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005212
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005213 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005214 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005215 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005216 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005217 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005218 Decimal('-0.77')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005219 >>> ExtendedContext.subtract(8, 5)
5220 Decimal('3')
5221 >>> ExtendedContext.subtract(Decimal(8), 5)
5222 Decimal('3')
5223 >>> ExtendedContext.subtract(8, Decimal(5))
5224 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005225 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005226 a = _convert_other(a, raiseit=True)
5227 r = a.__sub__(b, context=self)
5228 if r is NotImplemented:
5229 raise TypeError("Unable to convert %s to Decimal" % b)
5230 else:
5231 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005232
5233 def to_eng_string(self, a):
5234 """Converts a number to a string, using scientific notation.
5235
5236 The operation is not affected by the context.
5237 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005238 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005239 return a.to_eng_string(context=self)
5240
5241 def to_sci_string(self, a):
5242 """Converts a number to a string, using scientific notation.
5243
5244 The operation is not affected by the context.
5245 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005246 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005247 return a.__str__(context=self)
5248
Facundo Batista353750c2007-09-13 18:13:15 +00005249 def to_integral_exact(self, a):
5250 """Rounds to an integer.
5251
5252 When the operand has a negative exponent, the result is the same
5253 as using the quantize() operation using the given operand as the
5254 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5255 of the operand as the precision setting; Inexact and Rounded flags
5256 are allowed in this operation. The rounding mode is taken from the
5257 context.
5258
5259 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005260 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00005261 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005262 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005263 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005264 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005265 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005266 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00005267 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005268 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00005269 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005270 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00005271 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005272 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00005273 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005274 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00005275 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005276 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005277 return a.to_integral_exact(context=self)
5278
5279 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005280 """Rounds to an integer.
5281
5282 When the operand has a negative exponent, the result is the same
5283 as using the quantize() operation using the given operand as the
5284 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5285 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00005286 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005287
Facundo Batista353750c2007-09-13 18:13:15 +00005288 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005289 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00005290 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005291 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005292 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005293 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005294 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005295 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00005296 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005297 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00005298 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005299 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00005300 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005301 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00005302 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005303 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005304 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005305 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005306 return a.to_integral_value(context=self)
5307
5308 # the method name changed, but we provide also the old one, for compatibility
5309 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005310
5311class _WorkRep(object):
5312 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005313 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005314 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005315 # exp: None, int, or string
5316
5317 def __init__(self, value=None):
5318 if value is None:
5319 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005320 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005321 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005322 elif isinstance(value, Decimal):
5323 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00005324 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005325 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005326 else:
5327 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005328 self.sign = value[0]
5329 self.int = value[1]
5330 self.exp = value[2]
5331
5332 def __repr__(self):
5333 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5334
5335 __str__ = __repr__
5336
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005337
5338
Facundo Batistae64acfa2007-12-17 14:18:42 +00005339def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005340 """Normalizes op1, op2 to have the same exp and length of coefficient.
5341
5342 Done during addition.
5343 """
Facundo Batista353750c2007-09-13 18:13:15 +00005344 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005345 tmp = op2
5346 other = op1
5347 else:
5348 tmp = op1
5349 other = op2
5350
Facundo Batista353750c2007-09-13 18:13:15 +00005351 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5352 # Then adding 10**exp to tmp has the same effect (after rounding)
5353 # as adding any positive quantity smaller than 10**exp; similarly
5354 # for subtraction. So if other is smaller than 10**exp we replace
5355 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00005356 tmp_len = len(str(tmp.int))
5357 other_len = len(str(other.int))
5358 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5359 if other_len + other.exp - 1 < exp:
5360 other.int = 1
5361 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005362
Facundo Batista353750c2007-09-13 18:13:15 +00005363 tmp.int *= 10 ** (tmp.exp - other.exp)
5364 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005365 return op1, op2
5366
Facundo Batista353750c2007-09-13 18:13:15 +00005367##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
5368
5369# This function from Tim Peters was taken from here:
5370# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5371# The correction being in the function definition is for speed, and
5372# the whole function is not resolved with math.log because of avoiding
5373# the use of floats.
5374def _nbits(n, correction = {
5375 '0': 4, '1': 3, '2': 2, '3': 2,
5376 '4': 1, '5': 1, '6': 1, '7': 1,
5377 '8': 0, '9': 0, 'a': 0, 'b': 0,
5378 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5379 """Number of bits in binary representation of the positive integer n,
5380 or 0 if n == 0.
5381 """
5382 if n < 0:
5383 raise ValueError("The argument to _nbits should be nonnegative.")
5384 hex_n = "%x" % n
5385 return 4*len(hex_n) - correction[hex_n[0]]
5386
5387def _sqrt_nearest(n, a):
5388 """Closest integer to the square root of the positive integer n. a is
5389 an initial approximation to the square root. Any positive integer
5390 will do for a, but the closer a is to the square root of n the
5391 faster convergence will be.
5392
5393 """
5394 if n <= 0 or a <= 0:
5395 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5396
5397 b=0
5398 while a != b:
5399 b, a = a, a--n//a>>1
5400 return a
5401
5402def _rshift_nearest(x, shift):
5403 """Given an integer x and a nonnegative integer shift, return closest
5404 integer to x / 2**shift; use round-to-even in case of a tie.
5405
5406 """
5407 b, q = 1L << shift, x >> shift
5408 return q + (2*(x & (b-1)) + (q&1) > b)
5409
5410def _div_nearest(a, b):
5411 """Closest integer to a/b, a and b positive integers; rounds to even
5412 in the case of a tie.
5413
5414 """
5415 q, r = divmod(a, b)
5416 return q + (2*r + (q&1) > b)
5417
5418def _ilog(x, M, L = 8):
5419 """Integer approximation to M*log(x/M), with absolute error boundable
5420 in terms only of x/M.
5421
5422 Given positive integers x and M, return an integer approximation to
5423 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5424 between the approximation and the exact result is at most 22. For
5425 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5426 both cases these are upper bounds on the error; it will usually be
5427 much smaller."""
5428
5429 # The basic algorithm is the following: let log1p be the function
5430 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5431 # the reduction
5432 #
5433 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5434 #
5435 # repeatedly until the argument to log1p is small (< 2**-L in
5436 # absolute value). For small y we can use the Taylor series
5437 # expansion
5438 #
5439 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5440 #
5441 # truncating at T such that y**T is small enough. The whole
5442 # computation is carried out in a form of fixed-point arithmetic,
5443 # with a real number z being represented by an integer
5444 # approximation to z*M. To avoid loss of precision, the y below
5445 # is actually an integer approximation to 2**R*y*M, where R is the
5446 # number of reductions performed so far.
5447
5448 y = x-M
5449 # argument reduction; R = number of reductions performed
5450 R = 0
5451 while (R <= L and long(abs(y)) << L-R >= M or
5452 R > L and abs(y) >> R-L >= M):
5453 y = _div_nearest(long(M*y) << 1,
5454 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5455 R += 1
5456
5457 # Taylor series with T terms
5458 T = -int(-10*len(str(M))//(3*L))
5459 yshift = _rshift_nearest(y, R)
5460 w = _div_nearest(M, T)
5461 for k in xrange(T-1, 0, -1):
5462 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5463
5464 return _div_nearest(w*y, M)
5465
5466def _dlog10(c, e, p):
5467 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5468 approximation to 10**p * log10(c*10**e), with an absolute error of
5469 at most 1. Assumes that c*10**e is not exactly 1."""
5470
5471 # increase precision by 2; compensate for this by dividing
5472 # final result by 100
5473 p += 2
5474
5475 # write c*10**e as d*10**f with either:
5476 # f >= 0 and 1 <= d <= 10, or
5477 # f <= 0 and 0.1 <= d <= 1.
5478 # Thus for c*10**e close to 1, f = 0
5479 l = len(str(c))
5480 f = e+l - (e+l >= 1)
5481
5482 if p > 0:
5483 M = 10**p
5484 k = e+p-f
5485 if k >= 0:
5486 c *= 10**k
5487 else:
5488 c = _div_nearest(c, 10**-k)
5489
5490 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005491 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005492 log_d = _div_nearest(log_d*M, log_10)
5493 log_tenpower = f*M # exact
5494 else:
5495 log_d = 0 # error < 2.31
Neal Norwitz18aa3882008-08-24 05:04:52 +00005496 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Facundo Batista353750c2007-09-13 18:13:15 +00005497
5498 return _div_nearest(log_tenpower+log_d, 100)
5499
5500def _dlog(c, e, p):
5501 """Given integers c, e and p with c > 0, compute an integer
5502 approximation to 10**p * log(c*10**e), with an absolute error of
5503 at most 1. Assumes that c*10**e is not exactly 1."""
5504
5505 # Increase precision by 2. The precision increase is compensated
5506 # for at the end with a division by 100.
5507 p += 2
5508
5509 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5510 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5511 # as 10**p * log(d) + 10**p*f * log(10).
5512 l = len(str(c))
5513 f = e+l - (e+l >= 1)
5514
5515 # compute approximation to 10**p*log(d), with error < 27
5516 if p > 0:
5517 k = e+p-f
5518 if k >= 0:
5519 c *= 10**k
5520 else:
5521 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5522
5523 # _ilog magnifies existing error in c by a factor of at most 10
5524 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5525 else:
5526 # p <= 0: just approximate the whole thing by 0; error < 2.31
5527 log_d = 0
5528
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005529 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00005530 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005531 extra = len(str(abs(f)))-1
5532 if p + extra >= 0:
5533 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5534 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5535 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00005536 else:
5537 f_log_ten = 0
5538 else:
5539 f_log_ten = 0
5540
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005541 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005542 return _div_nearest(f_log_ten + log_d, 100)
5543
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005544class _Log10Memoize(object):
5545 """Class to compute, store, and allow retrieval of, digits of the
5546 constant log(10) = 2.302585.... This constant is needed by
5547 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5548 def __init__(self):
5549 self.digits = "23025850929940456840179914546843642076011014886"
5550
5551 def getdigits(self, p):
5552 """Given an integer p >= 0, return floor(10**p)*log(10).
5553
5554 For example, self.getdigits(3) returns 2302.
5555 """
5556 # digits are stored as a string, for quick conversion to
5557 # integer in the case that we've already computed enough
5558 # digits; the stored digits should always be correct
5559 # (truncated, not rounded to nearest).
5560 if p < 0:
5561 raise ValueError("p should be nonnegative")
5562
5563 if p >= len(self.digits):
5564 # compute p+3, p+6, p+9, ... digits; continue until at
5565 # least one of the extra digits is nonzero
5566 extra = 3
5567 while True:
5568 # compute p+extra digits, correct to within 1ulp
5569 M = 10**(p+extra+2)
5570 digits = str(_div_nearest(_ilog(10*M, M), 100))
5571 if digits[-extra:] != '0'*extra:
5572 break
5573 extra += 3
5574 # keep all reliable digits so far; remove trailing zeros
5575 # and next nonzero digit
5576 self.digits = digits.rstrip('0')[:-1]
5577 return int(self.digits[:p+1])
5578
5579_log10_digits = _Log10Memoize().getdigits
5580
Facundo Batista353750c2007-09-13 18:13:15 +00005581def _iexp(x, M, L=8):
5582 """Given integers x and M, M > 0, such that x/M is small in absolute
5583 value, compute an integer approximation to M*exp(x/M). For 0 <=
5584 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5585 is usually much smaller)."""
5586
5587 # Algorithm: to compute exp(z) for a real number z, first divide z
5588 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5589 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5590 # series
5591 #
5592 # expm1(x) = x + x**2/2! + x**3/3! + ...
5593 #
5594 # Now use the identity
5595 #
5596 # expm1(2x) = expm1(x)*(expm1(x)+2)
5597 #
5598 # R times to compute the sequence expm1(z/2**R),
5599 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5600
5601 # Find R such that x/2**R/M <= 2**-L
5602 R = _nbits((long(x)<<L)//M)
5603
5604 # Taylor series. (2**L)**T > M
5605 T = -int(-10*len(str(M))//(3*L))
5606 y = _div_nearest(x, T)
5607 Mshift = long(M)<<R
5608 for i in xrange(T-1, 0, -1):
5609 y = _div_nearest(x*(Mshift + y), Mshift * i)
5610
5611 # Expansion
5612 for k in xrange(R-1, -1, -1):
5613 Mshift = long(M)<<(k+2)
5614 y = _div_nearest(y*(y+Mshift), Mshift)
5615
5616 return M+y
5617
5618def _dexp(c, e, p):
5619 """Compute an approximation to exp(c*10**e), with p decimal places of
5620 precision.
5621
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005622 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005623
5624 10**(p-1) <= d <= 10**p, and
5625 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5626
5627 In other words, d*10**f is an approximation to exp(c*10**e) with p
5628 digits of precision, and with an error in d of at most 1. This is
5629 almost, but not quite, the same as the error being < 1ulp: when d
5630 = 10**(p-1) the error could be up to 10 ulp."""
5631
5632 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5633 p += 2
5634
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005635 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005636 extra = max(0, e + len(str(c)) - 1)
5637 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005638
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005639 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005640 # rounding down
5641 shift = e+q
5642 if shift >= 0:
5643 cshift = c*10**shift
5644 else:
5645 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005646 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005647
5648 # reduce remainder back to original precision
5649 rem = _div_nearest(rem, 10**extra)
5650
5651 # error in result of _iexp < 120; error after division < 0.62
5652 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5653
5654def _dpower(xc, xe, yc, ye, p):
5655 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5656 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5657
5658 10**(p-1) <= c <= 10**p, and
5659 (c-1)*10**e < x**y < (c+1)*10**e
5660
5661 in other words, c*10**e is an approximation to x**y with p digits
5662 of precision, and with an error in c of at most 1. (This is
5663 almost, but not quite, the same as the error being < 1ulp: when c
5664 == 10**(p-1) we can only guarantee error < 10ulp.)
5665
5666 We assume that: x is positive and not equal to 1, and y is nonzero.
5667 """
5668
5669 # Find b such that 10**(b-1) <= |y| <= 10**b
5670 b = len(str(abs(yc))) + ye
5671
5672 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5673 lxc = _dlog(xc, xe, p+b+1)
5674
5675 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5676 shift = ye-b
5677 if shift >= 0:
5678 pc = lxc*yc*10**shift
5679 else:
5680 pc = _div_nearest(lxc*yc, 10**-shift)
5681
5682 if pc == 0:
5683 # we prefer a result that isn't exactly 1; this makes it
5684 # easier to compute a correctly rounded result in __pow__
5685 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5686 coeff, exp = 10**(p-1)+1, 1-p
5687 else:
5688 coeff, exp = 10**p-1, -p
5689 else:
5690 coeff, exp = _dexp(pc, -(p+1), p+1)
5691 coeff = _div_nearest(coeff, 10)
5692 exp += 1
5693
5694 return coeff, exp
5695
5696def _log10_lb(c, correction = {
5697 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5698 '6': 23, '7': 16, '8': 10, '9': 5}):
5699 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5700 if c <= 0:
5701 raise ValueError("The argument to _log10_lb should be nonnegative.")
5702 str_c = str(c)
5703 return 100*len(str_c) - correction[str_c[0]]
5704
Facundo Batista59c58842007-04-10 12:58:45 +00005705##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005706
Mark Dickinson99d80962010-04-02 08:53:22 +00005707def _convert_other(other, raiseit=False, allow_float=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005708 """Convert other to Decimal.
5709
5710 Verifies that it's ok to use in an implicit construction.
Mark Dickinson99d80962010-04-02 08:53:22 +00005711 If allow_float is true, allow conversion from float; this
5712 is used in the comparison methods (__eq__ and friends).
5713
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005714 """
5715 if isinstance(other, Decimal):
5716 return other
5717 if isinstance(other, (int, long)):
5718 return Decimal(other)
Mark Dickinson99d80962010-04-02 08:53:22 +00005719 if allow_float and isinstance(other, float):
5720 return Decimal.from_float(other)
5721
Facundo Batista353750c2007-09-13 18:13:15 +00005722 if raiseit:
5723 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005724 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005725
Facundo Batista59c58842007-04-10 12:58:45 +00005726##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005727
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005728# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005729# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005730
5731DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005732 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005733 traps=[DivisionByZero, Overflow, InvalidOperation],
5734 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005735 Emax=999999999,
5736 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005737 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005738)
5739
5740# Pre-made alternate contexts offered by the specification
5741# Don't change these; the user should be able to select these
5742# contexts and be able to reproduce results from other implementations
5743# of the spec.
5744
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005745BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005746 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005747 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5748 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005749)
5750
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005751ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005752 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005753 traps=[],
5754 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005755)
5756
5757
Facundo Batista72bc54f2007-11-23 17:59:00 +00005758##### crud for parsing strings #############################################
Mark Dickinson6a123cb2008-02-24 18:12:36 +00005759#
Facundo Batista72bc54f2007-11-23 17:59:00 +00005760# Regular expression used for parsing numeric strings. Additional
5761# comments:
5762#
5763# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5764# whitespace. But note that the specification disallows whitespace in
5765# a numeric string.
5766#
5767# 2. For finite numbers (not infinities and NaNs) the body of the
5768# number between the optional sign and the optional exponent must have
5769# at least one decimal digit, possibly after the decimal point. The
5770# lookahead expression '(?=\d|\.\d)' checks this.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005771
5772import re
Mark Dickinson70c32892008-07-02 09:37:01 +00005773_parser = re.compile(r""" # A numeric string consists of:
Facundo Batista72bc54f2007-11-23 17:59:00 +00005774# \s*
Mark Dickinson70c32892008-07-02 09:37:01 +00005775 (?P<sign>[-+])? # an optional sign, followed by either...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005776 (
Mark Dickinson4326ad82009-08-02 10:59:36 +00005777 (?=\d|\.\d) # ...a number (with at least one digit)
5778 (?P<int>\d*) # having a (possibly empty) integer part
5779 (\.(?P<frac>\d*))? # followed by an optional fractional part
5780 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005781 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005782 Inf(inity)? # ...an infinity, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005783 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005784 (?P<signal>s)? # ...an (optionally signaling)
5785 NaN # NaN
Mark Dickinson4326ad82009-08-02 10:59:36 +00005786 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005787 )
5788# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005789 \Z
Mark Dickinson4326ad82009-08-02 10:59:36 +00005790""", re.VERBOSE | re.IGNORECASE | re.UNICODE).match
Facundo Batista72bc54f2007-11-23 17:59:00 +00005791
Facundo Batista2ec74152007-12-03 17:55:00 +00005792_all_zeros = re.compile('0*$').match
5793_exact_half = re.compile('50*$').match
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005794
5795##### PEP3101 support functions ##############################################
Mark Dickinson277859d2009-03-17 23:03:46 +00005796# The functions in this section have little to do with the Decimal
5797# class, and could potentially be reused or adapted for other pure
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005798# Python numeric classes that want to implement __format__
5799#
5800# A format specifier for Decimal looks like:
5801#
Mark Dickinson277859d2009-03-17 23:03:46 +00005802# [[fill]align][sign][0][minimumwidth][,][.precision][type]
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005803
5804_parse_format_specifier_regex = re.compile(r"""\A
5805(?:
5806 (?P<fill>.)?
5807 (?P<align>[<>=^])
5808)?
5809(?P<sign>[-+ ])?
5810(?P<zeropad>0)?
5811(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson277859d2009-03-17 23:03:46 +00005812(?P<thousands_sep>,)?
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005813(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson277859d2009-03-17 23:03:46 +00005814(?P<type>[eEfFgGn%])?
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005815\Z
5816""", re.VERBOSE)
5817
Facundo Batista72bc54f2007-11-23 17:59:00 +00005818del re
5819
Mark Dickinson277859d2009-03-17 23:03:46 +00005820# The locale module is only needed for the 'n' format specifier. The
5821# rest of the PEP 3101 code functions quite happily without it, so we
5822# don't care too much if locale isn't present.
5823try:
5824 import locale as _locale
5825except ImportError:
5826 pass
5827
5828def _parse_format_specifier(format_spec, _localeconv=None):
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005829 """Parse and validate a format specifier.
5830
5831 Turns a standard numeric format specifier into a dict, with the
5832 following entries:
5833
5834 fill: fill character to pad field to minimum width
5835 align: alignment type, either '<', '>', '=' or '^'
5836 sign: either '+', '-' or ' '
5837 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson277859d2009-03-17 23:03:46 +00005838 zeropad: boolean, indicating whether to pad with zeros
5839 thousands_sep: string to use as thousands separator, or ''
5840 grouping: grouping for thousands separators, in format
5841 used by localeconv
5842 decimal_point: string to use for decimal point
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005843 precision: nonnegative integer giving precision, or None
5844 type: one of the characters 'eEfFgG%', or None
Mark Dickinson277859d2009-03-17 23:03:46 +00005845 unicode: boolean (always True for Python 3.x)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005846
5847 """
5848 m = _parse_format_specifier_regex.match(format_spec)
5849 if m is None:
5850 raise ValueError("Invalid format specifier: " + format_spec)
5851
5852 # get the dictionary
5853 format_dict = m.groupdict()
5854
Mark Dickinson277859d2009-03-17 23:03:46 +00005855 # zeropad; defaults for fill and alignment. If zero padding
5856 # is requested, the fill and align fields should be absent.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005857 fill = format_dict['fill']
5858 align = format_dict['align']
Mark Dickinson277859d2009-03-17 23:03:46 +00005859 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
5860 if format_dict['zeropad']:
5861 if fill is not None:
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005862 raise ValueError("Fill character conflicts with '0'"
5863 " in format specifier: " + format_spec)
Mark Dickinson277859d2009-03-17 23:03:46 +00005864 if align is not None:
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005865 raise ValueError("Alignment conflicts with '0' in "
5866 "format specifier: " + format_spec)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005867 format_dict['fill'] = fill or ' '
Mark Dickinson5cfa8042009-09-08 20:20:19 +00005868 # PEP 3101 originally specified that the default alignment should
5869 # be left; it was later agreed that right-aligned makes more sense
5870 # for numeric types. See http://bugs.python.org/issue6857.
5871 format_dict['align'] = align or '>'
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005872
Mark Dickinson277859d2009-03-17 23:03:46 +00005873 # default sign handling: '-' for negative, '' for positive
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005874 if format_dict['sign'] is None:
5875 format_dict['sign'] = '-'
5876
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005877 # minimumwidth defaults to 0; precision remains None if not given
5878 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5879 if format_dict['precision'] is not None:
5880 format_dict['precision'] = int(format_dict['precision'])
5881
5882 # if format type is 'g' or 'G' then a precision of 0 makes little
5883 # sense; convert it to 1. Same if format type is unspecified.
5884 if format_dict['precision'] == 0:
Mark Dickinson491ea552009-09-07 16:17:41 +00005885 if format_dict['type'] is None or format_dict['type'] in 'gG':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005886 format_dict['precision'] = 1
5887
Mark Dickinson277859d2009-03-17 23:03:46 +00005888 # determine thousands separator, grouping, and decimal separator, and
5889 # add appropriate entries to format_dict
5890 if format_dict['type'] == 'n':
5891 # apart from separators, 'n' behaves just like 'g'
5892 format_dict['type'] = 'g'
5893 if _localeconv is None:
5894 _localeconv = _locale.localeconv()
5895 if format_dict['thousands_sep'] is not None:
5896 raise ValueError("Explicit thousands separator conflicts with "
5897 "'n' type in format specifier: " + format_spec)
5898 format_dict['thousands_sep'] = _localeconv['thousands_sep']
5899 format_dict['grouping'] = _localeconv['grouping']
5900 format_dict['decimal_point'] = _localeconv['decimal_point']
5901 else:
5902 if format_dict['thousands_sep'] is None:
5903 format_dict['thousands_sep'] = ''
5904 format_dict['grouping'] = [3, 0]
5905 format_dict['decimal_point'] = '.'
5906
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005907 # record whether return type should be str or unicode
5908 format_dict['unicode'] = isinstance(format_spec, unicode)
5909
5910 return format_dict
5911
Mark Dickinson277859d2009-03-17 23:03:46 +00005912def _format_align(sign, body, spec):
5913 """Given an unpadded, non-aligned numeric string 'body' and sign
5914 string 'sign', add padding and aligment conforming to the given
5915 format specifier dictionary 'spec' (as produced by
5916 parse_format_specifier).
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005917
Mark Dickinson277859d2009-03-17 23:03:46 +00005918 Also converts result to unicode if necessary.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005919
5920 """
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005921 # how much extra space do we have to play with?
Mark Dickinson277859d2009-03-17 23:03:46 +00005922 minimumwidth = spec['minimumwidth']
5923 fill = spec['fill']
5924 padding = fill*(minimumwidth - len(sign) - len(body))
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005925
Mark Dickinson277859d2009-03-17 23:03:46 +00005926 align = spec['align']
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005927 if align == '<':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005928 result = sign + body + padding
Mark Dickinsonb065e522009-03-17 18:01:03 +00005929 elif align == '>':
5930 result = padding + sign + body
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005931 elif align == '=':
5932 result = sign + padding + body
Mark Dickinson277859d2009-03-17 23:03:46 +00005933 elif align == '^':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005934 half = len(padding)//2
5935 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson277859d2009-03-17 23:03:46 +00005936 else:
5937 raise ValueError('Unrecognised alignment field')
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005938
5939 # make sure that result is unicode if necessary
Mark Dickinson277859d2009-03-17 23:03:46 +00005940 if spec['unicode']:
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005941 result = unicode(result)
5942
5943 return result
Facundo Batista72bc54f2007-11-23 17:59:00 +00005944
Mark Dickinson277859d2009-03-17 23:03:46 +00005945def _group_lengths(grouping):
5946 """Convert a localeconv-style grouping into a (possibly infinite)
5947 iterable of integers representing group lengths.
5948
5949 """
5950 # The result from localeconv()['grouping'], and the input to this
5951 # function, should be a list of integers in one of the
5952 # following three forms:
5953 #
5954 # (1) an empty list, or
5955 # (2) nonempty list of positive integers + [0]
5956 # (3) list of positive integers + [locale.CHAR_MAX], or
5957
5958 from itertools import chain, repeat
5959 if not grouping:
5960 return []
5961 elif grouping[-1] == 0 and len(grouping) >= 2:
5962 return chain(grouping[:-1], repeat(grouping[-2]))
5963 elif grouping[-1] == _locale.CHAR_MAX:
5964 return grouping[:-1]
5965 else:
5966 raise ValueError('unrecognised format for grouping')
5967
5968def _insert_thousands_sep(digits, spec, min_width=1):
5969 """Insert thousands separators into a digit string.
5970
5971 spec is a dictionary whose keys should include 'thousands_sep' and
5972 'grouping'; typically it's the result of parsing the format
5973 specifier using _parse_format_specifier.
5974
5975 The min_width keyword argument gives the minimum length of the
5976 result, which will be padded on the left with zeros if necessary.
5977
5978 If necessary, the zero padding adds an extra '0' on the left to
5979 avoid a leading thousands separator. For example, inserting
5980 commas every three digits in '123456', with min_width=8, gives
5981 '0,123,456', even though that has length 9.
5982
5983 """
5984
5985 sep = spec['thousands_sep']
5986 grouping = spec['grouping']
5987
5988 groups = []
5989 for l in _group_lengths(grouping):
Mark Dickinson277859d2009-03-17 23:03:46 +00005990 if l <= 0:
5991 raise ValueError("group length should be positive")
5992 # max(..., 1) forces at least 1 digit to the left of a separator
5993 l = min(max(len(digits), min_width, 1), l)
5994 groups.append('0'*(l - len(digits)) + digits[-l:])
5995 digits = digits[:-l]
5996 min_width -= l
5997 if not digits and min_width <= 0:
5998 break
Mark Dickinsonb14514a2009-03-18 08:22:51 +00005999 min_width -= len(sep)
Mark Dickinson277859d2009-03-17 23:03:46 +00006000 else:
6001 l = max(len(digits), min_width, 1)
6002 groups.append('0'*(l - len(digits)) + digits[-l:])
6003 return sep.join(reversed(groups))
6004
6005def _format_sign(is_negative, spec):
6006 """Determine sign character."""
6007
6008 if is_negative:
6009 return '-'
6010 elif spec['sign'] in ' +':
6011 return spec['sign']
6012 else:
6013 return ''
6014
6015def _format_number(is_negative, intpart, fracpart, exp, spec):
6016 """Format a number, given the following data:
6017
6018 is_negative: true if the number is negative, else false
6019 intpart: string of digits that must appear before the decimal point
6020 fracpart: string of digits that must come after the point
6021 exp: exponent, as an integer
6022 spec: dictionary resulting from parsing the format specifier
6023
6024 This function uses the information in spec to:
6025 insert separators (decimal separator and thousands separators)
6026 format the sign
6027 format the exponent
6028 add trailing '%' for the '%' type
6029 zero-pad if necessary
6030 fill and align if necessary
6031 """
6032
6033 sign = _format_sign(is_negative, spec)
6034
6035 if fracpart:
6036 fracpart = spec['decimal_point'] + fracpart
6037
6038 if exp != 0 or spec['type'] in 'eE':
6039 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6040 fracpart += "{0}{1:+}".format(echar, exp)
6041 if spec['type'] == '%':
6042 fracpart += '%'
6043
6044 if spec['zeropad']:
6045 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6046 else:
6047 min_width = 0
6048 intpart = _insert_thousands_sep(intpart, spec, min_width)
6049
6050 return _format_align(sign, intpart+fracpart, spec)
6051
6052
Facundo Batista59c58842007-04-10 12:58:45 +00006053##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006054
Facundo Batista59c58842007-04-10 12:58:45 +00006055# Reusable defaults
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00006056_Infinity = Decimal('Inf')
6057_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonc5de0962009-01-02 23:07:08 +00006058_NaN = Decimal('NaN')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00006059_Zero = Decimal(0)
6060_One = Decimal(1)
6061_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006062
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00006063# _SignedInfinity[sign] is infinity w/ that sign
6064_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006065
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006066
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006067
6068if __name__ == '__main__':
6069 import doctest, sys
6070 doctest.testmod(sys.modules[__name__])