blob: 6529cc8d77a70e45299cb702892536a343fb2c33 [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 Hettingereb260842005-06-07 18:52:34 +0000137import copy as _copy
Raymond Hettinger45fd4762009-02-03 03:42:07 +0000138import numbers as _numbers
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000139
Raymond Hettinger097a1902008-01-11 02:24:13 +0000140try:
141 from collections import namedtuple as _namedtuple
142 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
143except ImportError:
144 DecimalTuple = lambda *args: args
145
Facundo Batista59c58842007-04-10 12:58:45 +0000146# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000147ROUND_DOWN = 'ROUND_DOWN'
148ROUND_HALF_UP = 'ROUND_HALF_UP'
149ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
150ROUND_CEILING = 'ROUND_CEILING'
151ROUND_FLOOR = 'ROUND_FLOOR'
152ROUND_UP = 'ROUND_UP'
153ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Facundo Batista353750c2007-09-13 18:13:15 +0000154ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000155
Facundo Batista59c58842007-04-10 12:58:45 +0000156# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000157
158class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000159 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000160
161 Used exceptions derive from this.
162 If an exception derives from another exception besides this (such as
163 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
164 called if the others are present. This isn't actually used for
165 anything, though.
166
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000167 handle -- Called when context._raise_error is called and the
168 trap_enabler is set. First argument is self, second is the
169 context. More arguments can be given, those being after
170 the explanation in _raise_error (For example,
171 context._raise_error(NewError, '(-x)!', self._sign) would
172 call NewError().handle(context, self._sign).)
173
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000174 To define a new exception, it should be sufficient to have it derive
175 from DecimalException.
176 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000177 def handle(self, context, *args):
178 pass
179
180
181class Clamped(DecimalException):
182 """Exponent of a 0 changed to fit bounds.
183
184 This occurs and signals clamped if the exponent of a result has been
185 altered in order to fit the constraints of a specific concrete
Facundo Batista59c58842007-04-10 12:58:45 +0000186 representation. This may occur when the exponent of a zero result would
187 be outside the bounds of a representation, or when a large normal
188 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000189 this latter case, the exponent is reduced to fit and the corresponding
190 number of zero digits are appended to the coefficient ("fold-down").
191 """
192
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000193class InvalidOperation(DecimalException):
194 """An invalid operation was performed.
195
196 Various bad things cause this:
197
198 Something creates a signaling NaN
199 -INF + INF
Facundo Batista59c58842007-04-10 12:58:45 +0000200 0 * (+-)INF
201 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000202 x % 0
203 (+-)INF % x
204 x._rescale( non-integer )
205 sqrt(-x) , x > 0
206 0 ** 0
207 x ** (non-integer)
208 x ** (+-)INF
209 An operand is invalid
Facundo Batista353750c2007-09-13 18:13:15 +0000210
211 The result of the operation after these is a quiet positive NaN,
212 except when the cause is a signaling NaN, in which case the result is
213 also a quiet NaN, but with the original sign, and an optional
214 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000215 """
216 def handle(self, context, *args):
217 if args:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000218 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
219 return ans._fix_nan(context)
Mark Dickinsonfd6032d2009-01-02 23:16:51 +0000220 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221
222class ConversionSyntax(InvalidOperation):
223 """Trying to convert badly formed string.
224
225 This occurs and signals invalid-operation if an string is being
226 converted to a number and it does not conform to the numeric string
Facundo Batista59c58842007-04-10 12:58:45 +0000227 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000228 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000229 def handle(self, context, *args):
Mark Dickinsonfd6032d2009-01-02 23:16:51 +0000230 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000231
232class DivisionByZero(DecimalException, ZeroDivisionError):
233 """Division by 0.
234
235 This occurs and signals division-by-zero if division of a finite number
236 by zero was attempted (during a divide-integer or divide operation, or a
237 power operation with negative right-hand operand), and the dividend was
238 not zero.
239
240 The result of the operation is [sign,inf], where sign is the exclusive
241 or of the signs of the operands for divide, or is 1 for an odd power of
242 -0, for power.
243 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000244
Facundo Batistacce8df22007-09-18 16:53:18 +0000245 def handle(self, context, sign, *args):
Mark Dickinsone4d46b22009-01-03 12:09:22 +0000246 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000247
248class DivisionImpossible(InvalidOperation):
249 """Cannot perform the division adequately.
250
251 This occurs and signals invalid-operation if the integer result of a
252 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000253 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000254 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000255
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000256 def handle(self, context, *args):
Mark Dickinsonfd6032d2009-01-02 23:16:51 +0000257 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000258
259class DivisionUndefined(InvalidOperation, ZeroDivisionError):
260 """Undefined result of division.
261
262 This occurs and signals invalid-operation if division by zero was
263 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000264 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000265 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000266
Facundo Batistacce8df22007-09-18 16:53:18 +0000267 def handle(self, context, *args):
Mark Dickinsonfd6032d2009-01-02 23:16:51 +0000268 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000269
270class Inexact(DecimalException):
271 """Had to round, losing information.
272
273 This occurs and signals inexact whenever the result of an operation is
274 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000275 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000276 result in all cases is unchanged.
277
278 The inexact signal may be tested (or trapped) to determine if a given
279 operation (or sequence of operations) was inexact.
280 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000281
282class InvalidContext(InvalidOperation):
283 """Invalid context. Unknown rounding, for example.
284
285 This occurs and signals invalid-operation if an invalid context was
Facundo Batista59c58842007-04-10 12:58:45 +0000286 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000287 on creation and either the precision exceeds the capability of the
288 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista59c58842007-04-10 12:58:45 +0000289 was specified. These aspects of the context need only be checked when
290 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000291 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000292
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000293 def handle(self, context, *args):
Mark Dickinsonfd6032d2009-01-02 23:16:51 +0000294 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000295
296class Rounded(DecimalException):
297 """Number got rounded (not necessarily changed during rounding).
298
299 This occurs and signals rounded whenever the result of an operation is
300 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista59c58842007-04-10 12:58:45 +0000301 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000302 result in all cases is unchanged.
303
304 The rounded signal may be tested (or trapped) to determine if a given
305 operation (or sequence of operations) caused a loss of precision.
306 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000307
308class Subnormal(DecimalException):
309 """Exponent < Emin before rounding.
310
311 This occurs and signals subnormal whenever the result of a conversion or
312 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000313 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000314
315 The subnormal signal may be tested (or trapped) to determine if a given
316 or operation (or sequence of operations) yielded a subnormal result.
317 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000318
319class Overflow(Inexact, Rounded):
320 """Numerical overflow.
321
322 This occurs and signals overflow if the adjusted exponent of a result
323 (from a conversion or from an operation that is not an attempt to divide
324 by zero), after rounding, would be greater than the largest value that
325 can be handled by the implementation (the value Emax).
326
327 The result depends on the rounding mode:
328
329 For round-half-up and round-half-even (and for round-half-down and
330 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000331 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000332 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000333 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000334 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000335 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000336 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000337 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000338 will also be raised.
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000339 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000340
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 def handle(self, context, sign, *args):
342 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000343 ROUND_HALF_DOWN, ROUND_UP):
Mark Dickinsone4d46b22009-01-03 12:09:22 +0000344 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000345 if sign == 0:
346 if context.rounding == ROUND_CEILING:
Mark Dickinsone4d46b22009-01-03 12:09:22 +0000347 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000348 return _dec_from_triple(sign, '9'*context.prec,
349 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000350 if sign == 1:
351 if context.rounding == ROUND_FLOOR:
Mark Dickinsone4d46b22009-01-03 12:09:22 +0000352 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000353 return _dec_from_triple(sign, '9'*context.prec,
354 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000355
356
357class Underflow(Inexact, Rounded, Subnormal):
358 """Numerical underflow with result rounded to 0.
359
360 This occurs and signals underflow if a result is inexact and the
361 adjusted exponent of the result would be smaller (more negative) than
362 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000363 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000364
365 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000366 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000367 in 0 with the sign of the intermediate result and an exponent of Etiny.
368
369 In all cases, Inexact, Rounded, and Subnormal will also be raised.
370 """
371
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000372# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000373_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000374 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000375
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000376# Map conditions (per the spec) to signals
377_condition_map = {ConversionSyntax:InvalidOperation,
378 DivisionImpossible:InvalidOperation,
379 DivisionUndefined:InvalidOperation,
380 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000381
Facundo Batista59c58842007-04-10 12:58:45 +0000382##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000383
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000384# The getcontext() and setcontext() function manage access to a thread-local
385# current context. Py2.4 offers direct support for thread locals. If that
386# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000387# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000388# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000389
390try:
391 import threading
392except ImportError:
393 # Python was compiled without threads; create a mock object instead
394 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000395 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000396 def local(self, sys=sys):
397 return sys.modules[__name__]
398 threading = MockThreading()
399 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000400
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000401try:
402 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000403
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000404except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Facundo Batista59c58842007-04-10 12:58:45 +0000406 # To fix reloading, force it to create a new context
407 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000408 if hasattr(threading.currentThread(), '__decimal_context__'):
409 del threading.currentThread().__decimal_context__
410
411 def setcontext(context):
412 """Set this thread's context to context."""
413 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000414 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000415 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000416 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000417
418 def getcontext():
419 """Returns this thread's context.
420
421 If this thread does not yet have a context, returns
422 a new context and sets this thread's context.
423 New contexts are copies of DefaultContext.
424 """
425 try:
426 return threading.currentThread().__decimal_context__
427 except AttributeError:
428 context = Context()
429 threading.currentThread().__decimal_context__ = context
430 return context
431
432else:
433
434 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000435 if hasattr(local, '__decimal_context__'):
436 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000437
438 def getcontext(_local=local):
439 """Returns this thread's context.
440
441 If this thread does not yet have a context, returns
442 a new context and sets this thread's context.
443 New contexts are copies of DefaultContext.
444 """
445 try:
446 return _local.__decimal_context__
447 except AttributeError:
448 context = Context()
449 _local.__decimal_context__ = context
450 return context
451
452 def setcontext(context, _local=local):
453 """Set this thread's context to context."""
454 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000455 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000456 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000457 _local.__decimal_context__ = context
458
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000459 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000460
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000461def localcontext(ctx=None):
462 """Return a context manager for a copy of the supplied context
463
464 Uses a copy of the current context if no context is specified
465 The returned context manager creates a local decimal context
466 in a with statement:
467 def sin(x):
468 with localcontext() as ctx:
469 ctx.prec += 2
470 # Rest of sin calculation algorithm
471 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000472 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000473
474 def sin(x):
475 with localcontext(ExtendedContext):
476 # Rest of sin calculation algorithm
477 # uses the Extended Context from the
478 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000479 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000480
Facundo Batistaee340e52008-05-02 17:39:00 +0000481 >>> setcontext(DefaultContext)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000482 >>> print getcontext().prec
483 28
484 >>> with localcontext():
485 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000486 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000487 ... print ctx.prec
488 ...
489 30
490 >>> with localcontext(ExtendedContext):
491 ... print getcontext().prec
492 ...
493 9
494 >>> print getcontext().prec
495 28
496 """
Nick Coghlanced12182006-09-02 03:54:17 +0000497 if ctx is None: ctx = getcontext()
498 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000499
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000500
Facundo Batista59c58842007-04-10 12:58:45 +0000501##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000502
503class Decimal(object):
504 """Floating point class for decimal arithmetic."""
505
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000506 __slots__ = ('_exp','_int','_sign', '_is_special')
507 # Generally, the value of the Decimal instance is given by
508 # (-1)**_sign * _int * 10**_exp
509 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000510
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000511 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000512 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000513 """Create a decimal point instance.
514
515 >>> Decimal('3.14') # string input
Raymond Hettingerabe32372008-02-14 02:41:22 +0000516 Decimal('3.14')
Facundo Batista59c58842007-04-10 12:58:45 +0000517 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000518 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000519 >>> Decimal(314) # int or long
Raymond Hettingerabe32372008-02-14 02:41:22 +0000520 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000521 >>> Decimal(Decimal(314)) # another decimal instance
Raymond Hettingerabe32372008-02-14 02:41:22 +0000522 Decimal('314')
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000523 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Raymond Hettingerabe32372008-02-14 02:41:22 +0000524 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000525 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000526
Facundo Batista72bc54f2007-11-23 17:59:00 +0000527 # Note that the coefficient, self._int, is actually stored as
528 # a string rather than as a tuple of digits. This speeds up
529 # the "digits to integer" and "integer to digits" conversions
530 # that are used in almost every arithmetic operation on
531 # Decimals. This is an internal detail: the as_tuple function
532 # and the Decimal constructor still deal with tuples of
533 # digits.
534
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000535 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000536
Facundo Batista0d157a02007-11-30 17:15:25 +0000537 # From a string
538 # REs insist on real strings, so we can too.
539 if isinstance(value, basestring):
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000540 m = _parser(value.strip())
Facundo Batista0d157a02007-11-30 17:15:25 +0000541 if m is None:
542 if context is None:
543 context = getcontext()
544 return context._raise_error(ConversionSyntax,
545 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000546
Facundo Batista0d157a02007-11-30 17:15:25 +0000547 if m.group('sign') == "-":
548 self._sign = 1
549 else:
550 self._sign = 0
551 intpart = m.group('int')
552 if intpart is not None:
553 # finite number
554 fracpart = m.group('frac')
555 exp = int(m.group('exp') or '0')
556 if fracpart is not None:
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000557 self._int = str((intpart+fracpart).lstrip('0') or '0')
Facundo Batista0d157a02007-11-30 17:15:25 +0000558 self._exp = exp - len(fracpart)
559 else:
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000560 self._int = str(intpart.lstrip('0') or '0')
Facundo Batista0d157a02007-11-30 17:15:25 +0000561 self._exp = exp
562 self._is_special = False
563 else:
564 diag = m.group('diag')
565 if diag is not None:
566 # NaN
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000567 self._int = str(diag.lstrip('0'))
Facundo Batista0d157a02007-11-30 17:15:25 +0000568 if m.group('signal'):
569 self._exp = 'N'
570 else:
571 self._exp = 'n'
572 else:
573 # infinity
574 self._int = '0'
575 self._exp = 'F'
576 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000577 return self
578
579 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000580 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000581 if value >= 0:
582 self._sign = 0
583 else:
584 self._sign = 1
585 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000586 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000587 self._is_special = False
588 return self
589
590 # From another decimal
591 if isinstance(value, Decimal):
592 self._exp = value._exp
593 self._sign = value._sign
594 self._int = value._int
595 self._is_special = value._is_special
596 return self
597
598 # From an internal working value
599 if isinstance(value, _WorkRep):
600 self._sign = value.sign
601 self._int = str(value.int)
602 self._exp = int(value.exp)
603 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000604 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000605
606 # tuple/list conversion (possibly from as_tuple())
607 if isinstance(value, (list,tuple)):
608 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000609 raise ValueError('Invalid tuple size in creation of Decimal '
610 'from list or tuple. The list or tuple '
611 'should have exactly three elements.')
612 # process sign. The isinstance test rejects floats
613 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
614 raise ValueError("Invalid sign. The first value in the tuple "
615 "should be an integer; either 0 for a "
616 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000617 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000618 if value[2] == 'F':
619 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000620 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000621 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000622 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000623 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000624 # process and validate the digits in value[1]
625 digits = []
626 for digit in value[1]:
627 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
628 # skip leading zeros
629 if digits or digit != 0:
630 digits.append(digit)
631 else:
632 raise ValueError("The second value in the tuple must "
633 "be composed of integers in the range "
634 "0 through 9.")
635 if value[2] in ('n', 'N'):
636 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000637 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000638 self._exp = value[2]
639 self._is_special = True
640 elif isinstance(value[2], (int, long)):
641 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000642 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000643 self._exp = value[2]
644 self._is_special = False
645 else:
646 raise ValueError("The third value in the tuple must "
647 "be an integer, or one of the "
648 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000649 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000650
Raymond Hettingerbf440692004-07-10 14:14:37 +0000651 if isinstance(value, float):
652 raise TypeError("Cannot convert float to Decimal. " +
653 "First convert the float to a string")
654
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000655 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000656
657 def _isnan(self):
658 """Returns whether the number is not actually one.
659
660 0 if a number
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000661 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000662 2 if sNaN
663 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000664 if self._is_special:
665 exp = self._exp
666 if exp == 'n':
667 return 1
668 elif exp == 'N':
669 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000670 return 0
671
672 def _isinfinity(self):
673 """Returns whether the number is infinite
674
675 0 if finite or not a number
676 1 if +INF
677 -1 if -INF
678 """
679 if self._exp == 'F':
680 if self._sign:
681 return -1
682 return 1
683 return 0
684
Facundo Batista353750c2007-09-13 18:13:15 +0000685 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000686 """Returns whether the number is not actually one.
687
688 if self, other are sNaN, signal
689 if self, other are NaN return nan
690 return 0
691
692 Done before operations.
693 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000695 self_is_nan = self._isnan()
696 if other is None:
697 other_is_nan = False
698 else:
699 other_is_nan = other._isnan()
700
701 if self_is_nan or other_is_nan:
702 if context is None:
703 context = getcontext()
704
705 if self_is_nan == 2:
706 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000707 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000708 if other_is_nan == 2:
709 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000710 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000711 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000712 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000713
Facundo Batista353750c2007-09-13 18:13:15 +0000714 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000715 return 0
716
Mark Dickinson2fc92632008-02-06 22:10:50 +0000717 def _compare_check_nans(self, other, context):
718 """Version of _check_nans used for the signaling comparisons
719 compare_signal, __le__, __lt__, __ge__, __gt__.
720
721 Signal InvalidOperation if either self or other is a (quiet
722 or signaling) NaN. Signaling NaNs take precedence over quiet
723 NaNs.
724
725 Return 0 if neither operand is a NaN.
726
727 """
728 if context is None:
729 context = getcontext()
730
731 if self._is_special or other._is_special:
732 if self.is_snan():
733 return context._raise_error(InvalidOperation,
734 'comparison involving sNaN',
735 self)
736 elif other.is_snan():
737 return context._raise_error(InvalidOperation,
738 'comparison involving sNaN',
739 other)
740 elif self.is_qnan():
741 return context._raise_error(InvalidOperation,
742 'comparison involving NaN',
743 self)
744 elif other.is_qnan():
745 return context._raise_error(InvalidOperation,
746 'comparison involving NaN',
747 other)
748 return 0
749
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000750 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000751 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000752
Facundo Batista1a191df2007-10-02 17:01:24 +0000753 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000754 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000755 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000756
Mark Dickinson2fc92632008-02-06 22:10:50 +0000757 def _cmp(self, other):
758 """Compare the two non-NaN decimal instances self and other.
759
760 Returns -1 if self < other, 0 if self == other and 1
761 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000762
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000763 if self._is_special or other._is_special:
Mark Dickinson8ec69bc2009-01-25 10:47:45 +0000764 self_inf = self._isinfinity()
765 other_inf = other._isinfinity()
766 if self_inf == other_inf:
767 return 0
768 elif self_inf < other_inf:
769 return -1
770 else:
771 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000772
Mark Dickinson8ec69bc2009-01-25 10:47:45 +0000773 # check for zeros; Decimal('0') == Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000774 if not self:
775 if not other:
776 return 0
777 else:
778 return -((-1)**other._sign)
779 if not other:
780 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000781
Facundo Batista59c58842007-04-10 12:58:45 +0000782 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000783 if other._sign < self._sign:
784 return -1
785 if self._sign < other._sign:
786 return 1
787
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000788 self_adjusted = self.adjusted()
789 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000790 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000791 self_padded = self._int + '0'*(self._exp - other._exp)
792 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinson8ec69bc2009-01-25 10:47:45 +0000793 if self_padded == other_padded:
794 return 0
795 elif self_padded < other_padded:
796 return -(-1)**self._sign
797 else:
798 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000799 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000800 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000801 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000802 return -((-1)**self._sign)
803
Mark Dickinson2fc92632008-02-06 22:10:50 +0000804 # Note: The Decimal standard doesn't cover rich comparisons for
805 # Decimals. In particular, the specification is silent on the
806 # subject of what should happen for a comparison involving a NaN.
807 # We take the following approach:
808 #
809 # == comparisons involving a NaN always return False
810 # != comparisons involving a NaN always return True
811 # <, >, <= and >= comparisons involving a (quiet or signaling)
812 # NaN signal InvalidOperation, and return False if the
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000813 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000814 #
815 # This behavior is designed to conform as closely as possible to
816 # that specified by IEEE 754.
817
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000818 def __eq__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000819 other = _convert_other(other)
820 if other is NotImplemented:
821 return other
822 if self.is_nan() or other.is_nan():
823 return False
824 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000825
826 def __ne__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000827 other = _convert_other(other)
828 if other is NotImplemented:
829 return other
830 if self.is_nan() or other.is_nan():
831 return True
832 return self._cmp(other) != 0
833
834 def __lt__(self, other, context=None):
835 other = _convert_other(other)
836 if other is NotImplemented:
837 return other
838 ans = self._compare_check_nans(other, context)
839 if ans:
840 return False
841 return self._cmp(other) < 0
842
843 def __le__(self, other, context=None):
844 other = _convert_other(other)
845 if other is NotImplemented:
846 return other
847 ans = self._compare_check_nans(other, context)
848 if ans:
849 return False
850 return self._cmp(other) <= 0
851
852 def __gt__(self, other, context=None):
853 other = _convert_other(other)
854 if other is NotImplemented:
855 return other
856 ans = self._compare_check_nans(other, context)
857 if ans:
858 return False
859 return self._cmp(other) > 0
860
861 def __ge__(self, other, context=None):
862 other = _convert_other(other)
863 if other is NotImplemented:
864 return other
865 ans = self._compare_check_nans(other, context)
866 if ans:
867 return False
868 return self._cmp(other) >= 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000869
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000870 def compare(self, other, context=None):
871 """Compares one to another.
872
873 -1 => a < b
874 0 => a = b
875 1 => a > b
876 NaN => one is NaN
877 Like __cmp__, but returns Decimal instances.
878 """
Facundo Batista353750c2007-09-13 18:13:15 +0000879 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000880
Facundo Batista59c58842007-04-10 12:58:45 +0000881 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000882 if (self._is_special or other and other._is_special):
883 ans = self._check_nans(other, context)
884 if ans:
885 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000886
Mark Dickinson2fc92632008-02-06 22:10:50 +0000887 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000888
889 def __hash__(self):
890 """x.__hash__() <==> hash(x)"""
891 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000892 #
893 # The hash of a nonspecial noninteger Decimal must depend only
894 # on the value of that Decimal, and not on its representation.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000895 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000896 if self._is_special:
897 if self._isnan():
898 raise TypeError('Cannot hash a NaN value.')
899 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000900 if not self:
901 return 0
902 if self._isinteger():
903 op = _WorkRep(self.to_integral_value())
904 # to make computation feasible for Decimals with large
905 # exponent, we use the fact that hash(n) == hash(m) for
906 # any two nonzero integers n and m such that (i) n and m
907 # have the same sign, and (ii) n is congruent to m modulo
908 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
909 # hash((-1)**s*c*pow(10, e, 2**64-1).
910 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000911 # The value of a nonzero nonspecial Decimal instance is
912 # faithfully represented by the triple consisting of its sign,
913 # its adjusted exponent, and its coefficient with trailing
914 # zeros removed.
915 return hash((self._sign,
916 self._exp+len(self._int),
917 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000918
919 def as_tuple(self):
920 """Represents the number as a triple tuple.
921
922 To show the internals exactly as they are.
923 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000924 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000925
926 def __repr__(self):
927 """Represents the number as an instance of Decimal."""
928 # Invariant: eval(repr(d)) == d
Raymond Hettingerabe32372008-02-14 02:41:22 +0000929 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000930
Facundo Batista353750c2007-09-13 18:13:15 +0000931 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000932 """Return string representation of the number in scientific notation.
933
934 Captures all of the information in the underlying representation.
935 """
936
Facundo Batista62edb712007-12-03 16:29:52 +0000937 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000938 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000939 if self._exp == 'F':
940 return sign + 'Infinity'
941 elif self._exp == 'n':
942 return sign + 'NaN' + self._int
943 else: # self._exp == 'N'
944 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000945
Facundo Batista62edb712007-12-03 16:29:52 +0000946 # number of digits of self._int to left of decimal point
947 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000948
Facundo Batista62edb712007-12-03 16:29:52 +0000949 # dotplace is number of digits of self._int to the left of the
950 # decimal point in the mantissa of the output string (that is,
951 # after adjusting the exponent)
952 if self._exp <= 0 and leftdigits > -6:
953 # no exponent required
954 dotplace = leftdigits
955 elif not eng:
956 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000957 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000958 elif self._int == '0':
959 # engineering notation, zero
960 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000961 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000962 # engineering notation, nonzero
963 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000964
Facundo Batista62edb712007-12-03 16:29:52 +0000965 if dotplace <= 0:
966 intpart = '0'
967 fracpart = '.' + '0'*(-dotplace) + self._int
968 elif dotplace >= len(self._int):
969 intpart = self._int+'0'*(dotplace-len(self._int))
970 fracpart = ''
971 else:
972 intpart = self._int[:dotplace]
973 fracpart = '.' + self._int[dotplace:]
974 if leftdigits == dotplace:
975 exp = ''
976 else:
977 if context is None:
978 context = getcontext()
979 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
980
981 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000982
983 def to_eng_string(self, context=None):
984 """Convert to engineering-type string.
985
986 Engineering notation has an exponent which is a multiple of 3, so there
987 are up to 3 digits left of the decimal place.
988
989 Same rules for when in exponential and when as a value as in __str__.
990 """
Facundo Batista353750c2007-09-13 18:13:15 +0000991 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000992
993 def __neg__(self, context=None):
994 """Returns a copy with the sign switched.
995
996 Rounds, if it has reason.
997 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000998 if self._is_special:
999 ans = self._check_nans(context=context)
1000 if ans:
1001 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001002
1003 if not self:
1004 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001005 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001006 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001007 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001008
1009 if context is None:
1010 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001011 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012
1013 def __pos__(self, context=None):
1014 """Returns a copy, unless it is a sNaN.
1015
1016 Rounds the number (if more then precision digits)
1017 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001018 if self._is_special:
1019 ans = self._check_nans(context=context)
1020 if ans:
1021 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023 if not self:
1024 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001025 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +00001026 else:
1027 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001028
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001029 if context is None:
1030 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001031 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001032
Facundo Batistae64acfa2007-12-17 14:18:42 +00001033 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034 """Returns the absolute value of self.
1035
Facundo Batistae64acfa2007-12-17 14:18:42 +00001036 If the keyword argument 'round' is false, do not round. The
1037 expression self.__abs__(round=False) is equivalent to
1038 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001039 """
Facundo Batistae64acfa2007-12-17 14:18:42 +00001040 if not round:
1041 return self.copy_abs()
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
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001048 if self._sign:
1049 ans = self.__neg__(context=context)
1050 else:
1051 ans = self.__pos__(context=context)
1052
1053 return ans
1054
1055 def __add__(self, other, context=None):
1056 """Returns self + other.
1057
1058 -INF + INF (or the reverse) cause InvalidOperation errors.
1059 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001060 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001061 if other is NotImplemented:
1062 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001063
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064 if context is None:
1065 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001066
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001067 if self._is_special or other._is_special:
1068 ans = self._check_nans(other, context)
1069 if ans:
1070 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001072 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001073 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001074 if self._sign != other._sign and other._isinfinity():
1075 return context._raise_error(InvalidOperation, '-INF + INF')
1076 return Decimal(self)
1077 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001078 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001079
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001080 exp = min(self._exp, other._exp)
1081 negativezero = 0
1082 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001083 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084 negativezero = 1
1085
1086 if not self and not other:
1087 sign = min(self._sign, other._sign)
1088 if negativezero:
1089 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001090 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001091 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001092 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001093 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001094 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001095 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001096 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001097 return ans
1098 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001099 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001100 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001101 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001102 return ans
1103
1104 op1 = _WorkRep(self)
1105 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001106 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001107
1108 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001110 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001111 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001112 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001113 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001114 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001115 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001116 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001117 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001118 if op1.sign == 1:
1119 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001120 op1.sign, op2.sign = op2.sign, op1.sign
1121 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001122 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001123 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001124 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001125 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001126 op1.sign, op2.sign = (0, 0)
1127 else:
1128 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001129 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001130
Raymond Hettinger17931de2004-10-27 06:21:46 +00001131 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001132 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001133 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001134 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135
1136 result.exp = op1.exp
1137 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001138 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001139 return ans
1140
1141 __radd__ = __add__
1142
1143 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001144 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001145 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001146 if other is NotImplemented:
1147 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001149 if self._is_special or other._is_special:
1150 ans = self._check_nans(other, context=context)
1151 if ans:
1152 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001153
Facundo Batista353750c2007-09-13 18:13:15 +00001154 # self - other is computed as self + other.copy_negate()
1155 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001156
1157 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001158 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001159 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001160 if other is NotImplemented:
1161 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001162
Facundo Batista353750c2007-09-13 18:13:15 +00001163 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001164
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165 def __mul__(self, other, context=None):
1166 """Return self * other.
1167
1168 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1169 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001170 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001171 if other is NotImplemented:
1172 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001173
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001174 if context is None:
1175 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001177 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001178
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001179 if self._is_special or other._is_special:
1180 ans = self._check_nans(other, context)
1181 if ans:
1182 return ans
1183
1184 if self._isinfinity():
1185 if not other:
1186 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001187 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001188
1189 if other._isinfinity():
1190 if not self:
1191 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001192 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001193
1194 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001195
1196 # Special case for multiplying by zero
1197 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001198 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001199 # Fixing in case the exponent is out of bounds
1200 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001201 return ans
1202
1203 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001204 if self._int == '1':
1205 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001206 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001207 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001208 if other._int == '1':
1209 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001210 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001211 return ans
1212
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001213 op1 = _WorkRep(self)
1214 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001215
Facundo Batista72bc54f2007-11-23 17:59:00 +00001216 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001217 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001218
1219 return ans
1220 __rmul__ = __mul__
1221
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001222 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001224 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001225 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001226 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001227
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228 if context is None:
1229 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001230
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001231 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001232
1233 if self._is_special or other._is_special:
1234 ans = self._check_nans(other, context)
1235 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001236 return ans
1237
1238 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001239 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001241 if self._isinfinity():
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001242 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001243
1244 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001245 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001246 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001247
1248 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001249 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001250 if not self:
1251 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001252 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001253
Facundo Batistacce8df22007-09-18 16:53:18 +00001254 if not self:
1255 exp = self._exp - other._exp
1256 coeff = 0
1257 else:
1258 # OK, so neither = 0, INF or NaN
1259 shift = len(other._int) - len(self._int) + context.prec + 1
1260 exp = self._exp - other._exp - shift
1261 op1 = _WorkRep(self)
1262 op2 = _WorkRep(other)
1263 if shift >= 0:
1264 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1265 else:
1266 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1267 if remainder:
1268 # result is not exact; adjust to ensure correct rounding
1269 if coeff % 5 == 0:
1270 coeff += 1
1271 else:
1272 # result is exact; get as close to ideal exponent as possible
1273 ideal_exp = self._exp - other._exp
1274 while exp < ideal_exp and coeff % 10 == 0:
1275 coeff //= 10
1276 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001277
Facundo Batista72bc54f2007-11-23 17:59:00 +00001278 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001279 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001280
Facundo Batistacce8df22007-09-18 16:53:18 +00001281 def _divide(self, other, context):
1282 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001283
Facundo Batistacce8df22007-09-18 16:53:18 +00001284 Assumes that neither self nor other is a NaN, that self is not
1285 infinite and that other is nonzero.
1286 """
1287 sign = self._sign ^ other._sign
1288 if other._isinfinity():
1289 ideal_exp = self._exp
1290 else:
1291 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001292
Facundo Batistacce8df22007-09-18 16:53:18 +00001293 expdiff = self.adjusted() - other.adjusted()
1294 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001295 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001296 self._rescale(ideal_exp, context.rounding))
1297 if expdiff <= context.prec:
1298 op1 = _WorkRep(self)
1299 op2 = _WorkRep(other)
1300 if op1.exp >= op2.exp:
1301 op1.int *= 10**(op1.exp - op2.exp)
1302 else:
1303 op2.int *= 10**(op2.exp - op1.exp)
1304 q, r = divmod(op1.int, op2.int)
1305 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001306 return (_dec_from_triple(sign, str(q), 0),
1307 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001308
Facundo Batistacce8df22007-09-18 16:53:18 +00001309 # Here the quotient is too large to be representable
1310 ans = context._raise_error(DivisionImpossible,
1311 'quotient too large in //, % or divmod')
1312 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001313
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001314 def __rtruediv__(self, other, context=None):
1315 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001316 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001317 if other is NotImplemented:
1318 return other
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001319 return other.__truediv__(self, context=context)
1320
1321 __div__ = __truediv__
1322 __rdiv__ = __rtruediv__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001323
1324 def __divmod__(self, other, context=None):
1325 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001326 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001327 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001328 other = _convert_other(other)
1329 if other is NotImplemented:
1330 return other
1331
1332 if context is None:
1333 context = getcontext()
1334
1335 ans = self._check_nans(other, context)
1336 if ans:
1337 return (ans, ans)
1338
1339 sign = self._sign ^ other._sign
1340 if self._isinfinity():
1341 if other._isinfinity():
1342 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1343 return ans, ans
1344 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001345 return (_SignedInfinity[sign],
Facundo Batistacce8df22007-09-18 16:53:18 +00001346 context._raise_error(InvalidOperation, 'INF % x'))
1347
1348 if not other:
1349 if not self:
1350 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1351 return ans, ans
1352 else:
1353 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1354 context._raise_error(InvalidOperation, 'x % 0'))
1355
1356 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001357 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001358 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001359
1360 def __rdivmod__(self, other, context=None):
1361 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001362 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001363 if other is NotImplemented:
1364 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001365 return other.__divmod__(self, context=context)
1366
1367 def __mod__(self, other, context=None):
1368 """
1369 self % other
1370 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001371 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001372 if other is NotImplemented:
1373 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001374
Facundo Batistacce8df22007-09-18 16:53:18 +00001375 if context is None:
1376 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001377
Facundo Batistacce8df22007-09-18 16:53:18 +00001378 ans = self._check_nans(other, context)
1379 if ans:
1380 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001381
Facundo Batistacce8df22007-09-18 16:53:18 +00001382 if self._isinfinity():
1383 return context._raise_error(InvalidOperation, 'INF % x')
1384 elif not other:
1385 if self:
1386 return context._raise_error(InvalidOperation, 'x % 0')
1387 else:
1388 return context._raise_error(DivisionUndefined, '0 % 0')
1389
1390 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001391 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001392 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001393
1394 def __rmod__(self, other, context=None):
1395 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001396 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001397 if other is NotImplemented:
1398 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001399 return other.__mod__(self, context=context)
1400
1401 def remainder_near(self, other, context=None):
1402 """
1403 Remainder nearest to 0- abs(remainder-near) <= other/2
1404 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001405 if context is None:
1406 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001407
Facundo Batista353750c2007-09-13 18:13:15 +00001408 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001409
Facundo Batista353750c2007-09-13 18:13:15 +00001410 ans = self._check_nans(other, context)
1411 if ans:
1412 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001413
Facundo Batista353750c2007-09-13 18:13:15 +00001414 # self == +/-infinity -> InvalidOperation
1415 if self._isinfinity():
1416 return context._raise_error(InvalidOperation,
1417 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001418
Facundo Batista353750c2007-09-13 18:13:15 +00001419 # other == 0 -> either InvalidOperation or DivisionUndefined
1420 if not other:
1421 if self:
1422 return context._raise_error(InvalidOperation,
1423 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001424 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001425 return context._raise_error(DivisionUndefined,
1426 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001427
Facundo Batista353750c2007-09-13 18:13:15 +00001428 # other = +/-infinity -> remainder = self
1429 if other._isinfinity():
1430 ans = Decimal(self)
1431 return ans._fix(context)
1432
1433 # self = 0 -> remainder = self, with ideal exponent
1434 ideal_exponent = min(self._exp, other._exp)
1435 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001436 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001437 return ans._fix(context)
1438
1439 # catch most cases of large or small quotient
1440 expdiff = self.adjusted() - other.adjusted()
1441 if expdiff >= context.prec + 1:
1442 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001443 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001444 if expdiff <= -2:
1445 # expdiff <= -2 => abs(self/other) < 0.1
1446 ans = self._rescale(ideal_exponent, context.rounding)
1447 return ans._fix(context)
1448
1449 # adjust both arguments to have the same exponent, then divide
1450 op1 = _WorkRep(self)
1451 op2 = _WorkRep(other)
1452 if op1.exp >= op2.exp:
1453 op1.int *= 10**(op1.exp - op2.exp)
1454 else:
1455 op2.int *= 10**(op2.exp - op1.exp)
1456 q, r = divmod(op1.int, op2.int)
1457 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1458 # 10**ideal_exponent. Apply correction to ensure that
1459 # abs(remainder) <= abs(other)/2
1460 if 2*r + (q&1) > op2.int:
1461 r -= op2.int
1462 q += 1
1463
1464 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001465 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001466
1467 # result has same sign as self unless r is negative
1468 sign = self._sign
1469 if r < 0:
1470 sign = 1-sign
1471 r = -r
1472
Facundo Batista72bc54f2007-11-23 17:59:00 +00001473 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001474 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001475
1476 def __floordiv__(self, other, context=None):
1477 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001478 other = _convert_other(other)
1479 if other is NotImplemented:
1480 return other
1481
1482 if context is None:
1483 context = getcontext()
1484
1485 ans = self._check_nans(other, context)
1486 if ans:
1487 return ans
1488
1489 if self._isinfinity():
1490 if other._isinfinity():
1491 return context._raise_error(InvalidOperation, 'INF // INF')
1492 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001493 return _SignedInfinity[self._sign ^ other._sign]
Facundo Batistacce8df22007-09-18 16:53:18 +00001494
1495 if not other:
1496 if self:
1497 return context._raise_error(DivisionByZero, 'x // 0',
1498 self._sign ^ other._sign)
1499 else:
1500 return context._raise_error(DivisionUndefined, '0 // 0')
1501
1502 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001503
1504 def __rfloordiv__(self, other, context=None):
1505 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001506 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001507 if other is NotImplemented:
1508 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001509 return other.__floordiv__(self, context=context)
1510
1511 def __float__(self):
1512 """Float representation."""
1513 return float(str(self))
1514
1515 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001516 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001517 if self._is_special:
1518 if self._isnan():
1519 context = getcontext()
1520 return context._raise_error(InvalidContext)
1521 elif self._isinfinity():
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001522 raise OverflowError("Cannot convert infinity to int")
Facundo Batista353750c2007-09-13 18:13:15 +00001523 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001524 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001525 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001526 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001527 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001528
Raymond Hettinger5a053642008-01-24 19:05:29 +00001529 __trunc__ = __int__
1530
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001531 def real(self):
1532 return self
Mark Dickinsonc95c6f12009-01-04 21:30:17 +00001533 real = property(real)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001534
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001535 def imag(self):
1536 return Decimal(0)
Mark Dickinsonc95c6f12009-01-04 21:30:17 +00001537 imag = property(imag)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001538
1539 def conjugate(self):
1540 return self
1541
1542 def __complex__(self):
1543 return complex(float(self))
1544
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001545 def __long__(self):
1546 """Converts to a long.
1547
1548 Equivalent to long(int(self))
1549 """
1550 return long(self.__int__())
1551
Facundo Batista353750c2007-09-13 18:13:15 +00001552 def _fix_nan(self, context):
1553 """Decapitate the payload of a NaN to fit the context"""
1554 payload = self._int
1555
1556 # maximum length of payload is precision if _clamp=0,
1557 # precision-1 if _clamp=1.
1558 max_payload_len = context.prec - context._clamp
1559 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001560 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1561 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001562 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001563
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001564 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001565 """Round if it is necessary to keep self within prec precision.
1566
1567 Rounds and fixes the exponent. Does not raise on a sNaN.
1568
1569 Arguments:
1570 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001571 context - context used.
1572 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001573
Facundo Batista353750c2007-09-13 18:13:15 +00001574 if self._is_special:
1575 if self._isnan():
1576 # decapitate payload if necessary
1577 return self._fix_nan(context)
1578 else:
1579 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001580 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001581
Facundo Batista353750c2007-09-13 18:13:15 +00001582 # if self is zero then exponent should be between Etiny and
1583 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1584 Etiny = context.Etiny()
1585 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001586 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001587 exp_max = [context.Emax, Etop][context._clamp]
1588 new_exp = min(max(self._exp, Etiny), exp_max)
1589 if new_exp != self._exp:
1590 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001591 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001592 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001593 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001594
1595 # exp_min is the smallest allowable exponent of the result,
1596 # equal to max(self.adjusted()-context.prec+1, Etiny)
1597 exp_min = len(self._int) + self._exp - context.prec
1598 if exp_min > Etop:
1599 # overflow: exp_min > Etop iff self.adjusted() > Emax
1600 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001601 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001602 return context._raise_error(Overflow, 'above Emax', self._sign)
1603 self_is_subnormal = exp_min < Etiny
1604 if self_is_subnormal:
1605 context._raise_error(Subnormal)
1606 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001607
Facundo Batista353750c2007-09-13 18:13:15 +00001608 # round if self has too many digits
1609 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001610 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001611 digits = len(self._int) + self._exp - exp_min
1612 if digits < 0:
1613 self = _dec_from_triple(self._sign, '1', exp_min-1)
1614 digits = 0
1615 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1616 changed = this_function(digits)
1617 coeff = self._int[:digits] or '0'
1618 if changed == 1:
1619 coeff = str(int(coeff)+1)
1620 ans = _dec_from_triple(self._sign, coeff, exp_min)
1621
1622 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001623 context._raise_error(Inexact)
1624 if self_is_subnormal:
1625 context._raise_error(Underflow)
1626 if not ans:
1627 # raise Clamped on underflow to 0
1628 context._raise_error(Clamped)
1629 elif len(ans._int) == context.prec+1:
1630 # we get here only if rescaling rounds the
1631 # cofficient up to exactly 10**context.prec
1632 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001633 ans = _dec_from_triple(ans._sign,
1634 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001635 else:
1636 # Inexact and Rounded have already been raised
1637 ans = context._raise_error(Overflow, 'above Emax',
1638 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001639 return ans
1640
Facundo Batista353750c2007-09-13 18:13:15 +00001641 # fold down if _clamp == 1 and self has too few digits
1642 if context._clamp == 1 and self._exp > Etop:
1643 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001644 self_padded = self._int + '0'*(self._exp - Etop)
1645 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001646
Facundo Batista353750c2007-09-13 18:13:15 +00001647 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001648 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001649
1650 _pick_rounding_function = {}
1651
Facundo Batista353750c2007-09-13 18:13:15 +00001652 # for each of the rounding functions below:
1653 # self is a finite, nonzero Decimal
1654 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001655 #
1656 # each function returns either -1, 0, or 1, as follows:
1657 # 1 indicates that self should be rounded up (away from zero)
1658 # 0 indicates that self should be truncated, and that all the
1659 # digits to be truncated are zeros (so the value is unchanged)
1660 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001661
1662 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001663 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001664 if _all_zeros(self._int, prec):
1665 return 0
1666 else:
1667 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001668
Facundo Batista353750c2007-09-13 18:13:15 +00001669 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001670 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001671 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001672
Facundo Batista353750c2007-09-13 18:13:15 +00001673 def _round_half_up(self, prec):
1674 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001675 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001676 return 1
1677 elif _all_zeros(self._int, prec):
1678 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001679 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001680 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001681
1682 def _round_half_down(self, prec):
1683 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001684 if _exact_half(self._int, prec):
1685 return -1
1686 else:
1687 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001688
1689 def _round_half_even(self, prec):
1690 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001691 if _exact_half(self._int, prec) and \
1692 (prec == 0 or self._int[prec-1] in '02468'):
1693 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001694 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001695 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001696
1697 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001698 """Rounds up (not away from 0 if negative.)"""
1699 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001700 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001701 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001702 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001703
Facundo Batista353750c2007-09-13 18:13:15 +00001704 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001705 """Rounds down (not towards 0 if negative)"""
1706 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001707 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001708 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001709 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001710
Facundo Batista353750c2007-09-13 18:13:15 +00001711 def _round_05up(self, prec):
1712 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001713 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001714 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001715 else:
1716 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001717
Facundo Batista353750c2007-09-13 18:13:15 +00001718 def fma(self, other, third, context=None):
1719 """Fused multiply-add.
1720
1721 Returns self*other+third with no rounding of the intermediate
1722 product self*other.
1723
1724 self and other are multiplied together, with no rounding of
1725 the result. The third operand is then added to the result,
1726 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001727 """
Facundo Batista353750c2007-09-13 18:13:15 +00001728
1729 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001730
1731 # compute product; raise InvalidOperation if either operand is
1732 # a signaling NaN or if the product is zero times infinity.
1733 if self._is_special or other._is_special:
1734 if context is None:
1735 context = getcontext()
1736 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001737 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001738 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001739 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001740 if self._exp == 'n':
1741 product = self
1742 elif other._exp == 'n':
1743 product = other
1744 elif self._exp == 'F':
1745 if not other:
1746 return context._raise_error(InvalidOperation,
1747 'INF * 0 in fma')
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001748 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001749 elif other._exp == 'F':
1750 if not self:
1751 return context._raise_error(InvalidOperation,
1752 '0 * INF in fma')
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001753 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001754 else:
1755 product = _dec_from_triple(self._sign ^ other._sign,
1756 str(int(self._int) * int(other._int)),
1757 self._exp + other._exp)
1758
Facundo Batista353750c2007-09-13 18:13:15 +00001759 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001760 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001761
Facundo Batista353750c2007-09-13 18:13:15 +00001762 def _power_modulo(self, other, modulo, context=None):
1763 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001764
Facundo Batista353750c2007-09-13 18:13:15 +00001765 # if can't convert other and modulo to Decimal, raise
1766 # TypeError; there's no point returning NotImplemented (no
1767 # equivalent of __rpow__ for three argument pow)
1768 other = _convert_other(other, raiseit=True)
1769 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001770
Facundo Batista353750c2007-09-13 18:13:15 +00001771 if context is None:
1772 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001773
Facundo Batista353750c2007-09-13 18:13:15 +00001774 # deal with NaNs: if there are any sNaNs then first one wins,
1775 # (i.e. behaviour for NaNs is identical to that of fma)
1776 self_is_nan = self._isnan()
1777 other_is_nan = other._isnan()
1778 modulo_is_nan = modulo._isnan()
1779 if self_is_nan or other_is_nan or modulo_is_nan:
1780 if self_is_nan == 2:
1781 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001782 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001783 if other_is_nan == 2:
1784 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001785 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001786 if modulo_is_nan == 2:
1787 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001788 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001789 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001790 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001791 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001792 return other._fix_nan(context)
1793 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001794
Facundo Batista353750c2007-09-13 18:13:15 +00001795 # check inputs: we apply same restrictions as Python's pow()
1796 if not (self._isinteger() and
1797 other._isinteger() and
1798 modulo._isinteger()):
1799 return context._raise_error(InvalidOperation,
1800 'pow() 3rd argument not allowed '
1801 'unless all arguments are integers')
1802 if other < 0:
1803 return context._raise_error(InvalidOperation,
1804 'pow() 2nd argument cannot be '
1805 'negative when 3rd argument specified')
1806 if not modulo:
1807 return context._raise_error(InvalidOperation,
1808 'pow() 3rd argument cannot be 0')
1809
1810 # additional restriction for decimal: the modulus must be less
1811 # than 10**prec in absolute value
1812 if modulo.adjusted() >= context.prec:
1813 return context._raise_error(InvalidOperation,
1814 'insufficient precision: pow() 3rd '
1815 'argument must not have more than '
1816 'precision digits')
1817
1818 # define 0**0 == NaN, for consistency with two-argument pow
1819 # (even though it hurts!)
1820 if not other and not self:
1821 return context._raise_error(InvalidOperation,
1822 'at least one of pow() 1st argument '
1823 'and 2nd argument must be nonzero ;'
1824 '0**0 is not defined')
1825
1826 # compute sign of result
1827 if other._iseven():
1828 sign = 0
1829 else:
1830 sign = self._sign
1831
1832 # convert modulo to a Python integer, and self and other to
1833 # Decimal integers (i.e. force their exponents to be >= 0)
1834 modulo = abs(int(modulo))
1835 base = _WorkRep(self.to_integral_value())
1836 exponent = _WorkRep(other.to_integral_value())
1837
1838 # compute result using integer pow()
1839 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1840 for i in xrange(exponent.exp):
1841 base = pow(base, 10, modulo)
1842 base = pow(base, exponent.int, modulo)
1843
Facundo Batista72bc54f2007-11-23 17:59:00 +00001844 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001845
1846 def _power_exact(self, other, p):
1847 """Attempt to compute self**other exactly.
1848
1849 Given Decimals self and other and an integer p, attempt to
1850 compute an exact result for the power self**other, with p
1851 digits of precision. Return None if self**other is not
1852 exactly representable in p digits.
1853
1854 Assumes that elimination of special cases has already been
1855 performed: self and other must both be nonspecial; self must
1856 be positive and not numerically equal to 1; other must be
1857 nonzero. For efficiency, other._exp should not be too large,
1858 so that 10**abs(other._exp) is a feasible calculation."""
1859
1860 # In the comments below, we write x for the value of self and
1861 # y for the value of other. Write x = xc*10**xe and y =
1862 # yc*10**ye.
1863
1864 # The main purpose of this method is to identify the *failure*
1865 # of x**y to be exactly representable with as little effort as
1866 # possible. So we look for cheap and easy tests that
1867 # eliminate the possibility of x**y being exact. Only if all
1868 # these tests are passed do we go on to actually compute x**y.
1869
1870 # Here's the main idea. First normalize both x and y. We
1871 # express y as a rational m/n, with m and n relatively prime
1872 # and n>0. Then for x**y to be exactly representable (at
1873 # *any* precision), xc must be the nth power of a positive
1874 # integer and xe must be divisible by n. If m is negative
1875 # then additionally xc must be a power of either 2 or 5, hence
1876 # a power of 2**n or 5**n.
1877 #
1878 # There's a limit to how small |y| can be: if y=m/n as above
1879 # then:
1880 #
1881 # (1) if xc != 1 then for the result to be representable we
1882 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1883 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1884 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1885 # representable.
1886 #
1887 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1888 # |y| < 1/|xe| then the result is not representable.
1889 #
1890 # Note that since x is not equal to 1, at least one of (1) and
1891 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1892 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1893 #
1894 # There's also a limit to how large y can be, at least if it's
1895 # positive: the normalized result will have coefficient xc**y,
1896 # so if it's representable then xc**y < 10**p, and y <
1897 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1898 # not exactly representable.
1899
1900 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1901 # so |y| < 1/xe and the result is not representable.
1902 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1903 # < 1/nbits(xc).
1904
1905 x = _WorkRep(self)
1906 xc, xe = x.int, x.exp
1907 while xc % 10 == 0:
1908 xc //= 10
1909 xe += 1
1910
1911 y = _WorkRep(other)
1912 yc, ye = y.int, y.exp
1913 while yc % 10 == 0:
1914 yc //= 10
1915 ye += 1
1916
1917 # case where xc == 1: result is 10**(xe*y), with xe*y
1918 # required to be an integer
1919 if xc == 1:
1920 if ye >= 0:
1921 exponent = xe*yc*10**ye
1922 else:
1923 exponent, remainder = divmod(xe*yc, 10**-ye)
1924 if remainder:
1925 return None
1926 if y.sign == 1:
1927 exponent = -exponent
1928 # if other is a nonnegative integer, use ideal exponent
1929 if other._isinteger() and other._sign == 0:
1930 ideal_exponent = self._exp*int(other)
1931 zeros = min(exponent-ideal_exponent, p-1)
1932 else:
1933 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001934 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001935
1936 # case where y is negative: xc must be either a power
1937 # of 2 or a power of 5.
1938 if y.sign == 1:
1939 last_digit = xc % 10
1940 if last_digit in (2,4,6,8):
1941 # quick test for power of 2
1942 if xc & -xc != xc:
1943 return None
1944 # now xc is a power of 2; e is its exponent
1945 e = _nbits(xc)-1
1946 # find e*y and xe*y; both must be integers
1947 if ye >= 0:
1948 y_as_int = yc*10**ye
1949 e = e*y_as_int
1950 xe = xe*y_as_int
1951 else:
1952 ten_pow = 10**-ye
1953 e, remainder = divmod(e*yc, ten_pow)
1954 if remainder:
1955 return None
1956 xe, remainder = divmod(xe*yc, ten_pow)
1957 if remainder:
1958 return None
1959
1960 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1961 return None
1962 xc = 5**e
1963
1964 elif last_digit == 5:
1965 # e >= log_5(xc) if xc is a power of 5; we have
1966 # equality all the way up to xc=5**2658
1967 e = _nbits(xc)*28//65
1968 xc, remainder = divmod(5**e, xc)
1969 if remainder:
1970 return None
1971 while xc % 5 == 0:
1972 xc //= 5
1973 e -= 1
1974 if ye >= 0:
1975 y_as_integer = yc*10**ye
1976 e = e*y_as_integer
1977 xe = xe*y_as_integer
1978 else:
1979 ten_pow = 10**-ye
1980 e, remainder = divmod(e*yc, ten_pow)
1981 if remainder:
1982 return None
1983 xe, remainder = divmod(xe*yc, ten_pow)
1984 if remainder:
1985 return None
1986 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1987 return None
1988 xc = 2**e
1989 else:
1990 return None
1991
1992 if xc >= 10**p:
1993 return None
1994 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001995 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001996
1997 # now y is positive; find m and n such that y = m/n
1998 if ye >= 0:
1999 m, n = yc*10**ye, 1
2000 else:
2001 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2002 return None
2003 xc_bits = _nbits(xc)
2004 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2005 return None
2006 m, n = yc, 10**(-ye)
2007 while m % 2 == n % 2 == 0:
2008 m //= 2
2009 n //= 2
2010 while m % 5 == n % 5 == 0:
2011 m //= 5
2012 n //= 5
2013
2014 # compute nth root of xc*10**xe
2015 if n > 1:
2016 # if 1 < xc < 2**n then xc isn't an nth power
2017 if xc != 1 and xc_bits <= n:
2018 return None
2019
2020 xe, rem = divmod(xe, n)
2021 if rem != 0:
2022 return None
2023
2024 # compute nth root of xc using Newton's method
2025 a = 1L << -(-_nbits(xc)//n) # initial estimate
2026 while True:
2027 q, r = divmod(xc, a**(n-1))
2028 if a <= q:
2029 break
2030 else:
2031 a = (a*(n-1) + q)//n
2032 if not (a == q and r == 0):
2033 return None
2034 xc = a
2035
2036 # now xc*10**xe is the nth root of the original xc*10**xe
2037 # compute mth power of xc*10**xe
2038
2039 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2040 # 10**p and the result is not representable.
2041 if xc > 1 and m > p*100//_log10_lb(xc):
2042 return None
2043 xc = xc**m
2044 xe *= m
2045 if xc > 10**p:
2046 return None
2047
2048 # by this point the result *is* exactly representable
2049 # adjust the exponent to get as close as possible to the ideal
2050 # exponent, if necessary
2051 str_xc = str(xc)
2052 if other._isinteger() and other._sign == 0:
2053 ideal_exponent = self._exp*int(other)
2054 zeros = min(xe-ideal_exponent, p-len(str_xc))
2055 else:
2056 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002057 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002058
2059 def __pow__(self, other, modulo=None, context=None):
2060 """Return self ** other [ % modulo].
2061
2062 With two arguments, compute self**other.
2063
2064 With three arguments, compute (self**other) % modulo. For the
2065 three argument form, the following restrictions on the
2066 arguments hold:
2067
2068 - all three arguments must be integral
2069 - other must be nonnegative
2070 - either self or other (or both) must be nonzero
2071 - modulo must be nonzero and must have at most p digits,
2072 where p is the context precision.
2073
2074 If any of these restrictions is violated the InvalidOperation
2075 flag is raised.
2076
2077 The result of pow(self, other, modulo) is identical to the
2078 result that would be obtained by computing (self**other) %
2079 modulo with unbounded precision, but is computed more
2080 efficiently. It is always exact.
2081 """
2082
2083 if modulo is not None:
2084 return self._power_modulo(other, modulo, context)
2085
2086 other = _convert_other(other)
2087 if other is NotImplemented:
2088 return other
2089
2090 if context is None:
2091 context = getcontext()
2092
2093 # either argument is a NaN => result is NaN
2094 ans = self._check_nans(other, context)
2095 if ans:
2096 return ans
2097
2098 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2099 if not other:
2100 if not self:
2101 return context._raise_error(InvalidOperation, '0 ** 0')
2102 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002103 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002104
2105 # result has sign 1 iff self._sign is 1 and other is an odd integer
2106 result_sign = 0
2107 if self._sign == 1:
2108 if other._isinteger():
2109 if not other._iseven():
2110 result_sign = 1
2111 else:
2112 # -ve**noninteger = NaN
2113 # (-0)**noninteger = 0**noninteger
2114 if self:
2115 return context._raise_error(InvalidOperation,
2116 'x ** y with x negative and y not an integer')
2117 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002118 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002119
2120 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2121 if not self:
2122 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002123 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002124 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002125 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002126
2127 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002128 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002129 if other._sign == 0:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002130 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002131 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002132 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002133
Facundo Batista353750c2007-09-13 18:13:15 +00002134 # 1**other = 1, but the choice of exponent and the flags
2135 # depend on the exponent of self, and on whether other is a
2136 # positive integer, a negative integer, or neither
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002137 if self == _One:
Facundo Batista353750c2007-09-13 18:13:15 +00002138 if other._isinteger():
2139 # exp = max(self._exp*max(int(other), 0),
2140 # 1-context.prec) but evaluating int(other) directly
2141 # is dangerous until we know other is small (other
2142 # could be 1e999999999)
2143 if other._sign == 1:
2144 multiplier = 0
2145 elif other > context.prec:
2146 multiplier = context.prec
2147 else:
2148 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002149
Facundo Batista353750c2007-09-13 18:13:15 +00002150 exp = self._exp * multiplier
2151 if exp < 1-context.prec:
2152 exp = 1-context.prec
2153 context._raise_error(Rounded)
2154 else:
2155 context._raise_error(Inexact)
2156 context._raise_error(Rounded)
2157 exp = 1-context.prec
2158
Facundo Batista72bc54f2007-11-23 17:59:00 +00002159 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002160
2161 # compute adjusted exponent of self
2162 self_adj = self.adjusted()
2163
2164 # self ** infinity is infinity if self > 1, 0 if self < 1
2165 # self ** -infinity is infinity if self < 1, 0 if self > 1
2166 if other._isinfinity():
2167 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002168 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002169 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002170 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002171
2172 # from here on, the result always goes through the call
2173 # to _fix at the end of this function.
2174 ans = None
2175
2176 # crude test to catch cases of extreme overflow/underflow. If
2177 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2178 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2179 # self**other >= 10**(Emax+1), so overflow occurs. The test
2180 # for underflow is similar.
2181 bound = self._log10_exp_bound() + other.adjusted()
2182 if (self_adj >= 0) == (other._sign == 0):
2183 # self > 1 and other +ve, or self < 1 and other -ve
2184 # possibility of overflow
2185 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002186 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002187 else:
2188 # self > 1 and other -ve, or self < 1 and other +ve
2189 # possibility of underflow to 0
2190 Etiny = context.Etiny()
2191 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002192 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002193
2194 # try for an exact result with precision +1
2195 if ans is None:
2196 ans = self._power_exact(other, context.prec + 1)
2197 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002198 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002199
2200 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2201 if ans is None:
2202 p = context.prec
2203 x = _WorkRep(self)
2204 xc, xe = x.int, x.exp
2205 y = _WorkRep(other)
2206 yc, ye = y.int, y.exp
2207 if y.sign == 1:
2208 yc = -yc
2209
2210 # compute correctly rounded result: start with precision +3,
2211 # then increase precision until result is unambiguously roundable
2212 extra = 3
2213 while True:
2214 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2215 if coeff % (5*10**(len(str(coeff))-p-1)):
2216 break
2217 extra += 3
2218
Facundo Batista72bc54f2007-11-23 17:59:00 +00002219 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002220
2221 # the specification says that for non-integer other we need to
2222 # raise Inexact, even when the result is actually exact. In
2223 # the same way, we need to raise Underflow here if the result
2224 # is subnormal. (The call to _fix will take care of raising
2225 # Rounded and Subnormal, as usual.)
2226 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002227 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002228 # pad with zeros up to length context.prec+1 if necessary
2229 if len(ans._int) <= context.prec:
2230 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002231 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2232 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002233 if ans.adjusted() < context.Emin:
2234 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002235
Facundo Batista353750c2007-09-13 18:13:15 +00002236 # unlike exp, ln and log10, the power function respects the
2237 # rounding mode; no need to use ROUND_HALF_EVEN here
2238 ans = ans._fix(context)
2239 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002240
2241 def __rpow__(self, other, context=None):
2242 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002243 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002244 if other is NotImplemented:
2245 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002246 return other.__pow__(self, context=context)
2247
2248 def normalize(self, context=None):
2249 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002250
Facundo Batista353750c2007-09-13 18:13:15 +00002251 if context is None:
2252 context = getcontext()
2253
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002254 if self._is_special:
2255 ans = self._check_nans(context=context)
2256 if ans:
2257 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002258
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002259 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002260 if dup._isinfinity():
2261 return dup
2262
2263 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002264 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002265 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002266 end = len(dup._int)
2267 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002268 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002269 exp += 1
2270 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002271 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002272
Facundo Batistabd2fe832007-09-13 18:42:09 +00002273 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002274 """Quantize self so its exponent is the same as that of exp.
2275
2276 Similar to self._rescale(exp._exp) but with error checking.
2277 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002278 exp = _convert_other(exp, raiseit=True)
2279
Facundo Batista353750c2007-09-13 18:13:15 +00002280 if context is None:
2281 context = getcontext()
2282 if rounding is None:
2283 rounding = context.rounding
2284
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002285 if self._is_special or exp._is_special:
2286 ans = self._check_nans(exp, context)
2287 if ans:
2288 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002289
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002290 if exp._isinfinity() or self._isinfinity():
2291 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002292 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002293 return context._raise_error(InvalidOperation,
2294 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002295
Facundo Batistabd2fe832007-09-13 18:42:09 +00002296 # if we're not watching exponents, do a simple rescale
2297 if not watchexp:
2298 ans = self._rescale(exp._exp, rounding)
2299 # raise Inexact and Rounded where appropriate
2300 if ans._exp > self._exp:
2301 context._raise_error(Rounded)
2302 if ans != self:
2303 context._raise_error(Inexact)
2304 return ans
2305
Facundo Batista353750c2007-09-13 18:13:15 +00002306 # exp._exp should be between Etiny and Emax
2307 if not (context.Etiny() <= exp._exp <= context.Emax):
2308 return context._raise_error(InvalidOperation,
2309 'target exponent out of bounds in quantize')
2310
2311 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002312 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002313 return ans._fix(context)
2314
2315 self_adjusted = self.adjusted()
2316 if self_adjusted > context.Emax:
2317 return context._raise_error(InvalidOperation,
2318 'exponent of quantize result too large for current context')
2319 if self_adjusted - exp._exp + 1 > context.prec:
2320 return context._raise_error(InvalidOperation,
2321 'quantize result has too many digits for current context')
2322
2323 ans = self._rescale(exp._exp, rounding)
2324 if ans.adjusted() > context.Emax:
2325 return context._raise_error(InvalidOperation,
2326 'exponent of quantize result too large for current context')
2327 if len(ans._int) > context.prec:
2328 return context._raise_error(InvalidOperation,
2329 'quantize result has too many digits for current context')
2330
2331 # raise appropriate flags
2332 if ans._exp > self._exp:
2333 context._raise_error(Rounded)
2334 if ans != self:
2335 context._raise_error(Inexact)
2336 if ans and ans.adjusted() < context.Emin:
2337 context._raise_error(Subnormal)
2338
2339 # call to fix takes care of any necessary folddown
2340 ans = ans._fix(context)
2341 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002342
2343 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002344 """Return True if self and other have the same exponent; otherwise
2345 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002346
Facundo Batista1a191df2007-10-02 17:01:24 +00002347 If either operand is a special value, the following rules are used:
2348 * return True if both operands are infinities
2349 * return True if both operands are NaNs
2350 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002351 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002352 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002353 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002354 return (self.is_nan() and other.is_nan() or
2355 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002356 return self._exp == other._exp
2357
Facundo Batista353750c2007-09-13 18:13:15 +00002358 def _rescale(self, exp, rounding):
2359 """Rescale self so that the exponent is exp, either by padding with zeros
2360 or by truncating digits, using the given rounding mode.
2361
2362 Specials are returned without change. This operation is
2363 quiet: it raises no flags, and uses no information from the
2364 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002365
2366 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002367 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002368 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002369 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002370 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002371 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002372 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002373
Facundo Batista353750c2007-09-13 18:13:15 +00002374 if self._exp >= exp:
2375 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002376 return _dec_from_triple(self._sign,
2377 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002378
Facundo Batista353750c2007-09-13 18:13:15 +00002379 # too many digits; round and lose data. If self.adjusted() <
2380 # exp-1, replace self by 10**(exp-1) before rounding
2381 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002382 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002383 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002384 digits = 0
2385 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002386 changed = this_function(digits)
2387 coeff = self._int[:digits] or '0'
2388 if changed == 1:
2389 coeff = str(int(coeff)+1)
2390 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002391
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00002392 def _round(self, places, rounding):
2393 """Round a nonzero, nonspecial Decimal to a fixed number of
2394 significant figures, using the given rounding mode.
2395
2396 Infinities, NaNs and zeros are returned unaltered.
2397
2398 This operation is quiet: it raises no flags, and uses no
2399 information from the context.
2400
2401 """
2402 if places <= 0:
2403 raise ValueError("argument should be at least 1 in _round")
2404 if self._is_special or not self:
2405 return Decimal(self)
2406 ans = self._rescale(self.adjusted()+1-places, rounding)
2407 # it can happen that the rescale alters the adjusted exponent;
2408 # for example when rounding 99.97 to 3 significant figures.
2409 # When this happens we end up with an extra 0 at the end of
2410 # the number; a second rescale fixes this.
2411 if ans.adjusted() != self.adjusted():
2412 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2413 return ans
2414
Facundo Batista353750c2007-09-13 18:13:15 +00002415 def to_integral_exact(self, rounding=None, context=None):
2416 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002417
Facundo Batista353750c2007-09-13 18:13:15 +00002418 If no rounding mode is specified, take the rounding mode from
2419 the context. This method raises the Rounded and Inexact flags
2420 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002421
Facundo Batista353750c2007-09-13 18:13:15 +00002422 See also: to_integral_value, which does exactly the same as
2423 this method except that it doesn't raise Inexact or Rounded.
2424 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002425 if self._is_special:
2426 ans = self._check_nans(context=context)
2427 if ans:
2428 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002429 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002430 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002431 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002432 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002433 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002434 if context is None:
2435 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002436 if rounding is None:
2437 rounding = context.rounding
2438 context._raise_error(Rounded)
2439 ans = self._rescale(0, rounding)
2440 if ans != self:
2441 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002442 return ans
2443
Facundo Batista353750c2007-09-13 18:13:15 +00002444 def to_integral_value(self, rounding=None, context=None):
2445 """Rounds to the nearest integer, without raising inexact, rounded."""
2446 if context is None:
2447 context = getcontext()
2448 if rounding is None:
2449 rounding = context.rounding
2450 if self._is_special:
2451 ans = self._check_nans(context=context)
2452 if ans:
2453 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002454 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002455 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002456 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002457 else:
2458 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002459
Facundo Batista353750c2007-09-13 18:13:15 +00002460 # the method name changed, but we provide also the old one, for compatibility
2461 to_integral = to_integral_value
2462
2463 def sqrt(self, context=None):
2464 """Return the square root of self."""
Mark Dickinson3b24ccb2008-03-25 14:33:23 +00002465 if context is None:
2466 context = getcontext()
2467
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002468 if self._is_special:
2469 ans = self._check_nans(context=context)
2470 if ans:
2471 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002472
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002473 if self._isinfinity() and self._sign == 0:
2474 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002475
2476 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002477 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002478 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002479 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002480
2481 if self._sign == 1:
2482 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2483
Facundo Batista353750c2007-09-13 18:13:15 +00002484 # At this point self represents a positive number. Let p be
2485 # the desired precision and express self in the form c*100**e
2486 # with c a positive real number and e an integer, c and e
2487 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2488 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2489 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2490 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2491 # the closest integer to sqrt(c) with the even integer chosen
2492 # in the case of a tie.
2493 #
2494 # To ensure correct rounding in all cases, we use the
2495 # following trick: we compute the square root to an extra
2496 # place (precision p+1 instead of precision p), rounding down.
2497 # Then, if the result is inexact and its last digit is 0 or 5,
2498 # we increase the last digit to 1 or 6 respectively; if it's
2499 # exact we leave the last digit alone. Now the final round to
2500 # p places (or fewer in the case of underflow) will round
2501 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002502
Facundo Batista353750c2007-09-13 18:13:15 +00002503 # use an extra digit of precision
2504 prec = context.prec+1
2505
2506 # write argument in the form c*100**e where e = self._exp//2
2507 # is the 'ideal' exponent, to be used if the square root is
2508 # exactly representable. l is the number of 'digits' of c in
2509 # base 100, so that 100**(l-1) <= c < 100**l.
2510 op = _WorkRep(self)
2511 e = op.exp >> 1
2512 if op.exp & 1:
2513 c = op.int * 10
2514 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002515 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002516 c = op.int
2517 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002518
Facundo Batista353750c2007-09-13 18:13:15 +00002519 # rescale so that c has exactly prec base 100 'digits'
2520 shift = prec-l
2521 if shift >= 0:
2522 c *= 100**shift
2523 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002524 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002525 c, remainder = divmod(c, 100**-shift)
2526 exact = not remainder
2527 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002528
Facundo Batista353750c2007-09-13 18:13:15 +00002529 # find n = floor(sqrt(c)) using Newton's method
2530 n = 10**prec
2531 while True:
2532 q = c//n
2533 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002534 break
Facundo Batista353750c2007-09-13 18:13:15 +00002535 else:
2536 n = n + q >> 1
2537 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002538
Facundo Batista353750c2007-09-13 18:13:15 +00002539 if exact:
2540 # result is exact; rescale to use ideal exponent e
2541 if shift >= 0:
2542 # assert n % 10**shift == 0
2543 n //= 10**shift
2544 else:
2545 n *= 10**-shift
2546 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002547 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002548 # result is not exact; fix last digit as described above
2549 if n % 5 == 0:
2550 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002551
Facundo Batista72bc54f2007-11-23 17:59:00 +00002552 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002553
Facundo Batista353750c2007-09-13 18:13:15 +00002554 # round, and fit to current context
2555 context = context._shallow_copy()
2556 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002557 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002558 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002559
Facundo Batista353750c2007-09-13 18:13:15 +00002560 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002561
2562 def max(self, other, context=None):
2563 """Returns the larger value.
2564
Facundo Batista353750c2007-09-13 18:13:15 +00002565 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002566 NaN (and signals if one is sNaN). Also rounds.
2567 """
Facundo Batista353750c2007-09-13 18:13:15 +00002568 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002569
Facundo Batista6c398da2007-09-17 17:30:13 +00002570 if context is None:
2571 context = getcontext()
2572
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002573 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002574 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002575 # number is always returned
2576 sn = self._isnan()
2577 on = other._isnan()
2578 if sn or on:
Mark Dickinson7c62f892008-12-11 09:17:40 +00002579 if on == 1 and sn == 0:
2580 return self._fix(context)
2581 if sn == 1 and on == 0:
2582 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002583 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002584
Mark Dickinson2fc92632008-02-06 22:10:50 +00002585 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002586 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002587 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002588 # then an ordering is applied:
2589 #
Facundo Batista59c58842007-04-10 12:58:45 +00002590 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002591 # positive sign and min returns the operand with the negative sign
2592 #
Facundo Batista59c58842007-04-10 12:58:45 +00002593 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002594 # the result. This is exactly the ordering used in compare_total.
2595 c = self.compare_total(other)
2596
2597 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002598 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002599 else:
2600 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002601
Facundo Batistae64acfa2007-12-17 14:18:42 +00002602 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002603
2604 def min(self, other, context=None):
2605 """Returns the smaller value.
2606
Facundo Batista59c58842007-04-10 12:58:45 +00002607 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002608 NaN (and signals if one is sNaN). Also rounds.
2609 """
Facundo Batista353750c2007-09-13 18:13:15 +00002610 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002611
Facundo Batista6c398da2007-09-17 17:30:13 +00002612 if context is None:
2613 context = getcontext()
2614
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002615 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002616 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002617 # number is always returned
2618 sn = self._isnan()
2619 on = other._isnan()
2620 if sn or on:
Mark Dickinson7c62f892008-12-11 09:17:40 +00002621 if on == 1 and sn == 0:
2622 return self._fix(context)
2623 if sn == 1 and on == 0:
2624 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002625 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002626
Mark Dickinson2fc92632008-02-06 22:10:50 +00002627 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002628 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002629 c = self.compare_total(other)
2630
2631 if c == -1:
2632 ans = self
2633 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002634 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002635
Facundo Batistae64acfa2007-12-17 14:18:42 +00002636 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002637
2638 def _isinteger(self):
2639 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002640 if self._is_special:
2641 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002642 if self._exp >= 0:
2643 return True
2644 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002645 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002646
2647 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002648 """Returns True if self is even. Assumes self is an integer."""
2649 if not self or self._exp > 0:
2650 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002651 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002652
2653 def adjusted(self):
2654 """Return the adjusted exponent of self"""
2655 try:
2656 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002657 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002658 except TypeError:
2659 return 0
2660
Facundo Batista353750c2007-09-13 18:13:15 +00002661 def canonical(self, context=None):
2662 """Returns the same Decimal object.
2663
2664 As we do not have different encodings for the same number, the
2665 received object already is in its canonical form.
2666 """
2667 return self
2668
2669 def compare_signal(self, other, context=None):
2670 """Compares self to the other operand numerically.
2671
2672 It's pretty much like compare(), but all NaNs signal, with signaling
2673 NaNs taking precedence over quiet NaNs.
2674 """
Mark Dickinson2fc92632008-02-06 22:10:50 +00002675 other = _convert_other(other, raiseit = True)
2676 ans = self._compare_check_nans(other, context)
2677 if ans:
2678 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002679 return self.compare(other, context=context)
2680
2681 def compare_total(self, other):
2682 """Compares self to other using the abstract representations.
2683
2684 This is not like the standard compare, which use their numerical
2685 value. Note that a total ordering is defined for all possible abstract
2686 representations.
2687 """
2688 # if one is negative and the other is positive, it's easy
2689 if self._sign and not other._sign:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002690 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002691 if not self._sign and other._sign:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002692 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002693 sign = self._sign
2694
2695 # let's handle both NaN types
2696 self_nan = self._isnan()
2697 other_nan = other._isnan()
2698 if self_nan or other_nan:
2699 if self_nan == other_nan:
2700 if self._int < other._int:
2701 if sign:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002702 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002703 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002704 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002705 if self._int > other._int:
2706 if sign:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002707 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002708 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002709 return _One
2710 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002711
2712 if sign:
2713 if self_nan == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002714 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002715 if other_nan == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002716 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002717 if self_nan == 2:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002718 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002719 if other_nan == 2:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002720 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002721 else:
2722 if self_nan == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002723 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002724 if other_nan == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002725 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002726 if self_nan == 2:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002727 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002728 if other_nan == 2:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002729 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002730
2731 if self < other:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002732 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002733 if self > other:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002734 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002735
2736 if self._exp < other._exp:
2737 if sign:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002738 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002739 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002740 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002741 if self._exp > other._exp:
2742 if sign:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002743 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002744 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002745 return _One
2746 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002747
2748
2749 def compare_total_mag(self, other):
2750 """Compares self to other using abstract repr., ignoring sign.
2751
2752 Like compare_total, but with operand's sign ignored and assumed to be 0.
2753 """
2754 s = self.copy_abs()
2755 o = other.copy_abs()
2756 return s.compare_total(o)
2757
2758 def copy_abs(self):
2759 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002760 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002761
2762 def copy_negate(self):
2763 """Returns a copy with the sign inverted."""
2764 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002765 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002766 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002767 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002768
2769 def copy_sign(self, other):
2770 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002771 return _dec_from_triple(other._sign, self._int,
2772 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002773
2774 def exp(self, context=None):
2775 """Returns e ** self."""
2776
2777 if context is None:
2778 context = getcontext()
2779
2780 # exp(NaN) = NaN
2781 ans = self._check_nans(context=context)
2782 if ans:
2783 return ans
2784
2785 # exp(-Infinity) = 0
2786 if self._isinfinity() == -1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002787 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002788
2789 # exp(0) = 1
2790 if not self:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002791 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002792
2793 # exp(Infinity) = Infinity
2794 if self._isinfinity() == 1:
2795 return Decimal(self)
2796
2797 # the result is now guaranteed to be inexact (the true
2798 # mathematical result is transcendental). There's no need to
2799 # raise Rounded and Inexact here---they'll always be raised as
2800 # a result of the call to _fix.
2801 p = context.prec
2802 adj = self.adjusted()
2803
2804 # we only need to do any computation for quite a small range
2805 # of adjusted exponents---for example, -29 <= adj <= 10 for
2806 # the default context. For smaller exponent the result is
2807 # indistinguishable from 1 at the given precision, while for
2808 # larger exponent the result either overflows or underflows.
2809 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2810 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002811 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002812 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2813 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002814 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002815 elif self._sign == 0 and adj < -p:
2816 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002817 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002818 elif self._sign == 1 and adj < -p-1:
2819 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002820 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002821 # general case
2822 else:
2823 op = _WorkRep(self)
2824 c, e = op.int, op.exp
2825 if op.sign == 1:
2826 c = -c
2827
2828 # compute correctly rounded result: increase precision by
2829 # 3 digits at a time until we get an unambiguously
2830 # roundable result
2831 extra = 3
2832 while True:
2833 coeff, exp = _dexp(c, e, p+extra)
2834 if coeff % (5*10**(len(str(coeff))-p-1)):
2835 break
2836 extra += 3
2837
Facundo Batista72bc54f2007-11-23 17:59:00 +00002838 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002839
2840 # at this stage, ans should round correctly with *any*
2841 # rounding mode, not just with ROUND_HALF_EVEN
2842 context = context._shallow_copy()
2843 rounding = context._set_rounding(ROUND_HALF_EVEN)
2844 ans = ans._fix(context)
2845 context.rounding = rounding
2846
2847 return ans
2848
2849 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002850 """Return True if self is canonical; otherwise return False.
2851
2852 Currently, the encoding of a Decimal instance is always
2853 canonical, so this method returns True for any Decimal.
2854 """
2855 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002856
2857 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002858 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002859
Facundo Batista1a191df2007-10-02 17:01:24 +00002860 A Decimal instance is considered finite if it is neither
2861 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002862 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002863 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002864
2865 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002866 """Return True if self is infinite; otherwise return False."""
2867 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002868
2869 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002870 """Return True if self is a qNaN or sNaN; otherwise return False."""
2871 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002872
2873 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002874 """Return True if self is a normal number; otherwise return False."""
2875 if self._is_special or not self:
2876 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002877 if context is None:
2878 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002879 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002880
2881 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002882 """Return True if self is a quiet NaN; otherwise return False."""
2883 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002884
2885 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002886 """Return True if self is negative; otherwise return False."""
2887 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002888
2889 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002890 """Return True if self is a signaling NaN; otherwise return False."""
2891 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002892
2893 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002894 """Return True if self is subnormal; otherwise return False."""
2895 if self._is_special or not self:
2896 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002897 if context is None:
2898 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002899 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002900
2901 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002902 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002903 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002904
2905 def _ln_exp_bound(self):
2906 """Compute a lower bound for the adjusted exponent of self.ln().
2907 In other words, compute r such that self.ln() >= 10**r. Assumes
2908 that self is finite and positive and that self != 1.
2909 """
2910
2911 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2912 adj = self._exp + len(self._int) - 1
2913 if adj >= 1:
2914 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2915 return len(str(adj*23//10)) - 1
2916 if adj <= -2:
2917 # argument <= 0.1
2918 return len(str((-1-adj)*23//10)) - 1
2919 op = _WorkRep(self)
2920 c, e = op.int, op.exp
2921 if adj == 0:
2922 # 1 < self < 10
2923 num = str(c-10**-e)
2924 den = str(c)
2925 return len(num) - len(den) - (num < den)
2926 # adj == -1, 0.1 <= self < 1
2927 return e + len(str(10**-e - c)) - 1
2928
2929
2930 def ln(self, context=None):
2931 """Returns the natural (base e) logarithm of self."""
2932
2933 if context is None:
2934 context = getcontext()
2935
2936 # ln(NaN) = NaN
2937 ans = self._check_nans(context=context)
2938 if ans:
2939 return ans
2940
2941 # ln(0.0) == -Infinity
2942 if not self:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002943 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00002944
2945 # ln(Infinity) = Infinity
2946 if self._isinfinity() == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002947 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00002948
2949 # ln(1.0) == 0.0
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002950 if self == _One:
2951 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002952
2953 # ln(negative) raises InvalidOperation
2954 if self._sign == 1:
2955 return context._raise_error(InvalidOperation,
2956 'ln of a negative value')
2957
2958 # result is irrational, so necessarily inexact
2959 op = _WorkRep(self)
2960 c, e = op.int, op.exp
2961 p = context.prec
2962
2963 # correctly rounded result: repeatedly increase precision by 3
2964 # until we get an unambiguously roundable result
2965 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2966 while True:
2967 coeff = _dlog(c, e, places)
2968 # assert len(str(abs(coeff)))-p >= 1
2969 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2970 break
2971 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002972 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002973
2974 context = context._shallow_copy()
2975 rounding = context._set_rounding(ROUND_HALF_EVEN)
2976 ans = ans._fix(context)
2977 context.rounding = rounding
2978 return ans
2979
2980 def _log10_exp_bound(self):
2981 """Compute a lower bound for the adjusted exponent of self.log10().
2982 In other words, find r such that self.log10() >= 10**r.
2983 Assumes that self is finite and positive and that self != 1.
2984 """
2985
2986 # For x >= 10 or x < 0.1 we only need a bound on the integer
2987 # part of log10(self), and this comes directly from the
2988 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2989 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2990 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2991
2992 adj = self._exp + len(self._int) - 1
2993 if adj >= 1:
2994 # self >= 10
2995 return len(str(adj))-1
2996 if adj <= -2:
2997 # self < 0.1
2998 return len(str(-1-adj))-1
2999 op = _WorkRep(self)
3000 c, e = op.int, op.exp
3001 if adj == 0:
3002 # 1 < self < 10
3003 num = str(c-10**-e)
3004 den = str(231*c)
3005 return len(num) - len(den) - (num < den) + 2
3006 # adj == -1, 0.1 <= self < 1
3007 num = str(10**-e-c)
3008 return len(num) + e - (num < "231") - 1
3009
3010 def log10(self, context=None):
3011 """Returns the base 10 logarithm of self."""
3012
3013 if context is None:
3014 context = getcontext()
3015
3016 # log10(NaN) = NaN
3017 ans = self._check_nans(context=context)
3018 if ans:
3019 return ans
3020
3021 # log10(0.0) == -Infinity
3022 if not self:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00003023 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003024
3025 # log10(Infinity) = Infinity
3026 if self._isinfinity() == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00003027 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003028
3029 # log10(negative or -Infinity) raises InvalidOperation
3030 if self._sign == 1:
3031 return context._raise_error(InvalidOperation,
3032 'log10 of a negative value')
3033
3034 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00003035 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00003036 # answer may need rounding
3037 ans = Decimal(self._exp + len(self._int) - 1)
3038 else:
3039 # result is irrational, so necessarily inexact
3040 op = _WorkRep(self)
3041 c, e = op.int, op.exp
3042 p = context.prec
3043
3044 # correctly rounded result: repeatedly increase precision
3045 # until result is unambiguously roundable
3046 places = p-self._log10_exp_bound()+2
3047 while True:
3048 coeff = _dlog10(c, e, places)
3049 # assert len(str(abs(coeff)))-p >= 1
3050 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3051 break
3052 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003053 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003054
3055 context = context._shallow_copy()
3056 rounding = context._set_rounding(ROUND_HALF_EVEN)
3057 ans = ans._fix(context)
3058 context.rounding = rounding
3059 return ans
3060
3061 def logb(self, context=None):
3062 """ Returns the exponent of the magnitude of self's MSD.
3063
3064 The result is the integer which is the exponent of the magnitude
3065 of the most significant digit of self (as though it were truncated
3066 to a single digit while maintaining the value of that digit and
3067 without limiting the resulting exponent).
3068 """
3069 # logb(NaN) = NaN
3070 ans = self._check_nans(context=context)
3071 if ans:
3072 return ans
3073
3074 if context is None:
3075 context = getcontext()
3076
3077 # logb(+/-Inf) = +Inf
3078 if self._isinfinity():
Mark Dickinsone4d46b22009-01-03 12:09:22 +00003079 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003080
3081 # logb(0) = -Inf, DivisionByZero
3082 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003083 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003084
3085 # otherwise, simply return the adjusted exponent of self, as a
3086 # Decimal. Note that no attempt is made to fit the result
3087 # into the current context.
3088 return Decimal(self.adjusted())
3089
3090 def _islogical(self):
3091 """Return True if self is a logical operand.
3092
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00003093 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00003094 an exponent of 0, and a coefficient whose digits must all be
3095 either 0 or 1.
3096 """
3097 if self._sign != 0 or self._exp != 0:
3098 return False
3099 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003100 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003101 return False
3102 return True
3103
3104 def _fill_logical(self, context, opa, opb):
3105 dif = context.prec - len(opa)
3106 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003107 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003108 elif dif < 0:
3109 opa = opa[-context.prec:]
3110 dif = context.prec - len(opb)
3111 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003112 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003113 elif dif < 0:
3114 opb = opb[-context.prec:]
3115 return opa, opb
3116
3117 def logical_and(self, other, context=None):
3118 """Applies an 'and' operation between self and other's digits."""
3119 if context is None:
3120 context = getcontext()
3121 if not self._islogical() or not other._islogical():
3122 return context._raise_error(InvalidOperation)
3123
3124 # fill to context.prec
3125 (opa, opb) = self._fill_logical(context, self._int, other._int)
3126
3127 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003128 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3129 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003130
3131 def logical_invert(self, context=None):
3132 """Invert all its digits."""
3133 if context is None:
3134 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003135 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3136 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003137
3138 def logical_or(self, other, context=None):
3139 """Applies an 'or' operation between self and other's digits."""
3140 if context is None:
3141 context = getcontext()
3142 if not self._islogical() or not other._islogical():
3143 return context._raise_error(InvalidOperation)
3144
3145 # fill to context.prec
3146 (opa, opb) = self._fill_logical(context, self._int, other._int)
3147
3148 # make the operation, and clean starting zeroes
Mark Dickinsonc95c6f12009-01-04 21:30:17 +00003149 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003150 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003151
3152 def logical_xor(self, other, context=None):
3153 """Applies an 'xor' operation between self and other's digits."""
3154 if context is None:
3155 context = getcontext()
3156 if not self._islogical() or not other._islogical():
3157 return context._raise_error(InvalidOperation)
3158
3159 # fill to context.prec
3160 (opa, opb) = self._fill_logical(context, self._int, other._int)
3161
3162 # make the operation, and clean starting zeroes
Mark Dickinsonc95c6f12009-01-04 21:30:17 +00003163 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003164 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003165
3166 def max_mag(self, other, context=None):
3167 """Compares the values numerically with their sign ignored."""
3168 other = _convert_other(other, raiseit=True)
3169
Facundo Batista6c398da2007-09-17 17:30:13 +00003170 if context is None:
3171 context = getcontext()
3172
Facundo Batista353750c2007-09-13 18:13:15 +00003173 if self._is_special or other._is_special:
3174 # If one operand is a quiet NaN and the other is number, then the
3175 # number is always returned
3176 sn = self._isnan()
3177 on = other._isnan()
3178 if sn or on:
Mark Dickinson7c62f892008-12-11 09:17:40 +00003179 if on == 1 and sn == 0:
3180 return self._fix(context)
3181 if sn == 1 and on == 0:
3182 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003183 return self._check_nans(other, context)
3184
Mark Dickinson2fc92632008-02-06 22:10:50 +00003185 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003186 if c == 0:
3187 c = self.compare_total(other)
3188
3189 if c == -1:
3190 ans = other
3191 else:
3192 ans = self
3193
Facundo Batistae64acfa2007-12-17 14:18:42 +00003194 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003195
3196 def min_mag(self, other, context=None):
3197 """Compares the values numerically with their sign ignored."""
3198 other = _convert_other(other, raiseit=True)
3199
Facundo Batista6c398da2007-09-17 17:30:13 +00003200 if context is None:
3201 context = getcontext()
3202
Facundo Batista353750c2007-09-13 18:13:15 +00003203 if self._is_special or other._is_special:
3204 # If one operand is a quiet NaN and the other is number, then the
3205 # number is always returned
3206 sn = self._isnan()
3207 on = other._isnan()
3208 if sn or on:
Mark Dickinson7c62f892008-12-11 09:17:40 +00003209 if on == 1 and sn == 0:
3210 return self._fix(context)
3211 if sn == 1 and on == 0:
3212 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003213 return self._check_nans(other, context)
3214
Mark Dickinson2fc92632008-02-06 22:10:50 +00003215 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003216 if c == 0:
3217 c = self.compare_total(other)
3218
3219 if c == -1:
3220 ans = self
3221 else:
3222 ans = other
3223
Facundo Batistae64acfa2007-12-17 14:18:42 +00003224 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003225
3226 def next_minus(self, context=None):
3227 """Returns the largest representable number smaller than itself."""
3228 if context is None:
3229 context = getcontext()
3230
3231 ans = self._check_nans(context=context)
3232 if ans:
3233 return ans
3234
3235 if self._isinfinity() == -1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00003236 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003237 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003238 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003239
3240 context = context.copy()
3241 context._set_rounding(ROUND_FLOOR)
3242 context._ignore_all_flags()
3243 new_self = self._fix(context)
3244 if new_self != self:
3245 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003246 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3247 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003248
3249 def next_plus(self, context=None):
3250 """Returns the smallest representable number larger than itself."""
3251 if context is None:
3252 context = getcontext()
3253
3254 ans = self._check_nans(context=context)
3255 if ans:
3256 return ans
3257
3258 if self._isinfinity() == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00003259 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003260 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003261 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003262
3263 context = context.copy()
3264 context._set_rounding(ROUND_CEILING)
3265 context._ignore_all_flags()
3266 new_self = self._fix(context)
3267 if new_self != self:
3268 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003269 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3270 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003271
3272 def next_toward(self, other, context=None):
3273 """Returns the number closest to self, in the direction towards other.
3274
3275 The result is the closest representable number to self
3276 (excluding self) that is in the direction towards other,
3277 unless both have the same value. If the two operands are
3278 numerically equal, then the result is a copy of self with the
3279 sign set to be the same as the sign of other.
3280 """
3281 other = _convert_other(other, raiseit=True)
3282
3283 if context is None:
3284 context = getcontext()
3285
3286 ans = self._check_nans(other, context)
3287 if ans:
3288 return ans
3289
Mark Dickinson2fc92632008-02-06 22:10:50 +00003290 comparison = self._cmp(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003291 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003292 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003293
3294 if comparison == -1:
3295 ans = self.next_plus(context)
3296 else: # comparison == 1
3297 ans = self.next_minus(context)
3298
3299 # decide which flags to raise using value of ans
3300 if ans._isinfinity():
3301 context._raise_error(Overflow,
3302 'Infinite result from next_toward',
3303 ans._sign)
3304 context._raise_error(Rounded)
3305 context._raise_error(Inexact)
3306 elif ans.adjusted() < context.Emin:
3307 context._raise_error(Underflow)
3308 context._raise_error(Subnormal)
3309 context._raise_error(Rounded)
3310 context._raise_error(Inexact)
3311 # if precision == 1 then we don't raise Clamped for a
3312 # result 0E-Etiny.
3313 if not ans:
3314 context._raise_error(Clamped)
3315
3316 return ans
3317
3318 def number_class(self, context=None):
3319 """Returns an indication of the class of self.
3320
3321 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003322 sNaN
3323 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003324 -Infinity
3325 -Normal
3326 -Subnormal
3327 -Zero
3328 +Zero
3329 +Subnormal
3330 +Normal
3331 +Infinity
3332 """
3333 if self.is_snan():
3334 return "sNaN"
3335 if self.is_qnan():
3336 return "NaN"
3337 inf = self._isinfinity()
3338 if inf == 1:
3339 return "+Infinity"
3340 if inf == -1:
3341 return "-Infinity"
3342 if self.is_zero():
3343 if self._sign:
3344 return "-Zero"
3345 else:
3346 return "+Zero"
3347 if context is None:
3348 context = getcontext()
3349 if self.is_subnormal(context=context):
3350 if self._sign:
3351 return "-Subnormal"
3352 else:
3353 return "+Subnormal"
3354 # just a normal, regular, boring number, :)
3355 if self._sign:
3356 return "-Normal"
3357 else:
3358 return "+Normal"
3359
3360 def radix(self):
3361 """Just returns 10, as this is Decimal, :)"""
3362 return Decimal(10)
3363
3364 def rotate(self, other, context=None):
3365 """Returns a rotated copy of self, value-of-other times."""
3366 if context is None:
3367 context = getcontext()
3368
3369 ans = self._check_nans(other, context)
3370 if ans:
3371 return ans
3372
3373 if other._exp != 0:
3374 return context._raise_error(InvalidOperation)
3375 if not (-context.prec <= int(other) <= context.prec):
3376 return context._raise_error(InvalidOperation)
3377
3378 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003379 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003380
3381 # get values, pad if necessary
3382 torot = int(other)
3383 rotdig = self._int
3384 topad = context.prec - len(rotdig)
3385 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003386 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003387
3388 # let's rotate!
3389 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003390 return _dec_from_triple(self._sign,
3391 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003392
3393 def scaleb (self, other, context=None):
3394 """Returns self operand after adding the second value to its exp."""
3395 if context is None:
3396 context = getcontext()
3397
3398 ans = self._check_nans(other, context)
3399 if ans:
3400 return ans
3401
3402 if other._exp != 0:
3403 return context._raise_error(InvalidOperation)
3404 liminf = -2 * (context.Emax + context.prec)
3405 limsup = 2 * (context.Emax + context.prec)
3406 if not (liminf <= int(other) <= limsup):
3407 return context._raise_error(InvalidOperation)
3408
3409 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003410 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003411
Facundo Batista72bc54f2007-11-23 17:59:00 +00003412 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003413 d = d._fix(context)
3414 return d
3415
3416 def shift(self, other, context=None):
3417 """Returns a shifted copy of self, value-of-other times."""
3418 if context is None:
3419 context = getcontext()
3420
3421 ans = self._check_nans(other, context)
3422 if ans:
3423 return ans
3424
3425 if other._exp != 0:
3426 return context._raise_error(InvalidOperation)
3427 if not (-context.prec <= int(other) <= context.prec):
3428 return context._raise_error(InvalidOperation)
3429
3430 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003431 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003432
3433 # get values, pad if necessary
3434 torot = int(other)
3435 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003436 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003437 rotdig = self._int
3438 topad = context.prec - len(rotdig)
3439 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003440 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003441
3442 # let's shift!
3443 if torot < 0:
3444 rotated = rotdig[:torot]
3445 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003446 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003447 rotated = rotated[-context.prec:]
3448
Facundo Batista72bc54f2007-11-23 17:59:00 +00003449 return _dec_from_triple(self._sign,
3450 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003451
Facundo Batista59c58842007-04-10 12:58:45 +00003452 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003453 def __reduce__(self):
3454 return (self.__class__, (str(self),))
3455
3456 def __copy__(self):
3457 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003458 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003459 return self.__class__(str(self))
3460
3461 def __deepcopy__(self, memo):
3462 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003463 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003464 return self.__class__(str(self))
3465
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003466 # PEP 3101 support. See also _parse_format_specifier and _format_align
3467 def __format__(self, specifier, context=None):
Mark Dickinsonf4da7772008-02-29 03:29:17 +00003468 """Format a Decimal instance according to the given specifier.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003469
3470 The specifier should be a standard format specifier, with the
3471 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3472 'F', 'g', 'G', and '%' are supported. If the formatting type
3473 is omitted it defaults to 'g' or 'G', depending on the value
3474 of context.capitals.
3475
3476 At this time the 'n' format specifier type (which is supposed
3477 to use the current locale) is not supported.
3478 """
3479
3480 # Note: PEP 3101 says that if the type is not present then
3481 # there should be at least one digit after the decimal point.
3482 # We take the liberty of ignoring this requirement for
3483 # Decimal---it's presumably there to make sure that
3484 # format(float, '') behaves similarly to str(float).
3485 if context is None:
3486 context = getcontext()
3487
3488 spec = _parse_format_specifier(specifier)
3489
3490 # special values don't care about the type or precision...
3491 if self._is_special:
3492 return _format_align(str(self), spec)
3493
3494 # a type of None defaults to 'g' or 'G', depending on context
3495 # if type is '%', adjust exponent of self accordingly
3496 if spec['type'] is None:
3497 spec['type'] = ['g', 'G'][context.capitals]
3498 elif spec['type'] == '%':
3499 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3500
3501 # round if necessary, taking rounding mode from the context
3502 rounding = context.rounding
3503 precision = spec['precision']
3504 if precision is not None:
3505 if spec['type'] in 'eE':
3506 self = self._round(precision+1, rounding)
3507 elif spec['type'] in 'gG':
3508 if len(self._int) > precision:
3509 self = self._round(precision, rounding)
3510 elif spec['type'] in 'fF%':
3511 self = self._rescale(-precision, rounding)
3512 # special case: zeros with a positive exponent can't be
3513 # represented in fixed point; rescale them to 0e0.
3514 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3515 self = self._rescale(0, rounding)
3516
3517 # figure out placement of the decimal point
3518 leftdigits = self._exp + len(self._int)
3519 if spec['type'] in 'fF%':
3520 dotplace = leftdigits
3521 elif spec['type'] in 'eE':
3522 if not self and precision is not None:
3523 dotplace = 1 - precision
3524 else:
3525 dotplace = 1
3526 elif spec['type'] in 'gG':
3527 if self._exp <= 0 and leftdigits > -6:
3528 dotplace = leftdigits
3529 else:
3530 dotplace = 1
3531
3532 # figure out main part of numeric string...
3533 if dotplace <= 0:
3534 num = '0.' + '0'*(-dotplace) + self._int
3535 elif dotplace >= len(self._int):
3536 # make sure we're not padding a '0' with extra zeros on the right
3537 assert dotplace==len(self._int) or self._int != '0'
3538 num = self._int + '0'*(dotplace-len(self._int))
3539 else:
3540 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3541
3542 # ...then the trailing exponent, or trailing '%'
3543 if leftdigits != dotplace or spec['type'] in 'eE':
3544 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3545 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3546 elif spec['type'] == '%':
3547 num = num + '%'
3548
3549 # add sign
3550 if self._sign == 1:
3551 num = '-' + num
3552 return _format_align(num, spec)
3553
3554
Facundo Batista72bc54f2007-11-23 17:59:00 +00003555def _dec_from_triple(sign, coefficient, exponent, special=False):
3556 """Create a decimal instance directly, without any validation,
3557 normalization (e.g. removal of leading zeros) or argument
3558 conversion.
3559
3560 This function is for *internal use only*.
3561 """
3562
3563 self = object.__new__(Decimal)
3564 self._sign = sign
3565 self._int = coefficient
3566 self._exp = exponent
3567 self._is_special = special
3568
3569 return self
3570
Raymond Hettinger45fd4762009-02-03 03:42:07 +00003571# Register Decimal as a kind of Number (an abstract base class).
3572# However, do not register it as Real (because Decimals are not
3573# interoperable with floats).
3574_numbers.Number.register(Decimal)
3575
3576
Facundo Batista59c58842007-04-10 12:58:45 +00003577##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003578
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003579
3580# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003581rounding_functions = [name for name in Decimal.__dict__.keys()
3582 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003583for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003584 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003585 globalname = name[1:].upper()
3586 val = globals()[globalname]
3587 Decimal._pick_rounding_function[val] = name
3588
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003589del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003590
Nick Coghlanced12182006-09-02 03:54:17 +00003591class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003592 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003593
Nick Coghlanced12182006-09-02 03:54:17 +00003594 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003595 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003596 """
3597 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003598 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003599 def __enter__(self):
3600 self.saved_context = getcontext()
3601 setcontext(self.new_context)
3602 return self.new_context
3603 def __exit__(self, t, v, tb):
3604 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003605
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003606class Context(object):
3607 """Contains the context for a Decimal instance.
3608
3609 Contains:
3610 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003611 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003612 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003613 raised when it is caused. Otherwise, a value is
3614 substituted in.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003615 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003616 (Whether or not the trap_enabler is set)
3617 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003618 Emin - Minimum exponent
3619 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003620 capitals - If 1, 1*10^1 is printed as 1E+1.
3621 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003622 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003623 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003624
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003625 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003626 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003627 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003628 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003629 _ignored_flags=None):
3630 if flags is None:
3631 flags = []
3632 if _ignored_flags is None:
3633 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003634 if not isinstance(flags, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003635 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003636 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003637 if traps is not None and not isinstance(traps, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003638 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003639 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003640 for name, val in locals().items():
3641 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003642 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003643 else:
3644 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003645 del self.self
3646
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003647 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003648 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003649 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003650 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3651 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3652 % vars(self))
3653 names = [f.__name__ for f, v in self.flags.items() if v]
3654 s.append('flags=[' + ', '.join(names) + ']')
3655 names = [t.__name__ for t, v in self.traps.items() if v]
3656 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003657 return ', '.join(s) + ')'
3658
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003659 def clear_flags(self):
3660 """Reset all flags to zero"""
3661 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003662 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003663
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003664 def _shallow_copy(self):
3665 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003666 nc = Context(self.prec, self.rounding, self.traps,
3667 self.flags, self.Emin, self.Emax,
3668 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003669 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003670
3671 def copy(self):
3672 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003673 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003674 self.flags.copy(), self.Emin, self.Emax,
3675 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003676 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003677 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003678
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003679 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003680 """Handles an error
3681
3682 If the flag is in _ignored_flags, returns the default response.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003683 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003684 trap_enabler is set, it reaises the exception. Otherwise, it returns
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003685 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003686 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003687 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003688 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003689 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003690 return error().handle(self, *args)
3691
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003692 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003693 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003694 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003695 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003696
3697 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003698 # self._ignored_flags = []
Mark Dickinson8aca9d02008-05-04 02:05:06 +00003699 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003700
3701 def _ignore_all_flags(self):
3702 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003703 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003704
3705 def _ignore_flags(self, *flags):
3706 """Ignore the flags, if they are raised"""
3707 # Do not mutate-- This way, copies of a context leave the original
3708 # alone.
3709 self._ignored_flags = (self._ignored_flags + list(flags))
3710 return list(flags)
3711
3712 def _regard_flags(self, *flags):
3713 """Stop ignoring the flags, if they are raised"""
3714 if flags and isinstance(flags[0], (tuple,list)):
3715 flags = flags[0]
3716 for flag in flags:
3717 self._ignored_flags.remove(flag)
3718
Nick Coghlan53663a62008-07-15 14:27:37 +00003719 # We inherit object.__hash__, so we must deny this explicitly
3720 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003721
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003722 def Etiny(self):
3723 """Returns Etiny (= Emin - prec + 1)"""
3724 return int(self.Emin - self.prec + 1)
3725
3726 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003727 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003728 return int(self.Emax - self.prec + 1)
3729
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003730 def _set_rounding(self, type):
3731 """Sets the rounding type.
3732
3733 Sets the rounding type, and returns the current (previous)
3734 rounding type. Often used like:
3735
3736 context = context.copy()
3737 # so you don't change the calling context
3738 # if an error occurs in the middle.
3739 rounding = context._set_rounding(ROUND_UP)
3740 val = self.__sub__(other, context=context)
3741 context._set_rounding(rounding)
3742
3743 This will make it round up for that operation.
3744 """
3745 rounding = self.rounding
3746 self.rounding= type
3747 return rounding
3748
Raymond Hettingerfed52962004-07-14 15:41:57 +00003749 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003750 """Creates a new Decimal instance but using self as context.
3751
3752 This method implements the to-number operation of the
3753 IBM Decimal specification."""
3754
3755 if isinstance(num, basestring) and num != num.strip():
3756 return self._raise_error(ConversionSyntax,
3757 "no trailing or leading whitespace is "
3758 "permitted.")
3759
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003760 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003761 if d._isnan() and len(d._int) > self.prec - self._clamp:
3762 return self._raise_error(ConversionSyntax,
3763 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003764 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003765
Facundo Batista59c58842007-04-10 12:58:45 +00003766 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003767 def abs(self, a):
3768 """Returns the absolute value of the operand.
3769
3770 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003771 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003772 the plus operation on the operand.
3773
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003774 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003775 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003776 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003777 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003778 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003779 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003780 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003781 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003782 """
3783 return a.__abs__(context=self)
3784
3785 def add(self, a, b):
3786 """Return the sum of the two operands.
3787
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003788 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003789 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003790 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003791 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003792 """
3793 return a.__add__(b, context=self)
3794
3795 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003796 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003797
Facundo Batista353750c2007-09-13 18:13:15 +00003798 def canonical(self, a):
3799 """Returns the same Decimal object.
3800
3801 As we do not have different encodings for the same number, the
3802 received object already is in its canonical form.
3803
3804 >>> ExtendedContext.canonical(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003805 Decimal('2.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003806 """
3807 return a.canonical(context=self)
3808
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003809 def compare(self, a, b):
3810 """Compares values numerically.
3811
3812 If the signs of the operands differ, a value representing each operand
3813 ('-1' if the operand is less than zero, '0' if the operand is zero or
3814 negative zero, or '1' if the operand is greater than zero) is used in
3815 place of that operand for the comparison instead of the actual
3816 operand.
3817
3818 The comparison is then effected by subtracting the second operand from
3819 the first and then returning a value according to the result of the
3820 subtraction: '-1' if the result is less than zero, '0' if the result is
3821 zero or negative zero, or '1' if the result is greater than zero.
3822
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003823 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003824 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003825 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003826 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003827 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003828 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003829 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003830 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003831 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003832 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003833 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003834 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003835 """
3836 return a.compare(b, context=self)
3837
Facundo Batista353750c2007-09-13 18:13:15 +00003838 def compare_signal(self, a, b):
3839 """Compares the values of the two operands numerically.
3840
3841 It's pretty much like compare(), but all NaNs signal, with signaling
3842 NaNs taking precedence over quiet NaNs.
3843
3844 >>> c = ExtendedContext
3845 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003846 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003847 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003848 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003849 >>> c.flags[InvalidOperation] = 0
3850 >>> print c.flags[InvalidOperation]
3851 0
3852 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003853 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003854 >>> print c.flags[InvalidOperation]
3855 1
3856 >>> c.flags[InvalidOperation] = 0
3857 >>> print c.flags[InvalidOperation]
3858 0
3859 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003860 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003861 >>> print c.flags[InvalidOperation]
3862 1
3863 """
3864 return a.compare_signal(b, context=self)
3865
3866 def compare_total(self, a, b):
3867 """Compares two operands using their abstract representation.
3868
3869 This is not like the standard compare, which use their numerical
3870 value. Note that a total ordering is defined for all possible abstract
3871 representations.
3872
3873 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003874 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003875 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003876 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003877 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003878 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003879 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003880 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003881 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003882 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00003883 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003884 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003885 """
3886 return a.compare_total(b)
3887
3888 def compare_total_mag(self, a, b):
3889 """Compares two operands using their abstract representation ignoring sign.
3890
3891 Like compare_total, but with operand's sign ignored and assumed to be 0.
3892 """
3893 return a.compare_total_mag(b)
3894
3895 def copy_abs(self, a):
3896 """Returns a copy of the operand with the sign set to 0.
3897
3898 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003899 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003900 >>> ExtendedContext.copy_abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003901 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00003902 """
3903 return a.copy_abs()
3904
3905 def copy_decimal(self, a):
3906 """Returns a copy of the decimal objet.
3907
3908 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003909 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003910 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003911 Decimal('-1.00')
Facundo Batista353750c2007-09-13 18:13:15 +00003912 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003913 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003914
3915 def copy_negate(self, a):
3916 """Returns a copy of the operand with the sign inverted.
3917
3918 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003919 Decimal('-101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003920 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003921 Decimal('101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003922 """
3923 return a.copy_negate()
3924
3925 def copy_sign(self, a, b):
3926 """Copies the second operand's sign to the first one.
3927
3928 In detail, it returns a copy of the first operand with the sign
3929 equal to the sign of the second operand.
3930
3931 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003932 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003933 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003934 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003935 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003936 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003937 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003938 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003939 """
3940 return a.copy_sign(b)
3941
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003942 def divide(self, a, b):
3943 """Decimal division in a specified context.
3944
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003945 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003946 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003947 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003948 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003949 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003950 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003951 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003952 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003953 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003954 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003955 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003956 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003957 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003958 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003959 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003960 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003961 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003962 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003963 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003964 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003965 """
3966 return a.__div__(b, context=self)
3967
3968 def divide_int(self, a, b):
3969 """Divides two numbers and returns the integer part of the result.
3970
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003971 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003972 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003973 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003974 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003975 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003976 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003977 """
3978 return a.__floordiv__(b, context=self)
3979
3980 def divmod(self, a, b):
3981 return a.__divmod__(b, context=self)
3982
Facundo Batista353750c2007-09-13 18:13:15 +00003983 def exp(self, a):
3984 """Returns e ** a.
3985
3986 >>> c = ExtendedContext.copy()
3987 >>> c.Emin = -999
3988 >>> c.Emax = 999
3989 >>> c.exp(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003990 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003991 >>> c.exp(Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003992 Decimal('0.367879441')
Facundo Batista353750c2007-09-13 18:13:15 +00003993 >>> c.exp(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003994 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00003995 >>> c.exp(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003996 Decimal('2.71828183')
Facundo Batista353750c2007-09-13 18:13:15 +00003997 >>> c.exp(Decimal('0.693147181'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003998 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00003999 >>> c.exp(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004000 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004001 """
4002 return a.exp(context=self)
4003
4004 def fma(self, a, b, c):
4005 """Returns a multiplied by b, plus c.
4006
4007 The first two operands are multiplied together, using multiply,
4008 the third operand is then added to the result of that
4009 multiplication, using add, all with only one final rounding.
4010
4011 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004012 Decimal('22')
Facundo Batista353750c2007-09-13 18:13:15 +00004013 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004014 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004015 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004016 Decimal('1.38435736E+12')
Facundo Batista353750c2007-09-13 18:13:15 +00004017 """
4018 return a.fma(b, c, context=self)
4019
4020 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004021 """Return True if the operand is canonical; otherwise return False.
4022
4023 Currently, the encoding of a Decimal instance is always
4024 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00004025
4026 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004027 True
Facundo Batista353750c2007-09-13 18:13:15 +00004028 """
Facundo Batista1a191df2007-10-02 17:01:24 +00004029 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00004030
4031 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004032 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004033
Facundo Batista1a191df2007-10-02 17:01:24 +00004034 A Decimal instance is considered finite if it is neither
4035 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00004036
4037 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004038 True
Facundo Batista353750c2007-09-13 18:13:15 +00004039 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004040 True
Facundo Batista353750c2007-09-13 18:13:15 +00004041 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004042 True
Facundo Batista353750c2007-09-13 18:13:15 +00004043 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004044 False
Facundo Batista353750c2007-09-13 18:13:15 +00004045 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004046 False
Facundo Batista353750c2007-09-13 18:13:15 +00004047 """
4048 return a.is_finite()
4049
4050 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004051 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004052
4053 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004054 False
Facundo Batista353750c2007-09-13 18:13:15 +00004055 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004056 True
Facundo Batista353750c2007-09-13 18:13:15 +00004057 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004058 False
Facundo Batista353750c2007-09-13 18:13:15 +00004059 """
4060 return a.is_infinite()
4061
4062 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004063 """Return True if the operand is a qNaN or sNaN;
4064 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004065
4066 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004067 False
Facundo Batista353750c2007-09-13 18:13:15 +00004068 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004069 True
Facundo Batista353750c2007-09-13 18:13:15 +00004070 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004071 True
Facundo Batista353750c2007-09-13 18:13:15 +00004072 """
4073 return a.is_nan()
4074
4075 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004076 """Return True if the operand is a normal number;
4077 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004078
4079 >>> c = ExtendedContext.copy()
4080 >>> c.Emin = -999
4081 >>> c.Emax = 999
4082 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004083 True
Facundo Batista353750c2007-09-13 18:13:15 +00004084 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004085 False
Facundo Batista353750c2007-09-13 18:13:15 +00004086 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004087 False
Facundo Batista353750c2007-09-13 18:13:15 +00004088 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004089 False
Facundo Batista353750c2007-09-13 18:13:15 +00004090 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004091 False
Facundo Batista353750c2007-09-13 18:13:15 +00004092 """
4093 return a.is_normal(context=self)
4094
4095 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004096 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004097
4098 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004099 False
Facundo Batista353750c2007-09-13 18:13:15 +00004100 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004101 True
Facundo Batista353750c2007-09-13 18:13:15 +00004102 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004103 False
Facundo Batista353750c2007-09-13 18:13:15 +00004104 """
4105 return a.is_qnan()
4106
4107 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004108 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004109
4110 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004111 False
Facundo Batista353750c2007-09-13 18:13:15 +00004112 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004113 True
Facundo Batista353750c2007-09-13 18:13:15 +00004114 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004115 True
Facundo Batista353750c2007-09-13 18:13:15 +00004116 """
4117 return a.is_signed()
4118
4119 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004120 """Return True if the operand is a signaling NaN;
4121 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004122
4123 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004124 False
Facundo Batista353750c2007-09-13 18:13:15 +00004125 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004126 False
Facundo Batista353750c2007-09-13 18:13:15 +00004127 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004128 True
Facundo Batista353750c2007-09-13 18:13:15 +00004129 """
4130 return a.is_snan()
4131
4132 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004133 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004134
4135 >>> c = ExtendedContext.copy()
4136 >>> c.Emin = -999
4137 >>> c.Emax = 999
4138 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004139 False
Facundo Batista353750c2007-09-13 18:13:15 +00004140 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004141 True
Facundo Batista353750c2007-09-13 18:13:15 +00004142 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004143 False
Facundo Batista353750c2007-09-13 18:13:15 +00004144 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004145 False
Facundo Batista353750c2007-09-13 18:13:15 +00004146 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004147 False
Facundo Batista353750c2007-09-13 18:13:15 +00004148 """
4149 return a.is_subnormal(context=self)
4150
4151 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004152 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004153
4154 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004155 True
Facundo Batista353750c2007-09-13 18:13:15 +00004156 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004157 False
Facundo Batista353750c2007-09-13 18:13:15 +00004158 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004159 True
Facundo Batista353750c2007-09-13 18:13:15 +00004160 """
4161 return a.is_zero()
4162
4163 def ln(self, a):
4164 """Returns the natural (base e) logarithm of the operand.
4165
4166 >>> c = ExtendedContext.copy()
4167 >>> c.Emin = -999
4168 >>> c.Emax = 999
4169 >>> c.ln(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004170 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004171 >>> c.ln(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004172 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004173 >>> c.ln(Decimal('2.71828183'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004174 Decimal('1.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004175 >>> c.ln(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004176 Decimal('2.30258509')
Facundo Batista353750c2007-09-13 18:13:15 +00004177 >>> c.ln(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004178 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004179 """
4180 return a.ln(context=self)
4181
4182 def log10(self, a):
4183 """Returns the base 10 logarithm of the operand.
4184
4185 >>> c = ExtendedContext.copy()
4186 >>> c.Emin = -999
4187 >>> c.Emax = 999
4188 >>> c.log10(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004189 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004190 >>> c.log10(Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004191 Decimal('-3')
Facundo Batista353750c2007-09-13 18:13:15 +00004192 >>> c.log10(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004193 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004194 >>> c.log10(Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004195 Decimal('0.301029996')
Facundo Batista353750c2007-09-13 18:13:15 +00004196 >>> c.log10(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004197 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004198 >>> c.log10(Decimal('70'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004199 Decimal('1.84509804')
Facundo Batista353750c2007-09-13 18:13:15 +00004200 >>> c.log10(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004201 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004202 """
4203 return a.log10(context=self)
4204
4205 def logb(self, a):
4206 """ Returns the exponent of the magnitude of the operand's MSD.
4207
4208 The result is the integer which is the exponent of the magnitude
4209 of the most significant digit of the operand (as though the
4210 operand were truncated to a single digit while maintaining the
4211 value of that digit and without limiting the resulting exponent).
4212
4213 >>> ExtendedContext.logb(Decimal('250'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004214 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004215 >>> ExtendedContext.logb(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004216 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004217 >>> ExtendedContext.logb(Decimal('0.03'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004218 Decimal('-2')
Facundo Batista353750c2007-09-13 18:13:15 +00004219 >>> ExtendedContext.logb(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004220 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004221 """
4222 return a.logb(context=self)
4223
4224 def logical_and(self, a, b):
4225 """Applies the logical operation 'and' between each operand's digits.
4226
4227 The operands must be both logical numbers.
4228
4229 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004230 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004231 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004232 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004233 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004234 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004235 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004236 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004237 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004238 Decimal('1000')
Facundo Batista353750c2007-09-13 18:13:15 +00004239 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004240 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004241 """
4242 return a.logical_and(b, context=self)
4243
4244 def logical_invert(self, a):
4245 """Invert all the digits in the operand.
4246
4247 The operand must be a logical number.
4248
4249 >>> ExtendedContext.logical_invert(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004250 Decimal('111111111')
Facundo Batista353750c2007-09-13 18:13:15 +00004251 >>> ExtendedContext.logical_invert(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004252 Decimal('111111110')
Facundo Batista353750c2007-09-13 18:13:15 +00004253 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004254 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004255 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004256 Decimal('10101010')
Facundo Batista353750c2007-09-13 18:13:15 +00004257 """
4258 return a.logical_invert(context=self)
4259
4260 def logical_or(self, a, b):
4261 """Applies the logical operation 'or' between each operand's digits.
4262
4263 The operands must be both logical numbers.
4264
4265 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004266 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004267 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004268 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004269 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004270 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004271 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004272 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004273 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004274 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004275 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004276 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004277 """
4278 return a.logical_or(b, context=self)
4279
4280 def logical_xor(self, a, b):
4281 """Applies the logical operation 'xor' between each operand's digits.
4282
4283 The operands must be both logical numbers.
4284
4285 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004286 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004287 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004288 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004289 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004290 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004291 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004292 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004293 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004294 Decimal('110')
Facundo Batista353750c2007-09-13 18:13:15 +00004295 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004296 Decimal('1101')
Facundo Batista353750c2007-09-13 18:13:15 +00004297 """
4298 return a.logical_xor(b, context=self)
4299
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004300 def max(self, a,b):
4301 """max compares two values numerically and returns the maximum.
4302
4303 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004304 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004305 operation. If they are numerically equal then the left-hand operand
4306 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004307 infinity) of the two operands is chosen as the result.
4308
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004309 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004310 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004311 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004312 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004313 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004314 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004315 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004316 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004317 """
4318 return a.max(b, context=self)
4319
Facundo Batista353750c2007-09-13 18:13:15 +00004320 def max_mag(self, a, b):
4321 """Compares the values numerically with their sign ignored."""
4322 return a.max_mag(b, context=self)
4323
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004324 def min(self, a,b):
4325 """min compares two values numerically and returns the minimum.
4326
4327 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004328 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004329 operation. If they are numerically equal then the left-hand operand
4330 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004331 infinity) of the two operands is chosen as the result.
4332
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004333 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004334 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004335 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004336 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004337 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004338 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004339 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004340 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004341 """
4342 return a.min(b, context=self)
4343
Facundo Batista353750c2007-09-13 18:13:15 +00004344 def min_mag(self, a, b):
4345 """Compares the values numerically with their sign ignored."""
4346 return a.min_mag(b, context=self)
4347
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004348 def minus(self, a):
4349 """Minus corresponds to unary prefix minus in Python.
4350
4351 The operation is evaluated using the same rules as subtract; the
4352 operation minus(a) is calculated as subtract('0', a) where the '0'
4353 has the same exponent as the operand.
4354
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004355 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004356 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004357 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004358 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004359 """
4360 return a.__neg__(context=self)
4361
4362 def multiply(self, a, b):
4363 """multiply multiplies two operands.
4364
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004365 If either operand is a special value then the general rules apply.
4366 Otherwise, the operands are multiplied together ('long multiplication'),
4367 resulting in a number which may be as long as the sum of the lengths
4368 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004369
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004370 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004371 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004372 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004373 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004374 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004375 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004376 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004377 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004378 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004379 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004380 """
4381 return a.__mul__(b, context=self)
4382
Facundo Batista353750c2007-09-13 18:13:15 +00004383 def next_minus(self, a):
4384 """Returns the largest representable number smaller than a.
4385
4386 >>> c = ExtendedContext.copy()
4387 >>> c.Emin = -999
4388 >>> c.Emax = 999
4389 >>> ExtendedContext.next_minus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004390 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004391 >>> c.next_minus(Decimal('1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004392 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004393 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004394 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004395 >>> c.next_minus(Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004396 Decimal('9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004397 """
4398 return a.next_minus(context=self)
4399
4400 def next_plus(self, a):
4401 """Returns the smallest representable number larger than a.
4402
4403 >>> c = ExtendedContext.copy()
4404 >>> c.Emin = -999
4405 >>> c.Emax = 999
4406 >>> ExtendedContext.next_plus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004407 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004408 >>> c.next_plus(Decimal('-1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004409 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004410 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004411 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004412 >>> c.next_plus(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004413 Decimal('-9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004414 """
4415 return a.next_plus(context=self)
4416
4417 def next_toward(self, a, b):
4418 """Returns the number closest to a, in direction towards b.
4419
4420 The result is the closest representable number from the first
4421 operand (but not the first operand) that is in the direction
4422 towards the second operand, unless the operands have the same
4423 value.
4424
4425 >>> c = ExtendedContext.copy()
4426 >>> c.Emin = -999
4427 >>> c.Emax = 999
4428 >>> c.next_toward(Decimal('1'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004429 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004430 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004431 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004432 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004433 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004434 >>> c.next_toward(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004435 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004436 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004437 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004438 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004439 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004440 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004441 Decimal('-0.00')
Facundo Batista353750c2007-09-13 18:13:15 +00004442 """
4443 return a.next_toward(b, context=self)
4444
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004445 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004446 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004447
4448 Essentially a plus operation with all trailing zeros removed from the
4449 result.
4450
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004451 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004452 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004453 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004454 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004455 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004456 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004457 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004458 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004459 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004460 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004461 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004462 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004463 """
4464 return a.normalize(context=self)
4465
Facundo Batista353750c2007-09-13 18:13:15 +00004466 def number_class(self, a):
4467 """Returns an indication of the class of the operand.
4468
4469 The class is one of the following strings:
4470 -sNaN
4471 -NaN
4472 -Infinity
4473 -Normal
4474 -Subnormal
4475 -Zero
4476 +Zero
4477 +Subnormal
4478 +Normal
4479 +Infinity
4480
4481 >>> c = Context(ExtendedContext)
4482 >>> c.Emin = -999
4483 >>> c.Emax = 999
4484 >>> c.number_class(Decimal('Infinity'))
4485 '+Infinity'
4486 >>> c.number_class(Decimal('1E-10'))
4487 '+Normal'
4488 >>> c.number_class(Decimal('2.50'))
4489 '+Normal'
4490 >>> c.number_class(Decimal('0.1E-999'))
4491 '+Subnormal'
4492 >>> c.number_class(Decimal('0'))
4493 '+Zero'
4494 >>> c.number_class(Decimal('-0'))
4495 '-Zero'
4496 >>> c.number_class(Decimal('-0.1E-999'))
4497 '-Subnormal'
4498 >>> c.number_class(Decimal('-1E-10'))
4499 '-Normal'
4500 >>> c.number_class(Decimal('-2.50'))
4501 '-Normal'
4502 >>> c.number_class(Decimal('-Infinity'))
4503 '-Infinity'
4504 >>> c.number_class(Decimal('NaN'))
4505 'NaN'
4506 >>> c.number_class(Decimal('-NaN'))
4507 'NaN'
4508 >>> c.number_class(Decimal('sNaN'))
4509 'sNaN'
4510 """
4511 return a.number_class(context=self)
4512
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004513 def plus(self, a):
4514 """Plus corresponds to unary prefix plus in Python.
4515
4516 The operation is evaluated using the same rules as add; the
4517 operation plus(a) is calculated as add('0', a) where the '0'
4518 has the same exponent as the operand.
4519
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004520 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004521 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004522 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004523 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004524 """
4525 return a.__pos__(context=self)
4526
4527 def power(self, a, b, modulo=None):
4528 """Raises a to the power of b, to modulo if given.
4529
Facundo Batista353750c2007-09-13 18:13:15 +00004530 With two arguments, compute a**b. If a is negative then b
4531 must be integral. The result will be inexact unless b is
4532 integral and the result is finite and can be expressed exactly
4533 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004534
Facundo Batista353750c2007-09-13 18:13:15 +00004535 With three arguments, compute (a**b) % modulo. For the
4536 three argument form, the following restrictions on the
4537 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004538
Facundo Batista353750c2007-09-13 18:13:15 +00004539 - all three arguments must be integral
4540 - b must be nonnegative
4541 - at least one of a or b must be nonzero
4542 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004543
Facundo Batista353750c2007-09-13 18:13:15 +00004544 The result of pow(a, b, modulo) is identical to the result
4545 that would be obtained by computing (a**b) % modulo with
4546 unbounded precision, but is computed more efficiently. It is
4547 always exact.
4548
4549 >>> c = ExtendedContext.copy()
4550 >>> c.Emin = -999
4551 >>> c.Emax = 999
4552 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004553 Decimal('8')
Facundo Batista353750c2007-09-13 18:13:15 +00004554 >>> c.power(Decimal('-2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004555 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004556 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004557 Decimal('0.125')
Facundo Batista353750c2007-09-13 18:13:15 +00004558 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004559 Decimal('69.7575744')
Facundo Batista353750c2007-09-13 18:13:15 +00004560 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004561 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004562 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004563 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004564 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004565 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004566 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004567 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004568 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004569 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004570 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004571 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004572 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004573 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004574 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004575 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004576 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004577 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00004578
4579 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004580 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004581 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004582 Decimal('-11')
Facundo Batista353750c2007-09-13 18:13:15 +00004583 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004584 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004585 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004586 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004587 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004588 Decimal('11729830')
Facundo Batista353750c2007-09-13 18:13:15 +00004589 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004590 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004591 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004592 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004593 """
4594 return a.__pow__(b, modulo, context=self)
4595
4596 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004597 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004598
4599 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004600 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004601 exponent is being increased), multiplied by a positive power of ten (if
4602 the exponent is being decreased), or is unchanged (if the exponent is
4603 already equal to that of the right-hand operand).
4604
4605 Unlike other operations, if the length of the coefficient after the
4606 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004607 operation condition is raised. This guarantees that, unless there is
4608 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004609 equal to that of the right-hand operand.
4610
4611 Also unlike other operations, quantize will never raise Underflow, even
4612 if the result is subnormal and inexact.
4613
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004614 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004615 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004616 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004617 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004618 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004619 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004620 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004621 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004622 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004623 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004624 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004625 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004626 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004627 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004628 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004629 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004630 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004631 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004632 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004633 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004634 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004635 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004636 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004637 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004638 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004639 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004640 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004641 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004642 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004643 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004644 """
4645 return a.quantize(b, context=self)
4646
Facundo Batista353750c2007-09-13 18:13:15 +00004647 def radix(self):
4648 """Just returns 10, as this is Decimal, :)
4649
4650 >>> ExtendedContext.radix()
Raymond Hettingerabe32372008-02-14 02:41:22 +00004651 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004652 """
4653 return Decimal(10)
4654
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655 def remainder(self, a, b):
4656 """Returns the remainder from integer division.
4657
4658 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004659 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004660 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004661 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004662
4663 This operation will fail under the same conditions as integer division
4664 (that is, if integer division on the same two operands would fail, the
4665 remainder cannot be calculated).
4666
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004667 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004668 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004669 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004670 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004671 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004672 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004673 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004674 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004675 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004676 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004677 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004678 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004679 """
4680 return a.__mod__(b, context=self)
4681
4682 def remainder_near(self, a, b):
4683 """Returns to be "a - b * n", where n is the integer nearest the exact
4684 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004685 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004686 sign of a.
4687
4688 This operation will fail under the same conditions as integer division
4689 (that is, if integer division on the same two operands would fail, the
4690 remainder cannot be calculated).
4691
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004692 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004693 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004694 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004695 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004696 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004697 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004698 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004699 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004700 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004701 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004702 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004703 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004704 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004705 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004706 """
4707 return a.remainder_near(b, context=self)
4708
Facundo Batista353750c2007-09-13 18:13:15 +00004709 def rotate(self, a, b):
4710 """Returns a rotated copy of a, b times.
4711
4712 The coefficient of the result is a rotated copy of the digits in
4713 the coefficient of the first operand. The number of places of
4714 rotation is taken from the absolute value of the second operand,
4715 with the rotation being to the left if the second operand is
4716 positive or to the right otherwise.
4717
4718 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004719 Decimal('400000003')
Facundo Batista353750c2007-09-13 18:13:15 +00004720 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004721 Decimal('12')
Facundo Batista353750c2007-09-13 18:13:15 +00004722 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004723 Decimal('891234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004724 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004725 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004726 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004727 Decimal('345678912')
Facundo Batista353750c2007-09-13 18:13:15 +00004728 """
4729 return a.rotate(b, context=self)
4730
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004731 def same_quantum(self, a, b):
4732 """Returns True if the two operands have the same exponent.
4733
4734 The result is never affected by either the sign or the coefficient of
4735 either operand.
4736
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004737 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004738 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004739 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004740 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004741 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004742 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004743 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004744 True
4745 """
4746 return a.same_quantum(b)
4747
Facundo Batista353750c2007-09-13 18:13:15 +00004748 def scaleb (self, a, b):
4749 """Returns the first operand after adding the second value its exp.
4750
4751 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004752 Decimal('0.0750')
Facundo Batista353750c2007-09-13 18:13:15 +00004753 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004754 Decimal('7.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004755 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004756 Decimal('7.50E+3')
Facundo Batista353750c2007-09-13 18:13:15 +00004757 """
4758 return a.scaleb (b, context=self)
4759
4760 def shift(self, a, b):
4761 """Returns a shifted copy of a, b times.
4762
4763 The coefficient of the result is a shifted copy of the digits
4764 in the coefficient of the first operand. The number of places
4765 to shift is taken from the absolute value of the second operand,
4766 with the shift being to the left if the second operand is
4767 positive or to the right otherwise. Digits shifted into the
4768 coefficient are zeros.
4769
4770 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004771 Decimal('400000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004772 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004773 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004774 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004775 Decimal('1234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004776 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004777 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004778 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004779 Decimal('345678900')
Facundo Batista353750c2007-09-13 18:13:15 +00004780 """
4781 return a.shift(b, context=self)
4782
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004783 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004784 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004785
4786 If the result must be inexact, it is rounded using the round-half-even
4787 algorithm.
4788
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004789 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004790 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004791 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004792 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004793 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004794 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004795 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004796 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004797 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004798 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004799 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004800 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004801 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004802 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004803 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004804 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004805 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004806 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004807 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004808 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004809 """
4810 return a.sqrt(context=self)
4811
4812 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004813 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004814
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004815 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004816 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004817 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004818 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004819 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004820 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004821 """
4822 return a.__sub__(b, context=self)
4823
4824 def to_eng_string(self, a):
4825 """Converts a number to a string, using scientific notation.
4826
4827 The operation is not affected by the context.
4828 """
4829 return a.to_eng_string(context=self)
4830
4831 def to_sci_string(self, a):
4832 """Converts a number to a string, using scientific notation.
4833
4834 The operation is not affected by the context.
4835 """
4836 return a.__str__(context=self)
4837
Facundo Batista353750c2007-09-13 18:13:15 +00004838 def to_integral_exact(self, a):
4839 """Rounds to an integer.
4840
4841 When the operand has a negative exponent, the result is the same
4842 as using the quantize() operation using the given operand as the
4843 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4844 of the operand as the precision setting; Inexact and Rounded flags
4845 are allowed in this operation. The rounding mode is taken from the
4846 context.
4847
4848 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004849 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004850 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004851 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004852 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004853 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004854 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004855 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004856 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004857 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004858 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004859 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004860 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004861 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004862 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004863 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004864 """
4865 return a.to_integral_exact(context=self)
4866
4867 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004868 """Rounds to an integer.
4869
4870 When the operand has a negative exponent, the result is the same
4871 as using the quantize() operation using the given operand as the
4872 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4873 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004874 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004875
Facundo Batista353750c2007-09-13 18:13:15 +00004876 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004877 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004878 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004879 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004880 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004881 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004882 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004883 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004884 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004885 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004886 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004887 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004888 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004889 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004890 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004891 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004892 """
Facundo Batista353750c2007-09-13 18:13:15 +00004893 return a.to_integral_value(context=self)
4894
4895 # the method name changed, but we provide also the old one, for compatibility
4896 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004897
4898class _WorkRep(object):
4899 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004900 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004901 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004902 # exp: None, int, or string
4903
4904 def __init__(self, value=None):
4905 if value is None:
4906 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004907 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004908 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004909 elif isinstance(value, Decimal):
4910 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004911 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004912 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004913 else:
4914 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004915 self.sign = value[0]
4916 self.int = value[1]
4917 self.exp = value[2]
4918
4919 def __repr__(self):
4920 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4921
4922 __str__ = __repr__
4923
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004924
4925
Facundo Batistae64acfa2007-12-17 14:18:42 +00004926def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004927 """Normalizes op1, op2 to have the same exp and length of coefficient.
4928
4929 Done during addition.
4930 """
Facundo Batista353750c2007-09-13 18:13:15 +00004931 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004932 tmp = op2
4933 other = op1
4934 else:
4935 tmp = op1
4936 other = op2
4937
Facundo Batista353750c2007-09-13 18:13:15 +00004938 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4939 # Then adding 10**exp to tmp has the same effect (after rounding)
4940 # as adding any positive quantity smaller than 10**exp; similarly
4941 # for subtraction. So if other is smaller than 10**exp we replace
4942 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004943 tmp_len = len(str(tmp.int))
4944 other_len = len(str(other.int))
4945 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4946 if other_len + other.exp - 1 < exp:
4947 other.int = 1
4948 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004949
Facundo Batista353750c2007-09-13 18:13:15 +00004950 tmp.int *= 10 ** (tmp.exp - other.exp)
4951 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004952 return op1, op2
4953
Facundo Batista353750c2007-09-13 18:13:15 +00004954##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4955
4956# This function from Tim Peters was taken from here:
4957# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4958# The correction being in the function definition is for speed, and
4959# the whole function is not resolved with math.log because of avoiding
4960# the use of floats.
4961def _nbits(n, correction = {
4962 '0': 4, '1': 3, '2': 2, '3': 2,
4963 '4': 1, '5': 1, '6': 1, '7': 1,
4964 '8': 0, '9': 0, 'a': 0, 'b': 0,
4965 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4966 """Number of bits in binary representation of the positive integer n,
4967 or 0 if n == 0.
4968 """
4969 if n < 0:
4970 raise ValueError("The argument to _nbits should be nonnegative.")
4971 hex_n = "%x" % n
4972 return 4*len(hex_n) - correction[hex_n[0]]
4973
4974def _sqrt_nearest(n, a):
4975 """Closest integer to the square root of the positive integer n. a is
4976 an initial approximation to the square root. Any positive integer
4977 will do for a, but the closer a is to the square root of n the
4978 faster convergence will be.
4979
4980 """
4981 if n <= 0 or a <= 0:
4982 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4983
4984 b=0
4985 while a != b:
4986 b, a = a, a--n//a>>1
4987 return a
4988
4989def _rshift_nearest(x, shift):
4990 """Given an integer x and a nonnegative integer shift, return closest
4991 integer to x / 2**shift; use round-to-even in case of a tie.
4992
4993 """
4994 b, q = 1L << shift, x >> shift
4995 return q + (2*(x & (b-1)) + (q&1) > b)
4996
4997def _div_nearest(a, b):
4998 """Closest integer to a/b, a and b positive integers; rounds to even
4999 in the case of a tie.
5000
5001 """
5002 q, r = divmod(a, b)
5003 return q + (2*r + (q&1) > b)
5004
5005def _ilog(x, M, L = 8):
5006 """Integer approximation to M*log(x/M), with absolute error boundable
5007 in terms only of x/M.
5008
5009 Given positive integers x and M, return an integer approximation to
5010 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5011 between the approximation and the exact result is at most 22. For
5012 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5013 both cases these are upper bounds on the error; it will usually be
5014 much smaller."""
5015
5016 # The basic algorithm is the following: let log1p be the function
5017 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5018 # the reduction
5019 #
5020 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5021 #
5022 # repeatedly until the argument to log1p is small (< 2**-L in
5023 # absolute value). For small y we can use the Taylor series
5024 # expansion
5025 #
5026 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5027 #
5028 # truncating at T such that y**T is small enough. The whole
5029 # computation is carried out in a form of fixed-point arithmetic,
5030 # with a real number z being represented by an integer
5031 # approximation to z*M. To avoid loss of precision, the y below
5032 # is actually an integer approximation to 2**R*y*M, where R is the
5033 # number of reductions performed so far.
5034
5035 y = x-M
5036 # argument reduction; R = number of reductions performed
5037 R = 0
5038 while (R <= L and long(abs(y)) << L-R >= M or
5039 R > L and abs(y) >> R-L >= M):
5040 y = _div_nearest(long(M*y) << 1,
5041 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5042 R += 1
5043
5044 # Taylor series with T terms
5045 T = -int(-10*len(str(M))//(3*L))
5046 yshift = _rshift_nearest(y, R)
5047 w = _div_nearest(M, T)
5048 for k in xrange(T-1, 0, -1):
5049 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5050
5051 return _div_nearest(w*y, M)
5052
5053def _dlog10(c, e, p):
5054 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5055 approximation to 10**p * log10(c*10**e), with an absolute error of
5056 at most 1. Assumes that c*10**e is not exactly 1."""
5057
5058 # increase precision by 2; compensate for this by dividing
5059 # final result by 100
5060 p += 2
5061
5062 # write c*10**e as d*10**f with either:
5063 # f >= 0 and 1 <= d <= 10, or
5064 # f <= 0 and 0.1 <= d <= 1.
5065 # Thus for c*10**e close to 1, f = 0
5066 l = len(str(c))
5067 f = e+l - (e+l >= 1)
5068
5069 if p > 0:
5070 M = 10**p
5071 k = e+p-f
5072 if k >= 0:
5073 c *= 10**k
5074 else:
5075 c = _div_nearest(c, 10**-k)
5076
5077 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005078 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005079 log_d = _div_nearest(log_d*M, log_10)
5080 log_tenpower = f*M # exact
5081 else:
5082 log_d = 0 # error < 2.31
Neal Norwitz18aa3882008-08-24 05:04:52 +00005083 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Facundo Batista353750c2007-09-13 18:13:15 +00005084
5085 return _div_nearest(log_tenpower+log_d, 100)
5086
5087def _dlog(c, e, p):
5088 """Given integers c, e and p with c > 0, compute an integer
5089 approximation to 10**p * log(c*10**e), with an absolute error of
5090 at most 1. Assumes that c*10**e is not exactly 1."""
5091
5092 # Increase precision by 2. The precision increase is compensated
5093 # for at the end with a division by 100.
5094 p += 2
5095
5096 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5097 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5098 # as 10**p * log(d) + 10**p*f * log(10).
5099 l = len(str(c))
5100 f = e+l - (e+l >= 1)
5101
5102 # compute approximation to 10**p*log(d), with error < 27
5103 if p > 0:
5104 k = e+p-f
5105 if k >= 0:
5106 c *= 10**k
5107 else:
5108 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5109
5110 # _ilog magnifies existing error in c by a factor of at most 10
5111 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5112 else:
5113 # p <= 0: just approximate the whole thing by 0; error < 2.31
5114 log_d = 0
5115
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005116 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00005117 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005118 extra = len(str(abs(f)))-1
5119 if p + extra >= 0:
5120 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5121 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5122 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00005123 else:
5124 f_log_ten = 0
5125 else:
5126 f_log_ten = 0
5127
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005128 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005129 return _div_nearest(f_log_ten + log_d, 100)
5130
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005131class _Log10Memoize(object):
5132 """Class to compute, store, and allow retrieval of, digits of the
5133 constant log(10) = 2.302585.... This constant is needed by
5134 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5135 def __init__(self):
5136 self.digits = "23025850929940456840179914546843642076011014886"
5137
5138 def getdigits(self, p):
5139 """Given an integer p >= 0, return floor(10**p)*log(10).
5140
5141 For example, self.getdigits(3) returns 2302.
5142 """
5143 # digits are stored as a string, for quick conversion to
5144 # integer in the case that we've already computed enough
5145 # digits; the stored digits should always be correct
5146 # (truncated, not rounded to nearest).
5147 if p < 0:
5148 raise ValueError("p should be nonnegative")
5149
5150 if p >= len(self.digits):
5151 # compute p+3, p+6, p+9, ... digits; continue until at
5152 # least one of the extra digits is nonzero
5153 extra = 3
5154 while True:
5155 # compute p+extra digits, correct to within 1ulp
5156 M = 10**(p+extra+2)
5157 digits = str(_div_nearest(_ilog(10*M, M), 100))
5158 if digits[-extra:] != '0'*extra:
5159 break
5160 extra += 3
5161 # keep all reliable digits so far; remove trailing zeros
5162 # and next nonzero digit
5163 self.digits = digits.rstrip('0')[:-1]
5164 return int(self.digits[:p+1])
5165
5166_log10_digits = _Log10Memoize().getdigits
5167
Facundo Batista353750c2007-09-13 18:13:15 +00005168def _iexp(x, M, L=8):
5169 """Given integers x and M, M > 0, such that x/M is small in absolute
5170 value, compute an integer approximation to M*exp(x/M). For 0 <=
5171 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5172 is usually much smaller)."""
5173
5174 # Algorithm: to compute exp(z) for a real number z, first divide z
5175 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5176 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5177 # series
5178 #
5179 # expm1(x) = x + x**2/2! + x**3/3! + ...
5180 #
5181 # Now use the identity
5182 #
5183 # expm1(2x) = expm1(x)*(expm1(x)+2)
5184 #
5185 # R times to compute the sequence expm1(z/2**R),
5186 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5187
5188 # Find R such that x/2**R/M <= 2**-L
5189 R = _nbits((long(x)<<L)//M)
5190
5191 # Taylor series. (2**L)**T > M
5192 T = -int(-10*len(str(M))//(3*L))
5193 y = _div_nearest(x, T)
5194 Mshift = long(M)<<R
5195 for i in xrange(T-1, 0, -1):
5196 y = _div_nearest(x*(Mshift + y), Mshift * i)
5197
5198 # Expansion
5199 for k in xrange(R-1, -1, -1):
5200 Mshift = long(M)<<(k+2)
5201 y = _div_nearest(y*(y+Mshift), Mshift)
5202
5203 return M+y
5204
5205def _dexp(c, e, p):
5206 """Compute an approximation to exp(c*10**e), with p decimal places of
5207 precision.
5208
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005209 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005210
5211 10**(p-1) <= d <= 10**p, and
5212 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5213
5214 In other words, d*10**f is an approximation to exp(c*10**e) with p
5215 digits of precision, and with an error in d of at most 1. This is
5216 almost, but not quite, the same as the error being < 1ulp: when d
5217 = 10**(p-1) the error could be up to 10 ulp."""
5218
5219 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5220 p += 2
5221
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005222 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005223 extra = max(0, e + len(str(c)) - 1)
5224 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005225
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005226 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005227 # rounding down
5228 shift = e+q
5229 if shift >= 0:
5230 cshift = c*10**shift
5231 else:
5232 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005233 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005234
5235 # reduce remainder back to original precision
5236 rem = _div_nearest(rem, 10**extra)
5237
5238 # error in result of _iexp < 120; error after division < 0.62
5239 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5240
5241def _dpower(xc, xe, yc, ye, p):
5242 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5243 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5244
5245 10**(p-1) <= c <= 10**p, and
5246 (c-1)*10**e < x**y < (c+1)*10**e
5247
5248 in other words, c*10**e is an approximation to x**y with p digits
5249 of precision, and with an error in c of at most 1. (This is
5250 almost, but not quite, the same as the error being < 1ulp: when c
5251 == 10**(p-1) we can only guarantee error < 10ulp.)
5252
5253 We assume that: x is positive and not equal to 1, and y is nonzero.
5254 """
5255
5256 # Find b such that 10**(b-1) <= |y| <= 10**b
5257 b = len(str(abs(yc))) + ye
5258
5259 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5260 lxc = _dlog(xc, xe, p+b+1)
5261
5262 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5263 shift = ye-b
5264 if shift >= 0:
5265 pc = lxc*yc*10**shift
5266 else:
5267 pc = _div_nearest(lxc*yc, 10**-shift)
5268
5269 if pc == 0:
5270 # we prefer a result that isn't exactly 1; this makes it
5271 # easier to compute a correctly rounded result in __pow__
5272 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5273 coeff, exp = 10**(p-1)+1, 1-p
5274 else:
5275 coeff, exp = 10**p-1, -p
5276 else:
5277 coeff, exp = _dexp(pc, -(p+1), p+1)
5278 coeff = _div_nearest(coeff, 10)
5279 exp += 1
5280
5281 return coeff, exp
5282
5283def _log10_lb(c, correction = {
5284 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5285 '6': 23, '7': 16, '8': 10, '9': 5}):
5286 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5287 if c <= 0:
5288 raise ValueError("The argument to _log10_lb should be nonnegative.")
5289 str_c = str(c)
5290 return 100*len(str_c) - correction[str_c[0]]
5291
Facundo Batista59c58842007-04-10 12:58:45 +00005292##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005293
Facundo Batista353750c2007-09-13 18:13:15 +00005294def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005295 """Convert other to Decimal.
5296
5297 Verifies that it's ok to use in an implicit construction.
5298 """
5299 if isinstance(other, Decimal):
5300 return other
5301 if isinstance(other, (int, long)):
5302 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005303 if raiseit:
5304 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005305 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005306
Facundo Batista59c58842007-04-10 12:58:45 +00005307##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005308
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005309# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005310# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005311
5312DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005313 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005314 traps=[DivisionByZero, Overflow, InvalidOperation],
5315 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005316 Emax=999999999,
5317 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005318 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005319)
5320
5321# Pre-made alternate contexts offered by the specification
5322# Don't change these; the user should be able to select these
5323# contexts and be able to reproduce results from other implementations
5324# of the spec.
5325
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005326BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005327 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005328 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5329 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005330)
5331
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005332ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005333 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005334 traps=[],
5335 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005336)
5337
5338
Facundo Batista72bc54f2007-11-23 17:59:00 +00005339##### crud for parsing strings #############################################
Mark Dickinson6a123cb2008-02-24 18:12:36 +00005340#
Facundo Batista72bc54f2007-11-23 17:59:00 +00005341# Regular expression used for parsing numeric strings. Additional
5342# comments:
5343#
5344# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5345# whitespace. But note that the specification disallows whitespace in
5346# a numeric string.
5347#
5348# 2. For finite numbers (not infinities and NaNs) the body of the
5349# number between the optional sign and the optional exponent must have
5350# at least one decimal digit, possibly after the decimal point. The
5351# lookahead expression '(?=\d|\.\d)' checks this.
5352#
5353# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5354# other meaning for \d than the numbers [0-9].
5355
5356import re
Mark Dickinson70c32892008-07-02 09:37:01 +00005357_parser = re.compile(r""" # A numeric string consists of:
Facundo Batista72bc54f2007-11-23 17:59:00 +00005358# \s*
Mark Dickinson70c32892008-07-02 09:37:01 +00005359 (?P<sign>[-+])? # an optional sign, followed by either...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005360 (
Mark Dickinson70c32892008-07-02 09:37:01 +00005361 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5362 (?P<int>[0-9]*) # having a (possibly empty) integer part
5363 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5364 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005365 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005366 Inf(inity)? # ...an infinity, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005367 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005368 (?P<signal>s)? # ...an (optionally signaling)
5369 NaN # NaN
5370 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005371 )
5372# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005373 \Z
Facundo Batista72bc54f2007-11-23 17:59:00 +00005374""", re.VERBOSE | re.IGNORECASE).match
5375
Facundo Batista2ec74152007-12-03 17:55:00 +00005376_all_zeros = re.compile('0*$').match
5377_exact_half = re.compile('50*$').match
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005378
5379##### PEP3101 support functions ##############################################
5380# The functions parse_format_specifier and format_align have little to do
5381# with the Decimal class, and could potentially be reused for other pure
5382# Python numeric classes that want to implement __format__
5383#
5384# A format specifier for Decimal looks like:
5385#
5386# [[fill]align][sign][0][minimumwidth][.precision][type]
5387#
5388
5389_parse_format_specifier_regex = re.compile(r"""\A
5390(?:
5391 (?P<fill>.)?
5392 (?P<align>[<>=^])
5393)?
5394(?P<sign>[-+ ])?
5395(?P<zeropad>0)?
5396(?P<minimumwidth>(?!0)\d+)?
5397(?:\.(?P<precision>0|(?!0)\d+))?
5398(?P<type>[eEfFgG%])?
5399\Z
5400""", re.VERBOSE)
5401
Facundo Batista72bc54f2007-11-23 17:59:00 +00005402del re
5403
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005404def _parse_format_specifier(format_spec):
5405 """Parse and validate a format specifier.
5406
5407 Turns a standard numeric format specifier into a dict, with the
5408 following entries:
5409
5410 fill: fill character to pad field to minimum width
5411 align: alignment type, either '<', '>', '=' or '^'
5412 sign: either '+', '-' or ' '
5413 minimumwidth: nonnegative integer giving minimum width
5414 precision: nonnegative integer giving precision, or None
5415 type: one of the characters 'eEfFgG%', or None
5416 unicode: either True or False (always True for Python 3.x)
5417
5418 """
5419 m = _parse_format_specifier_regex.match(format_spec)
5420 if m is None:
5421 raise ValueError("Invalid format specifier: " + format_spec)
5422
5423 # get the dictionary
5424 format_dict = m.groupdict()
5425
5426 # defaults for fill and alignment
5427 fill = format_dict['fill']
5428 align = format_dict['align']
5429 if format_dict.pop('zeropad') is not None:
5430 # in the face of conflict, refuse the temptation to guess
5431 if fill is not None and fill != '0':
5432 raise ValueError("Fill character conflicts with '0'"
5433 " in format specifier: " + format_spec)
5434 if align is not None and align != '=':
5435 raise ValueError("Alignment conflicts with '0' in "
5436 "format specifier: " + format_spec)
5437 fill = '0'
5438 align = '='
5439 format_dict['fill'] = fill or ' '
5440 format_dict['align'] = align or '<'
5441
5442 if format_dict['sign'] is None:
5443 format_dict['sign'] = '-'
5444
5445 # turn minimumwidth and precision entries into integers.
5446 # minimumwidth defaults to 0; precision remains None if not given
5447 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5448 if format_dict['precision'] is not None:
5449 format_dict['precision'] = int(format_dict['precision'])
5450
5451 # if format type is 'g' or 'G' then a precision of 0 makes little
5452 # sense; convert it to 1. Same if format type is unspecified.
5453 if format_dict['precision'] == 0:
5454 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5455 format_dict['precision'] = 1
5456
5457 # record whether return type should be str or unicode
5458 format_dict['unicode'] = isinstance(format_spec, unicode)
5459
5460 return format_dict
5461
5462def _format_align(body, spec_dict):
5463 """Given an unpadded, non-aligned numeric string, add padding and
5464 aligment to conform with the given format specifier dictionary (as
5465 output from parse_format_specifier).
5466
5467 It's assumed that if body is negative then it starts with '-'.
5468 Any leading sign ('-' or '+') is stripped from the body before
5469 applying the alignment and padding rules, and replaced in the
5470 appropriate position.
5471
5472 """
5473 # figure out the sign; we only examine the first character, so if
5474 # body has leading whitespace the results may be surprising.
5475 if len(body) > 0 and body[0] in '-+':
5476 sign = body[0]
5477 body = body[1:]
5478 else:
5479 sign = ''
5480
5481 if sign != '-':
5482 if spec_dict['sign'] in ' +':
5483 sign = spec_dict['sign']
5484 else:
5485 sign = ''
5486
5487 # how much extra space do we have to play with?
5488 minimumwidth = spec_dict['minimumwidth']
5489 fill = spec_dict['fill']
5490 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5491
5492 align = spec_dict['align']
5493 if align == '<':
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005494 result = sign + body + padding
Mark Dickinson71416822009-03-17 18:07:41 +00005495 elif align == '>':
5496 result = padding + sign + body
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005497 elif align == '=':
5498 result = sign + padding + body
5499 else: #align == '^'
5500 half = len(padding)//2
5501 result = padding[:half] + sign + body + padding[half:]
5502
5503 # make sure that result is unicode if necessary
5504 if spec_dict['unicode']:
5505 result = unicode(result)
5506
5507 return result
Facundo Batista72bc54f2007-11-23 17:59:00 +00005508
Facundo Batista59c58842007-04-10 12:58:45 +00005509##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005510
Facundo Batista59c58842007-04-10 12:58:45 +00005511# Reusable defaults
Mark Dickinsone4d46b22009-01-03 12:09:22 +00005512_Infinity = Decimal('Inf')
5513_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonfd6032d2009-01-02 23:16:51 +00005514_NaN = Decimal('NaN')
Mark Dickinsone4d46b22009-01-03 12:09:22 +00005515_Zero = Decimal(0)
5516_One = Decimal(1)
5517_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005518
Mark Dickinsone4d46b22009-01-03 12:09:22 +00005519# _SignedInfinity[sign] is infinity w/ that sign
5520_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005521
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005522
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005523
5524if __name__ == '__main__':
5525 import doctest, sys
5526 doctest.testmod(sys.modules[__name__])