blob: 159669c3f3ceec0cbc95ae2b14fd2da9336284e4 [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 #
848 # == comparisons involving a NaN always return False
849 # != comparisons involving a NaN always return True
850 # <, >, <= and >= comparisons involving a (quiet or signaling)
851 # NaN signal InvalidOperation, and return False if the
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000852 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000853 #
854 # This behavior is designed to conform as closely as possible to
855 # that specified by IEEE 754.
856
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000857 def __eq__(self, other):
Mark Dickinson99d80962010-04-02 08:53:22 +0000858 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000859 if other is NotImplemented:
860 return other
861 if self.is_nan() or other.is_nan():
862 return False
863 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000864
865 def __ne__(self, other):
Mark Dickinson99d80962010-04-02 08:53:22 +0000866 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000867 if other is NotImplemented:
868 return other
869 if self.is_nan() or other.is_nan():
870 return True
871 return self._cmp(other) != 0
872
873 def __lt__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000874 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000875 if other is NotImplemented:
876 return other
877 ans = self._compare_check_nans(other, context)
878 if ans:
879 return False
880 return self._cmp(other) < 0
881
882 def __le__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000883 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000884 if other is NotImplemented:
885 return other
886 ans = self._compare_check_nans(other, context)
887 if ans:
888 return False
889 return self._cmp(other) <= 0
890
891 def __gt__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000892 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000893 if other is NotImplemented:
894 return other
895 ans = self._compare_check_nans(other, context)
896 if ans:
897 return False
898 return self._cmp(other) > 0
899
900 def __ge__(self, other, context=None):
Mark Dickinson99d80962010-04-02 08:53:22 +0000901 other = _convert_other(other, allow_float=True)
Mark Dickinson2fc92632008-02-06 22:10:50 +0000902 if other is NotImplemented:
903 return other
904 ans = self._compare_check_nans(other, context)
905 if ans:
906 return False
907 return self._cmp(other) >= 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000908
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000909 def compare(self, other, context=None):
910 """Compares one to another.
911
912 -1 => a < b
913 0 => a = b
914 1 => a > b
915 NaN => one is NaN
916 Like __cmp__, but returns Decimal instances.
917 """
Facundo Batista353750c2007-09-13 18:13:15 +0000918 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000919
Facundo Batista59c58842007-04-10 12:58:45 +0000920 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000921 if (self._is_special or other and other._is_special):
922 ans = self._check_nans(other, context)
923 if ans:
924 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000925
Mark Dickinson2fc92632008-02-06 22:10:50 +0000926 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000927
928 def __hash__(self):
929 """x.__hash__() <==> hash(x)"""
930 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000931 #
932 # The hash of a nonspecial noninteger Decimal must depend only
933 # on the value of that Decimal, and not on its representation.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000934 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Mark Dickinson99d80962010-04-02 08:53:22 +0000935 if self._is_special and self._isnan():
936 raise TypeError('Cannot hash a NaN value.')
937
938 # In Python 2.7, we're allowing comparisons (but not
939 # arithmetic operations) between floats and Decimals; so if
940 # a Decimal instance is exactly representable as a float then
941 # its hash should match that of the float. Note that this takes care
942 # of zeros and infinities, as well as small integers.
943 self_as_float = float(self)
944 if Decimal.from_float(self_as_float) == self:
945 return hash(self_as_float)
946
Facundo Batista8c202442007-09-19 17:53:25 +0000947 if self._isinteger():
948 op = _WorkRep(self.to_integral_value())
949 # to make computation feasible for Decimals with large
950 # exponent, we use the fact that hash(n) == hash(m) for
951 # any two nonzero integers n and m such that (i) n and m
952 # have the same sign, and (ii) n is congruent to m modulo
953 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
954 # hash((-1)**s*c*pow(10, e, 2**64-1).
955 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000956 # The value of a nonzero nonspecial Decimal instance is
957 # faithfully represented by the triple consisting of its sign,
958 # its adjusted exponent, and its coefficient with trailing
959 # zeros removed.
960 return hash((self._sign,
961 self._exp+len(self._int),
962 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000963
964 def as_tuple(self):
965 """Represents the number as a triple tuple.
966
967 To show the internals exactly as they are.
968 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000969 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000970
971 def __repr__(self):
972 """Represents the number as an instance of Decimal."""
973 # Invariant: eval(repr(d)) == d
Raymond Hettingerabe32372008-02-14 02:41:22 +0000974 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000975
Facundo Batista353750c2007-09-13 18:13:15 +0000976 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000977 """Return string representation of the number in scientific notation.
978
979 Captures all of the information in the underlying representation.
980 """
981
Facundo Batista62edb712007-12-03 16:29:52 +0000982 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000983 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000984 if self._exp == 'F':
985 return sign + 'Infinity'
986 elif self._exp == 'n':
987 return sign + 'NaN' + self._int
988 else: # self._exp == 'N'
989 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000990
Facundo Batista62edb712007-12-03 16:29:52 +0000991 # number of digits of self._int to left of decimal point
992 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000993
Facundo Batista62edb712007-12-03 16:29:52 +0000994 # dotplace is number of digits of self._int to the left of the
995 # decimal point in the mantissa of the output string (that is,
996 # after adjusting the exponent)
997 if self._exp <= 0 and leftdigits > -6:
998 # no exponent required
999 dotplace = leftdigits
1000 elif not eng:
1001 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001002 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +00001003 elif self._int == '0':
1004 # engineering notation, zero
1005 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001006 else:
Facundo Batista62edb712007-12-03 16:29:52 +00001007 # engineering notation, nonzero
1008 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009
Facundo Batista62edb712007-12-03 16:29:52 +00001010 if dotplace <= 0:
1011 intpart = '0'
1012 fracpart = '.' + '0'*(-dotplace) + self._int
1013 elif dotplace >= len(self._int):
1014 intpart = self._int+'0'*(dotplace-len(self._int))
1015 fracpart = ''
1016 else:
1017 intpart = self._int[:dotplace]
1018 fracpart = '.' + self._int[dotplace:]
1019 if leftdigits == dotplace:
1020 exp = ''
1021 else:
1022 if context is None:
1023 context = getcontext()
1024 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1025
1026 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001027
1028 def to_eng_string(self, context=None):
1029 """Convert to engineering-type string.
1030
1031 Engineering notation has an exponent which is a multiple of 3, so there
1032 are up to 3 digits left of the decimal place.
1033
1034 Same rules for when in exponential and when as a value as in __str__.
1035 """
Facundo Batista353750c2007-09-13 18:13:15 +00001036 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001037
1038 def __neg__(self, context=None):
1039 """Returns a copy with the sign switched.
1040
1041 Rounds, if it has reason.
1042 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001043 if self._is_special:
1044 ans = self._check_nans(context=context)
1045 if ans:
1046 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047
1048 if not self:
1049 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001050 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001052 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001053
1054 if context is None:
1055 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001056 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001057
1058 def __pos__(self, context=None):
1059 """Returns a copy, unless it is a sNaN.
1060
1061 Rounds the number (if more then precision digits)
1062 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001063 if self._is_special:
1064 ans = self._check_nans(context=context)
1065 if ans:
1066 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068 if not self:
1069 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001070 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +00001071 else:
1072 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001074 if context is None:
1075 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001076 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001077
Facundo Batistae64acfa2007-12-17 14:18:42 +00001078 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001079 """Returns the absolute value of self.
1080
Facundo Batistae64acfa2007-12-17 14:18:42 +00001081 If the keyword argument 'round' is false, do not round. The
1082 expression self.__abs__(round=False) is equivalent to
1083 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084 """
Facundo Batistae64acfa2007-12-17 14:18:42 +00001085 if not round:
1086 return self.copy_abs()
1087
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001088 if self._is_special:
1089 ans = self._check_nans(context=context)
1090 if ans:
1091 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001093 if self._sign:
1094 ans = self.__neg__(context=context)
1095 else:
1096 ans = self.__pos__(context=context)
1097
1098 return ans
1099
1100 def __add__(self, other, context=None):
1101 """Returns self + other.
1102
1103 -INF + INF (or the reverse) cause InvalidOperation errors.
1104 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001105 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001106 if other is NotImplemented:
1107 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001108
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109 if context is None:
1110 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001111
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001112 if self._is_special or other._is_special:
1113 ans = self._check_nans(other, context)
1114 if ans:
1115 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001116
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001117 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001118 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001119 if self._sign != other._sign and other._isinfinity():
1120 return context._raise_error(InvalidOperation, '-INF + INF')
1121 return Decimal(self)
1122 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001123 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001125 exp = min(self._exp, other._exp)
1126 negativezero = 0
1127 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001128 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129 negativezero = 1
1130
1131 if not self and not other:
1132 sign = min(self._sign, other._sign)
1133 if negativezero:
1134 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001135 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001136 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001137 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001139 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001140 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001141 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001142 return ans
1143 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001144 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001145 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001146 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001147 return ans
1148
1149 op1 = _WorkRep(self)
1150 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001151 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001152
1153 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001154 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001155 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001156 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001157 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001158 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001159 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001160 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001162 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001163 if op1.sign == 1:
1164 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165 op1.sign, op2.sign = op2.sign, op1.sign
1166 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001167 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001168 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001169 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001170 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001171 op1.sign, op2.sign = (0, 0)
1172 else:
1173 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001174 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001175
Raymond Hettinger17931de2004-10-27 06:21:46 +00001176 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001177 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001179 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001180
1181 result.exp = op1.exp
1182 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001183 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184 return ans
1185
1186 __radd__ = __add__
1187
1188 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001189 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001190 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001191 if other is NotImplemented:
1192 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001193
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001194 if self._is_special or other._is_special:
1195 ans = self._check_nans(other, context=context)
1196 if ans:
1197 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001198
Facundo Batista353750c2007-09-13 18:13:15 +00001199 # self - other is computed as self + other.copy_negate()
1200 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201
1202 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001203 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001204 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001205 if other is NotImplemented:
1206 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001207
Facundo Batista353750c2007-09-13 18:13:15 +00001208 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001209
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001210 def __mul__(self, other, context=None):
1211 """Return self * other.
1212
1213 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1214 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001215 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001216 if other is NotImplemented:
1217 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001218
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001219 if context is None:
1220 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001221
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001222 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001224 if self._is_special or other._is_special:
1225 ans = self._check_nans(other, context)
1226 if ans:
1227 return ans
1228
1229 if self._isinfinity():
1230 if not other:
1231 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001232 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001233
1234 if other._isinfinity():
1235 if not self:
1236 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001237 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001238
1239 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240
1241 # Special case for multiplying by zero
1242 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001243 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001244 # Fixing in case the exponent is out of bounds
1245 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001246 return ans
1247
1248 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001249 if self._int == '1':
1250 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001251 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001252 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001253 if other._int == '1':
1254 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001255 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001256 return ans
1257
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001258 op1 = _WorkRep(self)
1259 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001260
Facundo Batista72bc54f2007-11-23 17:59:00 +00001261 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001262 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001263
1264 return ans
1265 __rmul__ = __mul__
1266
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001267 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001268 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001269 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001270 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001271 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001272
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273 if context is None:
1274 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001275
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001276 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001277
1278 if self._is_special or other._is_special:
1279 ans = self._check_nans(other, context)
1280 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001281 return ans
1282
1283 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001284 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001285
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001286 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001287 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001288
1289 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001290 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001291 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001292
1293 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001294 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001295 if not self:
1296 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001297 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001298
Facundo Batistacce8df22007-09-18 16:53:18 +00001299 if not self:
1300 exp = self._exp - other._exp
1301 coeff = 0
1302 else:
1303 # OK, so neither = 0, INF or NaN
1304 shift = len(other._int) - len(self._int) + context.prec + 1
1305 exp = self._exp - other._exp - shift
1306 op1 = _WorkRep(self)
1307 op2 = _WorkRep(other)
1308 if shift >= 0:
1309 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1310 else:
1311 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1312 if remainder:
1313 # result is not exact; adjust to ensure correct rounding
1314 if coeff % 5 == 0:
1315 coeff += 1
1316 else:
1317 # result is exact; get as close to ideal exponent as possible
1318 ideal_exp = self._exp - other._exp
1319 while exp < ideal_exp and coeff % 10 == 0:
1320 coeff //= 10
1321 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001322
Facundo Batista72bc54f2007-11-23 17:59:00 +00001323 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001324 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001325
Facundo Batistacce8df22007-09-18 16:53:18 +00001326 def _divide(self, other, context):
1327 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001328
Facundo Batistacce8df22007-09-18 16:53:18 +00001329 Assumes that neither self nor other is a NaN, that self is not
1330 infinite and that other is nonzero.
1331 """
1332 sign = self._sign ^ other._sign
1333 if other._isinfinity():
1334 ideal_exp = self._exp
1335 else:
1336 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001337
Facundo Batistacce8df22007-09-18 16:53:18 +00001338 expdiff = self.adjusted() - other.adjusted()
1339 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001340 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001341 self._rescale(ideal_exp, context.rounding))
1342 if expdiff <= context.prec:
1343 op1 = _WorkRep(self)
1344 op2 = _WorkRep(other)
1345 if op1.exp >= op2.exp:
1346 op1.int *= 10**(op1.exp - op2.exp)
1347 else:
1348 op2.int *= 10**(op2.exp - op1.exp)
1349 q, r = divmod(op1.int, op2.int)
1350 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001351 return (_dec_from_triple(sign, str(q), 0),
1352 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001353
Facundo Batistacce8df22007-09-18 16:53:18 +00001354 # Here the quotient is too large to be representable
1355 ans = context._raise_error(DivisionImpossible,
1356 'quotient too large in //, % or divmod')
1357 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001358
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001359 def __rtruediv__(self, other, context=None):
1360 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001361 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001362 if other is NotImplemented:
1363 return other
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001364 return other.__truediv__(self, context=context)
1365
1366 __div__ = __truediv__
1367 __rdiv__ = __rtruediv__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001368
1369 def __divmod__(self, other, context=None):
1370 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001371 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001372 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001373 other = _convert_other(other)
1374 if other is NotImplemented:
1375 return other
1376
1377 if context is None:
1378 context = getcontext()
1379
1380 ans = self._check_nans(other, context)
1381 if ans:
1382 return (ans, ans)
1383
1384 sign = self._sign ^ other._sign
1385 if self._isinfinity():
1386 if other._isinfinity():
1387 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1388 return ans, ans
1389 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001390 return (_SignedInfinity[sign],
Facundo Batistacce8df22007-09-18 16:53:18 +00001391 context._raise_error(InvalidOperation, 'INF % x'))
1392
1393 if not other:
1394 if not self:
1395 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1396 return ans, ans
1397 else:
1398 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1399 context._raise_error(InvalidOperation, 'x % 0'))
1400
1401 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001402 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001403 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001404
1405 def __rdivmod__(self, other, context=None):
1406 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001407 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001408 if other is NotImplemented:
1409 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001410 return other.__divmod__(self, context=context)
1411
1412 def __mod__(self, other, context=None):
1413 """
1414 self % other
1415 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001416 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001417 if other is NotImplemented:
1418 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001419
Facundo Batistacce8df22007-09-18 16:53:18 +00001420 if context is None:
1421 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001422
Facundo Batistacce8df22007-09-18 16:53:18 +00001423 ans = self._check_nans(other, context)
1424 if ans:
1425 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001426
Facundo Batistacce8df22007-09-18 16:53:18 +00001427 if self._isinfinity():
1428 return context._raise_error(InvalidOperation, 'INF % x')
1429 elif not other:
1430 if self:
1431 return context._raise_error(InvalidOperation, 'x % 0')
1432 else:
1433 return context._raise_error(DivisionUndefined, '0 % 0')
1434
1435 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001436 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001437 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001438
1439 def __rmod__(self, other, context=None):
1440 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001441 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001442 if other is NotImplemented:
1443 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001444 return other.__mod__(self, context=context)
1445
1446 def remainder_near(self, other, context=None):
1447 """
1448 Remainder nearest to 0- abs(remainder-near) <= other/2
1449 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001450 if context is None:
1451 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001452
Facundo Batista353750c2007-09-13 18:13:15 +00001453 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001454
Facundo Batista353750c2007-09-13 18:13:15 +00001455 ans = self._check_nans(other, context)
1456 if ans:
1457 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001458
Facundo Batista353750c2007-09-13 18:13:15 +00001459 # self == +/-infinity -> InvalidOperation
1460 if self._isinfinity():
1461 return context._raise_error(InvalidOperation,
1462 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001463
Facundo Batista353750c2007-09-13 18:13:15 +00001464 # other == 0 -> either InvalidOperation or DivisionUndefined
1465 if not other:
1466 if self:
1467 return context._raise_error(InvalidOperation,
1468 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001469 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001470 return context._raise_error(DivisionUndefined,
1471 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001472
Facundo Batista353750c2007-09-13 18:13:15 +00001473 # other = +/-infinity -> remainder = self
1474 if other._isinfinity():
1475 ans = Decimal(self)
1476 return ans._fix(context)
1477
1478 # self = 0 -> remainder = self, with ideal exponent
1479 ideal_exponent = min(self._exp, other._exp)
1480 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001481 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001482 return ans._fix(context)
1483
1484 # catch most cases of large or small quotient
1485 expdiff = self.adjusted() - other.adjusted()
1486 if expdiff >= context.prec + 1:
1487 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001488 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001489 if expdiff <= -2:
1490 # expdiff <= -2 => abs(self/other) < 0.1
1491 ans = self._rescale(ideal_exponent, context.rounding)
1492 return ans._fix(context)
1493
1494 # adjust both arguments to have the same exponent, then divide
1495 op1 = _WorkRep(self)
1496 op2 = _WorkRep(other)
1497 if op1.exp >= op2.exp:
1498 op1.int *= 10**(op1.exp - op2.exp)
1499 else:
1500 op2.int *= 10**(op2.exp - op1.exp)
1501 q, r = divmod(op1.int, op2.int)
1502 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1503 # 10**ideal_exponent. Apply correction to ensure that
1504 # abs(remainder) <= abs(other)/2
1505 if 2*r + (q&1) > op2.int:
1506 r -= op2.int
1507 q += 1
1508
1509 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001510 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001511
1512 # result has same sign as self unless r is negative
1513 sign = self._sign
1514 if r < 0:
1515 sign = 1-sign
1516 r = -r
1517
Facundo Batista72bc54f2007-11-23 17:59:00 +00001518 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001519 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001520
1521 def __floordiv__(self, other, context=None):
1522 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001523 other = _convert_other(other)
1524 if other is NotImplemented:
1525 return other
1526
1527 if context is None:
1528 context = getcontext()
1529
1530 ans = self._check_nans(other, context)
1531 if ans:
1532 return ans
1533
1534 if self._isinfinity():
1535 if other._isinfinity():
1536 return context._raise_error(InvalidOperation, 'INF // INF')
1537 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001538 return _SignedInfinity[self._sign ^ other._sign]
Facundo Batistacce8df22007-09-18 16:53:18 +00001539
1540 if not other:
1541 if self:
1542 return context._raise_error(DivisionByZero, 'x // 0',
1543 self._sign ^ other._sign)
1544 else:
1545 return context._raise_error(DivisionUndefined, '0 // 0')
1546
1547 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001548
1549 def __rfloordiv__(self, other, context=None):
1550 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001551 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001552 if other is NotImplemented:
1553 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001554 return other.__floordiv__(self, context=context)
1555
1556 def __float__(self):
1557 """Float representation."""
1558 return float(str(self))
1559
1560 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001561 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001562 if self._is_special:
1563 if self._isnan():
Mark Dickinson968f1692009-09-07 18:04:58 +00001564 raise ValueError("Cannot convert NaN to integer")
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001565 elif self._isinfinity():
Mark Dickinson968f1692009-09-07 18:04:58 +00001566 raise OverflowError("Cannot convert infinity to integer")
Facundo Batista353750c2007-09-13 18:13:15 +00001567 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001568 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001569 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001570 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001571 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001572
Raymond Hettinger5a053642008-01-24 19:05:29 +00001573 __trunc__ = __int__
1574
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001575 def real(self):
1576 return self
Mark Dickinson65808ff2009-01-04 21:22:02 +00001577 real = property(real)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001578
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001579 def imag(self):
1580 return Decimal(0)
Mark Dickinson65808ff2009-01-04 21:22:02 +00001581 imag = property(imag)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001582
1583 def conjugate(self):
1584 return self
1585
1586 def __complex__(self):
1587 return complex(float(self))
1588
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001589 def __long__(self):
1590 """Converts to a long.
1591
1592 Equivalent to long(int(self))
1593 """
1594 return long(self.__int__())
1595
Facundo Batista353750c2007-09-13 18:13:15 +00001596 def _fix_nan(self, context):
1597 """Decapitate the payload of a NaN to fit the context"""
1598 payload = self._int
1599
1600 # maximum length of payload is precision if _clamp=0,
1601 # precision-1 if _clamp=1.
1602 max_payload_len = context.prec - context._clamp
1603 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001604 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1605 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001606 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001607
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001608 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001609 """Round if it is necessary to keep self within prec precision.
1610
1611 Rounds and fixes the exponent. Does not raise on a sNaN.
1612
1613 Arguments:
1614 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001615 context - context used.
1616 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001617
Facundo Batista353750c2007-09-13 18:13:15 +00001618 if self._is_special:
1619 if self._isnan():
1620 # decapitate payload if necessary
1621 return self._fix_nan(context)
1622 else:
1623 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001624 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001625
Facundo Batista353750c2007-09-13 18:13:15 +00001626 # if self is zero then exponent should be between Etiny and
1627 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1628 Etiny = context.Etiny()
1629 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001630 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001631 exp_max = [context.Emax, Etop][context._clamp]
1632 new_exp = min(max(self._exp, Etiny), exp_max)
1633 if new_exp != self._exp:
1634 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001635 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001636 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001637 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001638
1639 # exp_min is the smallest allowable exponent of the result,
1640 # equal to max(self.adjusted()-context.prec+1, Etiny)
1641 exp_min = len(self._int) + self._exp - context.prec
1642 if exp_min > Etop:
1643 # overflow: exp_min > Etop iff self.adjusted() > Emax
1644 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001645 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001646 return context._raise_error(Overflow, 'above Emax', self._sign)
1647 self_is_subnormal = exp_min < Etiny
1648 if self_is_subnormal:
1649 context._raise_error(Subnormal)
1650 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001651
Facundo Batista353750c2007-09-13 18:13:15 +00001652 # round if self has too many digits
1653 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001654 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001655 digits = len(self._int) + self._exp - exp_min
1656 if digits < 0:
1657 self = _dec_from_triple(self._sign, '1', exp_min-1)
1658 digits = 0
1659 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1660 changed = this_function(digits)
1661 coeff = self._int[:digits] or '0'
1662 if changed == 1:
1663 coeff = str(int(coeff)+1)
1664 ans = _dec_from_triple(self._sign, coeff, exp_min)
1665
1666 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001667 context._raise_error(Inexact)
1668 if self_is_subnormal:
1669 context._raise_error(Underflow)
1670 if not ans:
1671 # raise Clamped on underflow to 0
1672 context._raise_error(Clamped)
1673 elif len(ans._int) == context.prec+1:
1674 # we get here only if rescaling rounds the
1675 # cofficient up to exactly 10**context.prec
1676 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001677 ans = _dec_from_triple(ans._sign,
1678 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001679 else:
1680 # Inexact and Rounded have already been raised
1681 ans = context._raise_error(Overflow, 'above Emax',
1682 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001683 return ans
1684
Facundo Batista353750c2007-09-13 18:13:15 +00001685 # fold down if _clamp == 1 and self has too few digits
1686 if context._clamp == 1 and self._exp > Etop:
1687 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001688 self_padded = self._int + '0'*(self._exp - Etop)
1689 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001690
Facundo Batista353750c2007-09-13 18:13:15 +00001691 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001692 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001693
1694 _pick_rounding_function = {}
1695
Facundo Batista353750c2007-09-13 18:13:15 +00001696 # for each of the rounding functions below:
1697 # self is a finite, nonzero Decimal
1698 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001699 #
1700 # each function returns either -1, 0, or 1, as follows:
1701 # 1 indicates that self should be rounded up (away from zero)
1702 # 0 indicates that self should be truncated, and that all the
1703 # digits to be truncated are zeros (so the value is unchanged)
1704 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001705
1706 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001707 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001708 if _all_zeros(self._int, prec):
1709 return 0
1710 else:
1711 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001712
Facundo Batista353750c2007-09-13 18:13:15 +00001713 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001714 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001715 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001716
Facundo Batista353750c2007-09-13 18:13:15 +00001717 def _round_half_up(self, prec):
1718 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001719 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001720 return 1
1721 elif _all_zeros(self._int, prec):
1722 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001723 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001724 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001725
1726 def _round_half_down(self, prec):
1727 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001728 if _exact_half(self._int, prec):
1729 return -1
1730 else:
1731 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001732
1733 def _round_half_even(self, prec):
1734 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001735 if _exact_half(self._int, prec) and \
1736 (prec == 0 or self._int[prec-1] in '02468'):
1737 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001738 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001739 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001740
1741 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001742 """Rounds up (not away from 0 if negative.)"""
1743 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001744 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001745 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001746 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001747
Facundo Batista353750c2007-09-13 18:13:15 +00001748 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001749 """Rounds down (not towards 0 if negative)"""
1750 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001751 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001752 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001753 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001754
Facundo Batista353750c2007-09-13 18:13:15 +00001755 def _round_05up(self, prec):
1756 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001757 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001758 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001759 else:
1760 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001761
Facundo Batista353750c2007-09-13 18:13:15 +00001762 def fma(self, other, third, context=None):
1763 """Fused multiply-add.
1764
1765 Returns self*other+third with no rounding of the intermediate
1766 product self*other.
1767
1768 self and other are multiplied together, with no rounding of
1769 the result. The third operand is then added to the result,
1770 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001771 """
Facundo Batista353750c2007-09-13 18:13:15 +00001772
1773 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001774
1775 # compute product; raise InvalidOperation if either operand is
1776 # a signaling NaN or if the product is zero times infinity.
1777 if self._is_special or other._is_special:
1778 if context is None:
1779 context = getcontext()
1780 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001781 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001782 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001783 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001784 if self._exp == 'n':
1785 product = self
1786 elif other._exp == 'n':
1787 product = other
1788 elif self._exp == 'F':
1789 if not other:
1790 return context._raise_error(InvalidOperation,
1791 'INF * 0 in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001792 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001793 elif other._exp == 'F':
1794 if not self:
1795 return context._raise_error(InvalidOperation,
1796 '0 * INF in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001797 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001798 else:
1799 product = _dec_from_triple(self._sign ^ other._sign,
1800 str(int(self._int) * int(other._int)),
1801 self._exp + other._exp)
1802
Facundo Batista353750c2007-09-13 18:13:15 +00001803 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001804 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001805
Facundo Batista353750c2007-09-13 18:13:15 +00001806 def _power_modulo(self, other, modulo, context=None):
1807 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001808
Facundo Batista353750c2007-09-13 18:13:15 +00001809 # if can't convert other and modulo to Decimal, raise
1810 # TypeError; there's no point returning NotImplemented (no
1811 # equivalent of __rpow__ for three argument pow)
1812 other = _convert_other(other, raiseit=True)
1813 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001814
Facundo Batista353750c2007-09-13 18:13:15 +00001815 if context is None:
1816 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001817
Facundo Batista353750c2007-09-13 18:13:15 +00001818 # deal with NaNs: if there are any sNaNs then first one wins,
1819 # (i.e. behaviour for NaNs is identical to that of fma)
1820 self_is_nan = self._isnan()
1821 other_is_nan = other._isnan()
1822 modulo_is_nan = modulo._isnan()
1823 if self_is_nan or other_is_nan or modulo_is_nan:
1824 if self_is_nan == 2:
1825 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001826 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001827 if other_is_nan == 2:
1828 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001829 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001830 if modulo_is_nan == 2:
1831 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001832 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001833 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001834 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001835 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001836 return other._fix_nan(context)
1837 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001838
Facundo Batista353750c2007-09-13 18:13:15 +00001839 # check inputs: we apply same restrictions as Python's pow()
1840 if not (self._isinteger() and
1841 other._isinteger() and
1842 modulo._isinteger()):
1843 return context._raise_error(InvalidOperation,
1844 'pow() 3rd argument not allowed '
1845 'unless all arguments are integers')
1846 if other < 0:
1847 return context._raise_error(InvalidOperation,
1848 'pow() 2nd argument cannot be '
1849 'negative when 3rd argument specified')
1850 if not modulo:
1851 return context._raise_error(InvalidOperation,
1852 'pow() 3rd argument cannot be 0')
1853
1854 # additional restriction for decimal: the modulus must be less
1855 # than 10**prec in absolute value
1856 if modulo.adjusted() >= context.prec:
1857 return context._raise_error(InvalidOperation,
1858 'insufficient precision: pow() 3rd '
1859 'argument must not have more than '
1860 'precision digits')
1861
1862 # define 0**0 == NaN, for consistency with two-argument pow
1863 # (even though it hurts!)
1864 if not other and not self:
1865 return context._raise_error(InvalidOperation,
1866 'at least one of pow() 1st argument '
1867 'and 2nd argument must be nonzero ;'
1868 '0**0 is not defined')
1869
1870 # compute sign of result
1871 if other._iseven():
1872 sign = 0
1873 else:
1874 sign = self._sign
1875
1876 # convert modulo to a Python integer, and self and other to
1877 # Decimal integers (i.e. force their exponents to be >= 0)
1878 modulo = abs(int(modulo))
1879 base = _WorkRep(self.to_integral_value())
1880 exponent = _WorkRep(other.to_integral_value())
1881
1882 # compute result using integer pow()
1883 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1884 for i in xrange(exponent.exp):
1885 base = pow(base, 10, modulo)
1886 base = pow(base, exponent.int, modulo)
1887
Facundo Batista72bc54f2007-11-23 17:59:00 +00001888 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001889
1890 def _power_exact(self, other, p):
1891 """Attempt to compute self**other exactly.
1892
1893 Given Decimals self and other and an integer p, attempt to
1894 compute an exact result for the power self**other, with p
1895 digits of precision. Return None if self**other is not
1896 exactly representable in p digits.
1897
1898 Assumes that elimination of special cases has already been
1899 performed: self and other must both be nonspecial; self must
1900 be positive and not numerically equal to 1; other must be
1901 nonzero. For efficiency, other._exp should not be too large,
1902 so that 10**abs(other._exp) is a feasible calculation."""
1903
1904 # In the comments below, we write x for the value of self and
1905 # y for the value of other. Write x = xc*10**xe and y =
1906 # yc*10**ye.
1907
1908 # The main purpose of this method is to identify the *failure*
1909 # of x**y to be exactly representable with as little effort as
1910 # possible. So we look for cheap and easy tests that
1911 # eliminate the possibility of x**y being exact. Only if all
1912 # these tests are passed do we go on to actually compute x**y.
1913
1914 # Here's the main idea. First normalize both x and y. We
1915 # express y as a rational m/n, with m and n relatively prime
1916 # and n>0. Then for x**y to be exactly representable (at
1917 # *any* precision), xc must be the nth power of a positive
1918 # integer and xe must be divisible by n. If m is negative
1919 # then additionally xc must be a power of either 2 or 5, hence
1920 # a power of 2**n or 5**n.
1921 #
1922 # There's a limit to how small |y| can be: if y=m/n as above
1923 # then:
1924 #
1925 # (1) if xc != 1 then for the result to be representable we
1926 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1927 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1928 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1929 # representable.
1930 #
1931 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1932 # |y| < 1/|xe| then the result is not representable.
1933 #
1934 # Note that since x is not equal to 1, at least one of (1) and
1935 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1936 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1937 #
1938 # There's also a limit to how large y can be, at least if it's
1939 # positive: the normalized result will have coefficient xc**y,
1940 # so if it's representable then xc**y < 10**p, and y <
1941 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1942 # not exactly representable.
1943
1944 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1945 # so |y| < 1/xe and the result is not representable.
1946 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1947 # < 1/nbits(xc).
1948
1949 x = _WorkRep(self)
1950 xc, xe = x.int, x.exp
1951 while xc % 10 == 0:
1952 xc //= 10
1953 xe += 1
1954
1955 y = _WorkRep(other)
1956 yc, ye = y.int, y.exp
1957 while yc % 10 == 0:
1958 yc //= 10
1959 ye += 1
1960
1961 # case where xc == 1: result is 10**(xe*y), with xe*y
1962 # required to be an integer
1963 if xc == 1:
1964 if ye >= 0:
1965 exponent = xe*yc*10**ye
1966 else:
1967 exponent, remainder = divmod(xe*yc, 10**-ye)
1968 if remainder:
1969 return None
1970 if y.sign == 1:
1971 exponent = -exponent
1972 # if other is a nonnegative integer, use ideal exponent
1973 if other._isinteger() and other._sign == 0:
1974 ideal_exponent = self._exp*int(other)
1975 zeros = min(exponent-ideal_exponent, p-1)
1976 else:
1977 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001978 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001979
1980 # case where y is negative: xc must be either a power
1981 # of 2 or a power of 5.
1982 if y.sign == 1:
1983 last_digit = xc % 10
1984 if last_digit in (2,4,6,8):
1985 # quick test for power of 2
1986 if xc & -xc != xc:
1987 return None
1988 # now xc is a power of 2; e is its exponent
1989 e = _nbits(xc)-1
1990 # find e*y and xe*y; both must be integers
1991 if ye >= 0:
1992 y_as_int = yc*10**ye
1993 e = e*y_as_int
1994 xe = xe*y_as_int
1995 else:
1996 ten_pow = 10**-ye
1997 e, remainder = divmod(e*yc, ten_pow)
1998 if remainder:
1999 return None
2000 xe, remainder = divmod(xe*yc, ten_pow)
2001 if remainder:
2002 return None
2003
2004 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2005 return None
2006 xc = 5**e
2007
2008 elif last_digit == 5:
2009 # e >= log_5(xc) if xc is a power of 5; we have
2010 # equality all the way up to xc=5**2658
2011 e = _nbits(xc)*28//65
2012 xc, remainder = divmod(5**e, xc)
2013 if remainder:
2014 return None
2015 while xc % 5 == 0:
2016 xc //= 5
2017 e -= 1
2018 if ye >= 0:
2019 y_as_integer = yc*10**ye
2020 e = e*y_as_integer
2021 xe = xe*y_as_integer
2022 else:
2023 ten_pow = 10**-ye
2024 e, remainder = divmod(e*yc, ten_pow)
2025 if remainder:
2026 return None
2027 xe, remainder = divmod(xe*yc, ten_pow)
2028 if remainder:
2029 return None
2030 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2031 return None
2032 xc = 2**e
2033 else:
2034 return None
2035
2036 if xc >= 10**p:
2037 return None
2038 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00002039 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00002040
2041 # now y is positive; find m and n such that y = m/n
2042 if ye >= 0:
2043 m, n = yc*10**ye, 1
2044 else:
2045 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2046 return None
2047 xc_bits = _nbits(xc)
2048 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2049 return None
2050 m, n = yc, 10**(-ye)
2051 while m % 2 == n % 2 == 0:
2052 m //= 2
2053 n //= 2
2054 while m % 5 == n % 5 == 0:
2055 m //= 5
2056 n //= 5
2057
2058 # compute nth root of xc*10**xe
2059 if n > 1:
2060 # if 1 < xc < 2**n then xc isn't an nth power
2061 if xc != 1 and xc_bits <= n:
2062 return None
2063
2064 xe, rem = divmod(xe, n)
2065 if rem != 0:
2066 return None
2067
2068 # compute nth root of xc using Newton's method
2069 a = 1L << -(-_nbits(xc)//n) # initial estimate
2070 while True:
2071 q, r = divmod(xc, a**(n-1))
2072 if a <= q:
2073 break
2074 else:
2075 a = (a*(n-1) + q)//n
2076 if not (a == q and r == 0):
2077 return None
2078 xc = a
2079
2080 # now xc*10**xe is the nth root of the original xc*10**xe
2081 # compute mth power of xc*10**xe
2082
2083 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2084 # 10**p and the result is not representable.
2085 if xc > 1 and m > p*100//_log10_lb(xc):
2086 return None
2087 xc = xc**m
2088 xe *= m
2089 if xc > 10**p:
2090 return None
2091
2092 # by this point the result *is* exactly representable
2093 # adjust the exponent to get as close as possible to the ideal
2094 # exponent, if necessary
2095 str_xc = str(xc)
2096 if other._isinteger() and other._sign == 0:
2097 ideal_exponent = self._exp*int(other)
2098 zeros = min(xe-ideal_exponent, p-len(str_xc))
2099 else:
2100 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002101 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002102
2103 def __pow__(self, other, modulo=None, context=None):
2104 """Return self ** other [ % modulo].
2105
2106 With two arguments, compute self**other.
2107
2108 With three arguments, compute (self**other) % modulo. For the
2109 three argument form, the following restrictions on the
2110 arguments hold:
2111
2112 - all three arguments must be integral
2113 - other must be nonnegative
2114 - either self or other (or both) must be nonzero
2115 - modulo must be nonzero and must have at most p digits,
2116 where p is the context precision.
2117
2118 If any of these restrictions is violated the InvalidOperation
2119 flag is raised.
2120
2121 The result of pow(self, other, modulo) is identical to the
2122 result that would be obtained by computing (self**other) %
2123 modulo with unbounded precision, but is computed more
2124 efficiently. It is always exact.
2125 """
2126
2127 if modulo is not None:
2128 return self._power_modulo(other, modulo, context)
2129
2130 other = _convert_other(other)
2131 if other is NotImplemented:
2132 return other
2133
2134 if context is None:
2135 context = getcontext()
2136
2137 # either argument is a NaN => result is NaN
2138 ans = self._check_nans(other, context)
2139 if ans:
2140 return ans
2141
2142 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2143 if not other:
2144 if not self:
2145 return context._raise_error(InvalidOperation, '0 ** 0')
2146 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002147 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002148
2149 # result has sign 1 iff self._sign is 1 and other is an odd integer
2150 result_sign = 0
2151 if self._sign == 1:
2152 if other._isinteger():
2153 if not other._iseven():
2154 result_sign = 1
2155 else:
2156 # -ve**noninteger = NaN
2157 # (-0)**noninteger = 0**noninteger
2158 if self:
2159 return context._raise_error(InvalidOperation,
2160 'x ** y with x negative and y not an integer')
2161 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002162 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002163
2164 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2165 if not self:
2166 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002167 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002168 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002169 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002170
2171 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002172 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002173 if other._sign == 0:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002174 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002175 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002176 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002177
Facundo Batista353750c2007-09-13 18:13:15 +00002178 # 1**other = 1, but the choice of exponent and the flags
2179 # depend on the exponent of self, and on whether other is a
2180 # positive integer, a negative integer, or neither
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002181 if self == _One:
Facundo Batista353750c2007-09-13 18:13:15 +00002182 if other._isinteger():
2183 # exp = max(self._exp*max(int(other), 0),
2184 # 1-context.prec) but evaluating int(other) directly
2185 # is dangerous until we know other is small (other
2186 # could be 1e999999999)
2187 if other._sign == 1:
2188 multiplier = 0
2189 elif other > context.prec:
2190 multiplier = context.prec
2191 else:
2192 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002193
Facundo Batista353750c2007-09-13 18:13:15 +00002194 exp = self._exp * multiplier
2195 if exp < 1-context.prec:
2196 exp = 1-context.prec
2197 context._raise_error(Rounded)
2198 else:
2199 context._raise_error(Inexact)
2200 context._raise_error(Rounded)
2201 exp = 1-context.prec
2202
Facundo Batista72bc54f2007-11-23 17:59:00 +00002203 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002204
2205 # compute adjusted exponent of self
2206 self_adj = self.adjusted()
2207
2208 # self ** infinity is infinity if self > 1, 0 if self < 1
2209 # self ** -infinity is infinity if self < 1, 0 if self > 1
2210 if other._isinfinity():
2211 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002212 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002213 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002214 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002215
2216 # from here on, the result always goes through the call
2217 # to _fix at the end of this function.
2218 ans = None
2219
2220 # crude test to catch cases of extreme overflow/underflow. If
2221 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2222 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2223 # self**other >= 10**(Emax+1), so overflow occurs. The test
2224 # for underflow is similar.
2225 bound = self._log10_exp_bound() + other.adjusted()
2226 if (self_adj >= 0) == (other._sign == 0):
2227 # self > 1 and other +ve, or self < 1 and other -ve
2228 # possibility of overflow
2229 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002230 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002231 else:
2232 # self > 1 and other -ve, or self < 1 and other +ve
2233 # possibility of underflow to 0
2234 Etiny = context.Etiny()
2235 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002236 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002237
2238 # try for an exact result with precision +1
2239 if ans is None:
2240 ans = self._power_exact(other, context.prec + 1)
2241 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002242 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002243
2244 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2245 if ans is None:
2246 p = context.prec
2247 x = _WorkRep(self)
2248 xc, xe = x.int, x.exp
2249 y = _WorkRep(other)
2250 yc, ye = y.int, y.exp
2251 if y.sign == 1:
2252 yc = -yc
2253
2254 # compute correctly rounded result: start with precision +3,
2255 # then increase precision until result is unambiguously roundable
2256 extra = 3
2257 while True:
2258 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2259 if coeff % (5*10**(len(str(coeff))-p-1)):
2260 break
2261 extra += 3
2262
Facundo Batista72bc54f2007-11-23 17:59:00 +00002263 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002264
2265 # the specification says that for non-integer other we need to
2266 # raise Inexact, even when the result is actually exact. In
2267 # the same way, we need to raise Underflow here if the result
2268 # is subnormal. (The call to _fix will take care of raising
2269 # Rounded and Subnormal, as usual.)
2270 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002271 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002272 # pad with zeros up to length context.prec+1 if necessary
2273 if len(ans._int) <= context.prec:
2274 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002275 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2276 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002277 if ans.adjusted() < context.Emin:
2278 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002279
Facundo Batista353750c2007-09-13 18:13:15 +00002280 # unlike exp, ln and log10, the power function respects the
2281 # rounding mode; no need to use ROUND_HALF_EVEN here
2282 ans = ans._fix(context)
2283 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002284
2285 def __rpow__(self, other, context=None):
2286 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002287 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002288 if other is NotImplemented:
2289 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002290 return other.__pow__(self, context=context)
2291
2292 def normalize(self, context=None):
2293 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002294
Facundo Batista353750c2007-09-13 18:13:15 +00002295 if context is None:
2296 context = getcontext()
2297
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002298 if self._is_special:
2299 ans = self._check_nans(context=context)
2300 if ans:
2301 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002302
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002303 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002304 if dup._isinfinity():
2305 return dup
2306
2307 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002308 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002309 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002310 end = len(dup._int)
2311 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002312 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002313 exp += 1
2314 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002315 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002316
Facundo Batistabd2fe832007-09-13 18:42:09 +00002317 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002318 """Quantize self so its exponent is the same as that of exp.
2319
2320 Similar to self._rescale(exp._exp) but with error checking.
2321 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002322 exp = _convert_other(exp, raiseit=True)
2323
Facundo Batista353750c2007-09-13 18:13:15 +00002324 if context is None:
2325 context = getcontext()
2326 if rounding is None:
2327 rounding = context.rounding
2328
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002329 if self._is_special or exp._is_special:
2330 ans = self._check_nans(exp, context)
2331 if ans:
2332 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002333
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002334 if exp._isinfinity() or self._isinfinity():
2335 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002336 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002337 return context._raise_error(InvalidOperation,
2338 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002339
Facundo Batistabd2fe832007-09-13 18:42:09 +00002340 # if we're not watching exponents, do a simple rescale
2341 if not watchexp:
2342 ans = self._rescale(exp._exp, rounding)
2343 # raise Inexact and Rounded where appropriate
2344 if ans._exp > self._exp:
2345 context._raise_error(Rounded)
2346 if ans != self:
2347 context._raise_error(Inexact)
2348 return ans
2349
Facundo Batista353750c2007-09-13 18:13:15 +00002350 # exp._exp should be between Etiny and Emax
2351 if not (context.Etiny() <= exp._exp <= context.Emax):
2352 return context._raise_error(InvalidOperation,
2353 'target exponent out of bounds in quantize')
2354
2355 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002356 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002357 return ans._fix(context)
2358
2359 self_adjusted = self.adjusted()
2360 if self_adjusted > context.Emax:
2361 return context._raise_error(InvalidOperation,
2362 'exponent of quantize result too large for current context')
2363 if self_adjusted - exp._exp + 1 > context.prec:
2364 return context._raise_error(InvalidOperation,
2365 'quantize result has too many digits for current context')
2366
2367 ans = self._rescale(exp._exp, rounding)
2368 if ans.adjusted() > context.Emax:
2369 return context._raise_error(InvalidOperation,
2370 'exponent of quantize result too large for current context')
2371 if len(ans._int) > context.prec:
2372 return context._raise_error(InvalidOperation,
2373 'quantize result has too many digits for current context')
2374
2375 # raise appropriate flags
2376 if ans._exp > self._exp:
2377 context._raise_error(Rounded)
2378 if ans != self:
2379 context._raise_error(Inexact)
2380 if ans and ans.adjusted() < context.Emin:
2381 context._raise_error(Subnormal)
2382
2383 # call to fix takes care of any necessary folddown
2384 ans = ans._fix(context)
2385 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002386
2387 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002388 """Return True if self and other have the same exponent; otherwise
2389 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002390
Facundo Batista1a191df2007-10-02 17:01:24 +00002391 If either operand is a special value, the following rules are used:
2392 * return True if both operands are infinities
2393 * return True if both operands are NaNs
2394 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002395 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002396 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002397 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002398 return (self.is_nan() and other.is_nan() or
2399 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002400 return self._exp == other._exp
2401
Facundo Batista353750c2007-09-13 18:13:15 +00002402 def _rescale(self, exp, rounding):
2403 """Rescale self so that the exponent is exp, either by padding with zeros
2404 or by truncating digits, using the given rounding mode.
2405
2406 Specials are returned without change. This operation is
2407 quiet: it raises no flags, and uses no information from the
2408 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002409
2410 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002411 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002412 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002413 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002414 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002415 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002416 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002417
Facundo Batista353750c2007-09-13 18:13:15 +00002418 if self._exp >= exp:
2419 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002420 return _dec_from_triple(self._sign,
2421 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002422
Facundo Batista353750c2007-09-13 18:13:15 +00002423 # too many digits; round and lose data. If self.adjusted() <
2424 # exp-1, replace self by 10**(exp-1) before rounding
2425 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002426 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002427 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002428 digits = 0
2429 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002430 changed = this_function(digits)
2431 coeff = self._int[:digits] or '0'
2432 if changed == 1:
2433 coeff = str(int(coeff)+1)
2434 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002435
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00002436 def _round(self, places, rounding):
2437 """Round a nonzero, nonspecial Decimal to a fixed number of
2438 significant figures, using the given rounding mode.
2439
2440 Infinities, NaNs and zeros are returned unaltered.
2441
2442 This operation is quiet: it raises no flags, and uses no
2443 information from the context.
2444
2445 """
2446 if places <= 0:
2447 raise ValueError("argument should be at least 1 in _round")
2448 if self._is_special or not self:
2449 return Decimal(self)
2450 ans = self._rescale(self.adjusted()+1-places, rounding)
2451 # it can happen that the rescale alters the adjusted exponent;
2452 # for example when rounding 99.97 to 3 significant figures.
2453 # When this happens we end up with an extra 0 at the end of
2454 # the number; a second rescale fixes this.
2455 if ans.adjusted() != self.adjusted():
2456 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2457 return ans
2458
Facundo Batista353750c2007-09-13 18:13:15 +00002459 def to_integral_exact(self, rounding=None, context=None):
2460 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002461
Facundo Batista353750c2007-09-13 18:13:15 +00002462 If no rounding mode is specified, take the rounding mode from
2463 the context. This method raises the Rounded and Inexact flags
2464 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002465
Facundo Batista353750c2007-09-13 18:13:15 +00002466 See also: to_integral_value, which does exactly the same as
2467 this method except that it doesn't raise Inexact or Rounded.
2468 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002469 if self._is_special:
2470 ans = self._check_nans(context=context)
2471 if ans:
2472 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002473 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002474 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002475 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002476 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002477 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002478 if context is None:
2479 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002480 if rounding is None:
2481 rounding = context.rounding
2482 context._raise_error(Rounded)
2483 ans = self._rescale(0, rounding)
2484 if ans != self:
2485 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002486 return ans
2487
Facundo Batista353750c2007-09-13 18:13:15 +00002488 def to_integral_value(self, rounding=None, context=None):
2489 """Rounds to the nearest integer, without raising inexact, rounded."""
2490 if context is None:
2491 context = getcontext()
2492 if rounding is None:
2493 rounding = context.rounding
2494 if self._is_special:
2495 ans = self._check_nans(context=context)
2496 if ans:
2497 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002498 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002499 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002500 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002501 else:
2502 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503
Facundo Batista353750c2007-09-13 18:13:15 +00002504 # the method name changed, but we provide also the old one, for compatibility
2505 to_integral = to_integral_value
2506
2507 def sqrt(self, context=None):
2508 """Return the square root of self."""
Mark Dickinson3b24ccb2008-03-25 14:33:23 +00002509 if context is None:
2510 context = getcontext()
2511
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002512 if self._is_special:
2513 ans = self._check_nans(context=context)
2514 if ans:
2515 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002517 if self._isinfinity() and self._sign == 0:
2518 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002519
2520 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002521 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002522 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002523 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002524
2525 if self._sign == 1:
2526 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2527
Facundo Batista353750c2007-09-13 18:13:15 +00002528 # At this point self represents a positive number. Let p be
2529 # the desired precision and express self in the form c*100**e
2530 # with c a positive real number and e an integer, c and e
2531 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2532 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2533 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2534 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2535 # the closest integer to sqrt(c) with the even integer chosen
2536 # in the case of a tie.
2537 #
2538 # To ensure correct rounding in all cases, we use the
2539 # following trick: we compute the square root to an extra
2540 # place (precision p+1 instead of precision p), rounding down.
2541 # Then, if the result is inexact and its last digit is 0 or 5,
2542 # we increase the last digit to 1 or 6 respectively; if it's
2543 # exact we leave the last digit alone. Now the final round to
2544 # p places (or fewer in the case of underflow) will round
2545 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002546
Facundo Batista353750c2007-09-13 18:13:15 +00002547 # use an extra digit of precision
2548 prec = context.prec+1
2549
2550 # write argument in the form c*100**e where e = self._exp//2
2551 # is the 'ideal' exponent, to be used if the square root is
2552 # exactly representable. l is the number of 'digits' of c in
2553 # base 100, so that 100**(l-1) <= c < 100**l.
2554 op = _WorkRep(self)
2555 e = op.exp >> 1
2556 if op.exp & 1:
2557 c = op.int * 10
2558 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002559 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002560 c = op.int
2561 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002562
Facundo Batista353750c2007-09-13 18:13:15 +00002563 # rescale so that c has exactly prec base 100 'digits'
2564 shift = prec-l
2565 if shift >= 0:
2566 c *= 100**shift
2567 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002568 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002569 c, remainder = divmod(c, 100**-shift)
2570 exact = not remainder
2571 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002572
Facundo Batista353750c2007-09-13 18:13:15 +00002573 # find n = floor(sqrt(c)) using Newton's method
2574 n = 10**prec
2575 while True:
2576 q = c//n
2577 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002578 break
Facundo Batista353750c2007-09-13 18:13:15 +00002579 else:
2580 n = n + q >> 1
2581 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002582
Facundo Batista353750c2007-09-13 18:13:15 +00002583 if exact:
2584 # result is exact; rescale to use ideal exponent e
2585 if shift >= 0:
2586 # assert n % 10**shift == 0
2587 n //= 10**shift
2588 else:
2589 n *= 10**-shift
2590 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002591 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002592 # result is not exact; fix last digit as described above
2593 if n % 5 == 0:
2594 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002595
Facundo Batista72bc54f2007-11-23 17:59:00 +00002596 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002597
Facundo Batista353750c2007-09-13 18:13:15 +00002598 # round, and fit to current context
2599 context = context._shallow_copy()
2600 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002601 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002602 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002603
Facundo Batista353750c2007-09-13 18:13:15 +00002604 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002605
2606 def max(self, other, context=None):
2607 """Returns the larger value.
2608
Facundo Batista353750c2007-09-13 18:13:15 +00002609 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002610 NaN (and signals if one is sNaN). Also rounds.
2611 """
Facundo Batista353750c2007-09-13 18:13:15 +00002612 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002613
Facundo Batista6c398da2007-09-17 17:30:13 +00002614 if context is None:
2615 context = getcontext()
2616
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002617 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002618 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002619 # number is always returned
2620 sn = self._isnan()
2621 on = other._isnan()
2622 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002623 if on == 1 and sn == 0:
2624 return self._fix(context)
2625 if sn == 1 and on == 0:
2626 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002627 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002628
Mark Dickinson2fc92632008-02-06 22:10:50 +00002629 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002630 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002631 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002632 # then an ordering is applied:
2633 #
Facundo Batista59c58842007-04-10 12:58:45 +00002634 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002635 # positive sign and min returns the operand with the negative sign
2636 #
Facundo Batista59c58842007-04-10 12:58:45 +00002637 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002638 # the result. This is exactly the ordering used in compare_total.
2639 c = self.compare_total(other)
2640
2641 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002642 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002643 else:
2644 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002645
Facundo Batistae64acfa2007-12-17 14:18:42 +00002646 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002647
2648 def min(self, other, context=None):
2649 """Returns the smaller value.
2650
Facundo Batista59c58842007-04-10 12:58:45 +00002651 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002652 NaN (and signals if one is sNaN). Also rounds.
2653 """
Facundo Batista353750c2007-09-13 18:13:15 +00002654 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002655
Facundo Batista6c398da2007-09-17 17:30:13 +00002656 if context is None:
2657 context = getcontext()
2658
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002659 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002660 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002661 # number is always returned
2662 sn = self._isnan()
2663 on = other._isnan()
2664 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002665 if on == 1 and sn == 0:
2666 return self._fix(context)
2667 if sn == 1 and on == 0:
2668 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002669 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002670
Mark Dickinson2fc92632008-02-06 22:10:50 +00002671 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002672 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002673 c = self.compare_total(other)
2674
2675 if c == -1:
2676 ans = self
2677 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002678 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002679
Facundo Batistae64acfa2007-12-17 14:18:42 +00002680 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002681
2682 def _isinteger(self):
2683 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002684 if self._is_special:
2685 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002686 if self._exp >= 0:
2687 return True
2688 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002689 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002690
2691 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002692 """Returns True if self is even. Assumes self is an integer."""
2693 if not self or self._exp > 0:
2694 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002695 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002696
2697 def adjusted(self):
2698 """Return the adjusted exponent of self"""
2699 try:
2700 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002701 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002702 except TypeError:
2703 return 0
2704
Facundo Batista353750c2007-09-13 18:13:15 +00002705 def canonical(self, context=None):
2706 """Returns the same Decimal object.
2707
2708 As we do not have different encodings for the same number, the
2709 received object already is in its canonical form.
2710 """
2711 return self
2712
2713 def compare_signal(self, other, context=None):
2714 """Compares self to the other operand numerically.
2715
2716 It's pretty much like compare(), but all NaNs signal, with signaling
2717 NaNs taking precedence over quiet NaNs.
2718 """
Mark Dickinson2fc92632008-02-06 22:10:50 +00002719 other = _convert_other(other, raiseit = True)
2720 ans = self._compare_check_nans(other, context)
2721 if ans:
2722 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002723 return self.compare(other, context=context)
2724
2725 def compare_total(self, other):
2726 """Compares self to other using the abstract representations.
2727
2728 This is not like the standard compare, which use their numerical
2729 value. Note that a total ordering is defined for all possible abstract
2730 representations.
2731 """
Mark Dickinson0c673122009-10-29 12:04:00 +00002732 other = _convert_other(other, raiseit=True)
2733
Facundo Batista353750c2007-09-13 18:13:15 +00002734 # if one is negative and the other is positive, it's easy
2735 if self._sign and not other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002736 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002737 if not self._sign and other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002738 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002739 sign = self._sign
2740
2741 # let's handle both NaN types
2742 self_nan = self._isnan()
2743 other_nan = other._isnan()
2744 if self_nan or other_nan:
2745 if self_nan == other_nan:
Mark Dickinson7a7739d2009-08-28 13:25:02 +00002746 # compare payloads as though they're integers
2747 self_key = len(self._int), self._int
2748 other_key = len(other._int), other._int
2749 if self_key < other_key:
Facundo Batista353750c2007-09-13 18:13:15 +00002750 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002751 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002752 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002753 return _NegativeOne
Mark Dickinson7a7739d2009-08-28 13:25:02 +00002754 if self_key > other_key:
Facundo Batista353750c2007-09-13 18:13:15 +00002755 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002756 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002757 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002758 return _One
2759 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002760
2761 if sign:
2762 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002763 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002764 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002765 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002766 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002767 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002768 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002769 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002770 else:
2771 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002772 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002773 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002774 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002775 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002776 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002777 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002778 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002779
2780 if self < other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002781 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002782 if self > other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002783 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002784
2785 if self._exp < other._exp:
2786 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002787 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002788 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002789 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002790 if self._exp > other._exp:
2791 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002792 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002793 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002794 return _One
2795 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002796
2797
2798 def compare_total_mag(self, other):
2799 """Compares self to other using abstract repr., ignoring sign.
2800
2801 Like compare_total, but with operand's sign ignored and assumed to be 0.
2802 """
Mark Dickinson0c673122009-10-29 12:04:00 +00002803 other = _convert_other(other, raiseit=True)
2804
Facundo Batista353750c2007-09-13 18:13:15 +00002805 s = self.copy_abs()
2806 o = other.copy_abs()
2807 return s.compare_total(o)
2808
2809 def copy_abs(self):
2810 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002811 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002812
2813 def copy_negate(self):
2814 """Returns a copy with the sign inverted."""
2815 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002816 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002817 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002818 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002819
2820 def copy_sign(self, other):
2821 """Returns self with the sign of other."""
Mark Dickinson6d8effb2010-02-18 14:27:02 +00002822 other = _convert_other(other, raiseit=True)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002823 return _dec_from_triple(other._sign, self._int,
2824 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002825
2826 def exp(self, context=None):
2827 """Returns e ** self."""
2828
2829 if context is None:
2830 context = getcontext()
2831
2832 # exp(NaN) = NaN
2833 ans = self._check_nans(context=context)
2834 if ans:
2835 return ans
2836
2837 # exp(-Infinity) = 0
2838 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002839 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002840
2841 # exp(0) = 1
2842 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002843 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002844
2845 # exp(Infinity) = Infinity
2846 if self._isinfinity() == 1:
2847 return Decimal(self)
2848
2849 # the result is now guaranteed to be inexact (the true
2850 # mathematical result is transcendental). There's no need to
2851 # raise Rounded and Inexact here---they'll always be raised as
2852 # a result of the call to _fix.
2853 p = context.prec
2854 adj = self.adjusted()
2855
2856 # we only need to do any computation for quite a small range
2857 # of adjusted exponents---for example, -29 <= adj <= 10 for
2858 # the default context. For smaller exponent the result is
2859 # indistinguishable from 1 at the given precision, while for
2860 # larger exponent the result either overflows or underflows.
2861 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2862 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002863 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002864 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2865 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002866 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002867 elif self._sign == 0 and adj < -p:
2868 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002869 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002870 elif self._sign == 1 and adj < -p-1:
2871 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002872 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002873 # general case
2874 else:
2875 op = _WorkRep(self)
2876 c, e = op.int, op.exp
2877 if op.sign == 1:
2878 c = -c
2879
2880 # compute correctly rounded result: increase precision by
2881 # 3 digits at a time until we get an unambiguously
2882 # roundable result
2883 extra = 3
2884 while True:
2885 coeff, exp = _dexp(c, e, p+extra)
2886 if coeff % (5*10**(len(str(coeff))-p-1)):
2887 break
2888 extra += 3
2889
Facundo Batista72bc54f2007-11-23 17:59:00 +00002890 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002891
2892 # at this stage, ans should round correctly with *any*
2893 # rounding mode, not just with ROUND_HALF_EVEN
2894 context = context._shallow_copy()
2895 rounding = context._set_rounding(ROUND_HALF_EVEN)
2896 ans = ans._fix(context)
2897 context.rounding = rounding
2898
2899 return ans
2900
2901 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002902 """Return True if self is canonical; otherwise return False.
2903
2904 Currently, the encoding of a Decimal instance is always
2905 canonical, so this method returns True for any Decimal.
2906 """
2907 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002908
2909 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002910 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002911
Facundo Batista1a191df2007-10-02 17:01:24 +00002912 A Decimal instance is considered finite if it is neither
2913 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002914 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002915 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002916
2917 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002918 """Return True if self is infinite; otherwise return False."""
2919 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002920
2921 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002922 """Return True if self is a qNaN or sNaN; otherwise return False."""
2923 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002924
2925 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002926 """Return True if self is a normal number; otherwise return False."""
2927 if self._is_special or not self:
2928 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002929 if context is None:
2930 context = getcontext()
Mark Dickinsona7a52ab2009-10-20 13:33:03 +00002931 return context.Emin <= self.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +00002932
2933 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002934 """Return True if self is a quiet NaN; otherwise return False."""
2935 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002936
2937 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002938 """Return True if self is negative; otherwise return False."""
2939 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002940
2941 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002942 """Return True if self is a signaling NaN; otherwise return False."""
2943 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002944
2945 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002946 """Return True if self is subnormal; otherwise return False."""
2947 if self._is_special or not self:
2948 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002949 if context is None:
2950 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002951 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002952
2953 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002954 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002955 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002956
2957 def _ln_exp_bound(self):
2958 """Compute a lower bound for the adjusted exponent of self.ln().
2959 In other words, compute r such that self.ln() >= 10**r. Assumes
2960 that self is finite and positive and that self != 1.
2961 """
2962
2963 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2964 adj = self._exp + len(self._int) - 1
2965 if adj >= 1:
2966 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2967 return len(str(adj*23//10)) - 1
2968 if adj <= -2:
2969 # argument <= 0.1
2970 return len(str((-1-adj)*23//10)) - 1
2971 op = _WorkRep(self)
2972 c, e = op.int, op.exp
2973 if adj == 0:
2974 # 1 < self < 10
2975 num = str(c-10**-e)
2976 den = str(c)
2977 return len(num) - len(den) - (num < den)
2978 # adj == -1, 0.1 <= self < 1
2979 return e + len(str(10**-e - c)) - 1
2980
2981
2982 def ln(self, context=None):
2983 """Returns the natural (base e) logarithm of self."""
2984
2985 if context is None:
2986 context = getcontext()
2987
2988 # ln(NaN) = NaN
2989 ans = self._check_nans(context=context)
2990 if ans:
2991 return ans
2992
2993 # ln(0.0) == -Infinity
2994 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002995 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00002996
2997 # ln(Infinity) = Infinity
2998 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002999 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003000
3001 # ln(1.0) == 0.0
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003002 if self == _One:
3003 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00003004
3005 # ln(negative) raises InvalidOperation
3006 if self._sign == 1:
3007 return context._raise_error(InvalidOperation,
3008 'ln of a negative value')
3009
3010 # result is irrational, so necessarily inexact
3011 op = _WorkRep(self)
3012 c, e = op.int, op.exp
3013 p = context.prec
3014
3015 # correctly rounded result: repeatedly increase precision by 3
3016 # until we get an unambiguously roundable result
3017 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3018 while True:
3019 coeff = _dlog(c, e, places)
3020 # assert len(str(abs(coeff)))-p >= 1
3021 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3022 break
3023 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003024 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003025
3026 context = context._shallow_copy()
3027 rounding = context._set_rounding(ROUND_HALF_EVEN)
3028 ans = ans._fix(context)
3029 context.rounding = rounding
3030 return ans
3031
3032 def _log10_exp_bound(self):
3033 """Compute a lower bound for the adjusted exponent of self.log10().
3034 In other words, find r such that self.log10() >= 10**r.
3035 Assumes that self is finite and positive and that self != 1.
3036 """
3037
3038 # For x >= 10 or x < 0.1 we only need a bound on the integer
3039 # part of log10(self), and this comes directly from the
3040 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3041 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3042 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3043
3044 adj = self._exp + len(self._int) - 1
3045 if adj >= 1:
3046 # self >= 10
3047 return len(str(adj))-1
3048 if adj <= -2:
3049 # self < 0.1
3050 return len(str(-1-adj))-1
3051 op = _WorkRep(self)
3052 c, e = op.int, op.exp
3053 if adj == 0:
3054 # 1 < self < 10
3055 num = str(c-10**-e)
3056 den = str(231*c)
3057 return len(num) - len(den) - (num < den) + 2
3058 # adj == -1, 0.1 <= self < 1
3059 num = str(10**-e-c)
3060 return len(num) + e - (num < "231") - 1
3061
3062 def log10(self, context=None):
3063 """Returns the base 10 logarithm of self."""
3064
3065 if context is None:
3066 context = getcontext()
3067
3068 # log10(NaN) = NaN
3069 ans = self._check_nans(context=context)
3070 if ans:
3071 return ans
3072
3073 # log10(0.0) == -Infinity
3074 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003075 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003076
3077 # log10(Infinity) = Infinity
3078 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003079 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003080
3081 # log10(negative or -Infinity) raises InvalidOperation
3082 if self._sign == 1:
3083 return context._raise_error(InvalidOperation,
3084 'log10 of a negative value')
3085
3086 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00003087 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00003088 # answer may need rounding
3089 ans = Decimal(self._exp + len(self._int) - 1)
3090 else:
3091 # result is irrational, so necessarily inexact
3092 op = _WorkRep(self)
3093 c, e = op.int, op.exp
3094 p = context.prec
3095
3096 # correctly rounded result: repeatedly increase precision
3097 # until result is unambiguously roundable
3098 places = p-self._log10_exp_bound()+2
3099 while True:
3100 coeff = _dlog10(c, e, places)
3101 # assert len(str(abs(coeff)))-p >= 1
3102 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3103 break
3104 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003105 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003106
3107 context = context._shallow_copy()
3108 rounding = context._set_rounding(ROUND_HALF_EVEN)
3109 ans = ans._fix(context)
3110 context.rounding = rounding
3111 return ans
3112
3113 def logb(self, context=None):
3114 """ Returns the exponent of the magnitude of self's MSD.
3115
3116 The result is the integer which is the exponent of the magnitude
3117 of the most significant digit of self (as though it were truncated
3118 to a single digit while maintaining the value of that digit and
3119 without limiting the resulting exponent).
3120 """
3121 # logb(NaN) = NaN
3122 ans = self._check_nans(context=context)
3123 if ans:
3124 return ans
3125
3126 if context is None:
3127 context = getcontext()
3128
3129 # logb(+/-Inf) = +Inf
3130 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003131 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003132
3133 # logb(0) = -Inf, DivisionByZero
3134 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003135 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003136
3137 # otherwise, simply return the adjusted exponent of self, as a
3138 # Decimal. Note that no attempt is made to fit the result
3139 # into the current context.
Mark Dickinson15ae41c2009-10-07 19:22:05 +00003140 ans = Decimal(self.adjusted())
3141 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003142
3143 def _islogical(self):
3144 """Return True if self is a logical operand.
3145
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00003146 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00003147 an exponent of 0, and a coefficient whose digits must all be
3148 either 0 or 1.
3149 """
3150 if self._sign != 0 or self._exp != 0:
3151 return False
3152 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003153 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003154 return False
3155 return True
3156
3157 def _fill_logical(self, context, opa, opb):
3158 dif = context.prec - len(opa)
3159 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003160 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003161 elif dif < 0:
3162 opa = opa[-context.prec:]
3163 dif = context.prec - len(opb)
3164 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003165 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003166 elif dif < 0:
3167 opb = opb[-context.prec:]
3168 return opa, opb
3169
3170 def logical_and(self, other, context=None):
3171 """Applies an 'and' operation between self and other's digits."""
3172 if context is None:
3173 context = getcontext()
Mark Dickinson0c673122009-10-29 12:04:00 +00003174
3175 other = _convert_other(other, raiseit=True)
3176
Facundo Batista353750c2007-09-13 18:13:15 +00003177 if not self._islogical() or not other._islogical():
3178 return context._raise_error(InvalidOperation)
3179
3180 # fill to context.prec
3181 (opa, opb) = self._fill_logical(context, self._int, other._int)
3182
3183 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003184 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3185 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003186
3187 def logical_invert(self, context=None):
3188 """Invert all its digits."""
3189 if context is None:
3190 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003191 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3192 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003193
3194 def logical_or(self, other, context=None):
3195 """Applies an 'or' operation between self and other's digits."""
3196 if context is None:
3197 context = getcontext()
Mark Dickinson0c673122009-10-29 12:04:00 +00003198
3199 other = _convert_other(other, raiseit=True)
3200
Facundo Batista353750c2007-09-13 18:13:15 +00003201 if not self._islogical() or not other._islogical():
3202 return context._raise_error(InvalidOperation)
3203
3204 # fill to context.prec
3205 (opa, opb) = self._fill_logical(context, self._int, other._int)
3206
3207 # make the operation, and clean starting zeroes
Mark Dickinson65808ff2009-01-04 21:22:02 +00003208 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003209 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003210
3211 def logical_xor(self, other, context=None):
3212 """Applies an 'xor' operation between self and other's digits."""
3213 if context is None:
3214 context = getcontext()
Mark Dickinson0c673122009-10-29 12:04:00 +00003215
3216 other = _convert_other(other, raiseit=True)
3217
Facundo Batista353750c2007-09-13 18:13:15 +00003218 if not self._islogical() or not other._islogical():
3219 return context._raise_error(InvalidOperation)
3220
3221 # fill to context.prec
3222 (opa, opb) = self._fill_logical(context, self._int, other._int)
3223
3224 # make the operation, and clean starting zeroes
Mark Dickinson65808ff2009-01-04 21:22:02 +00003225 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003226 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003227
3228 def max_mag(self, other, context=None):
3229 """Compares the values numerically with their sign ignored."""
3230 other = _convert_other(other, raiseit=True)
3231
Facundo Batista6c398da2007-09-17 17:30:13 +00003232 if context is None:
3233 context = getcontext()
3234
Facundo Batista353750c2007-09-13 18:13:15 +00003235 if self._is_special or other._is_special:
3236 # If one operand is a quiet NaN and the other is number, then the
3237 # number is always returned
3238 sn = self._isnan()
3239 on = other._isnan()
3240 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003241 if on == 1 and sn == 0:
3242 return self._fix(context)
3243 if sn == 1 and on == 0:
3244 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003245 return self._check_nans(other, context)
3246
Mark Dickinson2fc92632008-02-06 22:10:50 +00003247 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003248 if c == 0:
3249 c = self.compare_total(other)
3250
3251 if c == -1:
3252 ans = other
3253 else:
3254 ans = self
3255
Facundo Batistae64acfa2007-12-17 14:18:42 +00003256 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003257
3258 def min_mag(self, other, context=None):
3259 """Compares the values numerically with their sign ignored."""
3260 other = _convert_other(other, raiseit=True)
3261
Facundo Batista6c398da2007-09-17 17:30:13 +00003262 if context is None:
3263 context = getcontext()
3264
Facundo Batista353750c2007-09-13 18:13:15 +00003265 if self._is_special or other._is_special:
3266 # If one operand is a quiet NaN and the other is number, then the
3267 # number is always returned
3268 sn = self._isnan()
3269 on = other._isnan()
3270 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003271 if on == 1 and sn == 0:
3272 return self._fix(context)
3273 if sn == 1 and on == 0:
3274 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003275 return self._check_nans(other, context)
3276
Mark Dickinson2fc92632008-02-06 22:10:50 +00003277 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003278 if c == 0:
3279 c = self.compare_total(other)
3280
3281 if c == -1:
3282 ans = self
3283 else:
3284 ans = other
3285
Facundo Batistae64acfa2007-12-17 14:18:42 +00003286 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003287
3288 def next_minus(self, context=None):
3289 """Returns the largest representable number smaller than itself."""
3290 if context is None:
3291 context = getcontext()
3292
3293 ans = self._check_nans(context=context)
3294 if ans:
3295 return ans
3296
3297 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003298 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003299 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003300 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003301
3302 context = context.copy()
3303 context._set_rounding(ROUND_FLOOR)
3304 context._ignore_all_flags()
3305 new_self = self._fix(context)
3306 if new_self != self:
3307 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003308 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3309 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003310
3311 def next_plus(self, context=None):
3312 """Returns the smallest representable number larger than itself."""
3313 if context is None:
3314 context = getcontext()
3315
3316 ans = self._check_nans(context=context)
3317 if ans:
3318 return ans
3319
3320 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003321 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003322 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003323 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003324
3325 context = context.copy()
3326 context._set_rounding(ROUND_CEILING)
3327 context._ignore_all_flags()
3328 new_self = self._fix(context)
3329 if new_self != self:
3330 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003331 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3332 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003333
3334 def next_toward(self, other, context=None):
3335 """Returns the number closest to self, in the direction towards other.
3336
3337 The result is the closest representable number to self
3338 (excluding self) that is in the direction towards other,
3339 unless both have the same value. If the two operands are
3340 numerically equal, then the result is a copy of self with the
3341 sign set to be the same as the sign of other.
3342 """
3343 other = _convert_other(other, raiseit=True)
3344
3345 if context is None:
3346 context = getcontext()
3347
3348 ans = self._check_nans(other, context)
3349 if ans:
3350 return ans
3351
Mark Dickinson2fc92632008-02-06 22:10:50 +00003352 comparison = self._cmp(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003353 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003354 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003355
3356 if comparison == -1:
3357 ans = self.next_plus(context)
3358 else: # comparison == 1
3359 ans = self.next_minus(context)
3360
3361 # decide which flags to raise using value of ans
3362 if ans._isinfinity():
3363 context._raise_error(Overflow,
3364 'Infinite result from next_toward',
3365 ans._sign)
3366 context._raise_error(Rounded)
3367 context._raise_error(Inexact)
3368 elif ans.adjusted() < context.Emin:
3369 context._raise_error(Underflow)
3370 context._raise_error(Subnormal)
3371 context._raise_error(Rounded)
3372 context._raise_error(Inexact)
3373 # if precision == 1 then we don't raise Clamped for a
3374 # result 0E-Etiny.
3375 if not ans:
3376 context._raise_error(Clamped)
3377
3378 return ans
3379
3380 def number_class(self, context=None):
3381 """Returns an indication of the class of self.
3382
3383 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003384 sNaN
3385 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003386 -Infinity
3387 -Normal
3388 -Subnormal
3389 -Zero
3390 +Zero
3391 +Subnormal
3392 +Normal
3393 +Infinity
3394 """
3395 if self.is_snan():
3396 return "sNaN"
3397 if self.is_qnan():
3398 return "NaN"
3399 inf = self._isinfinity()
3400 if inf == 1:
3401 return "+Infinity"
3402 if inf == -1:
3403 return "-Infinity"
3404 if self.is_zero():
3405 if self._sign:
3406 return "-Zero"
3407 else:
3408 return "+Zero"
3409 if context is None:
3410 context = getcontext()
3411 if self.is_subnormal(context=context):
3412 if self._sign:
3413 return "-Subnormal"
3414 else:
3415 return "+Subnormal"
3416 # just a normal, regular, boring number, :)
3417 if self._sign:
3418 return "-Normal"
3419 else:
3420 return "+Normal"
3421
3422 def radix(self):
3423 """Just returns 10, as this is Decimal, :)"""
3424 return Decimal(10)
3425
3426 def rotate(self, other, context=None):
3427 """Returns a rotated copy of self, value-of-other times."""
3428 if context is None:
3429 context = getcontext()
3430
Mark Dickinson0c673122009-10-29 12:04:00 +00003431 other = _convert_other(other, raiseit=True)
3432
Facundo Batista353750c2007-09-13 18:13:15 +00003433 ans = self._check_nans(other, context)
3434 if ans:
3435 return ans
3436
3437 if other._exp != 0:
3438 return context._raise_error(InvalidOperation)
3439 if not (-context.prec <= int(other) <= context.prec):
3440 return context._raise_error(InvalidOperation)
3441
3442 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003443 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003444
3445 # get values, pad if necessary
3446 torot = int(other)
3447 rotdig = self._int
3448 topad = context.prec - len(rotdig)
Mark Dickinson6f390012009-10-29 12:11:18 +00003449 if topad > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003450 rotdig = '0'*topad + rotdig
Mark Dickinson6f390012009-10-29 12:11:18 +00003451 elif topad < 0:
3452 rotdig = rotdig[-topad:]
Facundo Batista353750c2007-09-13 18:13:15 +00003453
3454 # let's rotate!
3455 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003456 return _dec_from_triple(self._sign,
3457 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003458
Mark Dickinson0c673122009-10-29 12:04:00 +00003459 def scaleb(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00003460 """Returns self operand after adding the second value to its exp."""
3461 if context is None:
3462 context = getcontext()
3463
Mark Dickinson0c673122009-10-29 12:04:00 +00003464 other = _convert_other(other, raiseit=True)
3465
Facundo Batista353750c2007-09-13 18:13:15 +00003466 ans = self._check_nans(other, context)
3467 if ans:
3468 return ans
3469
3470 if other._exp != 0:
3471 return context._raise_error(InvalidOperation)
3472 liminf = -2 * (context.Emax + context.prec)
3473 limsup = 2 * (context.Emax + context.prec)
3474 if not (liminf <= int(other) <= limsup):
3475 return context._raise_error(InvalidOperation)
3476
3477 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003478 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003479
Facundo Batista72bc54f2007-11-23 17:59:00 +00003480 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003481 d = d._fix(context)
3482 return d
3483
3484 def shift(self, other, context=None):
3485 """Returns a shifted copy of self, value-of-other times."""
3486 if context is None:
3487 context = getcontext()
3488
Mark Dickinson0c673122009-10-29 12:04:00 +00003489 other = _convert_other(other, raiseit=True)
3490
Facundo Batista353750c2007-09-13 18:13:15 +00003491 ans = self._check_nans(other, context)
3492 if ans:
3493 return ans
3494
3495 if other._exp != 0:
3496 return context._raise_error(InvalidOperation)
3497 if not (-context.prec <= int(other) <= context.prec):
3498 return context._raise_error(InvalidOperation)
3499
3500 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003501 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003502
3503 # get values, pad if necessary
3504 torot = int(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003505 rotdig = self._int
3506 topad = context.prec - len(rotdig)
Mark Dickinson6f390012009-10-29 12:11:18 +00003507 if topad > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003508 rotdig = '0'*topad + rotdig
Mark Dickinson6f390012009-10-29 12:11:18 +00003509 elif topad < 0:
3510 rotdig = rotdig[-topad:]
Facundo Batista353750c2007-09-13 18:13:15 +00003511
3512 # let's shift!
3513 if torot < 0:
Mark Dickinson6f390012009-10-29 12:11:18 +00003514 shifted = rotdig[:torot]
Facundo Batista353750c2007-09-13 18:13:15 +00003515 else:
Mark Dickinson6f390012009-10-29 12:11:18 +00003516 shifted = rotdig + '0'*torot
3517 shifted = shifted[-context.prec:]
Facundo Batista353750c2007-09-13 18:13:15 +00003518
Facundo Batista72bc54f2007-11-23 17:59:00 +00003519 return _dec_from_triple(self._sign,
Mark Dickinson6f390012009-10-29 12:11:18 +00003520 shifted.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003521
Facundo Batista59c58842007-04-10 12:58:45 +00003522 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003523 def __reduce__(self):
3524 return (self.__class__, (str(self),))
3525
3526 def __copy__(self):
Benjamin Peterson28e369a2010-01-25 03:58:21 +00003527 if type(self) is Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003528 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003529 return self.__class__(str(self))
3530
3531 def __deepcopy__(self, memo):
Benjamin Peterson28e369a2010-01-25 03:58:21 +00003532 if type(self) is Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003533 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003534 return self.__class__(str(self))
3535
Mark Dickinson277859d2009-03-17 23:03:46 +00003536 # PEP 3101 support. the _localeconv keyword argument should be
3537 # considered private: it's provided for ease of testing only.
3538 def __format__(self, specifier, context=None, _localeconv=None):
Mark Dickinsonf4da7772008-02-29 03:29:17 +00003539 """Format a Decimal instance according to the given specifier.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003540
3541 The specifier should be a standard format specifier, with the
3542 form described in PEP 3101. Formatting types 'e', 'E', 'f',
Mark Dickinson277859d2009-03-17 23:03:46 +00003543 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3544 type is omitted it defaults to 'g' or 'G', depending on the
3545 value of context.capitals.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003546 """
3547
3548 # Note: PEP 3101 says that if the type is not present then
3549 # there should be at least one digit after the decimal point.
3550 # We take the liberty of ignoring this requirement for
3551 # Decimal---it's presumably there to make sure that
3552 # format(float, '') behaves similarly to str(float).
3553 if context is None:
3554 context = getcontext()
3555
Mark Dickinson277859d2009-03-17 23:03:46 +00003556 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003557
Mark Dickinson277859d2009-03-17 23:03:46 +00003558 # special values don't care about the type or precision
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003559 if self._is_special:
Mark Dickinson277859d2009-03-17 23:03:46 +00003560 sign = _format_sign(self._sign, spec)
3561 body = str(self.copy_abs())
3562 return _format_align(sign, body, spec)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003563
3564 # a type of None defaults to 'g' or 'G', depending on context
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003565 if spec['type'] is None:
3566 spec['type'] = ['g', 'G'][context.capitals]
Mark Dickinson277859d2009-03-17 23:03:46 +00003567
3568 # if type is '%', adjust exponent of self accordingly
3569 if spec['type'] == '%':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003570 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3571
3572 # round if necessary, taking rounding mode from the context
3573 rounding = context.rounding
3574 precision = spec['precision']
3575 if precision is not None:
3576 if spec['type'] in 'eE':
3577 self = self._round(precision+1, rounding)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003578 elif spec['type'] in 'fF%':
3579 self = self._rescale(-precision, rounding)
Mark Dickinson277859d2009-03-17 23:03:46 +00003580 elif spec['type'] in 'gG' and len(self._int) > precision:
3581 self = self._round(precision, rounding)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003582 # special case: zeros with a positive exponent can't be
3583 # represented in fixed point; rescale them to 0e0.
Mark Dickinson277859d2009-03-17 23:03:46 +00003584 if not self and self._exp > 0 and spec['type'] in 'fF%':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003585 self = self._rescale(0, rounding)
3586
3587 # figure out placement of the decimal point
3588 leftdigits = self._exp + len(self._int)
Mark Dickinson277859d2009-03-17 23:03:46 +00003589 if spec['type'] in 'eE':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003590 if not self and precision is not None:
3591 dotplace = 1 - precision
3592 else:
3593 dotplace = 1
Mark Dickinson277859d2009-03-17 23:03:46 +00003594 elif spec['type'] in 'fF%':
3595 dotplace = leftdigits
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003596 elif spec['type'] in 'gG':
3597 if self._exp <= 0 and leftdigits > -6:
3598 dotplace = leftdigits
3599 else:
3600 dotplace = 1
3601
Mark Dickinson277859d2009-03-17 23:03:46 +00003602 # find digits before and after decimal point, and get exponent
3603 if dotplace < 0:
3604 intpart = '0'
3605 fracpart = '0'*(-dotplace) + self._int
3606 elif dotplace > len(self._int):
3607 intpart = self._int + '0'*(dotplace-len(self._int))
3608 fracpart = ''
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003609 else:
Mark Dickinson277859d2009-03-17 23:03:46 +00003610 intpart = self._int[:dotplace] or '0'
3611 fracpart = self._int[dotplace:]
3612 exp = leftdigits-dotplace
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003613
Mark Dickinson277859d2009-03-17 23:03:46 +00003614 # done with the decimal-specific stuff; hand over the rest
3615 # of the formatting to the _format_number function
3616 return _format_number(self._sign, intpart, fracpart, exp, spec)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003617
Facundo Batista72bc54f2007-11-23 17:59:00 +00003618def _dec_from_triple(sign, coefficient, exponent, special=False):
3619 """Create a decimal instance directly, without any validation,
3620 normalization (e.g. removal of leading zeros) or argument
3621 conversion.
3622
3623 This function is for *internal use only*.
3624 """
3625
3626 self = object.__new__(Decimal)
3627 self._sign = sign
3628 self._int = coefficient
3629 self._exp = exponent
3630 self._is_special = special
3631
3632 return self
3633
Raymond Hettinger2c8585b2009-02-03 03:37:03 +00003634# Register Decimal as a kind of Number (an abstract base class).
3635# However, do not register it as Real (because Decimals are not
3636# interoperable with floats).
3637_numbers.Number.register(Decimal)
3638
3639
Facundo Batista59c58842007-04-10 12:58:45 +00003640##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003641
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003642
3643# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003644rounding_functions = [name for name in Decimal.__dict__.keys()
3645 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003646for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003647 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003648 globalname = name[1:].upper()
3649 val = globals()[globalname]
3650 Decimal._pick_rounding_function[val] = name
3651
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003652del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003653
Nick Coghlanced12182006-09-02 03:54:17 +00003654class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003655 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003656
Nick Coghlanced12182006-09-02 03:54:17 +00003657 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003658 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003659 """
3660 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003661 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003662 def __enter__(self):
3663 self.saved_context = getcontext()
3664 setcontext(self.new_context)
3665 return self.new_context
3666 def __exit__(self, t, v, tb):
3667 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003668
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003669class Context(object):
3670 """Contains the context for a Decimal instance.
3671
3672 Contains:
3673 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003674 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003675 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003676 raised when it is caused. Otherwise, a value is
3677 substituted in.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003678 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003679 (Whether or not the trap_enabler is set)
3680 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003681 Emin - Minimum exponent
3682 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003683 capitals - If 1, 1*10^1 is printed as 1E+1.
3684 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003685 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003686 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003687
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003688 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003689 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003690 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003691 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003692 _ignored_flags=None):
3693 if flags is None:
3694 flags = []
3695 if _ignored_flags is None:
3696 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003697 if not isinstance(flags, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003698 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003699 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003700 if traps is not None and not isinstance(traps, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003701 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003702 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003703 for name, val in locals().items():
3704 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003705 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003706 else:
3707 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003708 del self.self
3709
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003710 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003711 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003712 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003713 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3714 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3715 % vars(self))
3716 names = [f.__name__ for f, v in self.flags.items() if v]
3717 s.append('flags=[' + ', '.join(names) + ']')
3718 names = [t.__name__ for t, v in self.traps.items() if v]
3719 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003720 return ', '.join(s) + ')'
3721
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003722 def clear_flags(self):
3723 """Reset all flags to zero"""
3724 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003725 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003726
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003727 def _shallow_copy(self):
3728 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003729 nc = Context(self.prec, self.rounding, self.traps,
3730 self.flags, self.Emin, self.Emax,
3731 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003732 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003733
3734 def copy(self):
3735 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003736 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003737 self.flags.copy(), self.Emin, self.Emax,
3738 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003739 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003740 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003741
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003742 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003743 """Handles an error
3744
3745 If the flag is in _ignored_flags, returns the default response.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003746 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003747 trap_enabler is set, it reaises the exception. Otherwise, it returns
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003748 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003749 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003750 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003751 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003752 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003753 return error().handle(self, *args)
3754
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003755 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003756 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003757 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003758 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003759
3760 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003761 # self._ignored_flags = []
Mark Dickinson8aca9d02008-05-04 02:05:06 +00003762 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003763
3764 def _ignore_all_flags(self):
3765 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003766 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003767
3768 def _ignore_flags(self, *flags):
3769 """Ignore the flags, if they are raised"""
3770 # Do not mutate-- This way, copies of a context leave the original
3771 # alone.
3772 self._ignored_flags = (self._ignored_flags + list(flags))
3773 return list(flags)
3774
3775 def _regard_flags(self, *flags):
3776 """Stop ignoring the flags, if they are raised"""
3777 if flags and isinstance(flags[0], (tuple,list)):
3778 flags = flags[0]
3779 for flag in flags:
3780 self._ignored_flags.remove(flag)
3781
Nick Coghlan53663a62008-07-15 14:27:37 +00003782 # We inherit object.__hash__, so we must deny this explicitly
3783 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003784
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003785 def Etiny(self):
3786 """Returns Etiny (= Emin - prec + 1)"""
3787 return int(self.Emin - self.prec + 1)
3788
3789 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003790 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003791 return int(self.Emax - self.prec + 1)
3792
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003793 def _set_rounding(self, type):
3794 """Sets the rounding type.
3795
3796 Sets the rounding type, and returns the current (previous)
3797 rounding type. Often used like:
3798
3799 context = context.copy()
3800 # so you don't change the calling context
3801 # if an error occurs in the middle.
3802 rounding = context._set_rounding(ROUND_UP)
3803 val = self.__sub__(other, context=context)
3804 context._set_rounding(rounding)
3805
3806 This will make it round up for that operation.
3807 """
3808 rounding = self.rounding
3809 self.rounding= type
3810 return rounding
3811
Raymond Hettingerfed52962004-07-14 15:41:57 +00003812 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003813 """Creates a new Decimal instance but using self as context.
3814
3815 This method implements the to-number operation of the
3816 IBM Decimal specification."""
3817
3818 if isinstance(num, basestring) and num != num.strip():
3819 return self._raise_error(ConversionSyntax,
3820 "no trailing or leading whitespace is "
3821 "permitted.")
3822
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003823 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003824 if d._isnan() and len(d._int) > self.prec - self._clamp:
3825 return self._raise_error(ConversionSyntax,
3826 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003827 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003828
Raymond Hettingerf4d85972009-01-03 19:02:23 +00003829 def create_decimal_from_float(self, f):
3830 """Creates a new Decimal instance from a float but rounding using self
3831 as the context.
3832
3833 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3834 >>> context.create_decimal_from_float(3.1415926535897932)
3835 Decimal('3.1415')
3836 >>> context = Context(prec=5, traps=[Inexact])
3837 >>> context.create_decimal_from_float(3.1415926535897932)
3838 Traceback (most recent call last):
3839 ...
3840 Inexact: None
3841
3842 """
3843 d = Decimal.from_float(f) # An exact conversion
3844 return d._fix(self) # Apply the context rounding
3845
Facundo Batista59c58842007-04-10 12:58:45 +00003846 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003847 def abs(self, a):
3848 """Returns the absolute value of the operand.
3849
3850 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003851 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003852 the plus operation on the operand.
3853
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003854 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003855 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003856 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003857 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003858 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003859 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003860 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003861 Decimal('101.5')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003862 >>> ExtendedContext.abs(-1)
3863 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003864 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003865 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003866 return a.__abs__(context=self)
3867
3868 def add(self, a, b):
3869 """Return the sum of the two operands.
3870
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003871 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003872 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003873 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003874 Decimal('1.02E+4')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003875 >>> ExtendedContext.add(1, Decimal(2))
3876 Decimal('3')
3877 >>> ExtendedContext.add(Decimal(8), 5)
3878 Decimal('13')
3879 >>> ExtendedContext.add(5, 5)
3880 Decimal('10')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003881 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003882 a = _convert_other(a, raiseit=True)
3883 r = a.__add__(b, context=self)
3884 if r is NotImplemented:
3885 raise TypeError("Unable to convert %s to Decimal" % b)
3886 else:
3887 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003888
3889 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003890 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003891
Facundo Batista353750c2007-09-13 18:13:15 +00003892 def canonical(self, a):
3893 """Returns the same Decimal object.
3894
3895 As we do not have different encodings for the same number, the
3896 received object already is in its canonical form.
3897
3898 >>> ExtendedContext.canonical(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003899 Decimal('2.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003900 """
3901 return a.canonical(context=self)
3902
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003903 def compare(self, a, b):
3904 """Compares values numerically.
3905
3906 If the signs of the operands differ, a value representing each operand
3907 ('-1' if the operand is less than zero, '0' if the operand is zero or
3908 negative zero, or '1' if the operand is greater than zero) is used in
3909 place of that operand for the comparison instead of the actual
3910 operand.
3911
3912 The comparison is then effected by subtracting the second operand from
3913 the first and then returning a value according to the result of the
3914 subtraction: '-1' if the result is less than zero, '0' if the result is
3915 zero or negative zero, or '1' if the result is greater than zero.
3916
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003917 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003918 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003919 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003920 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003921 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003922 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003923 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003924 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003925 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003926 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003927 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003928 Decimal('-1')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003929 >>> ExtendedContext.compare(1, 2)
3930 Decimal('-1')
3931 >>> ExtendedContext.compare(Decimal(1), 2)
3932 Decimal('-1')
3933 >>> ExtendedContext.compare(1, Decimal(2))
3934 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003935 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003936 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003937 return a.compare(b, context=self)
3938
Facundo Batista353750c2007-09-13 18:13:15 +00003939 def compare_signal(self, a, b):
3940 """Compares the values of the two operands numerically.
3941
3942 It's pretty much like compare(), but all NaNs signal, with signaling
3943 NaNs taking precedence over quiet NaNs.
3944
3945 >>> c = ExtendedContext
3946 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003947 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003948 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003949 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003950 >>> c.flags[InvalidOperation] = 0
3951 >>> print c.flags[InvalidOperation]
3952 0
3953 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003954 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003955 >>> print c.flags[InvalidOperation]
3956 1
3957 >>> c.flags[InvalidOperation] = 0
3958 >>> print c.flags[InvalidOperation]
3959 0
3960 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003961 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003962 >>> print c.flags[InvalidOperation]
3963 1
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003964 >>> c.compare_signal(-1, 2)
3965 Decimal('-1')
3966 >>> c.compare_signal(Decimal(-1), 2)
3967 Decimal('-1')
3968 >>> c.compare_signal(-1, Decimal(2))
3969 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003970 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003971 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00003972 return a.compare_signal(b, context=self)
3973
3974 def compare_total(self, a, b):
3975 """Compares two operands using their abstract representation.
3976
3977 This is not like the standard compare, which use their numerical
3978 value. Note that a total ordering is defined for all possible abstract
3979 representations.
3980
3981 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003982 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003983 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003984 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003985 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003986 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003987 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003988 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003989 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003990 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00003991 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003992 Decimal('-1')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00003993 >>> ExtendedContext.compare_total(1, 2)
3994 Decimal('-1')
3995 >>> ExtendedContext.compare_total(Decimal(1), 2)
3996 Decimal('-1')
3997 >>> ExtendedContext.compare_total(1, Decimal(2))
3998 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003999 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004000 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004001 return a.compare_total(b)
4002
4003 def compare_total_mag(self, a, b):
4004 """Compares two operands using their abstract representation ignoring sign.
4005
4006 Like compare_total, but with operand's sign ignored and assumed to be 0.
4007 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004008 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004009 return a.compare_total_mag(b)
4010
4011 def copy_abs(self, a):
4012 """Returns a copy of the operand with the sign set to 0.
4013
4014 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004015 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00004016 >>> ExtendedContext.copy_abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004017 Decimal('100')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004018 >>> ExtendedContext.copy_abs(-1)
4019 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004020 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004021 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004022 return a.copy_abs()
4023
4024 def copy_decimal(self, a):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004025 """Returns a copy of the decimal object.
Facundo Batista353750c2007-09-13 18:13:15 +00004026
4027 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004028 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00004029 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004030 Decimal('-1.00')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004031 >>> ExtendedContext.copy_decimal(1)
4032 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004033 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004034 a = _convert_other(a, raiseit=True)
Facundo Batista6c398da2007-09-17 17:30:13 +00004035 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00004036
4037 def copy_negate(self, a):
4038 """Returns a copy of the operand with the sign inverted.
4039
4040 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004041 Decimal('-101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00004042 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004043 Decimal('101.5')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004044 >>> ExtendedContext.copy_negate(1)
4045 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004046 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004047 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004048 return a.copy_negate()
4049
4050 def copy_sign(self, a, b):
4051 """Copies the second operand's sign to the first one.
4052
4053 In detail, it returns a copy of the first operand with the sign
4054 equal to the sign of the second operand.
4055
4056 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004057 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004058 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004059 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004060 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004061 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004062 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004063 Decimal('-1.50')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004064 >>> ExtendedContext.copy_sign(1, -2)
4065 Decimal('-1')
4066 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4067 Decimal('-1')
4068 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4069 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00004070 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004071 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004072 return a.copy_sign(b)
4073
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004074 def divide(self, a, b):
4075 """Decimal division in a specified context.
4076
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004077 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004078 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004079 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004080 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004081 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004082 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004083 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004084 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004085 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004086 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004087 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004088 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004089 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004090 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004091 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004092 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004093 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004094 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004095 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004096 Decimal('1.20E+6')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004097 >>> ExtendedContext.divide(5, 5)
4098 Decimal('1')
4099 >>> ExtendedContext.divide(Decimal(5), 5)
4100 Decimal('1')
4101 >>> ExtendedContext.divide(5, Decimal(5))
4102 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004103 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004104 a = _convert_other(a, raiseit=True)
4105 r = a.__div__(b, context=self)
4106 if r is NotImplemented:
4107 raise TypeError("Unable to convert %s to Decimal" % b)
4108 else:
4109 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004110
4111 def divide_int(self, a, b):
4112 """Divides two numbers and returns the integer part of the result.
4113
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004114 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004115 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004116 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004117 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004118 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004119 Decimal('3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004120 >>> ExtendedContext.divide_int(10, 3)
4121 Decimal('3')
4122 >>> ExtendedContext.divide_int(Decimal(10), 3)
4123 Decimal('3')
4124 >>> ExtendedContext.divide_int(10, Decimal(3))
4125 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004126 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004127 a = _convert_other(a, raiseit=True)
4128 r = a.__floordiv__(b, context=self)
4129 if r is NotImplemented:
4130 raise TypeError("Unable to convert %s to Decimal" % b)
4131 else:
4132 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004133
4134 def divmod(self, a, b):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004135 """Return (a // b, a % b).
Mark Dickinson202eb902010-01-06 16:20:22 +00004136
4137 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4138 (Decimal('2'), Decimal('2'))
4139 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4140 (Decimal('2'), Decimal('0'))
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004141 >>> ExtendedContext.divmod(8, 4)
4142 (Decimal('2'), Decimal('0'))
4143 >>> ExtendedContext.divmod(Decimal(8), 4)
4144 (Decimal('2'), Decimal('0'))
4145 >>> ExtendedContext.divmod(8, Decimal(4))
4146 (Decimal('2'), Decimal('0'))
Mark Dickinson202eb902010-01-06 16:20:22 +00004147 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004148 a = _convert_other(a, raiseit=True)
4149 r = a.__divmod__(b, context=self)
4150 if r is NotImplemented:
4151 raise TypeError("Unable to convert %s to Decimal" % b)
4152 else:
4153 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004154
Facundo Batista353750c2007-09-13 18:13:15 +00004155 def exp(self, a):
4156 """Returns e ** a.
4157
4158 >>> c = ExtendedContext.copy()
4159 >>> c.Emin = -999
4160 >>> c.Emax = 999
4161 >>> c.exp(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004162 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004163 >>> c.exp(Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004164 Decimal('0.367879441')
Facundo Batista353750c2007-09-13 18:13:15 +00004165 >>> c.exp(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004166 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004167 >>> c.exp(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004168 Decimal('2.71828183')
Facundo Batista353750c2007-09-13 18:13:15 +00004169 >>> c.exp(Decimal('0.693147181'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004170 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004171 >>> c.exp(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004172 Decimal('Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004173 >>> c.exp(10)
4174 Decimal('22026.4658')
Facundo Batista353750c2007-09-13 18:13:15 +00004175 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004176 a =_convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004177 return a.exp(context=self)
4178
4179 def fma(self, a, b, c):
4180 """Returns a multiplied by b, plus c.
4181
4182 The first two operands are multiplied together, using multiply,
4183 the third operand is then added to the result of that
4184 multiplication, using add, all with only one final rounding.
4185
4186 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004187 Decimal('22')
Facundo Batista353750c2007-09-13 18:13:15 +00004188 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004189 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004190 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004191 Decimal('1.38435736E+12')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004192 >>> ExtendedContext.fma(1, 3, 4)
4193 Decimal('7')
4194 >>> ExtendedContext.fma(1, Decimal(3), 4)
4195 Decimal('7')
4196 >>> ExtendedContext.fma(1, 3, Decimal(4))
4197 Decimal('7')
Facundo Batista353750c2007-09-13 18:13:15 +00004198 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004199 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004200 return a.fma(b, c, context=self)
4201
4202 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004203 """Return True if the operand is canonical; otherwise return False.
4204
4205 Currently, the encoding of a Decimal instance is always
4206 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00004207
4208 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004209 True
Facundo Batista353750c2007-09-13 18:13:15 +00004210 """
Facundo Batista1a191df2007-10-02 17:01:24 +00004211 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00004212
4213 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004214 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004215
Facundo Batista1a191df2007-10-02 17:01:24 +00004216 A Decimal instance is considered finite if it is neither
4217 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00004218
4219 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004220 True
Facundo Batista353750c2007-09-13 18:13:15 +00004221 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004222 True
Facundo Batista353750c2007-09-13 18:13:15 +00004223 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004224 True
Facundo Batista353750c2007-09-13 18:13:15 +00004225 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004226 False
Facundo Batista353750c2007-09-13 18:13:15 +00004227 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004228 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004229 >>> ExtendedContext.is_finite(1)
4230 True
Facundo Batista353750c2007-09-13 18:13:15 +00004231 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004232 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004233 return a.is_finite()
4234
4235 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004236 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004237
4238 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004239 False
Facundo Batista353750c2007-09-13 18:13:15 +00004240 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004241 True
Facundo Batista353750c2007-09-13 18:13:15 +00004242 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004243 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004244 >>> ExtendedContext.is_infinite(1)
4245 False
Facundo Batista353750c2007-09-13 18:13:15 +00004246 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004247 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004248 return a.is_infinite()
4249
4250 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004251 """Return True if the operand is a qNaN or sNaN;
4252 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004253
4254 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004255 False
Facundo Batista353750c2007-09-13 18:13:15 +00004256 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004257 True
Facundo Batista353750c2007-09-13 18:13:15 +00004258 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004259 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004260 >>> ExtendedContext.is_nan(1)
4261 False
Facundo Batista353750c2007-09-13 18:13:15 +00004262 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004263 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004264 return a.is_nan()
4265
4266 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004267 """Return True if the operand is a normal number;
4268 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004269
4270 >>> c = ExtendedContext.copy()
4271 >>> c.Emin = -999
4272 >>> c.Emax = 999
4273 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004274 True
Facundo Batista353750c2007-09-13 18:13:15 +00004275 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004276 False
Facundo Batista353750c2007-09-13 18:13:15 +00004277 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004278 False
Facundo Batista353750c2007-09-13 18:13:15 +00004279 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004280 False
Facundo Batista353750c2007-09-13 18:13:15 +00004281 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004282 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004283 >>> c.is_normal(1)
4284 True
Facundo Batista353750c2007-09-13 18:13:15 +00004285 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004286 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004287 return a.is_normal(context=self)
4288
4289 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004290 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004291
4292 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004293 False
Facundo Batista353750c2007-09-13 18:13:15 +00004294 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004295 True
Facundo Batista353750c2007-09-13 18:13:15 +00004296 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004297 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004298 >>> ExtendedContext.is_qnan(1)
4299 False
Facundo Batista353750c2007-09-13 18:13:15 +00004300 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004301 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004302 return a.is_qnan()
4303
4304 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004305 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004306
4307 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004308 False
Facundo Batista353750c2007-09-13 18:13:15 +00004309 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004310 True
Facundo Batista353750c2007-09-13 18:13:15 +00004311 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004312 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004313 >>> ExtendedContext.is_signed(8)
4314 False
4315 >>> ExtendedContext.is_signed(-8)
4316 True
Facundo Batista353750c2007-09-13 18:13:15 +00004317 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004318 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004319 return a.is_signed()
4320
4321 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004322 """Return True if the operand is a signaling NaN;
4323 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004324
4325 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004326 False
Facundo Batista353750c2007-09-13 18:13:15 +00004327 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004328 False
Facundo Batista353750c2007-09-13 18:13:15 +00004329 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004330 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004331 >>> ExtendedContext.is_snan(1)
4332 False
Facundo Batista353750c2007-09-13 18:13:15 +00004333 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004334 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004335 return a.is_snan()
4336
4337 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004338 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004339
4340 >>> c = ExtendedContext.copy()
4341 >>> c.Emin = -999
4342 >>> c.Emax = 999
4343 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004344 False
Facundo Batista353750c2007-09-13 18:13:15 +00004345 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004346 True
Facundo Batista353750c2007-09-13 18:13:15 +00004347 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004348 False
Facundo Batista353750c2007-09-13 18:13:15 +00004349 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004350 False
Facundo Batista353750c2007-09-13 18:13:15 +00004351 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004352 False
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004353 >>> c.is_subnormal(1)
4354 False
Facundo Batista353750c2007-09-13 18:13:15 +00004355 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004356 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004357 return a.is_subnormal(context=self)
4358
4359 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004360 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004361
4362 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004363 True
Facundo Batista353750c2007-09-13 18:13:15 +00004364 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004365 False
Facundo Batista353750c2007-09-13 18:13:15 +00004366 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004367 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004368 >>> ExtendedContext.is_zero(1)
4369 False
4370 >>> ExtendedContext.is_zero(0)
4371 True
Facundo Batista353750c2007-09-13 18:13:15 +00004372 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004373 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004374 return a.is_zero()
4375
4376 def ln(self, a):
4377 """Returns the natural (base e) logarithm of the operand.
4378
4379 >>> c = ExtendedContext.copy()
4380 >>> c.Emin = -999
4381 >>> c.Emax = 999
4382 >>> c.ln(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004383 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004384 >>> c.ln(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004385 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004386 >>> c.ln(Decimal('2.71828183'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004387 Decimal('1.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004388 >>> c.ln(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004389 Decimal('2.30258509')
Facundo Batista353750c2007-09-13 18:13:15 +00004390 >>> c.ln(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004391 Decimal('Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004392 >>> c.ln(1)
4393 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004394 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004395 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004396 return a.ln(context=self)
4397
4398 def log10(self, a):
4399 """Returns the base 10 logarithm of the operand.
4400
4401 >>> c = ExtendedContext.copy()
4402 >>> c.Emin = -999
4403 >>> c.Emax = 999
4404 >>> c.log10(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004405 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004406 >>> c.log10(Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004407 Decimal('-3')
Facundo Batista353750c2007-09-13 18:13:15 +00004408 >>> c.log10(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004409 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004410 >>> c.log10(Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004411 Decimal('0.301029996')
Facundo Batista353750c2007-09-13 18:13:15 +00004412 >>> c.log10(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004413 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004414 >>> c.log10(Decimal('70'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004415 Decimal('1.84509804')
Facundo Batista353750c2007-09-13 18:13:15 +00004416 >>> c.log10(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004417 Decimal('Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004418 >>> c.log10(0)
4419 Decimal('-Infinity')
4420 >>> c.log10(1)
4421 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004422 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004423 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004424 return a.log10(context=self)
4425
4426 def logb(self, a):
4427 """ Returns the exponent of the magnitude of the operand's MSD.
4428
4429 The result is the integer which is the exponent of the magnitude
4430 of the most significant digit of the operand (as though the
4431 operand were truncated to a single digit while maintaining the
4432 value of that digit and without limiting the resulting exponent).
4433
4434 >>> ExtendedContext.logb(Decimal('250'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004435 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004436 >>> ExtendedContext.logb(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004437 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004438 >>> ExtendedContext.logb(Decimal('0.03'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004439 Decimal('-2')
Facundo Batista353750c2007-09-13 18:13:15 +00004440 >>> ExtendedContext.logb(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004441 Decimal('-Infinity')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004442 >>> ExtendedContext.logb(1)
4443 Decimal('0')
4444 >>> ExtendedContext.logb(10)
4445 Decimal('1')
4446 >>> ExtendedContext.logb(100)
4447 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004448 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004449 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004450 return a.logb(context=self)
4451
4452 def logical_and(self, a, b):
4453 """Applies the logical operation 'and' between each operand's digits.
4454
4455 The operands must be both logical numbers.
4456
4457 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004458 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004459 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004460 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004461 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004462 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004463 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004464 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004465 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004466 Decimal('1000')
Facundo Batista353750c2007-09-13 18:13:15 +00004467 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004468 Decimal('10')
Mark Dickinson456e1652010-02-18 14:45:33 +00004469 >>> ExtendedContext.logical_and(110, 1101)
4470 Decimal('100')
4471 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4472 Decimal('100')
4473 >>> ExtendedContext.logical_and(110, Decimal(1101))
4474 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004475 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004476 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004477 return a.logical_and(b, context=self)
4478
4479 def logical_invert(self, a):
4480 """Invert all the digits in the operand.
4481
4482 The operand must be a logical number.
4483
4484 >>> ExtendedContext.logical_invert(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004485 Decimal('111111111')
Facundo Batista353750c2007-09-13 18:13:15 +00004486 >>> ExtendedContext.logical_invert(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004487 Decimal('111111110')
Facundo Batista353750c2007-09-13 18:13:15 +00004488 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004489 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004490 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004491 Decimal('10101010')
Mark Dickinson456e1652010-02-18 14:45:33 +00004492 >>> ExtendedContext.logical_invert(1101)
4493 Decimal('111110010')
Facundo Batista353750c2007-09-13 18:13:15 +00004494 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004495 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004496 return a.logical_invert(context=self)
4497
4498 def logical_or(self, a, b):
4499 """Applies the logical operation 'or' between each operand's digits.
4500
4501 The operands must be both logical numbers.
4502
4503 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004504 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004505 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004506 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004507 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004508 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004509 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004510 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004511 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004512 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004513 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004514 Decimal('1110')
Mark Dickinson456e1652010-02-18 14:45:33 +00004515 >>> ExtendedContext.logical_or(110, 1101)
4516 Decimal('1111')
4517 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4518 Decimal('1111')
4519 >>> ExtendedContext.logical_or(110, Decimal(1101))
4520 Decimal('1111')
Facundo Batista353750c2007-09-13 18:13:15 +00004521 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004522 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004523 return a.logical_or(b, context=self)
4524
4525 def logical_xor(self, a, b):
4526 """Applies the logical operation 'xor' between each operand's digits.
4527
4528 The operands must be both logical numbers.
4529
4530 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004531 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004532 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004533 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004534 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004535 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004536 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004537 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004538 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004539 Decimal('110')
Facundo Batista353750c2007-09-13 18:13:15 +00004540 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004541 Decimal('1101')
Mark Dickinson456e1652010-02-18 14:45:33 +00004542 >>> ExtendedContext.logical_xor(110, 1101)
4543 Decimal('1011')
4544 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4545 Decimal('1011')
4546 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4547 Decimal('1011')
Facundo Batista353750c2007-09-13 18:13:15 +00004548 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004549 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004550 return a.logical_xor(b, context=self)
4551
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004552 def max(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004553 """max compares two values numerically and returns the maximum.
4554
4555 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004556 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004557 operation. If they are numerically equal then the left-hand operand
4558 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004559 infinity) of the two operands is chosen as the result.
4560
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004561 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004562 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004563 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004564 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004565 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004566 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004567 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004568 Decimal('7')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004569 >>> ExtendedContext.max(1, 2)
4570 Decimal('2')
4571 >>> ExtendedContext.max(Decimal(1), 2)
4572 Decimal('2')
4573 >>> ExtendedContext.max(1, Decimal(2))
4574 Decimal('2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004575 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004576 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004577 return a.max(b, context=self)
4578
Facundo Batista353750c2007-09-13 18:13:15 +00004579 def max_mag(self, a, b):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004580 """Compares the values numerically with their sign ignored.
4581
4582 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4583 Decimal('7')
4584 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4585 Decimal('-10')
4586 >>> ExtendedContext.max_mag(1, -2)
4587 Decimal('-2')
4588 >>> ExtendedContext.max_mag(Decimal(1), -2)
4589 Decimal('-2')
4590 >>> ExtendedContext.max_mag(1, Decimal(-2))
4591 Decimal('-2')
4592 """
4593 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004594 return a.max_mag(b, context=self)
4595
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004596 def min(self, a, b):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004597 """min compares two values numerically and returns the minimum.
4598
4599 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004600 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004601 operation. If they are numerically equal then the left-hand operand
4602 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004603 infinity) of the two operands is chosen as the result.
4604
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004605 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004606 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004607 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004608 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004609 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004610 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004611 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004612 Decimal('7')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004613 >>> ExtendedContext.min(1, 2)
4614 Decimal('1')
4615 >>> ExtendedContext.min(Decimal(1), 2)
4616 Decimal('1')
4617 >>> ExtendedContext.min(1, Decimal(29))
4618 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004619 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004620 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004621 return a.min(b, context=self)
4622
Facundo Batista353750c2007-09-13 18:13:15 +00004623 def min_mag(self, a, b):
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004624 """Compares the values numerically with their sign ignored.
4625
4626 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4627 Decimal('-2')
4628 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4629 Decimal('-3')
4630 >>> ExtendedContext.min_mag(1, -2)
4631 Decimal('1')
4632 >>> ExtendedContext.min_mag(Decimal(1), -2)
4633 Decimal('1')
4634 >>> ExtendedContext.min_mag(1, Decimal(-2))
4635 Decimal('1')
4636 """
4637 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004638 return a.min_mag(b, context=self)
4639
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004640 def minus(self, a):
4641 """Minus corresponds to unary prefix minus in Python.
4642
4643 The operation is evaluated using the same rules as subtract; the
4644 operation minus(a) is calculated as subtract('0', a) where the '0'
4645 has the same exponent as the operand.
4646
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004647 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004648 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004649 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004650 Decimal('1.3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004651 >>> ExtendedContext.minus(1)
4652 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004653 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004654 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655 return a.__neg__(context=self)
4656
4657 def multiply(self, a, b):
4658 """multiply multiplies two operands.
4659
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004660 If either operand is a special value then the general rules apply.
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004661 Otherwise, the operands are multiplied together
4662 ('long multiplication'), resulting in a number which may be as long as
4663 the sum of the lengths of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004664
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004665 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004666 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004667 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004668 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004669 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004670 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004671 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004672 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004673 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004674 Decimal('4.28135971E+11')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004675 >>> ExtendedContext.multiply(7, 7)
4676 Decimal('49')
4677 >>> ExtendedContext.multiply(Decimal(7), 7)
4678 Decimal('49')
4679 >>> ExtendedContext.multiply(7, Decimal(7))
4680 Decimal('49')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004681 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004682 a = _convert_other(a, raiseit=True)
4683 r = a.__mul__(b, context=self)
4684 if r is NotImplemented:
4685 raise TypeError("Unable to convert %s to Decimal" % b)
4686 else:
4687 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004688
Facundo Batista353750c2007-09-13 18:13:15 +00004689 def next_minus(self, a):
4690 """Returns the largest representable number smaller than a.
4691
4692 >>> c = ExtendedContext.copy()
4693 >>> c.Emin = -999
4694 >>> c.Emax = 999
4695 >>> ExtendedContext.next_minus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004696 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004697 >>> c.next_minus(Decimal('1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004698 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004699 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004700 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004701 >>> c.next_minus(Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004702 Decimal('9.99999999E+999')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004703 >>> c.next_minus(1)
4704 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004705 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004706 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004707 return a.next_minus(context=self)
4708
4709 def next_plus(self, a):
4710 """Returns the smallest representable number larger than a.
4711
4712 >>> c = ExtendedContext.copy()
4713 >>> c.Emin = -999
4714 >>> c.Emax = 999
4715 >>> ExtendedContext.next_plus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004716 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004717 >>> c.next_plus(Decimal('-1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004718 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004719 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004720 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004721 >>> c.next_plus(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004722 Decimal('-9.99999999E+999')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004723 >>> c.next_plus(1)
4724 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004725 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004726 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004727 return a.next_plus(context=self)
4728
4729 def next_toward(self, a, b):
4730 """Returns the number closest to a, in direction towards b.
4731
4732 The result is the closest representable number from the first
4733 operand (but not the first operand) that is in the direction
4734 towards the second operand, unless the operands have the same
4735 value.
4736
4737 >>> c = ExtendedContext.copy()
4738 >>> c.Emin = -999
4739 >>> c.Emax = 999
4740 >>> c.next_toward(Decimal('1'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004741 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004742 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004743 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004744 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004745 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004746 >>> c.next_toward(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004747 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004748 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004749 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004750 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004751 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004752 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004753 Decimal('-0.00')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004754 >>> c.next_toward(0, 1)
4755 Decimal('1E-1007')
4756 >>> c.next_toward(Decimal(0), 1)
4757 Decimal('1E-1007')
4758 >>> c.next_toward(0, Decimal(1))
4759 Decimal('1E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004760 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004761 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004762 return a.next_toward(b, context=self)
4763
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004764 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004765 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004766
4767 Essentially a plus operation with all trailing zeros removed from the
4768 result.
4769
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004770 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004771 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004772 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004773 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004774 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004775 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004776 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004777 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004778 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004779 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004780 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004781 Decimal('0')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004782 >>> ExtendedContext.normalize(6)
4783 Decimal('6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004784 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004785 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004786 return a.normalize(context=self)
4787
Facundo Batista353750c2007-09-13 18:13:15 +00004788 def number_class(self, a):
4789 """Returns an indication of the class of the operand.
4790
4791 The class is one of the following strings:
4792 -sNaN
4793 -NaN
4794 -Infinity
4795 -Normal
4796 -Subnormal
4797 -Zero
4798 +Zero
4799 +Subnormal
4800 +Normal
4801 +Infinity
4802
4803 >>> c = Context(ExtendedContext)
4804 >>> c.Emin = -999
4805 >>> c.Emax = 999
4806 >>> c.number_class(Decimal('Infinity'))
4807 '+Infinity'
4808 >>> c.number_class(Decimal('1E-10'))
4809 '+Normal'
4810 >>> c.number_class(Decimal('2.50'))
4811 '+Normal'
4812 >>> c.number_class(Decimal('0.1E-999'))
4813 '+Subnormal'
4814 >>> c.number_class(Decimal('0'))
4815 '+Zero'
4816 >>> c.number_class(Decimal('-0'))
4817 '-Zero'
4818 >>> c.number_class(Decimal('-0.1E-999'))
4819 '-Subnormal'
4820 >>> c.number_class(Decimal('-1E-10'))
4821 '-Normal'
4822 >>> c.number_class(Decimal('-2.50'))
4823 '-Normal'
4824 >>> c.number_class(Decimal('-Infinity'))
4825 '-Infinity'
4826 >>> c.number_class(Decimal('NaN'))
4827 'NaN'
4828 >>> c.number_class(Decimal('-NaN'))
4829 'NaN'
4830 >>> c.number_class(Decimal('sNaN'))
4831 'sNaN'
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004832 >>> c.number_class(123)
4833 '+Normal'
Facundo Batista353750c2007-09-13 18:13:15 +00004834 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004835 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00004836 return a.number_class(context=self)
4837
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004838 def plus(self, a):
4839 """Plus corresponds to unary prefix plus in Python.
4840
4841 The operation is evaluated using the same rules as add; the
4842 operation plus(a) is calculated as add('0', a) where the '0'
4843 has the same exponent as the operand.
4844
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004845 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004846 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004847 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004848 Decimal('-1.3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004849 >>> ExtendedContext.plus(-1)
4850 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004851 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004852 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004853 return a.__pos__(context=self)
4854
4855 def power(self, a, b, modulo=None):
4856 """Raises a to the power of b, to modulo if given.
4857
Facundo Batista353750c2007-09-13 18:13:15 +00004858 With two arguments, compute a**b. If a is negative then b
4859 must be integral. The result will be inexact unless b is
4860 integral and the result is finite and can be expressed exactly
4861 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004862
Facundo Batista353750c2007-09-13 18:13:15 +00004863 With three arguments, compute (a**b) % modulo. For the
4864 three argument form, the following restrictions on the
4865 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004866
Facundo Batista353750c2007-09-13 18:13:15 +00004867 - all three arguments must be integral
4868 - b must be nonnegative
4869 - at least one of a or b must be nonzero
4870 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004871
Facundo Batista353750c2007-09-13 18:13:15 +00004872 The result of pow(a, b, modulo) is identical to the result
4873 that would be obtained by computing (a**b) % modulo with
4874 unbounded precision, but is computed more efficiently. It is
4875 always exact.
4876
4877 >>> c = ExtendedContext.copy()
4878 >>> c.Emin = -999
4879 >>> c.Emax = 999
4880 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004881 Decimal('8')
Facundo Batista353750c2007-09-13 18:13:15 +00004882 >>> c.power(Decimal('-2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004883 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004884 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004885 Decimal('0.125')
Facundo Batista353750c2007-09-13 18:13:15 +00004886 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004887 Decimal('69.7575744')
Facundo Batista353750c2007-09-13 18:13:15 +00004888 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004889 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004890 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004891 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004892 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004893 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004894 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004895 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004896 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004897 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004898 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004899 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004900 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004901 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004902 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004903 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004904 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004905 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00004906
4907 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004908 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004909 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004910 Decimal('-11')
Facundo Batista353750c2007-09-13 18:13:15 +00004911 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004912 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004913 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004914 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004915 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004916 Decimal('11729830')
Facundo Batista353750c2007-09-13 18:13:15 +00004917 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004918 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004919 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004920 Decimal('1')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004921 >>> ExtendedContext.power(7, 7)
4922 Decimal('823543')
4923 >>> ExtendedContext.power(Decimal(7), 7)
4924 Decimal('823543')
4925 >>> ExtendedContext.power(7, Decimal(7), 2)
4926 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004927 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004928 a = _convert_other(a, raiseit=True)
4929 r = a.__pow__(b, modulo, context=self)
4930 if r is NotImplemented:
4931 raise TypeError("Unable to convert %s to Decimal" % b)
4932 else:
4933 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004934
4935 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004936 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004937
4938 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004939 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004940 exponent is being increased), multiplied by a positive power of ten (if
4941 the exponent is being decreased), or is unchanged (if the exponent is
4942 already equal to that of the right-hand operand).
4943
4944 Unlike other operations, if the length of the coefficient after the
4945 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004946 operation condition is raised. This guarantees that, unless there is
4947 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004948 equal to that of the right-hand operand.
4949
4950 Also unlike other operations, quantize will never raise Underflow, even
4951 if the result is subnormal and inexact.
4952
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004953 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004954 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004955 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004956 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004957 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004958 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004959 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004960 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004961 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004962 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004963 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004964 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004965 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004966 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004967 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004968 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004969 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004970 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004971 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004972 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004973 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004974 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004975 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004976 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004977 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004978 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004979 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004980 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004981 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004982 Decimal('2E+2')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004983 >>> ExtendedContext.quantize(1, 2)
4984 Decimal('1')
4985 >>> ExtendedContext.quantize(Decimal(1), 2)
4986 Decimal('1')
4987 >>> ExtendedContext.quantize(1, Decimal(2))
4988 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004989 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00004990 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004991 return a.quantize(b, context=self)
4992
Facundo Batista353750c2007-09-13 18:13:15 +00004993 def radix(self):
4994 """Just returns 10, as this is Decimal, :)
4995
4996 >>> ExtendedContext.radix()
Raymond Hettingerabe32372008-02-14 02:41:22 +00004997 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004998 """
4999 return Decimal(10)
5000
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005001 def remainder(self, a, b):
5002 """Returns the remainder from integer division.
5003
5004 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00005005 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00005006 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00005007 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005008
5009 This operation will fail under the same conditions as integer division
5010 (that is, if integer division on the same two operands would fail, the
5011 remainder cannot be calculated).
5012
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005013 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005014 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005015 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005016 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005017 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005018 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005019 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005020 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005021 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005022 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005023 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005024 Decimal('1.0')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005025 >>> ExtendedContext.remainder(22, 6)
5026 Decimal('4')
5027 >>> ExtendedContext.remainder(Decimal(22), 6)
5028 Decimal('4')
5029 >>> ExtendedContext.remainder(22, Decimal(6))
5030 Decimal('4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005031 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005032 a = _convert_other(a, raiseit=True)
5033 r = a.__mod__(b, context=self)
5034 if r is NotImplemented:
5035 raise TypeError("Unable to convert %s to Decimal" % b)
5036 else:
5037 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005038
5039 def remainder_near(self, a, b):
5040 """Returns to be "a - b * n", where n is the integer nearest the exact
5041 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00005042 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005043 sign of a.
5044
5045 This operation will fail under the same conditions as integer division
5046 (that is, if integer division on the same two operands would fail, the
5047 remainder cannot be calculated).
5048
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005049 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005050 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005051 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005052 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005053 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005054 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005055 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005056 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005057 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005058 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005059 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005060 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005061 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005062 Decimal('-0.3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005063 >>> ExtendedContext.remainder_near(3, 11)
5064 Decimal('3')
5065 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5066 Decimal('3')
5067 >>> ExtendedContext.remainder_near(3, Decimal(11))
5068 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005069 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005070 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005071 return a.remainder_near(b, context=self)
5072
Facundo Batista353750c2007-09-13 18:13:15 +00005073 def rotate(self, a, b):
5074 """Returns a rotated copy of a, b times.
5075
5076 The coefficient of the result is a rotated copy of the digits in
5077 the coefficient of the first operand. The number of places of
5078 rotation is taken from the absolute value of the second operand,
5079 with the rotation being to the left if the second operand is
5080 positive or to the right otherwise.
5081
5082 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005083 Decimal('400000003')
Facundo Batista353750c2007-09-13 18:13:15 +00005084 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005085 Decimal('12')
Facundo Batista353750c2007-09-13 18:13:15 +00005086 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005087 Decimal('891234567')
Facundo Batista353750c2007-09-13 18:13:15 +00005088 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005089 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00005090 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005091 Decimal('345678912')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005092 >>> ExtendedContext.rotate(1333333, 1)
5093 Decimal('13333330')
5094 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5095 Decimal('13333330')
5096 >>> ExtendedContext.rotate(1333333, Decimal(1))
5097 Decimal('13333330')
Facundo Batista353750c2007-09-13 18:13:15 +00005098 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005099 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005100 return a.rotate(b, context=self)
5101
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005102 def same_quantum(self, a, b):
5103 """Returns True if the two operands have the same exponent.
5104
5105 The result is never affected by either the sign or the coefficient of
5106 either operand.
5107
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005108 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005109 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005110 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005111 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005112 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005113 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005114 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005115 True
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005116 >>> ExtendedContext.same_quantum(10000, -1)
5117 True
5118 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5119 True
5120 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5121 True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005122 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005123 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005124 return a.same_quantum(b)
5125
Facundo Batista353750c2007-09-13 18:13:15 +00005126 def scaleb (self, a, b):
5127 """Returns the first operand after adding the second value its exp.
5128
5129 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005130 Decimal('0.0750')
Facundo Batista353750c2007-09-13 18:13:15 +00005131 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005132 Decimal('7.50')
Facundo Batista353750c2007-09-13 18:13:15 +00005133 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005134 Decimal('7.50E+3')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005135 >>> ExtendedContext.scaleb(1, 4)
5136 Decimal('1E+4')
5137 >>> ExtendedContext.scaleb(Decimal(1), 4)
5138 Decimal('1E+4')
5139 >>> ExtendedContext.scaleb(1, Decimal(4))
5140 Decimal('1E+4')
Facundo Batista353750c2007-09-13 18:13:15 +00005141 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005142 a = _convert_other(a, raiseit=True)
5143 return a.scaleb(b, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00005144
5145 def shift(self, a, b):
5146 """Returns a shifted copy of a, b times.
5147
5148 The coefficient of the result is a shifted copy of the digits
5149 in the coefficient of the first operand. The number of places
5150 to shift is taken from the absolute value of the second operand,
5151 with the shift being to the left if the second operand is
5152 positive or to the right otherwise. Digits shifted into the
5153 coefficient are zeros.
5154
5155 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005156 Decimal('400000000')
Facundo Batista353750c2007-09-13 18:13:15 +00005157 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005158 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00005159 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005160 Decimal('1234567')
Facundo Batista353750c2007-09-13 18:13:15 +00005161 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005162 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00005163 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005164 Decimal('345678900')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005165 >>> ExtendedContext.shift(88888888, 2)
5166 Decimal('888888800')
5167 >>> ExtendedContext.shift(Decimal(88888888), 2)
5168 Decimal('888888800')
5169 >>> ExtendedContext.shift(88888888, Decimal(2))
5170 Decimal('888888800')
Facundo Batista353750c2007-09-13 18:13:15 +00005171 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005172 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005173 return a.shift(b, context=self)
5174
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005175 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00005176 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005177
5178 If the result must be inexact, it is rounded using the round-half-even
5179 algorithm.
5180
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005181 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005182 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005183 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005184 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005185 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005186 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005187 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005188 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005189 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005190 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005191 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005192 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005193 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005194 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005195 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005196 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005197 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005198 Decimal('3.16227766')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005199 >>> ExtendedContext.sqrt(2)
5200 Decimal('1.41421356')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005201 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005202 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005203 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005204 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005205 return a.sqrt(context=self)
5206
5207 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00005208 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005209
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005210 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005211 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005212 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005213 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005214 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005215 Decimal('-0.77')
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005216 >>> ExtendedContext.subtract(8, 5)
5217 Decimal('3')
5218 >>> ExtendedContext.subtract(Decimal(8), 5)
5219 Decimal('3')
5220 >>> ExtendedContext.subtract(8, Decimal(5))
5221 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005222 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005223 a = _convert_other(a, raiseit=True)
5224 r = a.__sub__(b, context=self)
5225 if r is NotImplemented:
5226 raise TypeError("Unable to convert %s to Decimal" % b)
5227 else:
5228 return r
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005229
5230 def to_eng_string(self, a):
5231 """Converts a number to a string, using scientific notation.
5232
5233 The operation is not affected by the context.
5234 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005235 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005236 return a.to_eng_string(context=self)
5237
5238 def to_sci_string(self, a):
5239 """Converts a number to a string, using scientific notation.
5240
5241 The operation is not affected by the context.
5242 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005243 a = _convert_other(a, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005244 return a.__str__(context=self)
5245
Facundo Batista353750c2007-09-13 18:13:15 +00005246 def to_integral_exact(self, a):
5247 """Rounds to an integer.
5248
5249 When the operand has a negative exponent, the result is the same
5250 as using the quantize() operation using the given operand as the
5251 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5252 of the operand as the precision setting; Inexact and Rounded flags
5253 are allowed in this operation. The rounding mode is taken from the
5254 context.
5255
5256 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005257 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00005258 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005259 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005260 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005261 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005262 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005263 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00005264 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005265 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00005266 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005267 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00005268 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005269 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00005270 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005271 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00005272 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005273 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005274 return a.to_integral_exact(context=self)
5275
5276 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005277 """Rounds to an integer.
5278
5279 When the operand has a negative exponent, the result is the same
5280 as using the quantize() operation using the given operand as the
5281 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5282 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00005283 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005284
Facundo Batista353750c2007-09-13 18:13:15 +00005285 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005286 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00005287 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005288 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005289 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005290 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00005291 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005292 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00005293 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005294 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00005295 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005296 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00005297 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005298 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00005299 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00005300 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005301 """
Mark Dickinson6d8effb2010-02-18 14:27:02 +00005302 a = _convert_other(a, raiseit=True)
Facundo Batista353750c2007-09-13 18:13:15 +00005303 return a.to_integral_value(context=self)
5304
5305 # the method name changed, but we provide also the old one, for compatibility
5306 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005307
5308class _WorkRep(object):
5309 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00005310 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005311 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005312 # exp: None, int, or string
5313
5314 def __init__(self, value=None):
5315 if value is None:
5316 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005317 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005318 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00005319 elif isinstance(value, Decimal):
5320 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00005321 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005322 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00005323 else:
5324 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005325 self.sign = value[0]
5326 self.int = value[1]
5327 self.exp = value[2]
5328
5329 def __repr__(self):
5330 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5331
5332 __str__ = __repr__
5333
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005334
5335
Facundo Batistae64acfa2007-12-17 14:18:42 +00005336def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005337 """Normalizes op1, op2 to have the same exp and length of coefficient.
5338
5339 Done during addition.
5340 """
Facundo Batista353750c2007-09-13 18:13:15 +00005341 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005342 tmp = op2
5343 other = op1
5344 else:
5345 tmp = op1
5346 other = op2
5347
Facundo Batista353750c2007-09-13 18:13:15 +00005348 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5349 # Then adding 10**exp to tmp has the same effect (after rounding)
5350 # as adding any positive quantity smaller than 10**exp; similarly
5351 # for subtraction. So if other is smaller than 10**exp we replace
5352 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00005353 tmp_len = len(str(tmp.int))
5354 other_len = len(str(other.int))
5355 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5356 if other_len + other.exp - 1 < exp:
5357 other.int = 1
5358 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005359
Facundo Batista353750c2007-09-13 18:13:15 +00005360 tmp.int *= 10 ** (tmp.exp - other.exp)
5361 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005362 return op1, op2
5363
Facundo Batista353750c2007-09-13 18:13:15 +00005364##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
5365
5366# This function from Tim Peters was taken from here:
5367# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5368# The correction being in the function definition is for speed, and
5369# the whole function is not resolved with math.log because of avoiding
5370# the use of floats.
5371def _nbits(n, correction = {
5372 '0': 4, '1': 3, '2': 2, '3': 2,
5373 '4': 1, '5': 1, '6': 1, '7': 1,
5374 '8': 0, '9': 0, 'a': 0, 'b': 0,
5375 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5376 """Number of bits in binary representation of the positive integer n,
5377 or 0 if n == 0.
5378 """
5379 if n < 0:
5380 raise ValueError("The argument to _nbits should be nonnegative.")
5381 hex_n = "%x" % n
5382 return 4*len(hex_n) - correction[hex_n[0]]
5383
5384def _sqrt_nearest(n, a):
5385 """Closest integer to the square root of the positive integer n. a is
5386 an initial approximation to the square root. Any positive integer
5387 will do for a, but the closer a is to the square root of n the
5388 faster convergence will be.
5389
5390 """
5391 if n <= 0 or a <= 0:
5392 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5393
5394 b=0
5395 while a != b:
5396 b, a = a, a--n//a>>1
5397 return a
5398
5399def _rshift_nearest(x, shift):
5400 """Given an integer x and a nonnegative integer shift, return closest
5401 integer to x / 2**shift; use round-to-even in case of a tie.
5402
5403 """
5404 b, q = 1L << shift, x >> shift
5405 return q + (2*(x & (b-1)) + (q&1) > b)
5406
5407def _div_nearest(a, b):
5408 """Closest integer to a/b, a and b positive integers; rounds to even
5409 in the case of a tie.
5410
5411 """
5412 q, r = divmod(a, b)
5413 return q + (2*r + (q&1) > b)
5414
5415def _ilog(x, M, L = 8):
5416 """Integer approximation to M*log(x/M), with absolute error boundable
5417 in terms only of x/M.
5418
5419 Given positive integers x and M, return an integer approximation to
5420 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5421 between the approximation and the exact result is at most 22. For
5422 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5423 both cases these are upper bounds on the error; it will usually be
5424 much smaller."""
5425
5426 # The basic algorithm is the following: let log1p be the function
5427 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5428 # the reduction
5429 #
5430 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5431 #
5432 # repeatedly until the argument to log1p is small (< 2**-L in
5433 # absolute value). For small y we can use the Taylor series
5434 # expansion
5435 #
5436 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5437 #
5438 # truncating at T such that y**T is small enough. The whole
5439 # computation is carried out in a form of fixed-point arithmetic,
5440 # with a real number z being represented by an integer
5441 # approximation to z*M. To avoid loss of precision, the y below
5442 # is actually an integer approximation to 2**R*y*M, where R is the
5443 # number of reductions performed so far.
5444
5445 y = x-M
5446 # argument reduction; R = number of reductions performed
5447 R = 0
5448 while (R <= L and long(abs(y)) << L-R >= M or
5449 R > L and abs(y) >> R-L >= M):
5450 y = _div_nearest(long(M*y) << 1,
5451 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5452 R += 1
5453
5454 # Taylor series with T terms
5455 T = -int(-10*len(str(M))//(3*L))
5456 yshift = _rshift_nearest(y, R)
5457 w = _div_nearest(M, T)
5458 for k in xrange(T-1, 0, -1):
5459 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5460
5461 return _div_nearest(w*y, M)
5462
5463def _dlog10(c, e, p):
5464 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5465 approximation to 10**p * log10(c*10**e), with an absolute error of
5466 at most 1. Assumes that c*10**e is not exactly 1."""
5467
5468 # increase precision by 2; compensate for this by dividing
5469 # final result by 100
5470 p += 2
5471
5472 # write c*10**e as d*10**f with either:
5473 # f >= 0 and 1 <= d <= 10, or
5474 # f <= 0 and 0.1 <= d <= 1.
5475 # Thus for c*10**e close to 1, f = 0
5476 l = len(str(c))
5477 f = e+l - (e+l >= 1)
5478
5479 if p > 0:
5480 M = 10**p
5481 k = e+p-f
5482 if k >= 0:
5483 c *= 10**k
5484 else:
5485 c = _div_nearest(c, 10**-k)
5486
5487 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005488 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005489 log_d = _div_nearest(log_d*M, log_10)
5490 log_tenpower = f*M # exact
5491 else:
5492 log_d = 0 # error < 2.31
Neal Norwitz18aa3882008-08-24 05:04:52 +00005493 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Facundo Batista353750c2007-09-13 18:13:15 +00005494
5495 return _div_nearest(log_tenpower+log_d, 100)
5496
5497def _dlog(c, e, p):
5498 """Given integers c, e and p with c > 0, compute an integer
5499 approximation to 10**p * log(c*10**e), with an absolute error of
5500 at most 1. Assumes that c*10**e is not exactly 1."""
5501
5502 # Increase precision by 2. The precision increase is compensated
5503 # for at the end with a division by 100.
5504 p += 2
5505
5506 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5507 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5508 # as 10**p * log(d) + 10**p*f * log(10).
5509 l = len(str(c))
5510 f = e+l - (e+l >= 1)
5511
5512 # compute approximation to 10**p*log(d), with error < 27
5513 if p > 0:
5514 k = e+p-f
5515 if k >= 0:
5516 c *= 10**k
5517 else:
5518 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5519
5520 # _ilog magnifies existing error in c by a factor of at most 10
5521 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5522 else:
5523 # p <= 0: just approximate the whole thing by 0; error < 2.31
5524 log_d = 0
5525
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005526 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00005527 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005528 extra = len(str(abs(f)))-1
5529 if p + extra >= 0:
5530 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5531 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5532 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00005533 else:
5534 f_log_ten = 0
5535 else:
5536 f_log_ten = 0
5537
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005538 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005539 return _div_nearest(f_log_ten + log_d, 100)
5540
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005541class _Log10Memoize(object):
5542 """Class to compute, store, and allow retrieval of, digits of the
5543 constant log(10) = 2.302585.... This constant is needed by
5544 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5545 def __init__(self):
5546 self.digits = "23025850929940456840179914546843642076011014886"
5547
5548 def getdigits(self, p):
5549 """Given an integer p >= 0, return floor(10**p)*log(10).
5550
5551 For example, self.getdigits(3) returns 2302.
5552 """
5553 # digits are stored as a string, for quick conversion to
5554 # integer in the case that we've already computed enough
5555 # digits; the stored digits should always be correct
5556 # (truncated, not rounded to nearest).
5557 if p < 0:
5558 raise ValueError("p should be nonnegative")
5559
5560 if p >= len(self.digits):
5561 # compute p+3, p+6, p+9, ... digits; continue until at
5562 # least one of the extra digits is nonzero
5563 extra = 3
5564 while True:
5565 # compute p+extra digits, correct to within 1ulp
5566 M = 10**(p+extra+2)
5567 digits = str(_div_nearest(_ilog(10*M, M), 100))
5568 if digits[-extra:] != '0'*extra:
5569 break
5570 extra += 3
5571 # keep all reliable digits so far; remove trailing zeros
5572 # and next nonzero digit
5573 self.digits = digits.rstrip('0')[:-1]
5574 return int(self.digits[:p+1])
5575
5576_log10_digits = _Log10Memoize().getdigits
5577
Facundo Batista353750c2007-09-13 18:13:15 +00005578def _iexp(x, M, L=8):
5579 """Given integers x and M, M > 0, such that x/M is small in absolute
5580 value, compute an integer approximation to M*exp(x/M). For 0 <=
5581 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5582 is usually much smaller)."""
5583
5584 # Algorithm: to compute exp(z) for a real number z, first divide z
5585 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5586 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5587 # series
5588 #
5589 # expm1(x) = x + x**2/2! + x**3/3! + ...
5590 #
5591 # Now use the identity
5592 #
5593 # expm1(2x) = expm1(x)*(expm1(x)+2)
5594 #
5595 # R times to compute the sequence expm1(z/2**R),
5596 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5597
5598 # Find R such that x/2**R/M <= 2**-L
5599 R = _nbits((long(x)<<L)//M)
5600
5601 # Taylor series. (2**L)**T > M
5602 T = -int(-10*len(str(M))//(3*L))
5603 y = _div_nearest(x, T)
5604 Mshift = long(M)<<R
5605 for i in xrange(T-1, 0, -1):
5606 y = _div_nearest(x*(Mshift + y), Mshift * i)
5607
5608 # Expansion
5609 for k in xrange(R-1, -1, -1):
5610 Mshift = long(M)<<(k+2)
5611 y = _div_nearest(y*(y+Mshift), Mshift)
5612
5613 return M+y
5614
5615def _dexp(c, e, p):
5616 """Compute an approximation to exp(c*10**e), with p decimal places of
5617 precision.
5618
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005619 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005620
5621 10**(p-1) <= d <= 10**p, and
5622 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5623
5624 In other words, d*10**f is an approximation to exp(c*10**e) with p
5625 digits of precision, and with an error in d of at most 1. This is
5626 almost, but not quite, the same as the error being < 1ulp: when d
5627 = 10**(p-1) the error could be up to 10 ulp."""
5628
5629 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5630 p += 2
5631
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005632 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005633 extra = max(0, e + len(str(c)) - 1)
5634 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005635
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005636 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005637 # rounding down
5638 shift = e+q
5639 if shift >= 0:
5640 cshift = c*10**shift
5641 else:
5642 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005643 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005644
5645 # reduce remainder back to original precision
5646 rem = _div_nearest(rem, 10**extra)
5647
5648 # error in result of _iexp < 120; error after division < 0.62
5649 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5650
5651def _dpower(xc, xe, yc, ye, p):
5652 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5653 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5654
5655 10**(p-1) <= c <= 10**p, and
5656 (c-1)*10**e < x**y < (c+1)*10**e
5657
5658 in other words, c*10**e is an approximation to x**y with p digits
5659 of precision, and with an error in c of at most 1. (This is
5660 almost, but not quite, the same as the error being < 1ulp: when c
5661 == 10**(p-1) we can only guarantee error < 10ulp.)
5662
5663 We assume that: x is positive and not equal to 1, and y is nonzero.
5664 """
5665
5666 # Find b such that 10**(b-1) <= |y| <= 10**b
5667 b = len(str(abs(yc))) + ye
5668
5669 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5670 lxc = _dlog(xc, xe, p+b+1)
5671
5672 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5673 shift = ye-b
5674 if shift >= 0:
5675 pc = lxc*yc*10**shift
5676 else:
5677 pc = _div_nearest(lxc*yc, 10**-shift)
5678
5679 if pc == 0:
5680 # we prefer a result that isn't exactly 1; this makes it
5681 # easier to compute a correctly rounded result in __pow__
5682 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5683 coeff, exp = 10**(p-1)+1, 1-p
5684 else:
5685 coeff, exp = 10**p-1, -p
5686 else:
5687 coeff, exp = _dexp(pc, -(p+1), p+1)
5688 coeff = _div_nearest(coeff, 10)
5689 exp += 1
5690
5691 return coeff, exp
5692
5693def _log10_lb(c, correction = {
5694 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5695 '6': 23, '7': 16, '8': 10, '9': 5}):
5696 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5697 if c <= 0:
5698 raise ValueError("The argument to _log10_lb should be nonnegative.")
5699 str_c = str(c)
5700 return 100*len(str_c) - correction[str_c[0]]
5701
Facundo Batista59c58842007-04-10 12:58:45 +00005702##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005703
Mark Dickinson99d80962010-04-02 08:53:22 +00005704def _convert_other(other, raiseit=False, allow_float=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005705 """Convert other to Decimal.
5706
5707 Verifies that it's ok to use in an implicit construction.
Mark Dickinson99d80962010-04-02 08:53:22 +00005708 If allow_float is true, allow conversion from float; this
5709 is used in the comparison methods (__eq__ and friends).
5710
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005711 """
5712 if isinstance(other, Decimal):
5713 return other
5714 if isinstance(other, (int, long)):
5715 return Decimal(other)
Mark Dickinson99d80962010-04-02 08:53:22 +00005716 if allow_float and isinstance(other, float):
5717 return Decimal.from_float(other)
5718
Facundo Batista353750c2007-09-13 18:13:15 +00005719 if raiseit:
5720 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005721 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005722
Facundo Batista59c58842007-04-10 12:58:45 +00005723##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005724
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005725# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005726# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005727
5728DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005729 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005730 traps=[DivisionByZero, Overflow, InvalidOperation],
5731 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005732 Emax=999999999,
5733 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005734 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005735)
5736
5737# Pre-made alternate contexts offered by the specification
5738# Don't change these; the user should be able to select these
5739# contexts and be able to reproduce results from other implementations
5740# of the spec.
5741
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005742BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005743 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005744 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5745 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005746)
5747
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005748ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005749 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005750 traps=[],
5751 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005752)
5753
5754
Facundo Batista72bc54f2007-11-23 17:59:00 +00005755##### crud for parsing strings #############################################
Mark Dickinson6a123cb2008-02-24 18:12:36 +00005756#
Facundo Batista72bc54f2007-11-23 17:59:00 +00005757# Regular expression used for parsing numeric strings. Additional
5758# comments:
5759#
5760# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5761# whitespace. But note that the specification disallows whitespace in
5762# a numeric string.
5763#
5764# 2. For finite numbers (not infinities and NaNs) the body of the
5765# number between the optional sign and the optional exponent must have
5766# at least one decimal digit, possibly after the decimal point. The
5767# lookahead expression '(?=\d|\.\d)' checks this.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005768
5769import re
Mark Dickinson70c32892008-07-02 09:37:01 +00005770_parser = re.compile(r""" # A numeric string consists of:
Facundo Batista72bc54f2007-11-23 17:59:00 +00005771# \s*
Mark Dickinson70c32892008-07-02 09:37:01 +00005772 (?P<sign>[-+])? # an optional sign, followed by either...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005773 (
Mark Dickinson4326ad82009-08-02 10:59:36 +00005774 (?=\d|\.\d) # ...a number (with at least one digit)
5775 (?P<int>\d*) # having a (possibly empty) integer part
5776 (\.(?P<frac>\d*))? # followed by an optional fractional part
5777 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005778 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005779 Inf(inity)? # ...an infinity, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005780 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005781 (?P<signal>s)? # ...an (optionally signaling)
5782 NaN # NaN
Mark Dickinson4326ad82009-08-02 10:59:36 +00005783 (?P<diag>\d*) # with (possibly empty) diagnostic info.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005784 )
5785# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005786 \Z
Mark Dickinson4326ad82009-08-02 10:59:36 +00005787""", re.VERBOSE | re.IGNORECASE | re.UNICODE).match
Facundo Batista72bc54f2007-11-23 17:59:00 +00005788
Facundo Batista2ec74152007-12-03 17:55:00 +00005789_all_zeros = re.compile('0*$').match
5790_exact_half = re.compile('50*$').match
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005791
5792##### PEP3101 support functions ##############################################
Mark Dickinson277859d2009-03-17 23:03:46 +00005793# The functions in this section have little to do with the Decimal
5794# class, and could potentially be reused or adapted for other pure
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005795# Python numeric classes that want to implement __format__
5796#
5797# A format specifier for Decimal looks like:
5798#
Mark Dickinson277859d2009-03-17 23:03:46 +00005799# [[fill]align][sign][0][minimumwidth][,][.precision][type]
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005800
5801_parse_format_specifier_regex = re.compile(r"""\A
5802(?:
5803 (?P<fill>.)?
5804 (?P<align>[<>=^])
5805)?
5806(?P<sign>[-+ ])?
5807(?P<zeropad>0)?
5808(?P<minimumwidth>(?!0)\d+)?
Mark Dickinson277859d2009-03-17 23:03:46 +00005809(?P<thousands_sep>,)?
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005810(?:\.(?P<precision>0|(?!0)\d+))?
Mark Dickinson277859d2009-03-17 23:03:46 +00005811(?P<type>[eEfFgGn%])?
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005812\Z
5813""", re.VERBOSE)
5814
Facundo Batista72bc54f2007-11-23 17:59:00 +00005815del re
5816
Mark Dickinson277859d2009-03-17 23:03:46 +00005817# The locale module is only needed for the 'n' format specifier. The
5818# rest of the PEP 3101 code functions quite happily without it, so we
5819# don't care too much if locale isn't present.
5820try:
5821 import locale as _locale
5822except ImportError:
5823 pass
5824
5825def _parse_format_specifier(format_spec, _localeconv=None):
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005826 """Parse and validate a format specifier.
5827
5828 Turns a standard numeric format specifier into a dict, with the
5829 following entries:
5830
5831 fill: fill character to pad field to minimum width
5832 align: alignment type, either '<', '>', '=' or '^'
5833 sign: either '+', '-' or ' '
5834 minimumwidth: nonnegative integer giving minimum width
Mark Dickinson277859d2009-03-17 23:03:46 +00005835 zeropad: boolean, indicating whether to pad with zeros
5836 thousands_sep: string to use as thousands separator, or ''
5837 grouping: grouping for thousands separators, in format
5838 used by localeconv
5839 decimal_point: string to use for decimal point
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005840 precision: nonnegative integer giving precision, or None
5841 type: one of the characters 'eEfFgG%', or None
Mark Dickinson277859d2009-03-17 23:03:46 +00005842 unicode: boolean (always True for Python 3.x)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005843
5844 """
5845 m = _parse_format_specifier_regex.match(format_spec)
5846 if m is None:
5847 raise ValueError("Invalid format specifier: " + format_spec)
5848
5849 # get the dictionary
5850 format_dict = m.groupdict()
5851
Mark Dickinson277859d2009-03-17 23:03:46 +00005852 # zeropad; defaults for fill and alignment. If zero padding
5853 # is requested, the fill and align fields should be absent.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005854 fill = format_dict['fill']
5855 align = format_dict['align']
Mark Dickinson277859d2009-03-17 23:03:46 +00005856 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
5857 if format_dict['zeropad']:
5858 if fill is not None:
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005859 raise ValueError("Fill character conflicts with '0'"
5860 " in format specifier: " + format_spec)
Mark Dickinson277859d2009-03-17 23:03:46 +00005861 if align is not None:
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005862 raise ValueError("Alignment conflicts with '0' in "
5863 "format specifier: " + format_spec)
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005864 format_dict['fill'] = fill or ' '
Mark Dickinson5cfa8042009-09-08 20:20:19 +00005865 # PEP 3101 originally specified that the default alignment should
5866 # be left; it was later agreed that right-aligned makes more sense
5867 # for numeric types. See http://bugs.python.org/issue6857.
5868 format_dict['align'] = align or '>'
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005869
Mark Dickinson277859d2009-03-17 23:03:46 +00005870 # default sign handling: '-' for negative, '' for positive
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005871 if format_dict['sign'] is None:
5872 format_dict['sign'] = '-'
5873
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005874 # minimumwidth defaults to 0; precision remains None if not given
5875 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5876 if format_dict['precision'] is not None:
5877 format_dict['precision'] = int(format_dict['precision'])
5878
5879 # if format type is 'g' or 'G' then a precision of 0 makes little
5880 # sense; convert it to 1. Same if format type is unspecified.
5881 if format_dict['precision'] == 0:
Mark Dickinson491ea552009-09-07 16:17:41 +00005882 if format_dict['type'] is None or format_dict['type'] in 'gG':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005883 format_dict['precision'] = 1
5884
Mark Dickinson277859d2009-03-17 23:03:46 +00005885 # determine thousands separator, grouping, and decimal separator, and
5886 # add appropriate entries to format_dict
5887 if format_dict['type'] == 'n':
5888 # apart from separators, 'n' behaves just like 'g'
5889 format_dict['type'] = 'g'
5890 if _localeconv is None:
5891 _localeconv = _locale.localeconv()
5892 if format_dict['thousands_sep'] is not None:
5893 raise ValueError("Explicit thousands separator conflicts with "
5894 "'n' type in format specifier: " + format_spec)
5895 format_dict['thousands_sep'] = _localeconv['thousands_sep']
5896 format_dict['grouping'] = _localeconv['grouping']
5897 format_dict['decimal_point'] = _localeconv['decimal_point']
5898 else:
5899 if format_dict['thousands_sep'] is None:
5900 format_dict['thousands_sep'] = ''
5901 format_dict['grouping'] = [3, 0]
5902 format_dict['decimal_point'] = '.'
5903
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005904 # record whether return type should be str or unicode
5905 format_dict['unicode'] = isinstance(format_spec, unicode)
5906
5907 return format_dict
5908
Mark Dickinson277859d2009-03-17 23:03:46 +00005909def _format_align(sign, body, spec):
5910 """Given an unpadded, non-aligned numeric string 'body' and sign
5911 string 'sign', add padding and aligment conforming to the given
5912 format specifier dictionary 'spec' (as produced by
5913 parse_format_specifier).
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005914
Mark Dickinson277859d2009-03-17 23:03:46 +00005915 Also converts result to unicode if necessary.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005916
5917 """
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005918 # how much extra space do we have to play with?
Mark Dickinson277859d2009-03-17 23:03:46 +00005919 minimumwidth = spec['minimumwidth']
5920 fill = spec['fill']
5921 padding = fill*(minimumwidth - len(sign) - len(body))
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005922
Mark Dickinson277859d2009-03-17 23:03:46 +00005923 align = spec['align']
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005924 if align == '<':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005925 result = sign + body + padding
Mark Dickinsonb065e522009-03-17 18:01:03 +00005926 elif align == '>':
5927 result = padding + sign + body
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005928 elif align == '=':
5929 result = sign + padding + body
Mark Dickinson277859d2009-03-17 23:03:46 +00005930 elif align == '^':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005931 half = len(padding)//2
5932 result = padding[:half] + sign + body + padding[half:]
Mark Dickinson277859d2009-03-17 23:03:46 +00005933 else:
5934 raise ValueError('Unrecognised alignment field')
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005935
5936 # make sure that result is unicode if necessary
Mark Dickinson277859d2009-03-17 23:03:46 +00005937 if spec['unicode']:
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005938 result = unicode(result)
5939
5940 return result
Facundo Batista72bc54f2007-11-23 17:59:00 +00005941
Mark Dickinson277859d2009-03-17 23:03:46 +00005942def _group_lengths(grouping):
5943 """Convert a localeconv-style grouping into a (possibly infinite)
5944 iterable of integers representing group lengths.
5945
5946 """
5947 # The result from localeconv()['grouping'], and the input to this
5948 # function, should be a list of integers in one of the
5949 # following three forms:
5950 #
5951 # (1) an empty list, or
5952 # (2) nonempty list of positive integers + [0]
5953 # (3) list of positive integers + [locale.CHAR_MAX], or
5954
5955 from itertools import chain, repeat
5956 if not grouping:
5957 return []
5958 elif grouping[-1] == 0 and len(grouping) >= 2:
5959 return chain(grouping[:-1], repeat(grouping[-2]))
5960 elif grouping[-1] == _locale.CHAR_MAX:
5961 return grouping[:-1]
5962 else:
5963 raise ValueError('unrecognised format for grouping')
5964
5965def _insert_thousands_sep(digits, spec, min_width=1):
5966 """Insert thousands separators into a digit string.
5967
5968 spec is a dictionary whose keys should include 'thousands_sep' and
5969 'grouping'; typically it's the result of parsing the format
5970 specifier using _parse_format_specifier.
5971
5972 The min_width keyword argument gives the minimum length of the
5973 result, which will be padded on the left with zeros if necessary.
5974
5975 If necessary, the zero padding adds an extra '0' on the left to
5976 avoid a leading thousands separator. For example, inserting
5977 commas every three digits in '123456', with min_width=8, gives
5978 '0,123,456', even though that has length 9.
5979
5980 """
5981
5982 sep = spec['thousands_sep']
5983 grouping = spec['grouping']
5984
5985 groups = []
5986 for l in _group_lengths(grouping):
Mark Dickinson277859d2009-03-17 23:03:46 +00005987 if l <= 0:
5988 raise ValueError("group length should be positive")
5989 # max(..., 1) forces at least 1 digit to the left of a separator
5990 l = min(max(len(digits), min_width, 1), l)
5991 groups.append('0'*(l - len(digits)) + digits[-l:])
5992 digits = digits[:-l]
5993 min_width -= l
5994 if not digits and min_width <= 0:
5995 break
Mark Dickinsonb14514a2009-03-18 08:22:51 +00005996 min_width -= len(sep)
Mark Dickinson277859d2009-03-17 23:03:46 +00005997 else:
5998 l = max(len(digits), min_width, 1)
5999 groups.append('0'*(l - len(digits)) + digits[-l:])
6000 return sep.join(reversed(groups))
6001
6002def _format_sign(is_negative, spec):
6003 """Determine sign character."""
6004
6005 if is_negative:
6006 return '-'
6007 elif spec['sign'] in ' +':
6008 return spec['sign']
6009 else:
6010 return ''
6011
6012def _format_number(is_negative, intpart, fracpart, exp, spec):
6013 """Format a number, given the following data:
6014
6015 is_negative: true if the number is negative, else false
6016 intpart: string of digits that must appear before the decimal point
6017 fracpart: string of digits that must come after the point
6018 exp: exponent, as an integer
6019 spec: dictionary resulting from parsing the format specifier
6020
6021 This function uses the information in spec to:
6022 insert separators (decimal separator and thousands separators)
6023 format the sign
6024 format the exponent
6025 add trailing '%' for the '%' type
6026 zero-pad if necessary
6027 fill and align if necessary
6028 """
6029
6030 sign = _format_sign(is_negative, spec)
6031
6032 if fracpart:
6033 fracpart = spec['decimal_point'] + fracpart
6034
6035 if exp != 0 or spec['type'] in 'eE':
6036 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6037 fracpart += "{0}{1:+}".format(echar, exp)
6038 if spec['type'] == '%':
6039 fracpart += '%'
6040
6041 if spec['zeropad']:
6042 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6043 else:
6044 min_width = 0
6045 intpart = _insert_thousands_sep(intpart, spec, min_width)
6046
6047 return _format_align(sign, intpart+fracpart, spec)
6048
6049
Facundo Batista59c58842007-04-10 12:58:45 +00006050##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006051
Facundo Batista59c58842007-04-10 12:58:45 +00006052# Reusable defaults
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00006053_Infinity = Decimal('Inf')
6054_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonc5de0962009-01-02 23:07:08 +00006055_NaN = Decimal('NaN')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00006056_Zero = Decimal(0)
6057_One = Decimal(1)
6058_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006059
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00006060# _SignedInfinity[sign] is infinity w/ that sign
6061_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006062
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006063
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00006064
6065if __name__ == '__main__':
6066 import doctest, sys
6067 doctest.testmod(sys.modules[__name__])