blob: dfc7043dde0f0de80e0c2882424685446038854d [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 Hettingerf4d85972009-01-03 19:02:23 +0000138import math as _math
Raymond Hettinger2c8585b2009-02-03 03:37:03 +0000139import numbers as _numbers
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000140
Raymond Hettinger097a1902008-01-11 02:24:13 +0000141try:
142 from collections import namedtuple as _namedtuple
143 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
144except ImportError:
145 DecimalTuple = lambda *args: args
146
Facundo Batista59c58842007-04-10 12:58:45 +0000147# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000148ROUND_DOWN = 'ROUND_DOWN'
149ROUND_HALF_UP = 'ROUND_HALF_UP'
150ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
151ROUND_CEILING = 'ROUND_CEILING'
152ROUND_FLOOR = 'ROUND_FLOOR'
153ROUND_UP = 'ROUND_UP'
154ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Facundo Batista353750c2007-09-13 18:13:15 +0000155ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000156
Facundo Batista59c58842007-04-10 12:58:45 +0000157# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000158
159class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000160 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000161
162 Used exceptions derive from this.
163 If an exception derives from another exception besides this (such as
164 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
165 called if the others are present. This isn't actually used for
166 anything, though.
167
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000168 handle -- Called when context._raise_error is called and the
169 trap_enabler is set. First argument is self, second is the
170 context. More arguments can be given, those being after
171 the explanation in _raise_error (For example,
172 context._raise_error(NewError, '(-x)!', self._sign) would
173 call NewError().handle(context, self._sign).)
174
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000175 To define a new exception, it should be sufficient to have it derive
176 from DecimalException.
177 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000178 def handle(self, context, *args):
179 pass
180
181
182class Clamped(DecimalException):
183 """Exponent of a 0 changed to fit bounds.
184
185 This occurs and signals clamped if the exponent of a result has been
186 altered in order to fit the constraints of a specific concrete
Facundo Batista59c58842007-04-10 12:58:45 +0000187 representation. This may occur when the exponent of a zero result would
188 be outside the bounds of a representation, or when a large normal
189 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000190 this latter case, the exponent is reduced to fit and the corresponding
191 number of zero digits are appended to the coefficient ("fold-down").
192 """
193
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000194class InvalidOperation(DecimalException):
195 """An invalid operation was performed.
196
197 Various bad things cause this:
198
199 Something creates a signaling NaN
200 -INF + INF
Facundo Batista59c58842007-04-10 12:58:45 +0000201 0 * (+-)INF
202 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000203 x % 0
204 (+-)INF % x
205 x._rescale( non-integer )
206 sqrt(-x) , x > 0
207 0 ** 0
208 x ** (non-integer)
209 x ** (+-)INF
210 An operand is invalid
Facundo Batista353750c2007-09-13 18:13:15 +0000211
212 The result of the operation after these is a quiet positive NaN,
213 except when the cause is a signaling NaN, in which case the result is
214 also a quiet NaN, but with the original sign, and an optional
215 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000216 """
217 def handle(self, context, *args):
218 if args:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000219 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
220 return ans._fix_nan(context)
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000221 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000222
223class ConversionSyntax(InvalidOperation):
224 """Trying to convert badly formed string.
225
226 This occurs and signals invalid-operation if an string is being
227 converted to a number and it does not conform to the numeric string
Facundo Batista59c58842007-04-10 12:58:45 +0000228 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000229 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000230 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000231 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000232
233class DivisionByZero(DecimalException, ZeroDivisionError):
234 """Division by 0.
235
236 This occurs and signals division-by-zero if division of a finite number
237 by zero was attempted (during a divide-integer or divide operation, or a
238 power operation with negative right-hand operand), and the dividend was
239 not zero.
240
241 The result of the operation is [sign,inf], where sign is the exclusive
242 or of the signs of the operands for divide, or is 1 for an odd power of
243 -0, for power.
244 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000245
Facundo Batistacce8df22007-09-18 16:53:18 +0000246 def handle(self, context, sign, *args):
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000247 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000248
249class DivisionImpossible(InvalidOperation):
250 """Cannot perform the division adequately.
251
252 This occurs and signals invalid-operation if the integer result of a
253 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000254 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000255 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000256
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000257 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000258 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000259
260class DivisionUndefined(InvalidOperation, ZeroDivisionError):
261 """Undefined result of division.
262
263 This occurs and signals invalid-operation if division by zero was
264 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000265 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000266 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000267
Facundo Batistacce8df22007-09-18 16:53:18 +0000268 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000269 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000270
271class Inexact(DecimalException):
272 """Had to round, losing information.
273
274 This occurs and signals inexact whenever the result of an operation is
275 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000276 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000277 result in all cases is unchanged.
278
279 The inexact signal may be tested (or trapped) to determine if a given
280 operation (or sequence of operations) was inexact.
281 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000282
283class InvalidContext(InvalidOperation):
284 """Invalid context. Unknown rounding, for example.
285
286 This occurs and signals invalid-operation if an invalid context was
Facundo Batista59c58842007-04-10 12:58:45 +0000287 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000288 on creation and either the precision exceeds the capability of the
289 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista59c58842007-04-10 12:58:45 +0000290 was specified. These aspects of the context need only be checked when
291 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000292 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000293
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000294 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000295 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000296
297class Rounded(DecimalException):
298 """Number got rounded (not necessarily changed during rounding).
299
300 This occurs and signals rounded whenever the result of an operation is
301 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista59c58842007-04-10 12:58:45 +0000302 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000303 result in all cases is unchanged.
304
305 The rounded signal may be tested (or trapped) to determine if a given
306 operation (or sequence of operations) caused a loss of precision.
307 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000308
309class Subnormal(DecimalException):
310 """Exponent < Emin before rounding.
311
312 This occurs and signals subnormal whenever the result of a conversion or
313 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000314 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000315
316 The subnormal signal may be tested (or trapped) to determine if a given
317 or operation (or sequence of operations) yielded a subnormal result.
318 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000319
320class Overflow(Inexact, Rounded):
321 """Numerical overflow.
322
323 This occurs and signals overflow if the adjusted exponent of a result
324 (from a conversion or from an operation that is not an attempt to divide
325 by zero), after rounding, would be greater than the largest value that
326 can be handled by the implementation (the value Emax).
327
328 The result depends on the rounding mode:
329
330 For round-half-up and round-half-even (and for round-half-down and
331 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000332 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000333 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000334 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000335 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000336 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000338 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000339 will also be raised.
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000340 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000341
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000342 def handle(self, context, sign, *args):
343 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000344 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000345 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000346 if sign == 0:
347 if context.rounding == ROUND_CEILING:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000348 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000349 return _dec_from_triple(sign, '9'*context.prec,
350 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000351 if sign == 1:
352 if context.rounding == ROUND_FLOOR:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000353 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000354 return _dec_from_triple(sign, '9'*context.prec,
355 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000356
357
358class Underflow(Inexact, Rounded, Subnormal):
359 """Numerical underflow with result rounded to 0.
360
361 This occurs and signals underflow if a result is inexact and the
362 adjusted exponent of the result would be smaller (more negative) than
363 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000364 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000365
366 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000367 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000368 in 0 with the sign of the intermediate result and an exponent of Etiny.
369
370 In all cases, Inexact, Rounded, and Subnormal will also be raised.
371 """
372
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000373# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000374_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000375 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000376
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000377# Map conditions (per the spec) to signals
378_condition_map = {ConversionSyntax:InvalidOperation,
379 DivisionImpossible:InvalidOperation,
380 DivisionUndefined:InvalidOperation,
381 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000382
Facundo Batista59c58842007-04-10 12:58:45 +0000383##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000384
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000385# The getcontext() and setcontext() function manage access to a thread-local
386# current context. Py2.4 offers direct support for thread locals. If that
387# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000388# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000389# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000390
391try:
392 import threading
393except ImportError:
394 # Python was compiled without threads; create a mock object instead
395 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000396 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000397 def local(self, sys=sys):
398 return sys.modules[__name__]
399 threading = MockThreading()
400 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000401
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000402try:
403 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000404
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000405except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000406
Facundo Batista59c58842007-04-10 12:58:45 +0000407 # To fix reloading, force it to create a new context
408 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000409 if hasattr(threading.currentThread(), '__decimal_context__'):
410 del threading.currentThread().__decimal_context__
411
412 def setcontext(context):
413 """Set this thread's context to context."""
414 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000415 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000416 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000417 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000418
419 def getcontext():
420 """Returns this thread's context.
421
422 If this thread does not yet have a context, returns
423 a new context and sets this thread's context.
424 New contexts are copies of DefaultContext.
425 """
426 try:
427 return threading.currentThread().__decimal_context__
428 except AttributeError:
429 context = Context()
430 threading.currentThread().__decimal_context__ = context
431 return context
432
433else:
434
435 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000436 if hasattr(local, '__decimal_context__'):
437 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000438
439 def getcontext(_local=local):
440 """Returns this thread's context.
441
442 If this thread does not yet have a context, returns
443 a new context and sets this thread's context.
444 New contexts are copies of DefaultContext.
445 """
446 try:
447 return _local.__decimal_context__
448 except AttributeError:
449 context = Context()
450 _local.__decimal_context__ = context
451 return context
452
453 def setcontext(context, _local=local):
454 """Set this thread's context to context."""
455 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000456 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000457 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000458 _local.__decimal_context__ = context
459
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000460 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000461
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000462def localcontext(ctx=None):
463 """Return a context manager for a copy of the supplied context
464
465 Uses a copy of the current context if no context is specified
466 The returned context manager creates a local decimal context
467 in a with statement:
468 def sin(x):
469 with localcontext() as ctx:
470 ctx.prec += 2
471 # Rest of sin calculation algorithm
472 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000473 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000474
475 def sin(x):
476 with localcontext(ExtendedContext):
477 # Rest of sin calculation algorithm
478 # uses the Extended Context from the
479 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000480 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000481
Facundo Batistaee340e52008-05-02 17:39:00 +0000482 >>> setcontext(DefaultContext)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000483 >>> print getcontext().prec
484 28
485 >>> with localcontext():
486 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000487 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000488 ... print ctx.prec
489 ...
490 30
491 >>> with localcontext(ExtendedContext):
492 ... print getcontext().prec
493 ...
494 9
495 >>> print getcontext().prec
496 28
497 """
Nick Coghlanced12182006-09-02 03:54:17 +0000498 if ctx is None: ctx = getcontext()
499 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000500
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000501
Facundo Batista59c58842007-04-10 12:58:45 +0000502##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000503
504class Decimal(object):
505 """Floating point class for decimal arithmetic."""
506
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000507 __slots__ = ('_exp','_int','_sign', '_is_special')
508 # Generally, the value of the Decimal instance is given by
509 # (-1)**_sign * _int * 10**_exp
510 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000511
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000512 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000513 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000514 """Create a decimal point instance.
515
516 >>> Decimal('3.14') # string input
Raymond Hettingerabe32372008-02-14 02:41:22 +0000517 Decimal('3.14')
Facundo Batista59c58842007-04-10 12:58:45 +0000518 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000519 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000520 >>> Decimal(314) # int or long
Raymond Hettingerabe32372008-02-14 02:41:22 +0000521 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 >>> Decimal(Decimal(314)) # another decimal instance
Raymond Hettingerabe32372008-02-14 02:41:22 +0000523 Decimal('314')
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000524 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Raymond Hettingerabe32372008-02-14 02:41:22 +0000525 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000526 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000527
Facundo Batista72bc54f2007-11-23 17:59:00 +0000528 # Note that the coefficient, self._int, is actually stored as
529 # a string rather than as a tuple of digits. This speeds up
530 # the "digits to integer" and "integer to digits" conversions
531 # that are used in almost every arithmetic operation on
532 # Decimals. This is an internal detail: the as_tuple function
533 # and the Decimal constructor still deal with tuples of
534 # digits.
535
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000536 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000537
Facundo Batista0d157a02007-11-30 17:15:25 +0000538 # From a string
539 # REs insist on real strings, so we can too.
540 if isinstance(value, basestring):
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000541 m = _parser(value.strip())
Facundo Batista0d157a02007-11-30 17:15:25 +0000542 if m is None:
543 if context is None:
544 context = getcontext()
545 return context._raise_error(ConversionSyntax,
546 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000547
Facundo Batista0d157a02007-11-30 17:15:25 +0000548 if m.group('sign') == "-":
549 self._sign = 1
550 else:
551 self._sign = 0
552 intpart = m.group('int')
553 if intpart is not None:
554 # finite number
555 fracpart = m.group('frac')
556 exp = int(m.group('exp') or '0')
557 if fracpart is not None:
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000558 self._int = str((intpart+fracpart).lstrip('0') or '0')
Facundo Batista0d157a02007-11-30 17:15:25 +0000559 self._exp = exp - len(fracpart)
560 else:
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000561 self._int = str(intpart.lstrip('0') or '0')
Facundo Batista0d157a02007-11-30 17:15:25 +0000562 self._exp = exp
563 self._is_special = False
564 else:
565 diag = m.group('diag')
566 if diag is not None:
567 # NaN
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000568 self._int = str(diag.lstrip('0'))
Facundo Batista0d157a02007-11-30 17:15:25 +0000569 if m.group('signal'):
570 self._exp = 'N'
571 else:
572 self._exp = 'n'
573 else:
574 # infinity
575 self._int = '0'
576 self._exp = 'F'
577 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000578 return self
579
580 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000581 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000582 if value >= 0:
583 self._sign = 0
584 else:
585 self._sign = 1
586 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000587 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000588 self._is_special = False
589 return self
590
591 # From another decimal
592 if isinstance(value, Decimal):
593 self._exp = value._exp
594 self._sign = value._sign
595 self._int = value._int
596 self._is_special = value._is_special
597 return self
598
599 # From an internal working value
600 if isinstance(value, _WorkRep):
601 self._sign = value.sign
602 self._int = str(value.int)
603 self._exp = int(value.exp)
604 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000605 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000606
607 # tuple/list conversion (possibly from as_tuple())
608 if isinstance(value, (list,tuple)):
609 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000610 raise ValueError('Invalid tuple size in creation of Decimal '
611 'from list or tuple. The list or tuple '
612 'should have exactly three elements.')
613 # process sign. The isinstance test rejects floats
614 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
615 raise ValueError("Invalid sign. The first value in the tuple "
616 "should be an integer; either 0 for a "
617 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000618 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000619 if value[2] == 'F':
620 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000621 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000622 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000623 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000625 # process and validate the digits in value[1]
626 digits = []
627 for digit in value[1]:
628 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
629 # skip leading zeros
630 if digits or digit != 0:
631 digits.append(digit)
632 else:
633 raise ValueError("The second value in the tuple must "
634 "be composed of integers in the range "
635 "0 through 9.")
636 if value[2] in ('n', 'N'):
637 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000638 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000639 self._exp = value[2]
640 self._is_special = True
641 elif isinstance(value[2], (int, long)):
642 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000643 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000644 self._exp = value[2]
645 self._is_special = False
646 else:
647 raise ValueError("The third value in the tuple must "
648 "be an integer, or one of the "
649 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000650 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000651
Raymond Hettingerbf440692004-07-10 14:14:37 +0000652 if isinstance(value, float):
653 raise TypeError("Cannot convert float to Decimal. " +
654 "First convert the float to a string")
655
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000656 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000657
Mark Dickinson6a961632009-01-04 21:10:56 +0000658 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
659 # don't use it (see notes on Py2.3 compatibility at top of file)
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000660 def from_float(cls, f):
661 """Converts a float to a decimal number, exactly.
662
663 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
664 Since 0.1 is not exactly representable in binary floating point, the
665 value is stored as the nearest representable value which is
666 0x1.999999999999ap-4. The exact equivalent of the value in decimal
667 is 0.1000000000000000055511151231257827021181583404541015625.
668
669 >>> Decimal.from_float(0.1)
670 Decimal('0.1000000000000000055511151231257827021181583404541015625')
671 >>> Decimal.from_float(float('nan'))
672 Decimal('NaN')
673 >>> Decimal.from_float(float('inf'))
674 Decimal('Infinity')
675 >>> Decimal.from_float(-float('inf'))
676 Decimal('-Infinity')
677 >>> Decimal.from_float(-0.0)
678 Decimal('-0')
679
680 """
681 if isinstance(f, (int, long)): # handle integer inputs
682 return cls(f)
683 if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
684 return cls(repr(f))
Mark Dickinson6a961632009-01-04 21:10:56 +0000685 if _math.copysign(1.0, f) == 1.0:
686 sign = 0
687 else:
688 sign = 1
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000689 n, d = abs(f).as_integer_ratio()
690 k = d.bit_length() - 1
691 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinson6a961632009-01-04 21:10:56 +0000692 if cls is Decimal:
693 return result
694 else:
695 return cls(result)
696 from_float = classmethod(from_float)
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000697
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000698 def _isnan(self):
699 """Returns whether the number is not actually one.
700
701 0 if a number
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000702 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000703 2 if sNaN
704 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000705 if self._is_special:
706 exp = self._exp
707 if exp == 'n':
708 return 1
709 elif exp == 'N':
710 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000711 return 0
712
713 def _isinfinity(self):
714 """Returns whether the number is infinite
715
716 0 if finite or not a number
717 1 if +INF
718 -1 if -INF
719 """
720 if self._exp == 'F':
721 if self._sign:
722 return -1
723 return 1
724 return 0
725
Facundo Batista353750c2007-09-13 18:13:15 +0000726 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000727 """Returns whether the number is not actually one.
728
729 if self, other are sNaN, signal
730 if self, other are NaN return nan
731 return 0
732
733 Done before operations.
734 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000735
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000736 self_is_nan = self._isnan()
737 if other is None:
738 other_is_nan = False
739 else:
740 other_is_nan = other._isnan()
741
742 if self_is_nan or other_is_nan:
743 if context is None:
744 context = getcontext()
745
746 if self_is_nan == 2:
747 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000748 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000749 if other_is_nan == 2:
750 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000751 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000752 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000753 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000754
Facundo Batista353750c2007-09-13 18:13:15 +0000755 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000756 return 0
757
Mark Dickinson2fc92632008-02-06 22:10:50 +0000758 def _compare_check_nans(self, other, context):
759 """Version of _check_nans used for the signaling comparisons
760 compare_signal, __le__, __lt__, __ge__, __gt__.
761
762 Signal InvalidOperation if either self or other is a (quiet
763 or signaling) NaN. Signaling NaNs take precedence over quiet
764 NaNs.
765
766 Return 0 if neither operand is a NaN.
767
768 """
769 if context is None:
770 context = getcontext()
771
772 if self._is_special or other._is_special:
773 if self.is_snan():
774 return context._raise_error(InvalidOperation,
775 'comparison involving sNaN',
776 self)
777 elif other.is_snan():
778 return context._raise_error(InvalidOperation,
779 'comparison involving sNaN',
780 other)
781 elif self.is_qnan():
782 return context._raise_error(InvalidOperation,
783 'comparison involving NaN',
784 self)
785 elif other.is_qnan():
786 return context._raise_error(InvalidOperation,
787 'comparison involving NaN',
788 other)
789 return 0
790
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000791 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000792 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000793
Facundo Batista1a191df2007-10-02 17:01:24 +0000794 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000795 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000796 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000797
Mark Dickinson2fc92632008-02-06 22:10:50 +0000798 def _cmp(self, other):
799 """Compare the two non-NaN decimal instances self and other.
800
801 Returns -1 if self < other, 0 if self == other and 1
802 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000803
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000804 if self._is_special or other._is_special:
Mark Dickinsone52c3142009-01-25 10:39:15 +0000805 self_inf = self._isinfinity()
806 other_inf = other._isinfinity()
807 if self_inf == other_inf:
808 return 0
809 elif self_inf < other_inf:
810 return -1
811 else:
812 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000813
Mark Dickinsone52c3142009-01-25 10:39:15 +0000814 # check for zeros; Decimal('0') == Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000815 if not self:
816 if not other:
817 return 0
818 else:
819 return -((-1)**other._sign)
820 if not other:
821 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000822
Facundo Batista59c58842007-04-10 12:58:45 +0000823 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000824 if other._sign < self._sign:
825 return -1
826 if self._sign < other._sign:
827 return 1
828
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000829 self_adjusted = self.adjusted()
830 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000831 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000832 self_padded = self._int + '0'*(self._exp - other._exp)
833 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinsone52c3142009-01-25 10:39:15 +0000834 if self_padded == other_padded:
835 return 0
836 elif self_padded < other_padded:
837 return -(-1)**self._sign
838 else:
839 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000840 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000841 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000842 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000843 return -((-1)**self._sign)
844
Mark Dickinson2fc92632008-02-06 22:10:50 +0000845 # Note: The Decimal standard doesn't cover rich comparisons for
846 # Decimals. In particular, the specification is silent on the
847 # subject of what should happen for a comparison involving a NaN.
848 # We take the following approach:
849 #
850 # == comparisons involving a NaN always return False
851 # != comparisons involving a NaN always return True
852 # <, >, <= and >= comparisons involving a (quiet or signaling)
853 # NaN signal InvalidOperation, and return False if the
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000854 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000855 #
856 # This behavior is designed to conform as closely as possible to
857 # that specified by IEEE 754.
858
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000859 def __eq__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000860 other = _convert_other(other)
861 if other is NotImplemented:
862 return other
863 if self.is_nan() or other.is_nan():
864 return False
865 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000866
867 def __ne__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000868 other = _convert_other(other)
869 if other is NotImplemented:
870 return other
871 if self.is_nan() or other.is_nan():
872 return True
873 return self._cmp(other) != 0
874
875 def __lt__(self, other, context=None):
876 other = _convert_other(other)
877 if other is NotImplemented:
878 return other
879 ans = self._compare_check_nans(other, context)
880 if ans:
881 return False
882 return self._cmp(other) < 0
883
884 def __le__(self, other, context=None):
885 other = _convert_other(other)
886 if other is NotImplemented:
887 return other
888 ans = self._compare_check_nans(other, context)
889 if ans:
890 return False
891 return self._cmp(other) <= 0
892
893 def __gt__(self, other, context=None):
894 other = _convert_other(other)
895 if other is NotImplemented:
896 return other
897 ans = self._compare_check_nans(other, context)
898 if ans:
899 return False
900 return self._cmp(other) > 0
901
902 def __ge__(self, other, context=None):
903 other = _convert_other(other)
904 if other is NotImplemented:
905 return other
906 ans = self._compare_check_nans(other, context)
907 if ans:
908 return False
909 return self._cmp(other) >= 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000910
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000911 def compare(self, other, context=None):
912 """Compares one to another.
913
914 -1 => a < b
915 0 => a = b
916 1 => a > b
917 NaN => one is NaN
918 Like __cmp__, but returns Decimal instances.
919 """
Facundo Batista353750c2007-09-13 18:13:15 +0000920 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000921
Facundo Batista59c58842007-04-10 12:58:45 +0000922 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000923 if (self._is_special or other and other._is_special):
924 ans = self._check_nans(other, context)
925 if ans:
926 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000927
Mark Dickinson2fc92632008-02-06 22:10:50 +0000928 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000929
930 def __hash__(self):
931 """x.__hash__() <==> hash(x)"""
932 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000933 #
934 # The hash of a nonspecial noninteger Decimal must depend only
935 # on the value of that Decimal, and not on its representation.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000936 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000937 if self._is_special:
938 if self._isnan():
939 raise TypeError('Cannot hash a NaN value.')
940 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000941 if not self:
942 return 0
943 if self._isinteger():
944 op = _WorkRep(self.to_integral_value())
945 # to make computation feasible for Decimals with large
946 # exponent, we use the fact that hash(n) == hash(m) for
947 # any two nonzero integers n and m such that (i) n and m
948 # have the same sign, and (ii) n is congruent to m modulo
949 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
950 # hash((-1)**s*c*pow(10, e, 2**64-1).
951 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000952 # The value of a nonzero nonspecial Decimal instance is
953 # faithfully represented by the triple consisting of its sign,
954 # its adjusted exponent, and its coefficient with trailing
955 # zeros removed.
956 return hash((self._sign,
957 self._exp+len(self._int),
958 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000959
960 def as_tuple(self):
961 """Represents the number as a triple tuple.
962
963 To show the internals exactly as they are.
964 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000965 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000966
967 def __repr__(self):
968 """Represents the number as an instance of Decimal."""
969 # Invariant: eval(repr(d)) == d
Raymond Hettingerabe32372008-02-14 02:41:22 +0000970 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000971
Facundo Batista353750c2007-09-13 18:13:15 +0000972 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000973 """Return string representation of the number in scientific notation.
974
975 Captures all of the information in the underlying representation.
976 """
977
Facundo Batista62edb712007-12-03 16:29:52 +0000978 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000979 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000980 if self._exp == 'F':
981 return sign + 'Infinity'
982 elif self._exp == 'n':
983 return sign + 'NaN' + self._int
984 else: # self._exp == 'N'
985 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000986
Facundo Batista62edb712007-12-03 16:29:52 +0000987 # number of digits of self._int to left of decimal point
988 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000989
Facundo Batista62edb712007-12-03 16:29:52 +0000990 # dotplace is number of digits of self._int to the left of the
991 # decimal point in the mantissa of the output string (that is,
992 # after adjusting the exponent)
993 if self._exp <= 0 and leftdigits > -6:
994 # no exponent required
995 dotplace = leftdigits
996 elif not eng:
997 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000998 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000999 elif self._int == '0':
1000 # engineering notation, zero
1001 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001002 else:
Facundo Batista62edb712007-12-03 16:29:52 +00001003 # engineering notation, nonzero
1004 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001005
Facundo Batista62edb712007-12-03 16:29:52 +00001006 if dotplace <= 0:
1007 intpart = '0'
1008 fracpart = '.' + '0'*(-dotplace) + self._int
1009 elif dotplace >= len(self._int):
1010 intpart = self._int+'0'*(dotplace-len(self._int))
1011 fracpart = ''
1012 else:
1013 intpart = self._int[:dotplace]
1014 fracpart = '.' + self._int[dotplace:]
1015 if leftdigits == dotplace:
1016 exp = ''
1017 else:
1018 if context is None:
1019 context = getcontext()
1020 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1021
1022 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023
1024 def to_eng_string(self, context=None):
1025 """Convert to engineering-type string.
1026
1027 Engineering notation has an exponent which is a multiple of 3, so there
1028 are up to 3 digits left of the decimal place.
1029
1030 Same rules for when in exponential and when as a value as in __str__.
1031 """
Facundo Batista353750c2007-09-13 18:13:15 +00001032 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001033
1034 def __neg__(self, context=None):
1035 """Returns a copy with the sign switched.
1036
1037 Rounds, if it has reason.
1038 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001039 if self._is_special:
1040 ans = self._check_nans(context=context)
1041 if ans:
1042 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001043
1044 if not self:
1045 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001046 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001048 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001049
1050 if context is None:
1051 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001052 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053
1054 def __pos__(self, context=None):
1055 """Returns a copy, unless it is a sNaN.
1056
1057 Rounds the number (if more then precision digits)
1058 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001059 if self._is_special:
1060 ans = self._check_nans(context=context)
1061 if ans:
1062 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001063
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001064 if not self:
1065 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001066 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +00001067 else:
1068 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001069
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001070 if context is None:
1071 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001072 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001073
Facundo Batistae64acfa2007-12-17 14:18:42 +00001074 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001075 """Returns the absolute value of self.
1076
Facundo Batistae64acfa2007-12-17 14:18:42 +00001077 If the keyword argument 'round' is false, do not round. The
1078 expression self.__abs__(round=False) is equivalent to
1079 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001080 """
Facundo Batistae64acfa2007-12-17 14:18:42 +00001081 if not round:
1082 return self.copy_abs()
1083
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001084 if self._is_special:
1085 ans = self._check_nans(context=context)
1086 if ans:
1087 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001088
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001089 if self._sign:
1090 ans = self.__neg__(context=context)
1091 else:
1092 ans = self.__pos__(context=context)
1093
1094 return ans
1095
1096 def __add__(self, other, context=None):
1097 """Returns self + other.
1098
1099 -INF + INF (or the reverse) cause InvalidOperation errors.
1100 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001101 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001102 if other is NotImplemented:
1103 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001104
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001105 if context is None:
1106 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001107
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001108 if self._is_special or other._is_special:
1109 ans = self._check_nans(other, context)
1110 if ans:
1111 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001112
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001113 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001114 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001115 if self._sign != other._sign and other._isinfinity():
1116 return context._raise_error(InvalidOperation, '-INF + INF')
1117 return Decimal(self)
1118 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001119 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001120
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001121 exp = min(self._exp, other._exp)
1122 negativezero = 0
1123 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001124 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001125 negativezero = 1
1126
1127 if not self and not other:
1128 sign = min(self._sign, other._sign)
1129 if negativezero:
1130 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001131 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001132 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001133 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001134 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001135 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001136 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001137 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138 return ans
1139 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001140 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001141 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001142 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001143 return ans
1144
1145 op1 = _WorkRep(self)
1146 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001147 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148
1149 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001150 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001151 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001152 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001153 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001154 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001155 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001156 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001157 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001158 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001159 if op1.sign == 1:
1160 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 op1.sign, op2.sign = op2.sign, op1.sign
1162 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001163 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001164 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001165 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001166 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001167 op1.sign, op2.sign = (0, 0)
1168 else:
1169 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001170 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001171
Raymond Hettinger17931de2004-10-27 06:21:46 +00001172 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001173 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001174 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001175 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176
1177 result.exp = op1.exp
1178 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001179 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001180 return ans
1181
1182 __radd__ = __add__
1183
1184 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001185 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001186 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001187 if other is NotImplemented:
1188 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001189
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001190 if self._is_special or other._is_special:
1191 ans = self._check_nans(other, context=context)
1192 if ans:
1193 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194
Facundo Batista353750c2007-09-13 18:13:15 +00001195 # self - other is computed as self + other.copy_negate()
1196 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001197
1198 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001199 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001200 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001201 if other is NotImplemented:
1202 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001203
Facundo Batista353750c2007-09-13 18:13:15 +00001204 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001205
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001206 def __mul__(self, other, context=None):
1207 """Return self * other.
1208
1209 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1210 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001211 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001212 if other is NotImplemented:
1213 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001214
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001215 if context is None:
1216 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001217
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001218 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001219
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001220 if self._is_special or other._is_special:
1221 ans = self._check_nans(other, context)
1222 if ans:
1223 return ans
1224
1225 if self._isinfinity():
1226 if not other:
1227 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001228 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001229
1230 if other._isinfinity():
1231 if not self:
1232 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001233 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001234
1235 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001236
1237 # Special case for multiplying by zero
1238 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001239 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001240 # Fixing in case the exponent is out of bounds
1241 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001242 return ans
1243
1244 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001245 if self._int == '1':
1246 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001247 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001248 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001249 if other._int == '1':
1250 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001251 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001252 return ans
1253
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001254 op1 = _WorkRep(self)
1255 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001256
Facundo Batista72bc54f2007-11-23 17:59:00 +00001257 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001258 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001259
1260 return ans
1261 __rmul__ = __mul__
1262
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001263 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001264 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001265 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001266 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001267 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001268
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001269 if context is None:
1270 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001271
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001272 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001273
1274 if self._is_special or other._is_special:
1275 ans = self._check_nans(other, context)
1276 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001277 return ans
1278
1279 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001280 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001281
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001282 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001283 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001284
1285 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001286 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001287 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001288
1289 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001290 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001291 if not self:
1292 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001293 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001294
Facundo Batistacce8df22007-09-18 16:53:18 +00001295 if not self:
1296 exp = self._exp - other._exp
1297 coeff = 0
1298 else:
1299 # OK, so neither = 0, INF or NaN
1300 shift = len(other._int) - len(self._int) + context.prec + 1
1301 exp = self._exp - other._exp - shift
1302 op1 = _WorkRep(self)
1303 op2 = _WorkRep(other)
1304 if shift >= 0:
1305 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1306 else:
1307 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1308 if remainder:
1309 # result is not exact; adjust to ensure correct rounding
1310 if coeff % 5 == 0:
1311 coeff += 1
1312 else:
1313 # result is exact; get as close to ideal exponent as possible
1314 ideal_exp = self._exp - other._exp
1315 while exp < ideal_exp and coeff % 10 == 0:
1316 coeff //= 10
1317 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001318
Facundo Batista72bc54f2007-11-23 17:59:00 +00001319 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001320 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001321
Facundo Batistacce8df22007-09-18 16:53:18 +00001322 def _divide(self, other, context):
1323 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001324
Facundo Batistacce8df22007-09-18 16:53:18 +00001325 Assumes that neither self nor other is a NaN, that self is not
1326 infinite and that other is nonzero.
1327 """
1328 sign = self._sign ^ other._sign
1329 if other._isinfinity():
1330 ideal_exp = self._exp
1331 else:
1332 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001333
Facundo Batistacce8df22007-09-18 16:53:18 +00001334 expdiff = self.adjusted() - other.adjusted()
1335 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001336 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001337 self._rescale(ideal_exp, context.rounding))
1338 if expdiff <= context.prec:
1339 op1 = _WorkRep(self)
1340 op2 = _WorkRep(other)
1341 if op1.exp >= op2.exp:
1342 op1.int *= 10**(op1.exp - op2.exp)
1343 else:
1344 op2.int *= 10**(op2.exp - op1.exp)
1345 q, r = divmod(op1.int, op2.int)
1346 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001347 return (_dec_from_triple(sign, str(q), 0),
1348 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001349
Facundo Batistacce8df22007-09-18 16:53:18 +00001350 # Here the quotient is too large to be representable
1351 ans = context._raise_error(DivisionImpossible,
1352 'quotient too large in //, % or divmod')
1353 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001354
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001355 def __rtruediv__(self, other, context=None):
1356 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001357 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001358 if other is NotImplemented:
1359 return other
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001360 return other.__truediv__(self, context=context)
1361
1362 __div__ = __truediv__
1363 __rdiv__ = __rtruediv__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001364
1365 def __divmod__(self, other, context=None):
1366 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001367 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001368 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001369 other = _convert_other(other)
1370 if other is NotImplemented:
1371 return other
1372
1373 if context is None:
1374 context = getcontext()
1375
1376 ans = self._check_nans(other, context)
1377 if ans:
1378 return (ans, ans)
1379
1380 sign = self._sign ^ other._sign
1381 if self._isinfinity():
1382 if other._isinfinity():
1383 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1384 return ans, ans
1385 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001386 return (_SignedInfinity[sign],
Facundo Batistacce8df22007-09-18 16:53:18 +00001387 context._raise_error(InvalidOperation, 'INF % x'))
1388
1389 if not other:
1390 if not self:
1391 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1392 return ans, ans
1393 else:
1394 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1395 context._raise_error(InvalidOperation, 'x % 0'))
1396
1397 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001398 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001399 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001400
1401 def __rdivmod__(self, other, context=None):
1402 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001403 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001404 if other is NotImplemented:
1405 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001406 return other.__divmod__(self, context=context)
1407
1408 def __mod__(self, other, context=None):
1409 """
1410 self % other
1411 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001412 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001413 if other is NotImplemented:
1414 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001415
Facundo Batistacce8df22007-09-18 16:53:18 +00001416 if context is None:
1417 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001418
Facundo Batistacce8df22007-09-18 16:53:18 +00001419 ans = self._check_nans(other, context)
1420 if ans:
1421 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001422
Facundo Batistacce8df22007-09-18 16:53:18 +00001423 if self._isinfinity():
1424 return context._raise_error(InvalidOperation, 'INF % x')
1425 elif not other:
1426 if self:
1427 return context._raise_error(InvalidOperation, 'x % 0')
1428 else:
1429 return context._raise_error(DivisionUndefined, '0 % 0')
1430
1431 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001432 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001433 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001434
1435 def __rmod__(self, other, context=None):
1436 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001437 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001438 if other is NotImplemented:
1439 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001440 return other.__mod__(self, context=context)
1441
1442 def remainder_near(self, other, context=None):
1443 """
1444 Remainder nearest to 0- abs(remainder-near) <= other/2
1445 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001446 if context is None:
1447 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001448
Facundo Batista353750c2007-09-13 18:13:15 +00001449 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001450
Facundo Batista353750c2007-09-13 18:13:15 +00001451 ans = self._check_nans(other, context)
1452 if ans:
1453 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001454
Facundo Batista353750c2007-09-13 18:13:15 +00001455 # self == +/-infinity -> InvalidOperation
1456 if self._isinfinity():
1457 return context._raise_error(InvalidOperation,
1458 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001459
Facundo Batista353750c2007-09-13 18:13:15 +00001460 # other == 0 -> either InvalidOperation or DivisionUndefined
1461 if not other:
1462 if self:
1463 return context._raise_error(InvalidOperation,
1464 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001465 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001466 return context._raise_error(DivisionUndefined,
1467 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001468
Facundo Batista353750c2007-09-13 18:13:15 +00001469 # other = +/-infinity -> remainder = self
1470 if other._isinfinity():
1471 ans = Decimal(self)
1472 return ans._fix(context)
1473
1474 # self = 0 -> remainder = self, with ideal exponent
1475 ideal_exponent = min(self._exp, other._exp)
1476 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001477 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001478 return ans._fix(context)
1479
1480 # catch most cases of large or small quotient
1481 expdiff = self.adjusted() - other.adjusted()
1482 if expdiff >= context.prec + 1:
1483 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001484 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001485 if expdiff <= -2:
1486 # expdiff <= -2 => abs(self/other) < 0.1
1487 ans = self._rescale(ideal_exponent, context.rounding)
1488 return ans._fix(context)
1489
1490 # adjust both arguments to have the same exponent, then divide
1491 op1 = _WorkRep(self)
1492 op2 = _WorkRep(other)
1493 if op1.exp >= op2.exp:
1494 op1.int *= 10**(op1.exp - op2.exp)
1495 else:
1496 op2.int *= 10**(op2.exp - op1.exp)
1497 q, r = divmod(op1.int, op2.int)
1498 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1499 # 10**ideal_exponent. Apply correction to ensure that
1500 # abs(remainder) <= abs(other)/2
1501 if 2*r + (q&1) > op2.int:
1502 r -= op2.int
1503 q += 1
1504
1505 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001506 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001507
1508 # result has same sign as self unless r is negative
1509 sign = self._sign
1510 if r < 0:
1511 sign = 1-sign
1512 r = -r
1513
Facundo Batista72bc54f2007-11-23 17:59:00 +00001514 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001515 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001516
1517 def __floordiv__(self, other, context=None):
1518 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001519 other = _convert_other(other)
1520 if other is NotImplemented:
1521 return other
1522
1523 if context is None:
1524 context = getcontext()
1525
1526 ans = self._check_nans(other, context)
1527 if ans:
1528 return ans
1529
1530 if self._isinfinity():
1531 if other._isinfinity():
1532 return context._raise_error(InvalidOperation, 'INF // INF')
1533 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001534 return _SignedInfinity[self._sign ^ other._sign]
Facundo Batistacce8df22007-09-18 16:53:18 +00001535
1536 if not other:
1537 if self:
1538 return context._raise_error(DivisionByZero, 'x // 0',
1539 self._sign ^ other._sign)
1540 else:
1541 return context._raise_error(DivisionUndefined, '0 // 0')
1542
1543 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001544
1545 def __rfloordiv__(self, other, context=None):
1546 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001547 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001548 if other is NotImplemented:
1549 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001550 return other.__floordiv__(self, context=context)
1551
1552 def __float__(self):
1553 """Float representation."""
1554 return float(str(self))
1555
1556 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001557 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001558 if self._is_special:
1559 if self._isnan():
1560 context = getcontext()
1561 return context._raise_error(InvalidContext)
1562 elif self._isinfinity():
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001563 raise OverflowError("Cannot convert infinity to int")
Facundo Batista353750c2007-09-13 18:13:15 +00001564 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001565 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001566 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001567 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001568 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001569
Raymond Hettinger5a053642008-01-24 19:05:29 +00001570 __trunc__ = __int__
1571
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001572 def real(self):
1573 return self
Mark Dickinson65808ff2009-01-04 21:22:02 +00001574 real = property(real)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001575
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001576 def imag(self):
1577 return Decimal(0)
Mark Dickinson65808ff2009-01-04 21:22:02 +00001578 imag = property(imag)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001579
1580 def conjugate(self):
1581 return self
1582
1583 def __complex__(self):
1584 return complex(float(self))
1585
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001586 def __long__(self):
1587 """Converts to a long.
1588
1589 Equivalent to long(int(self))
1590 """
1591 return long(self.__int__())
1592
Facundo Batista353750c2007-09-13 18:13:15 +00001593 def _fix_nan(self, context):
1594 """Decapitate the payload of a NaN to fit the context"""
1595 payload = self._int
1596
1597 # maximum length of payload is precision if _clamp=0,
1598 # precision-1 if _clamp=1.
1599 max_payload_len = context.prec - context._clamp
1600 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001601 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1602 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001603 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001604
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001605 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001606 """Round if it is necessary to keep self within prec precision.
1607
1608 Rounds and fixes the exponent. Does not raise on a sNaN.
1609
1610 Arguments:
1611 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001612 context - context used.
1613 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001614
Facundo Batista353750c2007-09-13 18:13:15 +00001615 if self._is_special:
1616 if self._isnan():
1617 # decapitate payload if necessary
1618 return self._fix_nan(context)
1619 else:
1620 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001621 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001622
Facundo Batista353750c2007-09-13 18:13:15 +00001623 # if self is zero then exponent should be between Etiny and
1624 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1625 Etiny = context.Etiny()
1626 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001627 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001628 exp_max = [context.Emax, Etop][context._clamp]
1629 new_exp = min(max(self._exp, Etiny), exp_max)
1630 if new_exp != self._exp:
1631 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001632 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001633 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001634 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001635
1636 # exp_min is the smallest allowable exponent of the result,
1637 # equal to max(self.adjusted()-context.prec+1, Etiny)
1638 exp_min = len(self._int) + self._exp - context.prec
1639 if exp_min > Etop:
1640 # overflow: exp_min > Etop iff self.adjusted() > Emax
1641 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001642 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001643 return context._raise_error(Overflow, 'above Emax', self._sign)
1644 self_is_subnormal = exp_min < Etiny
1645 if self_is_subnormal:
1646 context._raise_error(Subnormal)
1647 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001648
Facundo Batista353750c2007-09-13 18:13:15 +00001649 # round if self has too many digits
1650 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001651 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001652 digits = len(self._int) + self._exp - exp_min
1653 if digits < 0:
1654 self = _dec_from_triple(self._sign, '1', exp_min-1)
1655 digits = 0
1656 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1657 changed = this_function(digits)
1658 coeff = self._int[:digits] or '0'
1659 if changed == 1:
1660 coeff = str(int(coeff)+1)
1661 ans = _dec_from_triple(self._sign, coeff, exp_min)
1662
1663 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001664 context._raise_error(Inexact)
1665 if self_is_subnormal:
1666 context._raise_error(Underflow)
1667 if not ans:
1668 # raise Clamped on underflow to 0
1669 context._raise_error(Clamped)
1670 elif len(ans._int) == context.prec+1:
1671 # we get here only if rescaling rounds the
1672 # cofficient up to exactly 10**context.prec
1673 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001674 ans = _dec_from_triple(ans._sign,
1675 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001676 else:
1677 # Inexact and Rounded have already been raised
1678 ans = context._raise_error(Overflow, 'above Emax',
1679 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001680 return ans
1681
Facundo Batista353750c2007-09-13 18:13:15 +00001682 # fold down if _clamp == 1 and self has too few digits
1683 if context._clamp == 1 and self._exp > Etop:
1684 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001685 self_padded = self._int + '0'*(self._exp - Etop)
1686 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001687
Facundo Batista353750c2007-09-13 18:13:15 +00001688 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001689 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001690
1691 _pick_rounding_function = {}
1692
Facundo Batista353750c2007-09-13 18:13:15 +00001693 # for each of the rounding functions below:
1694 # self is a finite, nonzero Decimal
1695 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001696 #
1697 # each function returns either -1, 0, or 1, as follows:
1698 # 1 indicates that self should be rounded up (away from zero)
1699 # 0 indicates that self should be truncated, and that all the
1700 # digits to be truncated are zeros (so the value is unchanged)
1701 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001702
1703 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001704 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001705 if _all_zeros(self._int, prec):
1706 return 0
1707 else:
1708 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001709
Facundo Batista353750c2007-09-13 18:13:15 +00001710 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001711 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001712 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001713
Facundo Batista353750c2007-09-13 18:13:15 +00001714 def _round_half_up(self, prec):
1715 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001716 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001717 return 1
1718 elif _all_zeros(self._int, prec):
1719 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001720 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001721 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001722
1723 def _round_half_down(self, prec):
1724 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001725 if _exact_half(self._int, prec):
1726 return -1
1727 else:
1728 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001729
1730 def _round_half_even(self, prec):
1731 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001732 if _exact_half(self._int, prec) and \
1733 (prec == 0 or self._int[prec-1] in '02468'):
1734 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001735 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001736 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001737
1738 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001739 """Rounds up (not away from 0 if negative.)"""
1740 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001741 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001742 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001743 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001744
Facundo Batista353750c2007-09-13 18:13:15 +00001745 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001746 """Rounds down (not towards 0 if negative)"""
1747 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001748 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001749 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001750 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001751
Facundo Batista353750c2007-09-13 18:13:15 +00001752 def _round_05up(self, prec):
1753 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001754 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001755 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001756 else:
1757 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001758
Facundo Batista353750c2007-09-13 18:13:15 +00001759 def fma(self, other, third, context=None):
1760 """Fused multiply-add.
1761
1762 Returns self*other+third with no rounding of the intermediate
1763 product self*other.
1764
1765 self and other are multiplied together, with no rounding of
1766 the result. The third operand is then added to the result,
1767 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001768 """
Facundo Batista353750c2007-09-13 18:13:15 +00001769
1770 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001771
1772 # compute product; raise InvalidOperation if either operand is
1773 # a signaling NaN or if the product is zero times infinity.
1774 if self._is_special or other._is_special:
1775 if context is None:
1776 context = getcontext()
1777 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001778 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001779 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001780 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001781 if self._exp == 'n':
1782 product = self
1783 elif other._exp == 'n':
1784 product = other
1785 elif self._exp == 'F':
1786 if not other:
1787 return context._raise_error(InvalidOperation,
1788 'INF * 0 in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001789 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001790 elif other._exp == 'F':
1791 if not self:
1792 return context._raise_error(InvalidOperation,
1793 '0 * INF in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001794 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001795 else:
1796 product = _dec_from_triple(self._sign ^ other._sign,
1797 str(int(self._int) * int(other._int)),
1798 self._exp + other._exp)
1799
Facundo Batista353750c2007-09-13 18:13:15 +00001800 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001801 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001802
Facundo Batista353750c2007-09-13 18:13:15 +00001803 def _power_modulo(self, other, modulo, context=None):
1804 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001805
Facundo Batista353750c2007-09-13 18:13:15 +00001806 # if can't convert other and modulo to Decimal, raise
1807 # TypeError; there's no point returning NotImplemented (no
1808 # equivalent of __rpow__ for three argument pow)
1809 other = _convert_other(other, raiseit=True)
1810 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001811
Facundo Batista353750c2007-09-13 18:13:15 +00001812 if context is None:
1813 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001814
Facundo Batista353750c2007-09-13 18:13:15 +00001815 # deal with NaNs: if there are any sNaNs then first one wins,
1816 # (i.e. behaviour for NaNs is identical to that of fma)
1817 self_is_nan = self._isnan()
1818 other_is_nan = other._isnan()
1819 modulo_is_nan = modulo._isnan()
1820 if self_is_nan or other_is_nan or modulo_is_nan:
1821 if self_is_nan == 2:
1822 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001823 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001824 if other_is_nan == 2:
1825 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001826 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001827 if modulo_is_nan == 2:
1828 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001829 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001830 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001831 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001832 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001833 return other._fix_nan(context)
1834 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001835
Facundo Batista353750c2007-09-13 18:13:15 +00001836 # check inputs: we apply same restrictions as Python's pow()
1837 if not (self._isinteger() and
1838 other._isinteger() and
1839 modulo._isinteger()):
1840 return context._raise_error(InvalidOperation,
1841 'pow() 3rd argument not allowed '
1842 'unless all arguments are integers')
1843 if other < 0:
1844 return context._raise_error(InvalidOperation,
1845 'pow() 2nd argument cannot be '
1846 'negative when 3rd argument specified')
1847 if not modulo:
1848 return context._raise_error(InvalidOperation,
1849 'pow() 3rd argument cannot be 0')
1850
1851 # additional restriction for decimal: the modulus must be less
1852 # than 10**prec in absolute value
1853 if modulo.adjusted() >= context.prec:
1854 return context._raise_error(InvalidOperation,
1855 'insufficient precision: pow() 3rd '
1856 'argument must not have more than '
1857 'precision digits')
1858
1859 # define 0**0 == NaN, for consistency with two-argument pow
1860 # (even though it hurts!)
1861 if not other and not self:
1862 return context._raise_error(InvalidOperation,
1863 'at least one of pow() 1st argument '
1864 'and 2nd argument must be nonzero ;'
1865 '0**0 is not defined')
1866
1867 # compute sign of result
1868 if other._iseven():
1869 sign = 0
1870 else:
1871 sign = self._sign
1872
1873 # convert modulo to a Python integer, and self and other to
1874 # Decimal integers (i.e. force their exponents to be >= 0)
1875 modulo = abs(int(modulo))
1876 base = _WorkRep(self.to_integral_value())
1877 exponent = _WorkRep(other.to_integral_value())
1878
1879 # compute result using integer pow()
1880 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1881 for i in xrange(exponent.exp):
1882 base = pow(base, 10, modulo)
1883 base = pow(base, exponent.int, modulo)
1884
Facundo Batista72bc54f2007-11-23 17:59:00 +00001885 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001886
1887 def _power_exact(self, other, p):
1888 """Attempt to compute self**other exactly.
1889
1890 Given Decimals self and other and an integer p, attempt to
1891 compute an exact result for the power self**other, with p
1892 digits of precision. Return None if self**other is not
1893 exactly representable in p digits.
1894
1895 Assumes that elimination of special cases has already been
1896 performed: self and other must both be nonspecial; self must
1897 be positive and not numerically equal to 1; other must be
1898 nonzero. For efficiency, other._exp should not be too large,
1899 so that 10**abs(other._exp) is a feasible calculation."""
1900
1901 # In the comments below, we write x for the value of self and
1902 # y for the value of other. Write x = xc*10**xe and y =
1903 # yc*10**ye.
1904
1905 # The main purpose of this method is to identify the *failure*
1906 # of x**y to be exactly representable with as little effort as
1907 # possible. So we look for cheap and easy tests that
1908 # eliminate the possibility of x**y being exact. Only if all
1909 # these tests are passed do we go on to actually compute x**y.
1910
1911 # Here's the main idea. First normalize both x and y. We
1912 # express y as a rational m/n, with m and n relatively prime
1913 # and n>0. Then for x**y to be exactly representable (at
1914 # *any* precision), xc must be the nth power of a positive
1915 # integer and xe must be divisible by n. If m is negative
1916 # then additionally xc must be a power of either 2 or 5, hence
1917 # a power of 2**n or 5**n.
1918 #
1919 # There's a limit to how small |y| can be: if y=m/n as above
1920 # then:
1921 #
1922 # (1) if xc != 1 then for the result to be representable we
1923 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1924 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1925 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1926 # representable.
1927 #
1928 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1929 # |y| < 1/|xe| then the result is not representable.
1930 #
1931 # Note that since x is not equal to 1, at least one of (1) and
1932 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1933 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1934 #
1935 # There's also a limit to how large y can be, at least if it's
1936 # positive: the normalized result will have coefficient xc**y,
1937 # so if it's representable then xc**y < 10**p, and y <
1938 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1939 # not exactly representable.
1940
1941 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1942 # so |y| < 1/xe and the result is not representable.
1943 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1944 # < 1/nbits(xc).
1945
1946 x = _WorkRep(self)
1947 xc, xe = x.int, x.exp
1948 while xc % 10 == 0:
1949 xc //= 10
1950 xe += 1
1951
1952 y = _WorkRep(other)
1953 yc, ye = y.int, y.exp
1954 while yc % 10 == 0:
1955 yc //= 10
1956 ye += 1
1957
1958 # case where xc == 1: result is 10**(xe*y), with xe*y
1959 # required to be an integer
1960 if xc == 1:
1961 if ye >= 0:
1962 exponent = xe*yc*10**ye
1963 else:
1964 exponent, remainder = divmod(xe*yc, 10**-ye)
1965 if remainder:
1966 return None
1967 if y.sign == 1:
1968 exponent = -exponent
1969 # if other is a nonnegative integer, use ideal exponent
1970 if other._isinteger() and other._sign == 0:
1971 ideal_exponent = self._exp*int(other)
1972 zeros = min(exponent-ideal_exponent, p-1)
1973 else:
1974 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001975 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001976
1977 # case where y is negative: xc must be either a power
1978 # of 2 or a power of 5.
1979 if y.sign == 1:
1980 last_digit = xc % 10
1981 if last_digit in (2,4,6,8):
1982 # quick test for power of 2
1983 if xc & -xc != xc:
1984 return None
1985 # now xc is a power of 2; e is its exponent
1986 e = _nbits(xc)-1
1987 # find e*y and xe*y; both must be integers
1988 if ye >= 0:
1989 y_as_int = yc*10**ye
1990 e = e*y_as_int
1991 xe = xe*y_as_int
1992 else:
1993 ten_pow = 10**-ye
1994 e, remainder = divmod(e*yc, ten_pow)
1995 if remainder:
1996 return None
1997 xe, remainder = divmod(xe*yc, ten_pow)
1998 if remainder:
1999 return None
2000
2001 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2002 return None
2003 xc = 5**e
2004
2005 elif last_digit == 5:
2006 # e >= log_5(xc) if xc is a power of 5; we have
2007 # equality all the way up to xc=5**2658
2008 e = _nbits(xc)*28//65
2009 xc, remainder = divmod(5**e, xc)
2010 if remainder:
2011 return None
2012 while xc % 5 == 0:
2013 xc //= 5
2014 e -= 1
2015 if ye >= 0:
2016 y_as_integer = yc*10**ye
2017 e = e*y_as_integer
2018 xe = xe*y_as_integer
2019 else:
2020 ten_pow = 10**-ye
2021 e, remainder = divmod(e*yc, ten_pow)
2022 if remainder:
2023 return None
2024 xe, remainder = divmod(xe*yc, ten_pow)
2025 if remainder:
2026 return None
2027 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2028 return None
2029 xc = 2**e
2030 else:
2031 return None
2032
2033 if xc >= 10**p:
2034 return None
2035 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00002036 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00002037
2038 # now y is positive; find m and n such that y = m/n
2039 if ye >= 0:
2040 m, n = yc*10**ye, 1
2041 else:
2042 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2043 return None
2044 xc_bits = _nbits(xc)
2045 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2046 return None
2047 m, n = yc, 10**(-ye)
2048 while m % 2 == n % 2 == 0:
2049 m //= 2
2050 n //= 2
2051 while m % 5 == n % 5 == 0:
2052 m //= 5
2053 n //= 5
2054
2055 # compute nth root of xc*10**xe
2056 if n > 1:
2057 # if 1 < xc < 2**n then xc isn't an nth power
2058 if xc != 1 and xc_bits <= n:
2059 return None
2060
2061 xe, rem = divmod(xe, n)
2062 if rem != 0:
2063 return None
2064
2065 # compute nth root of xc using Newton's method
2066 a = 1L << -(-_nbits(xc)//n) # initial estimate
2067 while True:
2068 q, r = divmod(xc, a**(n-1))
2069 if a <= q:
2070 break
2071 else:
2072 a = (a*(n-1) + q)//n
2073 if not (a == q and r == 0):
2074 return None
2075 xc = a
2076
2077 # now xc*10**xe is the nth root of the original xc*10**xe
2078 # compute mth power of xc*10**xe
2079
2080 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2081 # 10**p and the result is not representable.
2082 if xc > 1 and m > p*100//_log10_lb(xc):
2083 return None
2084 xc = xc**m
2085 xe *= m
2086 if xc > 10**p:
2087 return None
2088
2089 # by this point the result *is* exactly representable
2090 # adjust the exponent to get as close as possible to the ideal
2091 # exponent, if necessary
2092 str_xc = str(xc)
2093 if other._isinteger() and other._sign == 0:
2094 ideal_exponent = self._exp*int(other)
2095 zeros = min(xe-ideal_exponent, p-len(str_xc))
2096 else:
2097 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002098 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002099
2100 def __pow__(self, other, modulo=None, context=None):
2101 """Return self ** other [ % modulo].
2102
2103 With two arguments, compute self**other.
2104
2105 With three arguments, compute (self**other) % modulo. For the
2106 three argument form, the following restrictions on the
2107 arguments hold:
2108
2109 - all three arguments must be integral
2110 - other must be nonnegative
2111 - either self or other (or both) must be nonzero
2112 - modulo must be nonzero and must have at most p digits,
2113 where p is the context precision.
2114
2115 If any of these restrictions is violated the InvalidOperation
2116 flag is raised.
2117
2118 The result of pow(self, other, modulo) is identical to the
2119 result that would be obtained by computing (self**other) %
2120 modulo with unbounded precision, but is computed more
2121 efficiently. It is always exact.
2122 """
2123
2124 if modulo is not None:
2125 return self._power_modulo(other, modulo, context)
2126
2127 other = _convert_other(other)
2128 if other is NotImplemented:
2129 return other
2130
2131 if context is None:
2132 context = getcontext()
2133
2134 # either argument is a NaN => result is NaN
2135 ans = self._check_nans(other, context)
2136 if ans:
2137 return ans
2138
2139 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2140 if not other:
2141 if not self:
2142 return context._raise_error(InvalidOperation, '0 ** 0')
2143 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002144 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002145
2146 # result has sign 1 iff self._sign is 1 and other is an odd integer
2147 result_sign = 0
2148 if self._sign == 1:
2149 if other._isinteger():
2150 if not other._iseven():
2151 result_sign = 1
2152 else:
2153 # -ve**noninteger = NaN
2154 # (-0)**noninteger = 0**noninteger
2155 if self:
2156 return context._raise_error(InvalidOperation,
2157 'x ** y with x negative and y not an integer')
2158 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002159 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002160
2161 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2162 if not self:
2163 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002164 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002165 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002166 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002167
2168 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002169 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002170 if other._sign == 0:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002171 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002172 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002173 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002174
Facundo Batista353750c2007-09-13 18:13:15 +00002175 # 1**other = 1, but the choice of exponent and the flags
2176 # depend on the exponent of self, and on whether other is a
2177 # positive integer, a negative integer, or neither
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002178 if self == _One:
Facundo Batista353750c2007-09-13 18:13:15 +00002179 if other._isinteger():
2180 # exp = max(self._exp*max(int(other), 0),
2181 # 1-context.prec) but evaluating int(other) directly
2182 # is dangerous until we know other is small (other
2183 # could be 1e999999999)
2184 if other._sign == 1:
2185 multiplier = 0
2186 elif other > context.prec:
2187 multiplier = context.prec
2188 else:
2189 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002190
Facundo Batista353750c2007-09-13 18:13:15 +00002191 exp = self._exp * multiplier
2192 if exp < 1-context.prec:
2193 exp = 1-context.prec
2194 context._raise_error(Rounded)
2195 else:
2196 context._raise_error(Inexact)
2197 context._raise_error(Rounded)
2198 exp = 1-context.prec
2199
Facundo Batista72bc54f2007-11-23 17:59:00 +00002200 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002201
2202 # compute adjusted exponent of self
2203 self_adj = self.adjusted()
2204
2205 # self ** infinity is infinity if self > 1, 0 if self < 1
2206 # self ** -infinity is infinity if self < 1, 0 if self > 1
2207 if other._isinfinity():
2208 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002209 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002210 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002211 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002212
2213 # from here on, the result always goes through the call
2214 # to _fix at the end of this function.
2215 ans = None
2216
2217 # crude test to catch cases of extreme overflow/underflow. If
2218 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2219 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2220 # self**other >= 10**(Emax+1), so overflow occurs. The test
2221 # for underflow is similar.
2222 bound = self._log10_exp_bound() + other.adjusted()
2223 if (self_adj >= 0) == (other._sign == 0):
2224 # self > 1 and other +ve, or self < 1 and other -ve
2225 # possibility of overflow
2226 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002227 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002228 else:
2229 # self > 1 and other -ve, or self < 1 and other +ve
2230 # possibility of underflow to 0
2231 Etiny = context.Etiny()
2232 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002233 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002234
2235 # try for an exact result with precision +1
2236 if ans is None:
2237 ans = self._power_exact(other, context.prec + 1)
2238 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002239 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002240
2241 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2242 if ans is None:
2243 p = context.prec
2244 x = _WorkRep(self)
2245 xc, xe = x.int, x.exp
2246 y = _WorkRep(other)
2247 yc, ye = y.int, y.exp
2248 if y.sign == 1:
2249 yc = -yc
2250
2251 # compute correctly rounded result: start with precision +3,
2252 # then increase precision until result is unambiguously roundable
2253 extra = 3
2254 while True:
2255 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2256 if coeff % (5*10**(len(str(coeff))-p-1)):
2257 break
2258 extra += 3
2259
Facundo Batista72bc54f2007-11-23 17:59:00 +00002260 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002261
2262 # the specification says that for non-integer other we need to
2263 # raise Inexact, even when the result is actually exact. In
2264 # the same way, we need to raise Underflow here if the result
2265 # is subnormal. (The call to _fix will take care of raising
2266 # Rounded and Subnormal, as usual.)
2267 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002268 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002269 # pad with zeros up to length context.prec+1 if necessary
2270 if len(ans._int) <= context.prec:
2271 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002272 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2273 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002274 if ans.adjusted() < context.Emin:
2275 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002276
Facundo Batista353750c2007-09-13 18:13:15 +00002277 # unlike exp, ln and log10, the power function respects the
2278 # rounding mode; no need to use ROUND_HALF_EVEN here
2279 ans = ans._fix(context)
2280 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002281
2282 def __rpow__(self, other, context=None):
2283 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002284 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002285 if other is NotImplemented:
2286 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002287 return other.__pow__(self, context=context)
2288
2289 def normalize(self, context=None):
2290 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002291
Facundo Batista353750c2007-09-13 18:13:15 +00002292 if context is None:
2293 context = getcontext()
2294
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002295 if self._is_special:
2296 ans = self._check_nans(context=context)
2297 if ans:
2298 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002299
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002300 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002301 if dup._isinfinity():
2302 return dup
2303
2304 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002305 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002306 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002307 end = len(dup._int)
2308 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002309 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002310 exp += 1
2311 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002312 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002313
Facundo Batistabd2fe832007-09-13 18:42:09 +00002314 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002315 """Quantize self so its exponent is the same as that of exp.
2316
2317 Similar to self._rescale(exp._exp) but with error checking.
2318 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002319 exp = _convert_other(exp, raiseit=True)
2320
Facundo Batista353750c2007-09-13 18:13:15 +00002321 if context is None:
2322 context = getcontext()
2323 if rounding is None:
2324 rounding = context.rounding
2325
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002326 if self._is_special or exp._is_special:
2327 ans = self._check_nans(exp, context)
2328 if ans:
2329 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002330
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002331 if exp._isinfinity() or self._isinfinity():
2332 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002333 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002334 return context._raise_error(InvalidOperation,
2335 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002336
Facundo Batistabd2fe832007-09-13 18:42:09 +00002337 # if we're not watching exponents, do a simple rescale
2338 if not watchexp:
2339 ans = self._rescale(exp._exp, rounding)
2340 # raise Inexact and Rounded where appropriate
2341 if ans._exp > self._exp:
2342 context._raise_error(Rounded)
2343 if ans != self:
2344 context._raise_error(Inexact)
2345 return ans
2346
Facundo Batista353750c2007-09-13 18:13:15 +00002347 # exp._exp should be between Etiny and Emax
2348 if not (context.Etiny() <= exp._exp <= context.Emax):
2349 return context._raise_error(InvalidOperation,
2350 'target exponent out of bounds in quantize')
2351
2352 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002353 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002354 return ans._fix(context)
2355
2356 self_adjusted = self.adjusted()
2357 if self_adjusted > context.Emax:
2358 return context._raise_error(InvalidOperation,
2359 'exponent of quantize result too large for current context')
2360 if self_adjusted - exp._exp + 1 > context.prec:
2361 return context._raise_error(InvalidOperation,
2362 'quantize result has too many digits for current context')
2363
2364 ans = self._rescale(exp._exp, rounding)
2365 if ans.adjusted() > context.Emax:
2366 return context._raise_error(InvalidOperation,
2367 'exponent of quantize result too large for current context')
2368 if len(ans._int) > context.prec:
2369 return context._raise_error(InvalidOperation,
2370 'quantize result has too many digits for current context')
2371
2372 # raise appropriate flags
2373 if ans._exp > self._exp:
2374 context._raise_error(Rounded)
2375 if ans != self:
2376 context._raise_error(Inexact)
2377 if ans and ans.adjusted() < context.Emin:
2378 context._raise_error(Subnormal)
2379
2380 # call to fix takes care of any necessary folddown
2381 ans = ans._fix(context)
2382 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002383
2384 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002385 """Return True if self and other have the same exponent; otherwise
2386 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002387
Facundo Batista1a191df2007-10-02 17:01:24 +00002388 If either operand is a special value, the following rules are used:
2389 * return True if both operands are infinities
2390 * return True if both operands are NaNs
2391 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002392 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002393 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002394 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002395 return (self.is_nan() and other.is_nan() or
2396 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002397 return self._exp == other._exp
2398
Facundo Batista353750c2007-09-13 18:13:15 +00002399 def _rescale(self, exp, rounding):
2400 """Rescale self so that the exponent is exp, either by padding with zeros
2401 or by truncating digits, using the given rounding mode.
2402
2403 Specials are returned without change. This operation is
2404 quiet: it raises no flags, and uses no information from the
2405 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002406
2407 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002408 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002409 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002410 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002411 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002412 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002413 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002414
Facundo Batista353750c2007-09-13 18:13:15 +00002415 if self._exp >= exp:
2416 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002417 return _dec_from_triple(self._sign,
2418 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002419
Facundo Batista353750c2007-09-13 18:13:15 +00002420 # too many digits; round and lose data. If self.adjusted() <
2421 # exp-1, replace self by 10**(exp-1) before rounding
2422 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002423 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002424 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002425 digits = 0
2426 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002427 changed = this_function(digits)
2428 coeff = self._int[:digits] or '0'
2429 if changed == 1:
2430 coeff = str(int(coeff)+1)
2431 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002432
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00002433 def _round(self, places, rounding):
2434 """Round a nonzero, nonspecial Decimal to a fixed number of
2435 significant figures, using the given rounding mode.
2436
2437 Infinities, NaNs and zeros are returned unaltered.
2438
2439 This operation is quiet: it raises no flags, and uses no
2440 information from the context.
2441
2442 """
2443 if places <= 0:
2444 raise ValueError("argument should be at least 1 in _round")
2445 if self._is_special or not self:
2446 return Decimal(self)
2447 ans = self._rescale(self.adjusted()+1-places, rounding)
2448 # it can happen that the rescale alters the adjusted exponent;
2449 # for example when rounding 99.97 to 3 significant figures.
2450 # When this happens we end up with an extra 0 at the end of
2451 # the number; a second rescale fixes this.
2452 if ans.adjusted() != self.adjusted():
2453 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2454 return ans
2455
Facundo Batista353750c2007-09-13 18:13:15 +00002456 def to_integral_exact(self, rounding=None, context=None):
2457 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002458
Facundo Batista353750c2007-09-13 18:13:15 +00002459 If no rounding mode is specified, take the rounding mode from
2460 the context. This method raises the Rounded and Inexact flags
2461 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002462
Facundo Batista353750c2007-09-13 18:13:15 +00002463 See also: to_integral_value, which does exactly the same as
2464 this method except that it doesn't raise Inexact or Rounded.
2465 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002466 if self._is_special:
2467 ans = self._check_nans(context=context)
2468 if ans:
2469 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002470 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002471 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002472 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002473 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002474 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002475 if context is None:
2476 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002477 if rounding is None:
2478 rounding = context.rounding
2479 context._raise_error(Rounded)
2480 ans = self._rescale(0, rounding)
2481 if ans != self:
2482 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002483 return ans
2484
Facundo Batista353750c2007-09-13 18:13:15 +00002485 def to_integral_value(self, rounding=None, context=None):
2486 """Rounds to the nearest integer, without raising inexact, rounded."""
2487 if context is None:
2488 context = getcontext()
2489 if rounding is None:
2490 rounding = context.rounding
2491 if self._is_special:
2492 ans = self._check_nans(context=context)
2493 if ans:
2494 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002495 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002496 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002497 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002498 else:
2499 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002500
Facundo Batista353750c2007-09-13 18:13:15 +00002501 # the method name changed, but we provide also the old one, for compatibility
2502 to_integral = to_integral_value
2503
2504 def sqrt(self, context=None):
2505 """Return the square root of self."""
Mark Dickinson3b24ccb2008-03-25 14:33:23 +00002506 if context is None:
2507 context = getcontext()
2508
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002509 if self._is_special:
2510 ans = self._check_nans(context=context)
2511 if ans:
2512 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002513
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002514 if self._isinfinity() and self._sign == 0:
2515 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002516
2517 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002518 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002519 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002520 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002521
2522 if self._sign == 1:
2523 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2524
Facundo Batista353750c2007-09-13 18:13:15 +00002525 # At this point self represents a positive number. Let p be
2526 # the desired precision and express self in the form c*100**e
2527 # with c a positive real number and e an integer, c and e
2528 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2529 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2530 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2531 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2532 # the closest integer to sqrt(c) with the even integer chosen
2533 # in the case of a tie.
2534 #
2535 # To ensure correct rounding in all cases, we use the
2536 # following trick: we compute the square root to an extra
2537 # place (precision p+1 instead of precision p), rounding down.
2538 # Then, if the result is inexact and its last digit is 0 or 5,
2539 # we increase the last digit to 1 or 6 respectively; if it's
2540 # exact we leave the last digit alone. Now the final round to
2541 # p places (or fewer in the case of underflow) will round
2542 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002543
Facundo Batista353750c2007-09-13 18:13:15 +00002544 # use an extra digit of precision
2545 prec = context.prec+1
2546
2547 # write argument in the form c*100**e where e = self._exp//2
2548 # is the 'ideal' exponent, to be used if the square root is
2549 # exactly representable. l is the number of 'digits' of c in
2550 # base 100, so that 100**(l-1) <= c < 100**l.
2551 op = _WorkRep(self)
2552 e = op.exp >> 1
2553 if op.exp & 1:
2554 c = op.int * 10
2555 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002556 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002557 c = op.int
2558 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002559
Facundo Batista353750c2007-09-13 18:13:15 +00002560 # rescale so that c has exactly prec base 100 'digits'
2561 shift = prec-l
2562 if shift >= 0:
2563 c *= 100**shift
2564 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002565 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002566 c, remainder = divmod(c, 100**-shift)
2567 exact = not remainder
2568 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002569
Facundo Batista353750c2007-09-13 18:13:15 +00002570 # find n = floor(sqrt(c)) using Newton's method
2571 n = 10**prec
2572 while True:
2573 q = c//n
2574 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002575 break
Facundo Batista353750c2007-09-13 18:13:15 +00002576 else:
2577 n = n + q >> 1
2578 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002579
Facundo Batista353750c2007-09-13 18:13:15 +00002580 if exact:
2581 # result is exact; rescale to use ideal exponent e
2582 if shift >= 0:
2583 # assert n % 10**shift == 0
2584 n //= 10**shift
2585 else:
2586 n *= 10**-shift
2587 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002588 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002589 # result is not exact; fix last digit as described above
2590 if n % 5 == 0:
2591 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002592
Facundo Batista72bc54f2007-11-23 17:59:00 +00002593 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002594
Facundo Batista353750c2007-09-13 18:13:15 +00002595 # round, and fit to current context
2596 context = context._shallow_copy()
2597 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002598 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002599 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002600
Facundo Batista353750c2007-09-13 18:13:15 +00002601 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002602
2603 def max(self, other, context=None):
2604 """Returns the larger value.
2605
Facundo Batista353750c2007-09-13 18:13:15 +00002606 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002607 NaN (and signals if one is sNaN). Also rounds.
2608 """
Facundo Batista353750c2007-09-13 18:13:15 +00002609 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002610
Facundo Batista6c398da2007-09-17 17:30:13 +00002611 if context is None:
2612 context = getcontext()
2613
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002614 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002615 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002616 # number is always returned
2617 sn = self._isnan()
2618 on = other._isnan()
2619 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002620 if on == 1 and sn == 0:
2621 return self._fix(context)
2622 if sn == 1 and on == 0:
2623 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002624 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002625
Mark Dickinson2fc92632008-02-06 22:10:50 +00002626 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002627 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002628 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002629 # then an ordering is applied:
2630 #
Facundo Batista59c58842007-04-10 12:58:45 +00002631 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002632 # positive sign and min returns the operand with the negative sign
2633 #
Facundo Batista59c58842007-04-10 12:58:45 +00002634 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002635 # the result. This is exactly the ordering used in compare_total.
2636 c = self.compare_total(other)
2637
2638 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002639 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002640 else:
2641 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002642
Facundo Batistae64acfa2007-12-17 14:18:42 +00002643 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002644
2645 def min(self, other, context=None):
2646 """Returns the smaller value.
2647
Facundo Batista59c58842007-04-10 12:58:45 +00002648 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002649 NaN (and signals if one is sNaN). Also rounds.
2650 """
Facundo Batista353750c2007-09-13 18:13:15 +00002651 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002652
Facundo Batista6c398da2007-09-17 17:30:13 +00002653 if context is None:
2654 context = getcontext()
2655
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002656 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002657 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002658 # number is always returned
2659 sn = self._isnan()
2660 on = other._isnan()
2661 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002662 if on == 1 and sn == 0:
2663 return self._fix(context)
2664 if sn == 1 and on == 0:
2665 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002666 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002667
Mark Dickinson2fc92632008-02-06 22:10:50 +00002668 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002669 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002670 c = self.compare_total(other)
2671
2672 if c == -1:
2673 ans = self
2674 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002675 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002676
Facundo Batistae64acfa2007-12-17 14:18:42 +00002677 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002678
2679 def _isinteger(self):
2680 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002681 if self._is_special:
2682 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002683 if self._exp >= 0:
2684 return True
2685 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002686 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002687
2688 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002689 """Returns True if self is even. Assumes self is an integer."""
2690 if not self or self._exp > 0:
2691 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002692 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002693
2694 def adjusted(self):
2695 """Return the adjusted exponent of self"""
2696 try:
2697 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002698 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002699 except TypeError:
2700 return 0
2701
Facundo Batista353750c2007-09-13 18:13:15 +00002702 def canonical(self, context=None):
2703 """Returns the same Decimal object.
2704
2705 As we do not have different encodings for the same number, the
2706 received object already is in its canonical form.
2707 """
2708 return self
2709
2710 def compare_signal(self, other, context=None):
2711 """Compares self to the other operand numerically.
2712
2713 It's pretty much like compare(), but all NaNs signal, with signaling
2714 NaNs taking precedence over quiet NaNs.
2715 """
Mark Dickinson2fc92632008-02-06 22:10:50 +00002716 other = _convert_other(other, raiseit = True)
2717 ans = self._compare_check_nans(other, context)
2718 if ans:
2719 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002720 return self.compare(other, context=context)
2721
2722 def compare_total(self, other):
2723 """Compares self to other using the abstract representations.
2724
2725 This is not like the standard compare, which use their numerical
2726 value. Note that a total ordering is defined for all possible abstract
2727 representations.
2728 """
2729 # if one is negative and the other is positive, it's easy
2730 if self._sign and not other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002731 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002732 if not self._sign and other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002733 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002734 sign = self._sign
2735
2736 # let's handle both NaN types
2737 self_nan = self._isnan()
2738 other_nan = other._isnan()
2739 if self_nan or other_nan:
2740 if self_nan == other_nan:
2741 if self._int < other._int:
2742 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002743 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002744 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002745 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002746 if self._int > other._int:
2747 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002748 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002749 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002750 return _One
2751 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002752
2753 if sign:
2754 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002755 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002756 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002757 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002758 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002759 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002760 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002761 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002762 else:
2763 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002764 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002765 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002766 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002767 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002768 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002769 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002770 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002771
2772 if self < other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002773 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002774 if self > other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002775 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002776
2777 if self._exp < other._exp:
2778 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002779 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002780 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002781 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002782 if self._exp > other._exp:
2783 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002784 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002785 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002786 return _One
2787 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002788
2789
2790 def compare_total_mag(self, other):
2791 """Compares self to other using abstract repr., ignoring sign.
2792
2793 Like compare_total, but with operand's sign ignored and assumed to be 0.
2794 """
2795 s = self.copy_abs()
2796 o = other.copy_abs()
2797 return s.compare_total(o)
2798
2799 def copy_abs(self):
2800 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002801 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002802
2803 def copy_negate(self):
2804 """Returns a copy with the sign inverted."""
2805 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002806 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002807 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002808 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002809
2810 def copy_sign(self, other):
2811 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002812 return _dec_from_triple(other._sign, self._int,
2813 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002814
2815 def exp(self, context=None):
2816 """Returns e ** self."""
2817
2818 if context is None:
2819 context = getcontext()
2820
2821 # exp(NaN) = NaN
2822 ans = self._check_nans(context=context)
2823 if ans:
2824 return ans
2825
2826 # exp(-Infinity) = 0
2827 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002828 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002829
2830 # exp(0) = 1
2831 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002832 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002833
2834 # exp(Infinity) = Infinity
2835 if self._isinfinity() == 1:
2836 return Decimal(self)
2837
2838 # the result is now guaranteed to be inexact (the true
2839 # mathematical result is transcendental). There's no need to
2840 # raise Rounded and Inexact here---they'll always be raised as
2841 # a result of the call to _fix.
2842 p = context.prec
2843 adj = self.adjusted()
2844
2845 # we only need to do any computation for quite a small range
2846 # of adjusted exponents---for example, -29 <= adj <= 10 for
2847 # the default context. For smaller exponent the result is
2848 # indistinguishable from 1 at the given precision, while for
2849 # larger exponent the result either overflows or underflows.
2850 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2851 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002852 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002853 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2854 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002855 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002856 elif self._sign == 0 and adj < -p:
2857 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002858 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002859 elif self._sign == 1 and adj < -p-1:
2860 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002861 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002862 # general case
2863 else:
2864 op = _WorkRep(self)
2865 c, e = op.int, op.exp
2866 if op.sign == 1:
2867 c = -c
2868
2869 # compute correctly rounded result: increase precision by
2870 # 3 digits at a time until we get an unambiguously
2871 # roundable result
2872 extra = 3
2873 while True:
2874 coeff, exp = _dexp(c, e, p+extra)
2875 if coeff % (5*10**(len(str(coeff))-p-1)):
2876 break
2877 extra += 3
2878
Facundo Batista72bc54f2007-11-23 17:59:00 +00002879 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002880
2881 # at this stage, ans should round correctly with *any*
2882 # rounding mode, not just with ROUND_HALF_EVEN
2883 context = context._shallow_copy()
2884 rounding = context._set_rounding(ROUND_HALF_EVEN)
2885 ans = ans._fix(context)
2886 context.rounding = rounding
2887
2888 return ans
2889
2890 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002891 """Return True if self is canonical; otherwise return False.
2892
2893 Currently, the encoding of a Decimal instance is always
2894 canonical, so this method returns True for any Decimal.
2895 """
2896 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002897
2898 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002899 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002900
Facundo Batista1a191df2007-10-02 17:01:24 +00002901 A Decimal instance is considered finite if it is neither
2902 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002903 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002904 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002905
2906 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002907 """Return True if self is infinite; otherwise return False."""
2908 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002909
2910 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002911 """Return True if self is a qNaN or sNaN; otherwise return False."""
2912 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002913
2914 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002915 """Return True if self is a normal number; otherwise return False."""
2916 if self._is_special or not self:
2917 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002918 if context is None:
2919 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002920 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002921
2922 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002923 """Return True if self is a quiet NaN; otherwise return False."""
2924 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002925
2926 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002927 """Return True if self is negative; otherwise return False."""
2928 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002929
2930 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002931 """Return True if self is a signaling NaN; otherwise return False."""
2932 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002933
2934 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002935 """Return True if self is subnormal; otherwise return False."""
2936 if self._is_special or not self:
2937 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002938 if context is None:
2939 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002940 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002941
2942 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002943 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002944 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002945
2946 def _ln_exp_bound(self):
2947 """Compute a lower bound for the adjusted exponent of self.ln().
2948 In other words, compute r such that self.ln() >= 10**r. Assumes
2949 that self is finite and positive and that self != 1.
2950 """
2951
2952 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2953 adj = self._exp + len(self._int) - 1
2954 if adj >= 1:
2955 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2956 return len(str(adj*23//10)) - 1
2957 if adj <= -2:
2958 # argument <= 0.1
2959 return len(str((-1-adj)*23//10)) - 1
2960 op = _WorkRep(self)
2961 c, e = op.int, op.exp
2962 if adj == 0:
2963 # 1 < self < 10
2964 num = str(c-10**-e)
2965 den = str(c)
2966 return len(num) - len(den) - (num < den)
2967 # adj == -1, 0.1 <= self < 1
2968 return e + len(str(10**-e - c)) - 1
2969
2970
2971 def ln(self, context=None):
2972 """Returns the natural (base e) logarithm of self."""
2973
2974 if context is None:
2975 context = getcontext()
2976
2977 # ln(NaN) = NaN
2978 ans = self._check_nans(context=context)
2979 if ans:
2980 return ans
2981
2982 # ln(0.0) == -Infinity
2983 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002984 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00002985
2986 # ln(Infinity) = Infinity
2987 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002988 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00002989
2990 # ln(1.0) == 0.0
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002991 if self == _One:
2992 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002993
2994 # ln(negative) raises InvalidOperation
2995 if self._sign == 1:
2996 return context._raise_error(InvalidOperation,
2997 'ln of a negative value')
2998
2999 # result is irrational, so necessarily inexact
3000 op = _WorkRep(self)
3001 c, e = op.int, op.exp
3002 p = context.prec
3003
3004 # correctly rounded result: repeatedly increase precision by 3
3005 # until we get an unambiguously roundable result
3006 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3007 while True:
3008 coeff = _dlog(c, e, places)
3009 # assert len(str(abs(coeff)))-p >= 1
3010 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3011 break
3012 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003013 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003014
3015 context = context._shallow_copy()
3016 rounding = context._set_rounding(ROUND_HALF_EVEN)
3017 ans = ans._fix(context)
3018 context.rounding = rounding
3019 return ans
3020
3021 def _log10_exp_bound(self):
3022 """Compute a lower bound for the adjusted exponent of self.log10().
3023 In other words, find r such that self.log10() >= 10**r.
3024 Assumes that self is finite and positive and that self != 1.
3025 """
3026
3027 # For x >= 10 or x < 0.1 we only need a bound on the integer
3028 # part of log10(self), and this comes directly from the
3029 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3030 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3031 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3032
3033 adj = self._exp + len(self._int) - 1
3034 if adj >= 1:
3035 # self >= 10
3036 return len(str(adj))-1
3037 if adj <= -2:
3038 # self < 0.1
3039 return len(str(-1-adj))-1
3040 op = _WorkRep(self)
3041 c, e = op.int, op.exp
3042 if adj == 0:
3043 # 1 < self < 10
3044 num = str(c-10**-e)
3045 den = str(231*c)
3046 return len(num) - len(den) - (num < den) + 2
3047 # adj == -1, 0.1 <= self < 1
3048 num = str(10**-e-c)
3049 return len(num) + e - (num < "231") - 1
3050
3051 def log10(self, context=None):
3052 """Returns the base 10 logarithm of self."""
3053
3054 if context is None:
3055 context = getcontext()
3056
3057 # log10(NaN) = NaN
3058 ans = self._check_nans(context=context)
3059 if ans:
3060 return ans
3061
3062 # log10(0.0) == -Infinity
3063 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003064 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003065
3066 # log10(Infinity) = Infinity
3067 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003068 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003069
3070 # log10(negative or -Infinity) raises InvalidOperation
3071 if self._sign == 1:
3072 return context._raise_error(InvalidOperation,
3073 'log10 of a negative value')
3074
3075 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00003076 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00003077 # answer may need rounding
3078 ans = Decimal(self._exp + len(self._int) - 1)
3079 else:
3080 # result is irrational, so necessarily inexact
3081 op = _WorkRep(self)
3082 c, e = op.int, op.exp
3083 p = context.prec
3084
3085 # correctly rounded result: repeatedly increase precision
3086 # until result is unambiguously roundable
3087 places = p-self._log10_exp_bound()+2
3088 while True:
3089 coeff = _dlog10(c, e, places)
3090 # assert len(str(abs(coeff)))-p >= 1
3091 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3092 break
3093 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003094 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003095
3096 context = context._shallow_copy()
3097 rounding = context._set_rounding(ROUND_HALF_EVEN)
3098 ans = ans._fix(context)
3099 context.rounding = rounding
3100 return ans
3101
3102 def logb(self, context=None):
3103 """ Returns the exponent of the magnitude of self's MSD.
3104
3105 The result is the integer which is the exponent of the magnitude
3106 of the most significant digit of self (as though it were truncated
3107 to a single digit while maintaining the value of that digit and
3108 without limiting the resulting exponent).
3109 """
3110 # logb(NaN) = NaN
3111 ans = self._check_nans(context=context)
3112 if ans:
3113 return ans
3114
3115 if context is None:
3116 context = getcontext()
3117
3118 # logb(+/-Inf) = +Inf
3119 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003120 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003121
3122 # logb(0) = -Inf, DivisionByZero
3123 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003124 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003125
3126 # otherwise, simply return the adjusted exponent of self, as a
3127 # Decimal. Note that no attempt is made to fit the result
3128 # into the current context.
3129 return Decimal(self.adjusted())
3130
3131 def _islogical(self):
3132 """Return True if self is a logical operand.
3133
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00003134 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00003135 an exponent of 0, and a coefficient whose digits must all be
3136 either 0 or 1.
3137 """
3138 if self._sign != 0 or self._exp != 0:
3139 return False
3140 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003141 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003142 return False
3143 return True
3144
3145 def _fill_logical(self, context, opa, opb):
3146 dif = context.prec - len(opa)
3147 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003148 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003149 elif dif < 0:
3150 opa = opa[-context.prec:]
3151 dif = context.prec - len(opb)
3152 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003153 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003154 elif dif < 0:
3155 opb = opb[-context.prec:]
3156 return opa, opb
3157
3158 def logical_and(self, other, context=None):
3159 """Applies an 'and' operation between self and other's digits."""
3160 if context is None:
3161 context = getcontext()
3162 if not self._islogical() or not other._islogical():
3163 return context._raise_error(InvalidOperation)
3164
3165 # fill to context.prec
3166 (opa, opb) = self._fill_logical(context, self._int, other._int)
3167
3168 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003169 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3170 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003171
3172 def logical_invert(self, context=None):
3173 """Invert all its digits."""
3174 if context is None:
3175 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003176 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3177 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003178
3179 def logical_or(self, other, context=None):
3180 """Applies an 'or' operation between self and other's digits."""
3181 if context is None:
3182 context = getcontext()
3183 if not self._islogical() or not other._islogical():
3184 return context._raise_error(InvalidOperation)
3185
3186 # fill to context.prec
3187 (opa, opb) = self._fill_logical(context, self._int, other._int)
3188
3189 # make the operation, and clean starting zeroes
Mark Dickinson65808ff2009-01-04 21:22:02 +00003190 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003191 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003192
3193 def logical_xor(self, other, context=None):
3194 """Applies an 'xor' operation between self and other's digits."""
3195 if context is None:
3196 context = getcontext()
3197 if not self._islogical() or not other._islogical():
3198 return context._raise_error(InvalidOperation)
3199
3200 # fill to context.prec
3201 (opa, opb) = self._fill_logical(context, self._int, other._int)
3202
3203 # make the operation, and clean starting zeroes
Mark Dickinson65808ff2009-01-04 21:22:02 +00003204 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003205 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003206
3207 def max_mag(self, other, context=None):
3208 """Compares the values numerically with their sign ignored."""
3209 other = _convert_other(other, raiseit=True)
3210
Facundo Batista6c398da2007-09-17 17:30:13 +00003211 if context is None:
3212 context = getcontext()
3213
Facundo Batista353750c2007-09-13 18:13:15 +00003214 if self._is_special or other._is_special:
3215 # If one operand is a quiet NaN and the other is number, then the
3216 # number is always returned
3217 sn = self._isnan()
3218 on = other._isnan()
3219 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003220 if on == 1 and sn == 0:
3221 return self._fix(context)
3222 if sn == 1 and on == 0:
3223 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003224 return self._check_nans(other, context)
3225
Mark Dickinson2fc92632008-02-06 22:10:50 +00003226 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003227 if c == 0:
3228 c = self.compare_total(other)
3229
3230 if c == -1:
3231 ans = other
3232 else:
3233 ans = self
3234
Facundo Batistae64acfa2007-12-17 14:18:42 +00003235 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003236
3237 def min_mag(self, other, context=None):
3238 """Compares the values numerically with their sign ignored."""
3239 other = _convert_other(other, raiseit=True)
3240
Facundo Batista6c398da2007-09-17 17:30:13 +00003241 if context is None:
3242 context = getcontext()
3243
Facundo Batista353750c2007-09-13 18:13:15 +00003244 if self._is_special or other._is_special:
3245 # If one operand is a quiet NaN and the other is number, then the
3246 # number is always returned
3247 sn = self._isnan()
3248 on = other._isnan()
3249 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003250 if on == 1 and sn == 0:
3251 return self._fix(context)
3252 if sn == 1 and on == 0:
3253 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003254 return self._check_nans(other, context)
3255
Mark Dickinson2fc92632008-02-06 22:10:50 +00003256 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003257 if c == 0:
3258 c = self.compare_total(other)
3259
3260 if c == -1:
3261 ans = self
3262 else:
3263 ans = other
3264
Facundo Batistae64acfa2007-12-17 14:18:42 +00003265 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003266
3267 def next_minus(self, context=None):
3268 """Returns the largest representable number smaller than itself."""
3269 if context is None:
3270 context = getcontext()
3271
3272 ans = self._check_nans(context=context)
3273 if ans:
3274 return ans
3275
3276 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003277 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003278 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003279 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003280
3281 context = context.copy()
3282 context._set_rounding(ROUND_FLOOR)
3283 context._ignore_all_flags()
3284 new_self = self._fix(context)
3285 if new_self != self:
3286 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003287 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3288 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003289
3290 def next_plus(self, context=None):
3291 """Returns the smallest representable number larger than itself."""
3292 if context is None:
3293 context = getcontext()
3294
3295 ans = self._check_nans(context=context)
3296 if ans:
3297 return ans
3298
3299 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003300 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003301 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003302 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003303
3304 context = context.copy()
3305 context._set_rounding(ROUND_CEILING)
3306 context._ignore_all_flags()
3307 new_self = self._fix(context)
3308 if new_self != self:
3309 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003310 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3311 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003312
3313 def next_toward(self, other, context=None):
3314 """Returns the number closest to self, in the direction towards other.
3315
3316 The result is the closest representable number to self
3317 (excluding self) that is in the direction towards other,
3318 unless both have the same value. If the two operands are
3319 numerically equal, then the result is a copy of self with the
3320 sign set to be the same as the sign of other.
3321 """
3322 other = _convert_other(other, raiseit=True)
3323
3324 if context is None:
3325 context = getcontext()
3326
3327 ans = self._check_nans(other, context)
3328 if ans:
3329 return ans
3330
Mark Dickinson2fc92632008-02-06 22:10:50 +00003331 comparison = self._cmp(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003332 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003333 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003334
3335 if comparison == -1:
3336 ans = self.next_plus(context)
3337 else: # comparison == 1
3338 ans = self.next_minus(context)
3339
3340 # decide which flags to raise using value of ans
3341 if ans._isinfinity():
3342 context._raise_error(Overflow,
3343 'Infinite result from next_toward',
3344 ans._sign)
3345 context._raise_error(Rounded)
3346 context._raise_error(Inexact)
3347 elif ans.adjusted() < context.Emin:
3348 context._raise_error(Underflow)
3349 context._raise_error(Subnormal)
3350 context._raise_error(Rounded)
3351 context._raise_error(Inexact)
3352 # if precision == 1 then we don't raise Clamped for a
3353 # result 0E-Etiny.
3354 if not ans:
3355 context._raise_error(Clamped)
3356
3357 return ans
3358
3359 def number_class(self, context=None):
3360 """Returns an indication of the class of self.
3361
3362 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003363 sNaN
3364 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003365 -Infinity
3366 -Normal
3367 -Subnormal
3368 -Zero
3369 +Zero
3370 +Subnormal
3371 +Normal
3372 +Infinity
3373 """
3374 if self.is_snan():
3375 return "sNaN"
3376 if self.is_qnan():
3377 return "NaN"
3378 inf = self._isinfinity()
3379 if inf == 1:
3380 return "+Infinity"
3381 if inf == -1:
3382 return "-Infinity"
3383 if self.is_zero():
3384 if self._sign:
3385 return "-Zero"
3386 else:
3387 return "+Zero"
3388 if context is None:
3389 context = getcontext()
3390 if self.is_subnormal(context=context):
3391 if self._sign:
3392 return "-Subnormal"
3393 else:
3394 return "+Subnormal"
3395 # just a normal, regular, boring number, :)
3396 if self._sign:
3397 return "-Normal"
3398 else:
3399 return "+Normal"
3400
3401 def radix(self):
3402 """Just returns 10, as this is Decimal, :)"""
3403 return Decimal(10)
3404
3405 def rotate(self, other, context=None):
3406 """Returns a rotated copy of self, value-of-other times."""
3407 if context is None:
3408 context = getcontext()
3409
3410 ans = self._check_nans(other, context)
3411 if ans:
3412 return ans
3413
3414 if other._exp != 0:
3415 return context._raise_error(InvalidOperation)
3416 if not (-context.prec <= int(other) <= context.prec):
3417 return context._raise_error(InvalidOperation)
3418
3419 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003420 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003421
3422 # get values, pad if necessary
3423 torot = int(other)
3424 rotdig = self._int
3425 topad = context.prec - len(rotdig)
3426 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003427 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003428
3429 # let's rotate!
3430 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003431 return _dec_from_triple(self._sign,
3432 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003433
3434 def scaleb (self, other, context=None):
3435 """Returns self operand after adding the second value to its exp."""
3436 if context is None:
3437 context = getcontext()
3438
3439 ans = self._check_nans(other, context)
3440 if ans:
3441 return ans
3442
3443 if other._exp != 0:
3444 return context._raise_error(InvalidOperation)
3445 liminf = -2 * (context.Emax + context.prec)
3446 limsup = 2 * (context.Emax + context.prec)
3447 if not (liminf <= int(other) <= limsup):
3448 return context._raise_error(InvalidOperation)
3449
3450 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003451 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003452
Facundo Batista72bc54f2007-11-23 17:59:00 +00003453 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003454 d = d._fix(context)
3455 return d
3456
3457 def shift(self, other, context=None):
3458 """Returns a shifted copy of self, value-of-other times."""
3459 if context is None:
3460 context = getcontext()
3461
3462 ans = self._check_nans(other, context)
3463 if ans:
3464 return ans
3465
3466 if other._exp != 0:
3467 return context._raise_error(InvalidOperation)
3468 if not (-context.prec <= int(other) <= context.prec):
3469 return context._raise_error(InvalidOperation)
3470
3471 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003472 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003473
3474 # get values, pad if necessary
3475 torot = int(other)
3476 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003477 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003478 rotdig = self._int
3479 topad = context.prec - len(rotdig)
3480 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003481 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003482
3483 # let's shift!
3484 if torot < 0:
3485 rotated = rotdig[:torot]
3486 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003487 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003488 rotated = rotated[-context.prec:]
3489
Facundo Batista72bc54f2007-11-23 17:59:00 +00003490 return _dec_from_triple(self._sign,
3491 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003492
Facundo Batista59c58842007-04-10 12:58:45 +00003493 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003494 def __reduce__(self):
3495 return (self.__class__, (str(self),))
3496
3497 def __copy__(self):
3498 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003499 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003500 return self.__class__(str(self))
3501
3502 def __deepcopy__(self, memo):
3503 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003504 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003505 return self.__class__(str(self))
3506
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003507 # PEP 3101 support. See also _parse_format_specifier and _format_align
3508 def __format__(self, specifier, context=None):
Mark Dickinsonf4da7772008-02-29 03:29:17 +00003509 """Format a Decimal instance according to the given specifier.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003510
3511 The specifier should be a standard format specifier, with the
3512 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3513 'F', 'g', 'G', and '%' are supported. If the formatting type
3514 is omitted it defaults to 'g' or 'G', depending on the value
3515 of context.capitals.
3516
3517 At this time the 'n' format specifier type (which is supposed
3518 to use the current locale) is not supported.
3519 """
3520
3521 # Note: PEP 3101 says that if the type is not present then
3522 # there should be at least one digit after the decimal point.
3523 # We take the liberty of ignoring this requirement for
3524 # Decimal---it's presumably there to make sure that
3525 # format(float, '') behaves similarly to str(float).
3526 if context is None:
3527 context = getcontext()
3528
3529 spec = _parse_format_specifier(specifier)
3530
3531 # special values don't care about the type or precision...
3532 if self._is_special:
3533 return _format_align(str(self), spec)
3534
3535 # a type of None defaults to 'g' or 'G', depending on context
3536 # if type is '%', adjust exponent of self accordingly
3537 if spec['type'] is None:
3538 spec['type'] = ['g', 'G'][context.capitals]
3539 elif spec['type'] == '%':
3540 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3541
3542 # round if necessary, taking rounding mode from the context
3543 rounding = context.rounding
3544 precision = spec['precision']
3545 if precision is not None:
3546 if spec['type'] in 'eE':
3547 self = self._round(precision+1, rounding)
3548 elif spec['type'] in 'gG':
3549 if len(self._int) > precision:
3550 self = self._round(precision, rounding)
3551 elif spec['type'] in 'fF%':
3552 self = self._rescale(-precision, rounding)
3553 # special case: zeros with a positive exponent can't be
3554 # represented in fixed point; rescale them to 0e0.
3555 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3556 self = self._rescale(0, rounding)
3557
3558 # figure out placement of the decimal point
3559 leftdigits = self._exp + len(self._int)
3560 if spec['type'] in 'fF%':
3561 dotplace = leftdigits
3562 elif spec['type'] in 'eE':
3563 if not self and precision is not None:
3564 dotplace = 1 - precision
3565 else:
3566 dotplace = 1
3567 elif spec['type'] in 'gG':
3568 if self._exp <= 0 and leftdigits > -6:
3569 dotplace = leftdigits
3570 else:
3571 dotplace = 1
3572
3573 # figure out main part of numeric string...
3574 if dotplace <= 0:
3575 num = '0.' + '0'*(-dotplace) + self._int
3576 elif dotplace >= len(self._int):
3577 # make sure we're not padding a '0' with extra zeros on the right
3578 assert dotplace==len(self._int) or self._int != '0'
3579 num = self._int + '0'*(dotplace-len(self._int))
3580 else:
3581 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3582
3583 # ...then the trailing exponent, or trailing '%'
3584 if leftdigits != dotplace or spec['type'] in 'eE':
3585 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3586 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3587 elif spec['type'] == '%':
3588 num = num + '%'
3589
3590 # add sign
3591 if self._sign == 1:
3592 num = '-' + num
3593 return _format_align(num, spec)
3594
3595
Facundo Batista72bc54f2007-11-23 17:59:00 +00003596def _dec_from_triple(sign, coefficient, exponent, special=False):
3597 """Create a decimal instance directly, without any validation,
3598 normalization (e.g. removal of leading zeros) or argument
3599 conversion.
3600
3601 This function is for *internal use only*.
3602 """
3603
3604 self = object.__new__(Decimal)
3605 self._sign = sign
3606 self._int = coefficient
3607 self._exp = exponent
3608 self._is_special = special
3609
3610 return self
3611
Raymond Hettinger2c8585b2009-02-03 03:37:03 +00003612# Register Decimal as a kind of Number (an abstract base class).
3613# However, do not register it as Real (because Decimals are not
3614# interoperable with floats).
3615_numbers.Number.register(Decimal)
3616
3617
Facundo Batista59c58842007-04-10 12:58:45 +00003618##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003619
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003620
3621# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003622rounding_functions = [name for name in Decimal.__dict__.keys()
3623 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003624for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003625 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003626 globalname = name[1:].upper()
3627 val = globals()[globalname]
3628 Decimal._pick_rounding_function[val] = name
3629
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003630del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003631
Nick Coghlanced12182006-09-02 03:54:17 +00003632class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003633 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003634
Nick Coghlanced12182006-09-02 03:54:17 +00003635 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003636 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003637 """
3638 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003639 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003640 def __enter__(self):
3641 self.saved_context = getcontext()
3642 setcontext(self.new_context)
3643 return self.new_context
3644 def __exit__(self, t, v, tb):
3645 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003646
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003647class Context(object):
3648 """Contains the context for a Decimal instance.
3649
3650 Contains:
3651 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003652 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003653 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003654 raised when it is caused. Otherwise, a value is
3655 substituted in.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003656 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003657 (Whether or not the trap_enabler is set)
3658 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003659 Emin - Minimum exponent
3660 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003661 capitals - If 1, 1*10^1 is printed as 1E+1.
3662 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003663 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003664 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003665
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003666 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003667 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003668 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003669 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003670 _ignored_flags=None):
3671 if flags is None:
3672 flags = []
3673 if _ignored_flags is None:
3674 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003675 if not isinstance(flags, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003676 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003677 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003678 if traps is not None and not isinstance(traps, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003679 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003680 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003681 for name, val in locals().items():
3682 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003683 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003684 else:
3685 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003686 del self.self
3687
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003688 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003689 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003690 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003691 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3692 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3693 % vars(self))
3694 names = [f.__name__ for f, v in self.flags.items() if v]
3695 s.append('flags=[' + ', '.join(names) + ']')
3696 names = [t.__name__ for t, v in self.traps.items() if v]
3697 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003698 return ', '.join(s) + ')'
3699
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003700 def clear_flags(self):
3701 """Reset all flags to zero"""
3702 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003703 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003704
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003705 def _shallow_copy(self):
3706 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003707 nc = Context(self.prec, self.rounding, self.traps,
3708 self.flags, self.Emin, self.Emax,
3709 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003710 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003711
3712 def copy(self):
3713 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003714 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003715 self.flags.copy(), self.Emin, self.Emax,
3716 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003717 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003718 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003719
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003720 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003721 """Handles an error
3722
3723 If the flag is in _ignored_flags, returns the default response.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003724 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003725 trap_enabler is set, it reaises the exception. Otherwise, it returns
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003726 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003727 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003728 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003729 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003730 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003731 return error().handle(self, *args)
3732
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003733 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003734 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003735 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003736 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003737
3738 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003739 # self._ignored_flags = []
Mark Dickinson8aca9d02008-05-04 02:05:06 +00003740 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003741
3742 def _ignore_all_flags(self):
3743 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003744 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003745
3746 def _ignore_flags(self, *flags):
3747 """Ignore the flags, if they are raised"""
3748 # Do not mutate-- This way, copies of a context leave the original
3749 # alone.
3750 self._ignored_flags = (self._ignored_flags + list(flags))
3751 return list(flags)
3752
3753 def _regard_flags(self, *flags):
3754 """Stop ignoring the flags, if they are raised"""
3755 if flags and isinstance(flags[0], (tuple,list)):
3756 flags = flags[0]
3757 for flag in flags:
3758 self._ignored_flags.remove(flag)
3759
Nick Coghlan53663a62008-07-15 14:27:37 +00003760 # We inherit object.__hash__, so we must deny this explicitly
3761 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003762
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003763 def Etiny(self):
3764 """Returns Etiny (= Emin - prec + 1)"""
3765 return int(self.Emin - self.prec + 1)
3766
3767 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003768 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003769 return int(self.Emax - self.prec + 1)
3770
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003771 def _set_rounding(self, type):
3772 """Sets the rounding type.
3773
3774 Sets the rounding type, and returns the current (previous)
3775 rounding type. Often used like:
3776
3777 context = context.copy()
3778 # so you don't change the calling context
3779 # if an error occurs in the middle.
3780 rounding = context._set_rounding(ROUND_UP)
3781 val = self.__sub__(other, context=context)
3782 context._set_rounding(rounding)
3783
3784 This will make it round up for that operation.
3785 """
3786 rounding = self.rounding
3787 self.rounding= type
3788 return rounding
3789
Raymond Hettingerfed52962004-07-14 15:41:57 +00003790 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003791 """Creates a new Decimal instance but using self as context.
3792
3793 This method implements the to-number operation of the
3794 IBM Decimal specification."""
3795
3796 if isinstance(num, basestring) and num != num.strip():
3797 return self._raise_error(ConversionSyntax,
3798 "no trailing or leading whitespace is "
3799 "permitted.")
3800
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003801 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003802 if d._isnan() and len(d._int) > self.prec - self._clamp:
3803 return self._raise_error(ConversionSyntax,
3804 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003805 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003806
Raymond Hettingerf4d85972009-01-03 19:02:23 +00003807 def create_decimal_from_float(self, f):
3808 """Creates a new Decimal instance from a float but rounding using self
3809 as the context.
3810
3811 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3812 >>> context.create_decimal_from_float(3.1415926535897932)
3813 Decimal('3.1415')
3814 >>> context = Context(prec=5, traps=[Inexact])
3815 >>> context.create_decimal_from_float(3.1415926535897932)
3816 Traceback (most recent call last):
3817 ...
3818 Inexact: None
3819
3820 """
3821 d = Decimal.from_float(f) # An exact conversion
3822 return d._fix(self) # Apply the context rounding
3823
Facundo Batista59c58842007-04-10 12:58:45 +00003824 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003825 def abs(self, a):
3826 """Returns the absolute value of the operand.
3827
3828 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003829 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003830 the plus operation on the operand.
3831
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003832 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003833 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003834 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003835 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003836 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003837 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003838 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003839 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003840 """
3841 return a.__abs__(context=self)
3842
3843 def add(self, a, b):
3844 """Return the sum of the two operands.
3845
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003846 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003847 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003848 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003849 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003850 """
3851 return a.__add__(b, context=self)
3852
3853 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003854 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003855
Facundo Batista353750c2007-09-13 18:13:15 +00003856 def canonical(self, a):
3857 """Returns the same Decimal object.
3858
3859 As we do not have different encodings for the same number, the
3860 received object already is in its canonical form.
3861
3862 >>> ExtendedContext.canonical(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003863 Decimal('2.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003864 """
3865 return a.canonical(context=self)
3866
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003867 def compare(self, a, b):
3868 """Compares values numerically.
3869
3870 If the signs of the operands differ, a value representing each operand
3871 ('-1' if the operand is less than zero, '0' if the operand is zero or
3872 negative zero, or '1' if the operand is greater than zero) is used in
3873 place of that operand for the comparison instead of the actual
3874 operand.
3875
3876 The comparison is then effected by subtracting the second operand from
3877 the first and then returning a value according to the result of the
3878 subtraction: '-1' if the result is less than zero, '0' if the result is
3879 zero or negative zero, or '1' if the result is greater than zero.
3880
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003881 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003882 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003883 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003884 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003885 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003886 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003887 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003888 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003889 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003890 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003891 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003892 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003893 """
3894 return a.compare(b, context=self)
3895
Facundo Batista353750c2007-09-13 18:13:15 +00003896 def compare_signal(self, a, b):
3897 """Compares the values of the two operands numerically.
3898
3899 It's pretty much like compare(), but all NaNs signal, with signaling
3900 NaNs taking precedence over quiet NaNs.
3901
3902 >>> c = ExtendedContext
3903 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003904 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003905 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003906 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003907 >>> c.flags[InvalidOperation] = 0
3908 >>> print c.flags[InvalidOperation]
3909 0
3910 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003911 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003912 >>> print c.flags[InvalidOperation]
3913 1
3914 >>> c.flags[InvalidOperation] = 0
3915 >>> print c.flags[InvalidOperation]
3916 0
3917 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003918 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003919 >>> print c.flags[InvalidOperation]
3920 1
3921 """
3922 return a.compare_signal(b, context=self)
3923
3924 def compare_total(self, a, b):
3925 """Compares two operands using their abstract representation.
3926
3927 This is not like the standard compare, which use their numerical
3928 value. Note that a total ordering is defined for all possible abstract
3929 representations.
3930
3931 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003932 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003933 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003934 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003935 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003936 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003937 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003938 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003939 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003940 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00003941 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003942 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003943 """
3944 return a.compare_total(b)
3945
3946 def compare_total_mag(self, a, b):
3947 """Compares two operands using their abstract representation ignoring sign.
3948
3949 Like compare_total, but with operand's sign ignored and assumed to be 0.
3950 """
3951 return a.compare_total_mag(b)
3952
3953 def copy_abs(self, a):
3954 """Returns a copy of the operand with the sign set to 0.
3955
3956 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003957 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003958 >>> ExtendedContext.copy_abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003959 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00003960 """
3961 return a.copy_abs()
3962
3963 def copy_decimal(self, a):
3964 """Returns a copy of the decimal objet.
3965
3966 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003967 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003968 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003969 Decimal('-1.00')
Facundo Batista353750c2007-09-13 18:13:15 +00003970 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003971 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003972
3973 def copy_negate(self, a):
3974 """Returns a copy of the operand with the sign inverted.
3975
3976 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003977 Decimal('-101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003978 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003979 Decimal('101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003980 """
3981 return a.copy_negate()
3982
3983 def copy_sign(self, a, b):
3984 """Copies the second operand's sign to the first one.
3985
3986 In detail, it returns a copy of the first operand with the sign
3987 equal to the sign of the second operand.
3988
3989 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003990 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003991 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003992 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003993 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003994 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003995 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003996 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003997 """
3998 return a.copy_sign(b)
3999
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004000 def divide(self, a, b):
4001 """Decimal division in a specified context.
4002
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004003 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004004 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004005 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004006 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004007 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004008 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004009 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004010 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004011 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004012 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004013 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004014 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004015 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004016 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004017 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004018 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004019 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004020 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004021 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004022 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004023 """
4024 return a.__div__(b, context=self)
4025
4026 def divide_int(self, a, b):
4027 """Divides two numbers and returns the integer part of the result.
4028
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004029 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004030 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004031 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004032 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004033 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004034 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004035 """
4036 return a.__floordiv__(b, context=self)
4037
4038 def divmod(self, a, b):
4039 return a.__divmod__(b, context=self)
4040
Facundo Batista353750c2007-09-13 18:13:15 +00004041 def exp(self, a):
4042 """Returns e ** a.
4043
4044 >>> c = ExtendedContext.copy()
4045 >>> c.Emin = -999
4046 >>> c.Emax = 999
4047 >>> c.exp(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004048 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004049 >>> c.exp(Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004050 Decimal('0.367879441')
Facundo Batista353750c2007-09-13 18:13:15 +00004051 >>> c.exp(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004052 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004053 >>> c.exp(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004054 Decimal('2.71828183')
Facundo Batista353750c2007-09-13 18:13:15 +00004055 >>> c.exp(Decimal('0.693147181'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004056 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004057 >>> c.exp(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004058 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004059 """
4060 return a.exp(context=self)
4061
4062 def fma(self, a, b, c):
4063 """Returns a multiplied by b, plus c.
4064
4065 The first two operands are multiplied together, using multiply,
4066 the third operand is then added to the result of that
4067 multiplication, using add, all with only one final rounding.
4068
4069 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004070 Decimal('22')
Facundo Batista353750c2007-09-13 18:13:15 +00004071 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004072 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004073 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004074 Decimal('1.38435736E+12')
Facundo Batista353750c2007-09-13 18:13:15 +00004075 """
4076 return a.fma(b, c, context=self)
4077
4078 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004079 """Return True if the operand is canonical; otherwise return False.
4080
4081 Currently, the encoding of a Decimal instance is always
4082 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00004083
4084 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004085 True
Facundo Batista353750c2007-09-13 18:13:15 +00004086 """
Facundo Batista1a191df2007-10-02 17:01:24 +00004087 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00004088
4089 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004090 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004091
Facundo Batista1a191df2007-10-02 17:01:24 +00004092 A Decimal instance is considered finite if it is neither
4093 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00004094
4095 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004096 True
Facundo Batista353750c2007-09-13 18:13:15 +00004097 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004098 True
Facundo Batista353750c2007-09-13 18:13:15 +00004099 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004100 True
Facundo Batista353750c2007-09-13 18:13:15 +00004101 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004102 False
Facundo Batista353750c2007-09-13 18:13:15 +00004103 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004104 False
Facundo Batista353750c2007-09-13 18:13:15 +00004105 """
4106 return a.is_finite()
4107
4108 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004109 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004110
4111 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004112 False
Facundo Batista353750c2007-09-13 18:13:15 +00004113 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004114 True
Facundo Batista353750c2007-09-13 18:13:15 +00004115 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004116 False
Facundo Batista353750c2007-09-13 18:13:15 +00004117 """
4118 return a.is_infinite()
4119
4120 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004121 """Return True if the operand is a qNaN or sNaN;
4122 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004123
4124 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004125 False
Facundo Batista353750c2007-09-13 18:13:15 +00004126 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004127 True
Facundo Batista353750c2007-09-13 18:13:15 +00004128 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004129 True
Facundo Batista353750c2007-09-13 18:13:15 +00004130 """
4131 return a.is_nan()
4132
4133 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004134 """Return True if the operand is a normal number;
4135 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004136
4137 >>> c = ExtendedContext.copy()
4138 >>> c.Emin = -999
4139 >>> c.Emax = 999
4140 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004141 True
Facundo Batista353750c2007-09-13 18:13:15 +00004142 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004143 False
Facundo Batista353750c2007-09-13 18:13:15 +00004144 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004145 False
Facundo Batista353750c2007-09-13 18:13:15 +00004146 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004147 False
Facundo Batista353750c2007-09-13 18:13:15 +00004148 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004149 False
Facundo Batista353750c2007-09-13 18:13:15 +00004150 """
4151 return a.is_normal(context=self)
4152
4153 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004154 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004155
4156 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004157 False
Facundo Batista353750c2007-09-13 18:13:15 +00004158 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004159 True
Facundo Batista353750c2007-09-13 18:13:15 +00004160 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004161 False
Facundo Batista353750c2007-09-13 18:13:15 +00004162 """
4163 return a.is_qnan()
4164
4165 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004166 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004167
4168 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004169 False
Facundo Batista353750c2007-09-13 18:13:15 +00004170 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004171 True
Facundo Batista353750c2007-09-13 18:13:15 +00004172 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004173 True
Facundo Batista353750c2007-09-13 18:13:15 +00004174 """
4175 return a.is_signed()
4176
4177 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004178 """Return True if the operand is a signaling NaN;
4179 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004180
4181 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004182 False
Facundo Batista353750c2007-09-13 18:13:15 +00004183 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004184 False
Facundo Batista353750c2007-09-13 18:13:15 +00004185 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004186 True
Facundo Batista353750c2007-09-13 18:13:15 +00004187 """
4188 return a.is_snan()
4189
4190 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004191 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004192
4193 >>> c = ExtendedContext.copy()
4194 >>> c.Emin = -999
4195 >>> c.Emax = 999
4196 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004197 False
Facundo Batista353750c2007-09-13 18:13:15 +00004198 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004199 True
Facundo Batista353750c2007-09-13 18:13:15 +00004200 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004201 False
Facundo Batista353750c2007-09-13 18:13:15 +00004202 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004203 False
Facundo Batista353750c2007-09-13 18:13:15 +00004204 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004205 False
Facundo Batista353750c2007-09-13 18:13:15 +00004206 """
4207 return a.is_subnormal(context=self)
4208
4209 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004210 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004211
4212 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004213 True
Facundo Batista353750c2007-09-13 18:13:15 +00004214 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004215 False
Facundo Batista353750c2007-09-13 18:13:15 +00004216 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004217 True
Facundo Batista353750c2007-09-13 18:13:15 +00004218 """
4219 return a.is_zero()
4220
4221 def ln(self, a):
4222 """Returns the natural (base e) logarithm of the operand.
4223
4224 >>> c = ExtendedContext.copy()
4225 >>> c.Emin = -999
4226 >>> c.Emax = 999
4227 >>> c.ln(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004228 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004229 >>> c.ln(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004230 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004231 >>> c.ln(Decimal('2.71828183'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004232 Decimal('1.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004233 >>> c.ln(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004234 Decimal('2.30258509')
Facundo Batista353750c2007-09-13 18:13:15 +00004235 >>> c.ln(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004236 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004237 """
4238 return a.ln(context=self)
4239
4240 def log10(self, a):
4241 """Returns the base 10 logarithm of the operand.
4242
4243 >>> c = ExtendedContext.copy()
4244 >>> c.Emin = -999
4245 >>> c.Emax = 999
4246 >>> c.log10(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004247 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004248 >>> c.log10(Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004249 Decimal('-3')
Facundo Batista353750c2007-09-13 18:13:15 +00004250 >>> c.log10(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004251 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004252 >>> c.log10(Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004253 Decimal('0.301029996')
Facundo Batista353750c2007-09-13 18:13:15 +00004254 >>> c.log10(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004255 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004256 >>> c.log10(Decimal('70'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004257 Decimal('1.84509804')
Facundo Batista353750c2007-09-13 18:13:15 +00004258 >>> c.log10(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004259 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004260 """
4261 return a.log10(context=self)
4262
4263 def logb(self, a):
4264 """ Returns the exponent of the magnitude of the operand's MSD.
4265
4266 The result is the integer which is the exponent of the magnitude
4267 of the most significant digit of the operand (as though the
4268 operand were truncated to a single digit while maintaining the
4269 value of that digit and without limiting the resulting exponent).
4270
4271 >>> ExtendedContext.logb(Decimal('250'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004272 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004273 >>> ExtendedContext.logb(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004274 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004275 >>> ExtendedContext.logb(Decimal('0.03'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004276 Decimal('-2')
Facundo Batista353750c2007-09-13 18:13:15 +00004277 >>> ExtendedContext.logb(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004278 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004279 """
4280 return a.logb(context=self)
4281
4282 def logical_and(self, a, b):
4283 """Applies the logical operation 'and' between each operand's digits.
4284
4285 The operands must be both logical numbers.
4286
4287 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004288 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004289 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004290 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004291 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004292 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004293 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004294 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004295 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004296 Decimal('1000')
Facundo Batista353750c2007-09-13 18:13:15 +00004297 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004298 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004299 """
4300 return a.logical_and(b, context=self)
4301
4302 def logical_invert(self, a):
4303 """Invert all the digits in the operand.
4304
4305 The operand must be a logical number.
4306
4307 >>> ExtendedContext.logical_invert(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004308 Decimal('111111111')
Facundo Batista353750c2007-09-13 18:13:15 +00004309 >>> ExtendedContext.logical_invert(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004310 Decimal('111111110')
Facundo Batista353750c2007-09-13 18:13:15 +00004311 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004312 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004313 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004314 Decimal('10101010')
Facundo Batista353750c2007-09-13 18:13:15 +00004315 """
4316 return a.logical_invert(context=self)
4317
4318 def logical_or(self, a, b):
4319 """Applies the logical operation 'or' between each operand's digits.
4320
4321 The operands must be both logical numbers.
4322
4323 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004324 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004325 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004326 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004327 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004328 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004329 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004330 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004331 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004332 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004333 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004334 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004335 """
4336 return a.logical_or(b, context=self)
4337
4338 def logical_xor(self, a, b):
4339 """Applies the logical operation 'xor' between each operand's digits.
4340
4341 The operands must be both logical numbers.
4342
4343 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004344 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004345 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004346 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004347 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004348 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004349 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004350 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004351 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004352 Decimal('110')
Facundo Batista353750c2007-09-13 18:13:15 +00004353 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004354 Decimal('1101')
Facundo Batista353750c2007-09-13 18:13:15 +00004355 """
4356 return a.logical_xor(b, context=self)
4357
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004358 def max(self, a,b):
4359 """max compares two values numerically and returns the maximum.
4360
4361 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004362 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004363 operation. If they are numerically equal then the left-hand operand
4364 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004365 infinity) of the two operands is chosen as the result.
4366
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004367 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004368 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004369 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004370 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004371 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004372 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004373 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004374 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004375 """
4376 return a.max(b, context=self)
4377
Facundo Batista353750c2007-09-13 18:13:15 +00004378 def max_mag(self, a, b):
4379 """Compares the values numerically with their sign ignored."""
4380 return a.max_mag(b, context=self)
4381
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004382 def min(self, a,b):
4383 """min compares two values numerically and returns the minimum.
4384
4385 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004386 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004387 operation. If they are numerically equal then the left-hand operand
4388 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004389 infinity) of the two operands is chosen as the result.
4390
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004391 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004392 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004393 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004394 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004395 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004396 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004397 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004398 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004399 """
4400 return a.min(b, context=self)
4401
Facundo Batista353750c2007-09-13 18:13:15 +00004402 def min_mag(self, a, b):
4403 """Compares the values numerically with their sign ignored."""
4404 return a.min_mag(b, context=self)
4405
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004406 def minus(self, a):
4407 """Minus corresponds to unary prefix minus in Python.
4408
4409 The operation is evaluated using the same rules as subtract; the
4410 operation minus(a) is calculated as subtract('0', a) where the '0'
4411 has the same exponent as the operand.
4412
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004413 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004414 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004415 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004416 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004417 """
4418 return a.__neg__(context=self)
4419
4420 def multiply(self, a, b):
4421 """multiply multiplies two operands.
4422
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004423 If either operand is a special value then the general rules apply.
4424 Otherwise, the operands are multiplied together ('long multiplication'),
4425 resulting in a number which may be as long as the sum of the lengths
4426 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004427
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004428 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004429 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004430 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004431 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004432 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004433 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004434 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004435 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004436 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004437 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004438 """
4439 return a.__mul__(b, context=self)
4440
Facundo Batista353750c2007-09-13 18:13:15 +00004441 def next_minus(self, a):
4442 """Returns the largest representable number smaller than a.
4443
4444 >>> c = ExtendedContext.copy()
4445 >>> c.Emin = -999
4446 >>> c.Emax = 999
4447 >>> ExtendedContext.next_minus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004448 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004449 >>> c.next_minus(Decimal('1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004450 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004451 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004452 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004453 >>> c.next_minus(Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004454 Decimal('9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004455 """
4456 return a.next_minus(context=self)
4457
4458 def next_plus(self, a):
4459 """Returns the smallest representable number larger than a.
4460
4461 >>> c = ExtendedContext.copy()
4462 >>> c.Emin = -999
4463 >>> c.Emax = 999
4464 >>> ExtendedContext.next_plus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004465 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004466 >>> c.next_plus(Decimal('-1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004467 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004468 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004469 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004470 >>> c.next_plus(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004471 Decimal('-9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004472 """
4473 return a.next_plus(context=self)
4474
4475 def next_toward(self, a, b):
4476 """Returns the number closest to a, in direction towards b.
4477
4478 The result is the closest representable number from the first
4479 operand (but not the first operand) that is in the direction
4480 towards the second operand, unless the operands have the same
4481 value.
4482
4483 >>> c = ExtendedContext.copy()
4484 >>> c.Emin = -999
4485 >>> c.Emax = 999
4486 >>> c.next_toward(Decimal('1'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004487 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004488 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004489 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004490 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004491 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004492 >>> c.next_toward(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004493 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004494 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004495 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004496 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004497 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004498 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004499 Decimal('-0.00')
Facundo Batista353750c2007-09-13 18:13:15 +00004500 """
4501 return a.next_toward(b, context=self)
4502
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004503 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004504 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004505
4506 Essentially a plus operation with all trailing zeros removed from the
4507 result.
4508
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004509 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004510 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004511 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004512 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004513 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004514 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004515 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004516 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004517 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004518 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004519 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004520 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004521 """
4522 return a.normalize(context=self)
4523
Facundo Batista353750c2007-09-13 18:13:15 +00004524 def number_class(self, a):
4525 """Returns an indication of the class of the operand.
4526
4527 The class is one of the following strings:
4528 -sNaN
4529 -NaN
4530 -Infinity
4531 -Normal
4532 -Subnormal
4533 -Zero
4534 +Zero
4535 +Subnormal
4536 +Normal
4537 +Infinity
4538
4539 >>> c = Context(ExtendedContext)
4540 >>> c.Emin = -999
4541 >>> c.Emax = 999
4542 >>> c.number_class(Decimal('Infinity'))
4543 '+Infinity'
4544 >>> c.number_class(Decimal('1E-10'))
4545 '+Normal'
4546 >>> c.number_class(Decimal('2.50'))
4547 '+Normal'
4548 >>> c.number_class(Decimal('0.1E-999'))
4549 '+Subnormal'
4550 >>> c.number_class(Decimal('0'))
4551 '+Zero'
4552 >>> c.number_class(Decimal('-0'))
4553 '-Zero'
4554 >>> c.number_class(Decimal('-0.1E-999'))
4555 '-Subnormal'
4556 >>> c.number_class(Decimal('-1E-10'))
4557 '-Normal'
4558 >>> c.number_class(Decimal('-2.50'))
4559 '-Normal'
4560 >>> c.number_class(Decimal('-Infinity'))
4561 '-Infinity'
4562 >>> c.number_class(Decimal('NaN'))
4563 'NaN'
4564 >>> c.number_class(Decimal('-NaN'))
4565 'NaN'
4566 >>> c.number_class(Decimal('sNaN'))
4567 'sNaN'
4568 """
4569 return a.number_class(context=self)
4570
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004571 def plus(self, a):
4572 """Plus corresponds to unary prefix plus in Python.
4573
4574 The operation is evaluated using the same rules as add; the
4575 operation plus(a) is calculated as add('0', a) where the '0'
4576 has the same exponent as the operand.
4577
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004578 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004579 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004580 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004581 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004582 """
4583 return a.__pos__(context=self)
4584
4585 def power(self, a, b, modulo=None):
4586 """Raises a to the power of b, to modulo if given.
4587
Facundo Batista353750c2007-09-13 18:13:15 +00004588 With two arguments, compute a**b. If a is negative then b
4589 must be integral. The result will be inexact unless b is
4590 integral and the result is finite and can be expressed exactly
4591 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004592
Facundo Batista353750c2007-09-13 18:13:15 +00004593 With three arguments, compute (a**b) % modulo. For the
4594 three argument form, the following restrictions on the
4595 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004596
Facundo Batista353750c2007-09-13 18:13:15 +00004597 - all three arguments must be integral
4598 - b must be nonnegative
4599 - at least one of a or b must be nonzero
4600 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004601
Facundo Batista353750c2007-09-13 18:13:15 +00004602 The result of pow(a, b, modulo) is identical to the result
4603 that would be obtained by computing (a**b) % modulo with
4604 unbounded precision, but is computed more efficiently. It is
4605 always exact.
4606
4607 >>> c = ExtendedContext.copy()
4608 >>> c.Emin = -999
4609 >>> c.Emax = 999
4610 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004611 Decimal('8')
Facundo Batista353750c2007-09-13 18:13:15 +00004612 >>> c.power(Decimal('-2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004613 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004614 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004615 Decimal('0.125')
Facundo Batista353750c2007-09-13 18:13:15 +00004616 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004617 Decimal('69.7575744')
Facundo Batista353750c2007-09-13 18:13:15 +00004618 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004619 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004620 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004621 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004622 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004623 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004624 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004625 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004626 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004627 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004628 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004629 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004630 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004631 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004632 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004633 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004634 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004635 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00004636
4637 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004638 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004639 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004640 Decimal('-11')
Facundo Batista353750c2007-09-13 18:13:15 +00004641 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004642 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004643 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004644 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004645 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004646 Decimal('11729830')
Facundo Batista353750c2007-09-13 18:13:15 +00004647 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004648 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004649 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004650 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004651 """
4652 return a.__pow__(b, modulo, context=self)
4653
4654 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004655 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004656
4657 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004658 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004659 exponent is being increased), multiplied by a positive power of ten (if
4660 the exponent is being decreased), or is unchanged (if the exponent is
4661 already equal to that of the right-hand operand).
4662
4663 Unlike other operations, if the length of the coefficient after the
4664 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004665 operation condition is raised. This guarantees that, unless there is
4666 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 equal to that of the right-hand operand.
4668
4669 Also unlike other operations, quantize will never raise Underflow, even
4670 if the result is subnormal and inexact.
4671
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004672 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004673 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004674 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004675 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004676 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004677 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004678 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004679 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004680 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004681 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004682 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004683 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004684 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004685 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004686 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004687 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004688 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004689 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004690 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004691 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004692 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004693 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004694 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004695 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004696 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004697 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004698 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004699 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004700 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004701 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004702 """
4703 return a.quantize(b, context=self)
4704
Facundo Batista353750c2007-09-13 18:13:15 +00004705 def radix(self):
4706 """Just returns 10, as this is Decimal, :)
4707
4708 >>> ExtendedContext.radix()
Raymond Hettingerabe32372008-02-14 02:41:22 +00004709 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004710 """
4711 return Decimal(10)
4712
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004713 def remainder(self, a, b):
4714 """Returns the remainder from integer division.
4715
4716 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004717 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004718 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004719 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004720
4721 This operation will fail under the same conditions as integer division
4722 (that is, if integer division on the same two operands would fail, the
4723 remainder cannot be calculated).
4724
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004725 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004726 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004727 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004728 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004729 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004730 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004731 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004732 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004733 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004734 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004735 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004736 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004737 """
4738 return a.__mod__(b, context=self)
4739
4740 def remainder_near(self, a, b):
4741 """Returns to be "a - b * n", where n is the integer nearest the exact
4742 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004743 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004744 sign of a.
4745
4746 This operation will fail under the same conditions as integer division
4747 (that is, if integer division on the same two operands would fail, the
4748 remainder cannot be calculated).
4749
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004750 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004751 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004752 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004753 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004754 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004755 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004756 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004757 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004758 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004759 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004760 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004761 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004762 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004763 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004764 """
4765 return a.remainder_near(b, context=self)
4766
Facundo Batista353750c2007-09-13 18:13:15 +00004767 def rotate(self, a, b):
4768 """Returns a rotated copy of a, b times.
4769
4770 The coefficient of the result is a rotated copy of the digits in
4771 the coefficient of the first operand. The number of places of
4772 rotation is taken from the absolute value of the second operand,
4773 with the rotation being to the left if the second operand is
4774 positive or to the right otherwise.
4775
4776 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004777 Decimal('400000003')
Facundo Batista353750c2007-09-13 18:13:15 +00004778 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004779 Decimal('12')
Facundo Batista353750c2007-09-13 18:13:15 +00004780 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004781 Decimal('891234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004782 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004783 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004784 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004785 Decimal('345678912')
Facundo Batista353750c2007-09-13 18:13:15 +00004786 """
4787 return a.rotate(b, context=self)
4788
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004789 def same_quantum(self, a, b):
4790 """Returns True if the two operands have the same exponent.
4791
4792 The result is never affected by either the sign or the coefficient of
4793 either operand.
4794
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004795 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004796 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004797 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004798 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004799 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004800 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004801 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004802 True
4803 """
4804 return a.same_quantum(b)
4805
Facundo Batista353750c2007-09-13 18:13:15 +00004806 def scaleb (self, a, b):
4807 """Returns the first operand after adding the second value its exp.
4808
4809 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004810 Decimal('0.0750')
Facundo Batista353750c2007-09-13 18:13:15 +00004811 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004812 Decimal('7.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004813 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004814 Decimal('7.50E+3')
Facundo Batista353750c2007-09-13 18:13:15 +00004815 """
4816 return a.scaleb (b, context=self)
4817
4818 def shift(self, a, b):
4819 """Returns a shifted copy of a, b times.
4820
4821 The coefficient of the result is a shifted copy of the digits
4822 in the coefficient of the first operand. The number of places
4823 to shift is taken from the absolute value of the second operand,
4824 with the shift being to the left if the second operand is
4825 positive or to the right otherwise. Digits shifted into the
4826 coefficient are zeros.
4827
4828 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004829 Decimal('400000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004830 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004831 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004832 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004833 Decimal('1234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004834 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004835 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004836 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004837 Decimal('345678900')
Facundo Batista353750c2007-09-13 18:13:15 +00004838 """
4839 return a.shift(b, context=self)
4840
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004841 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004842 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004843
4844 If the result must be inexact, it is rounded using the round-half-even
4845 algorithm.
4846
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004847 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004848 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004849 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004850 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004851 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004852 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004853 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004854 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004855 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004856 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004857 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004858 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004859 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004860 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004861 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004862 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004863 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004864 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004865 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004866 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004867 """
4868 return a.sqrt(context=self)
4869
4870 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004871 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004872
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004873 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004874 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004875 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004876 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004877 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004878 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004879 """
4880 return a.__sub__(b, context=self)
4881
4882 def to_eng_string(self, a):
4883 """Converts a number to a string, using scientific notation.
4884
4885 The operation is not affected by the context.
4886 """
4887 return a.to_eng_string(context=self)
4888
4889 def to_sci_string(self, a):
4890 """Converts a number to a string, using scientific notation.
4891
4892 The operation is not affected by the context.
4893 """
4894 return a.__str__(context=self)
4895
Facundo Batista353750c2007-09-13 18:13:15 +00004896 def to_integral_exact(self, a):
4897 """Rounds to an integer.
4898
4899 When the operand has a negative exponent, the result is the same
4900 as using the quantize() operation using the given operand as the
4901 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4902 of the operand as the precision setting; Inexact and Rounded flags
4903 are allowed in this operation. The rounding mode is taken from the
4904 context.
4905
4906 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004907 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004908 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004909 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004910 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004911 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004912 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004913 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004914 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004915 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004916 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004917 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004918 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004919 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004920 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004921 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004922 """
4923 return a.to_integral_exact(context=self)
4924
4925 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004926 """Rounds to an integer.
4927
4928 When the operand has a negative exponent, the result is the same
4929 as using the quantize() operation using the given operand as the
4930 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4931 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004932 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004933
Facundo Batista353750c2007-09-13 18:13:15 +00004934 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004935 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004936 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004937 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004938 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004939 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004940 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004941 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004942 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004943 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004944 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004945 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004946 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004947 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004948 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004949 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004950 """
Facundo Batista353750c2007-09-13 18:13:15 +00004951 return a.to_integral_value(context=self)
4952
4953 # the method name changed, but we provide also the old one, for compatibility
4954 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004955
4956class _WorkRep(object):
4957 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004958 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004959 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004960 # exp: None, int, or string
4961
4962 def __init__(self, value=None):
4963 if value is None:
4964 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004965 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004966 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004967 elif isinstance(value, Decimal):
4968 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004969 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004970 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004971 else:
4972 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004973 self.sign = value[0]
4974 self.int = value[1]
4975 self.exp = value[2]
4976
4977 def __repr__(self):
4978 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4979
4980 __str__ = __repr__
4981
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004982
4983
Facundo Batistae64acfa2007-12-17 14:18:42 +00004984def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004985 """Normalizes op1, op2 to have the same exp and length of coefficient.
4986
4987 Done during addition.
4988 """
Facundo Batista353750c2007-09-13 18:13:15 +00004989 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004990 tmp = op2
4991 other = op1
4992 else:
4993 tmp = op1
4994 other = op2
4995
Facundo Batista353750c2007-09-13 18:13:15 +00004996 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4997 # Then adding 10**exp to tmp has the same effect (after rounding)
4998 # as adding any positive quantity smaller than 10**exp; similarly
4999 # for subtraction. So if other is smaller than 10**exp we replace
5000 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00005001 tmp_len = len(str(tmp.int))
5002 other_len = len(str(other.int))
5003 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5004 if other_len + other.exp - 1 < exp:
5005 other.int = 1
5006 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005007
Facundo Batista353750c2007-09-13 18:13:15 +00005008 tmp.int *= 10 ** (tmp.exp - other.exp)
5009 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005010 return op1, op2
5011
Facundo Batista353750c2007-09-13 18:13:15 +00005012##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
5013
5014# This function from Tim Peters was taken from here:
5015# http://mail.python.org/pipermail/python-list/1999-July/007758.html
5016# The correction being in the function definition is for speed, and
5017# the whole function is not resolved with math.log because of avoiding
5018# the use of floats.
5019def _nbits(n, correction = {
5020 '0': 4, '1': 3, '2': 2, '3': 2,
5021 '4': 1, '5': 1, '6': 1, '7': 1,
5022 '8': 0, '9': 0, 'a': 0, 'b': 0,
5023 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5024 """Number of bits in binary representation of the positive integer n,
5025 or 0 if n == 0.
5026 """
5027 if n < 0:
5028 raise ValueError("The argument to _nbits should be nonnegative.")
5029 hex_n = "%x" % n
5030 return 4*len(hex_n) - correction[hex_n[0]]
5031
5032def _sqrt_nearest(n, a):
5033 """Closest integer to the square root of the positive integer n. a is
5034 an initial approximation to the square root. Any positive integer
5035 will do for a, but the closer a is to the square root of n the
5036 faster convergence will be.
5037
5038 """
5039 if n <= 0 or a <= 0:
5040 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5041
5042 b=0
5043 while a != b:
5044 b, a = a, a--n//a>>1
5045 return a
5046
5047def _rshift_nearest(x, shift):
5048 """Given an integer x and a nonnegative integer shift, return closest
5049 integer to x / 2**shift; use round-to-even in case of a tie.
5050
5051 """
5052 b, q = 1L << shift, x >> shift
5053 return q + (2*(x & (b-1)) + (q&1) > b)
5054
5055def _div_nearest(a, b):
5056 """Closest integer to a/b, a and b positive integers; rounds to even
5057 in the case of a tie.
5058
5059 """
5060 q, r = divmod(a, b)
5061 return q + (2*r + (q&1) > b)
5062
5063def _ilog(x, M, L = 8):
5064 """Integer approximation to M*log(x/M), with absolute error boundable
5065 in terms only of x/M.
5066
5067 Given positive integers x and M, return an integer approximation to
5068 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5069 between the approximation and the exact result is at most 22. For
5070 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5071 both cases these are upper bounds on the error; it will usually be
5072 much smaller."""
5073
5074 # The basic algorithm is the following: let log1p be the function
5075 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5076 # the reduction
5077 #
5078 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5079 #
5080 # repeatedly until the argument to log1p is small (< 2**-L in
5081 # absolute value). For small y we can use the Taylor series
5082 # expansion
5083 #
5084 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5085 #
5086 # truncating at T such that y**T is small enough. The whole
5087 # computation is carried out in a form of fixed-point arithmetic,
5088 # with a real number z being represented by an integer
5089 # approximation to z*M. To avoid loss of precision, the y below
5090 # is actually an integer approximation to 2**R*y*M, where R is the
5091 # number of reductions performed so far.
5092
5093 y = x-M
5094 # argument reduction; R = number of reductions performed
5095 R = 0
5096 while (R <= L and long(abs(y)) << L-R >= M or
5097 R > L and abs(y) >> R-L >= M):
5098 y = _div_nearest(long(M*y) << 1,
5099 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5100 R += 1
5101
5102 # Taylor series with T terms
5103 T = -int(-10*len(str(M))//(3*L))
5104 yshift = _rshift_nearest(y, R)
5105 w = _div_nearest(M, T)
5106 for k in xrange(T-1, 0, -1):
5107 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5108
5109 return _div_nearest(w*y, M)
5110
5111def _dlog10(c, e, p):
5112 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5113 approximation to 10**p * log10(c*10**e), with an absolute error of
5114 at most 1. Assumes that c*10**e is not exactly 1."""
5115
5116 # increase precision by 2; compensate for this by dividing
5117 # final result by 100
5118 p += 2
5119
5120 # write c*10**e as d*10**f with either:
5121 # f >= 0 and 1 <= d <= 10, or
5122 # f <= 0 and 0.1 <= d <= 1.
5123 # Thus for c*10**e close to 1, f = 0
5124 l = len(str(c))
5125 f = e+l - (e+l >= 1)
5126
5127 if p > 0:
5128 M = 10**p
5129 k = e+p-f
5130 if k >= 0:
5131 c *= 10**k
5132 else:
5133 c = _div_nearest(c, 10**-k)
5134
5135 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005136 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005137 log_d = _div_nearest(log_d*M, log_10)
5138 log_tenpower = f*M # exact
5139 else:
5140 log_d = 0 # error < 2.31
Neal Norwitz18aa3882008-08-24 05:04:52 +00005141 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Facundo Batista353750c2007-09-13 18:13:15 +00005142
5143 return _div_nearest(log_tenpower+log_d, 100)
5144
5145def _dlog(c, e, p):
5146 """Given integers c, e and p with c > 0, compute an integer
5147 approximation to 10**p * log(c*10**e), with an absolute error of
5148 at most 1. Assumes that c*10**e is not exactly 1."""
5149
5150 # Increase precision by 2. The precision increase is compensated
5151 # for at the end with a division by 100.
5152 p += 2
5153
5154 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5155 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5156 # as 10**p * log(d) + 10**p*f * log(10).
5157 l = len(str(c))
5158 f = e+l - (e+l >= 1)
5159
5160 # compute approximation to 10**p*log(d), with error < 27
5161 if p > 0:
5162 k = e+p-f
5163 if k >= 0:
5164 c *= 10**k
5165 else:
5166 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5167
5168 # _ilog magnifies existing error in c by a factor of at most 10
5169 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5170 else:
5171 # p <= 0: just approximate the whole thing by 0; error < 2.31
5172 log_d = 0
5173
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005174 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00005175 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005176 extra = len(str(abs(f)))-1
5177 if p + extra >= 0:
5178 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5179 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5180 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00005181 else:
5182 f_log_ten = 0
5183 else:
5184 f_log_ten = 0
5185
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005186 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005187 return _div_nearest(f_log_ten + log_d, 100)
5188
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005189class _Log10Memoize(object):
5190 """Class to compute, store, and allow retrieval of, digits of the
5191 constant log(10) = 2.302585.... This constant is needed by
5192 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5193 def __init__(self):
5194 self.digits = "23025850929940456840179914546843642076011014886"
5195
5196 def getdigits(self, p):
5197 """Given an integer p >= 0, return floor(10**p)*log(10).
5198
5199 For example, self.getdigits(3) returns 2302.
5200 """
5201 # digits are stored as a string, for quick conversion to
5202 # integer in the case that we've already computed enough
5203 # digits; the stored digits should always be correct
5204 # (truncated, not rounded to nearest).
5205 if p < 0:
5206 raise ValueError("p should be nonnegative")
5207
5208 if p >= len(self.digits):
5209 # compute p+3, p+6, p+9, ... digits; continue until at
5210 # least one of the extra digits is nonzero
5211 extra = 3
5212 while True:
5213 # compute p+extra digits, correct to within 1ulp
5214 M = 10**(p+extra+2)
5215 digits = str(_div_nearest(_ilog(10*M, M), 100))
5216 if digits[-extra:] != '0'*extra:
5217 break
5218 extra += 3
5219 # keep all reliable digits so far; remove trailing zeros
5220 # and next nonzero digit
5221 self.digits = digits.rstrip('0')[:-1]
5222 return int(self.digits[:p+1])
5223
5224_log10_digits = _Log10Memoize().getdigits
5225
Facundo Batista353750c2007-09-13 18:13:15 +00005226def _iexp(x, M, L=8):
5227 """Given integers x and M, M > 0, such that x/M is small in absolute
5228 value, compute an integer approximation to M*exp(x/M). For 0 <=
5229 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5230 is usually much smaller)."""
5231
5232 # Algorithm: to compute exp(z) for a real number z, first divide z
5233 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5234 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5235 # series
5236 #
5237 # expm1(x) = x + x**2/2! + x**3/3! + ...
5238 #
5239 # Now use the identity
5240 #
5241 # expm1(2x) = expm1(x)*(expm1(x)+2)
5242 #
5243 # R times to compute the sequence expm1(z/2**R),
5244 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5245
5246 # Find R such that x/2**R/M <= 2**-L
5247 R = _nbits((long(x)<<L)//M)
5248
5249 # Taylor series. (2**L)**T > M
5250 T = -int(-10*len(str(M))//(3*L))
5251 y = _div_nearest(x, T)
5252 Mshift = long(M)<<R
5253 for i in xrange(T-1, 0, -1):
5254 y = _div_nearest(x*(Mshift + y), Mshift * i)
5255
5256 # Expansion
5257 for k in xrange(R-1, -1, -1):
5258 Mshift = long(M)<<(k+2)
5259 y = _div_nearest(y*(y+Mshift), Mshift)
5260
5261 return M+y
5262
5263def _dexp(c, e, p):
5264 """Compute an approximation to exp(c*10**e), with p decimal places of
5265 precision.
5266
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005267 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005268
5269 10**(p-1) <= d <= 10**p, and
5270 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5271
5272 In other words, d*10**f is an approximation to exp(c*10**e) with p
5273 digits of precision, and with an error in d of at most 1. This is
5274 almost, but not quite, the same as the error being < 1ulp: when d
5275 = 10**(p-1) the error could be up to 10 ulp."""
5276
5277 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5278 p += 2
5279
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005280 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005281 extra = max(0, e + len(str(c)) - 1)
5282 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005283
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005284 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005285 # rounding down
5286 shift = e+q
5287 if shift >= 0:
5288 cshift = c*10**shift
5289 else:
5290 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005291 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005292
5293 # reduce remainder back to original precision
5294 rem = _div_nearest(rem, 10**extra)
5295
5296 # error in result of _iexp < 120; error after division < 0.62
5297 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5298
5299def _dpower(xc, xe, yc, ye, p):
5300 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5301 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5302
5303 10**(p-1) <= c <= 10**p, and
5304 (c-1)*10**e < x**y < (c+1)*10**e
5305
5306 in other words, c*10**e is an approximation to x**y with p digits
5307 of precision, and with an error in c of at most 1. (This is
5308 almost, but not quite, the same as the error being < 1ulp: when c
5309 == 10**(p-1) we can only guarantee error < 10ulp.)
5310
5311 We assume that: x is positive and not equal to 1, and y is nonzero.
5312 """
5313
5314 # Find b such that 10**(b-1) <= |y| <= 10**b
5315 b = len(str(abs(yc))) + ye
5316
5317 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5318 lxc = _dlog(xc, xe, p+b+1)
5319
5320 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5321 shift = ye-b
5322 if shift >= 0:
5323 pc = lxc*yc*10**shift
5324 else:
5325 pc = _div_nearest(lxc*yc, 10**-shift)
5326
5327 if pc == 0:
5328 # we prefer a result that isn't exactly 1; this makes it
5329 # easier to compute a correctly rounded result in __pow__
5330 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5331 coeff, exp = 10**(p-1)+1, 1-p
5332 else:
5333 coeff, exp = 10**p-1, -p
5334 else:
5335 coeff, exp = _dexp(pc, -(p+1), p+1)
5336 coeff = _div_nearest(coeff, 10)
5337 exp += 1
5338
5339 return coeff, exp
5340
5341def _log10_lb(c, correction = {
5342 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5343 '6': 23, '7': 16, '8': 10, '9': 5}):
5344 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5345 if c <= 0:
5346 raise ValueError("The argument to _log10_lb should be nonnegative.")
5347 str_c = str(c)
5348 return 100*len(str_c) - correction[str_c[0]]
5349
Facundo Batista59c58842007-04-10 12:58:45 +00005350##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005351
Facundo Batista353750c2007-09-13 18:13:15 +00005352def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005353 """Convert other to Decimal.
5354
5355 Verifies that it's ok to use in an implicit construction.
5356 """
5357 if isinstance(other, Decimal):
5358 return other
5359 if isinstance(other, (int, long)):
5360 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005361 if raiseit:
5362 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005363 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005364
Facundo Batista59c58842007-04-10 12:58:45 +00005365##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005366
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005367# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005368# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005369
5370DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005371 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005372 traps=[DivisionByZero, Overflow, InvalidOperation],
5373 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005374 Emax=999999999,
5375 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005376 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005377)
5378
5379# Pre-made alternate contexts offered by the specification
5380# Don't change these; the user should be able to select these
5381# contexts and be able to reproduce results from other implementations
5382# of the spec.
5383
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005384BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005385 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005386 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5387 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005388)
5389
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005390ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005391 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005392 traps=[],
5393 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005394)
5395
5396
Facundo Batista72bc54f2007-11-23 17:59:00 +00005397##### crud for parsing strings #############################################
Mark Dickinson6a123cb2008-02-24 18:12:36 +00005398#
Facundo Batista72bc54f2007-11-23 17:59:00 +00005399# Regular expression used for parsing numeric strings. Additional
5400# comments:
5401#
5402# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5403# whitespace. But note that the specification disallows whitespace in
5404# a numeric string.
5405#
5406# 2. For finite numbers (not infinities and NaNs) the body of the
5407# number between the optional sign and the optional exponent must have
5408# at least one decimal digit, possibly after the decimal point. The
5409# lookahead expression '(?=\d|\.\d)' checks this.
5410#
5411# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5412# other meaning for \d than the numbers [0-9].
5413
5414import re
Mark Dickinson70c32892008-07-02 09:37:01 +00005415_parser = re.compile(r""" # A numeric string consists of:
Facundo Batista72bc54f2007-11-23 17:59:00 +00005416# \s*
Mark Dickinson70c32892008-07-02 09:37:01 +00005417 (?P<sign>[-+])? # an optional sign, followed by either...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005418 (
Mark Dickinson70c32892008-07-02 09:37:01 +00005419 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5420 (?P<int>[0-9]*) # having a (possibly empty) integer part
5421 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5422 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005423 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005424 Inf(inity)? # ...an infinity, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005425 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005426 (?P<signal>s)? # ...an (optionally signaling)
5427 NaN # NaN
5428 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005429 )
5430# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005431 \Z
Facundo Batista72bc54f2007-11-23 17:59:00 +00005432""", re.VERBOSE | re.IGNORECASE).match
5433
Facundo Batista2ec74152007-12-03 17:55:00 +00005434_all_zeros = re.compile('0*$').match
5435_exact_half = re.compile('50*$').match
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005436
5437##### PEP3101 support functions ##############################################
5438# The functions parse_format_specifier and format_align have little to do
5439# with the Decimal class, and could potentially be reused for other pure
5440# Python numeric classes that want to implement __format__
5441#
5442# A format specifier for Decimal looks like:
5443#
5444# [[fill]align][sign][0][minimumwidth][.precision][type]
5445#
5446
5447_parse_format_specifier_regex = re.compile(r"""\A
5448(?:
5449 (?P<fill>.)?
5450 (?P<align>[<>=^])
5451)?
5452(?P<sign>[-+ ])?
5453(?P<zeropad>0)?
5454(?P<minimumwidth>(?!0)\d+)?
5455(?:\.(?P<precision>0|(?!0)\d+))?
5456(?P<type>[eEfFgG%])?
5457\Z
5458""", re.VERBOSE)
5459
Facundo Batista72bc54f2007-11-23 17:59:00 +00005460del re
5461
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005462def _parse_format_specifier(format_spec):
5463 """Parse and validate a format specifier.
5464
5465 Turns a standard numeric format specifier into a dict, with the
5466 following entries:
5467
5468 fill: fill character to pad field to minimum width
5469 align: alignment type, either '<', '>', '=' or '^'
5470 sign: either '+', '-' or ' '
5471 minimumwidth: nonnegative integer giving minimum width
5472 precision: nonnegative integer giving precision, or None
5473 type: one of the characters 'eEfFgG%', or None
5474 unicode: either True or False (always True for Python 3.x)
5475
5476 """
5477 m = _parse_format_specifier_regex.match(format_spec)
5478 if m is None:
5479 raise ValueError("Invalid format specifier: " + format_spec)
5480
5481 # get the dictionary
5482 format_dict = m.groupdict()
5483
5484 # defaults for fill and alignment
5485 fill = format_dict['fill']
5486 align = format_dict['align']
5487 if format_dict.pop('zeropad') is not None:
5488 # in the face of conflict, refuse the temptation to guess
5489 if fill is not None and fill != '0':
5490 raise ValueError("Fill character conflicts with '0'"
5491 " in format specifier: " + format_spec)
5492 if align is not None and align != '=':
5493 raise ValueError("Alignment conflicts with '0' in "
5494 "format specifier: " + format_spec)
5495 fill = '0'
5496 align = '='
5497 format_dict['fill'] = fill or ' '
5498 format_dict['align'] = align or '<'
5499
5500 if format_dict['sign'] is None:
5501 format_dict['sign'] = '-'
5502
5503 # turn minimumwidth and precision entries into integers.
5504 # minimumwidth defaults to 0; precision remains None if not given
5505 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5506 if format_dict['precision'] is not None:
5507 format_dict['precision'] = int(format_dict['precision'])
5508
5509 # if format type is 'g' or 'G' then a precision of 0 makes little
5510 # sense; convert it to 1. Same if format type is unspecified.
5511 if format_dict['precision'] == 0:
5512 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5513 format_dict['precision'] = 1
5514
5515 # record whether return type should be str or unicode
5516 format_dict['unicode'] = isinstance(format_spec, unicode)
5517
5518 return format_dict
5519
5520def _format_align(body, spec_dict):
5521 """Given an unpadded, non-aligned numeric string, add padding and
5522 aligment to conform with the given format specifier dictionary (as
5523 output from parse_format_specifier).
5524
5525 It's assumed that if body is negative then it starts with '-'.
5526 Any leading sign ('-' or '+') is stripped from the body before
5527 applying the alignment and padding rules, and replaced in the
5528 appropriate position.
5529
5530 """
5531 # figure out the sign; we only examine the first character, so if
5532 # body has leading whitespace the results may be surprising.
5533 if len(body) > 0 and body[0] in '-+':
5534 sign = body[0]
5535 body = body[1:]
5536 else:
5537 sign = ''
5538
5539 if sign != '-':
5540 if spec_dict['sign'] in ' +':
5541 sign = spec_dict['sign']
5542 else:
5543 sign = ''
5544
5545 # how much extra space do we have to play with?
5546 minimumwidth = spec_dict['minimumwidth']
5547 fill = spec_dict['fill']
5548 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5549
5550 align = spec_dict['align']
5551 if align == '<':
5552 result = padding + sign + body
5553 elif align == '>':
5554 result = sign + body + padding
5555 elif align == '=':
5556 result = sign + padding + body
5557 else: #align == '^'
5558 half = len(padding)//2
5559 result = padding[:half] + sign + body + padding[half:]
5560
5561 # make sure that result is unicode if necessary
5562 if spec_dict['unicode']:
5563 result = unicode(result)
5564
5565 return result
Facundo Batista72bc54f2007-11-23 17:59:00 +00005566
Facundo Batista59c58842007-04-10 12:58:45 +00005567##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005568
Facundo Batista59c58842007-04-10 12:58:45 +00005569# Reusable defaults
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00005570_Infinity = Decimal('Inf')
5571_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonc5de0962009-01-02 23:07:08 +00005572_NaN = Decimal('NaN')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00005573_Zero = Decimal(0)
5574_One = Decimal(1)
5575_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005576
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00005577# _SignedInfinity[sign] is infinity w/ that sign
5578_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005579
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005580
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005581
5582if __name__ == '__main__':
5583 import doctest, sys
5584 doctest.testmod(sys.modules[__name__])