blob: 4140bea2f214bee00a37b5b853980f74c16aafab [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 Hettinger7c85fa42004-07-01 11:01:35 +0000139
Raymond Hettinger097a1902008-01-11 02:24:13 +0000140try:
141 from collections import namedtuple as _namedtuple
142 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
143except ImportError:
144 DecimalTuple = lambda *args: args
145
Facundo Batista59c58842007-04-10 12:58:45 +0000146# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000147ROUND_DOWN = 'ROUND_DOWN'
148ROUND_HALF_UP = 'ROUND_HALF_UP'
149ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
150ROUND_CEILING = 'ROUND_CEILING'
151ROUND_FLOOR = 'ROUND_FLOOR'
152ROUND_UP = 'ROUND_UP'
153ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Facundo Batista353750c2007-09-13 18:13:15 +0000154ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000155
Facundo Batista59c58842007-04-10 12:58:45 +0000156# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000157
158class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000159 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000160
161 Used exceptions derive from this.
162 If an exception derives from another exception besides this (such as
163 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
164 called if the others are present. This isn't actually used for
165 anything, though.
166
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000167 handle -- Called when context._raise_error is called and the
168 trap_enabler is set. First argument is self, second is the
169 context. More arguments can be given, those being after
170 the explanation in _raise_error (For example,
171 context._raise_error(NewError, '(-x)!', self._sign) would
172 call NewError().handle(context, self._sign).)
173
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000174 To define a new exception, it should be sufficient to have it derive
175 from DecimalException.
176 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000177 def handle(self, context, *args):
178 pass
179
180
181class Clamped(DecimalException):
182 """Exponent of a 0 changed to fit bounds.
183
184 This occurs and signals clamped if the exponent of a result has been
185 altered in order to fit the constraints of a specific concrete
Facundo Batista59c58842007-04-10 12:58:45 +0000186 representation. This may occur when the exponent of a zero result would
187 be outside the bounds of a representation, or when a large normal
188 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000189 this latter case, the exponent is reduced to fit and the corresponding
190 number of zero digits are appended to the coefficient ("fold-down").
191 """
192
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000193class InvalidOperation(DecimalException):
194 """An invalid operation was performed.
195
196 Various bad things cause this:
197
198 Something creates a signaling NaN
199 -INF + INF
Facundo Batista59c58842007-04-10 12:58:45 +0000200 0 * (+-)INF
201 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000202 x % 0
203 (+-)INF % x
204 x._rescale( non-integer )
205 sqrt(-x) , x > 0
206 0 ** 0
207 x ** (non-integer)
208 x ** (+-)INF
209 An operand is invalid
Facundo Batista353750c2007-09-13 18:13:15 +0000210
211 The result of the operation after these is a quiet positive NaN,
212 except when the cause is a signaling NaN, in which case the result is
213 also a quiet NaN, but with the original sign, and an optional
214 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000215 """
216 def handle(self, context, *args):
217 if args:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000218 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
219 return ans._fix_nan(context)
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000220 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000221
222class ConversionSyntax(InvalidOperation):
223 """Trying to convert badly formed string.
224
225 This occurs and signals invalid-operation if an string is being
226 converted to a number and it does not conform to the numeric string
Facundo Batista59c58842007-04-10 12:58:45 +0000227 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000228 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000229 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000230 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000231
232class DivisionByZero(DecimalException, ZeroDivisionError):
233 """Division by 0.
234
235 This occurs and signals division-by-zero if division of a finite number
236 by zero was attempted (during a divide-integer or divide operation, or a
237 power operation with negative right-hand operand), and the dividend was
238 not zero.
239
240 The result of the operation is [sign,inf], where sign is the exclusive
241 or of the signs of the operands for divide, or is 1 for an odd power of
242 -0, for power.
243 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000244
Facundo Batistacce8df22007-09-18 16:53:18 +0000245 def handle(self, context, sign, *args):
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000246 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000247
248class DivisionImpossible(InvalidOperation):
249 """Cannot perform the division adequately.
250
251 This occurs and signals invalid-operation if the integer result of a
252 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000253 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000254 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000255
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000256 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000257 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000258
259class DivisionUndefined(InvalidOperation, ZeroDivisionError):
260 """Undefined result of division.
261
262 This occurs and signals invalid-operation if division by zero was
263 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000264 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000265 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000266
Facundo Batistacce8df22007-09-18 16:53:18 +0000267 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000268 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000269
270class Inexact(DecimalException):
271 """Had to round, losing information.
272
273 This occurs and signals inexact whenever the result of an operation is
274 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000275 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000276 result in all cases is unchanged.
277
278 The inexact signal may be tested (or trapped) to determine if a given
279 operation (or sequence of operations) was inexact.
280 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000281
282class InvalidContext(InvalidOperation):
283 """Invalid context. Unknown rounding, for example.
284
285 This occurs and signals invalid-operation if an invalid context was
Facundo Batista59c58842007-04-10 12:58:45 +0000286 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000287 on creation and either the precision exceeds the capability of the
288 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista59c58842007-04-10 12:58:45 +0000289 was specified. These aspects of the context need only be checked when
290 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000291 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000292
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000293 def handle(self, context, *args):
Mark Dickinsonc5de0962009-01-02 23:07:08 +0000294 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000295
296class Rounded(DecimalException):
297 """Number got rounded (not necessarily changed during rounding).
298
299 This occurs and signals rounded whenever the result of an operation is
300 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista59c58842007-04-10 12:58:45 +0000301 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000302 result in all cases is unchanged.
303
304 The rounded signal may be tested (or trapped) to determine if a given
305 operation (or sequence of operations) caused a loss of precision.
306 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000307
308class Subnormal(DecimalException):
309 """Exponent < Emin before rounding.
310
311 This occurs and signals subnormal whenever the result of a conversion or
312 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000313 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000314
315 The subnormal signal may be tested (or trapped) to determine if a given
316 or operation (or sequence of operations) yielded a subnormal result.
317 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000318
319class Overflow(Inexact, Rounded):
320 """Numerical overflow.
321
322 This occurs and signals overflow if the adjusted exponent of a result
323 (from a conversion or from an operation that is not an attempt to divide
324 by zero), after rounding, would be greater than the largest value that
325 can be handled by the implementation (the value Emax).
326
327 The result depends on the rounding mode:
328
329 For round-half-up and round-half-even (and for round-half-down and
330 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000331 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000332 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000333 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000334 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000335 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000336 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000337 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000338 will also be raised.
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000339 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000340
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 def handle(self, context, sign, *args):
342 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000343 ROUND_HALF_DOWN, ROUND_UP):
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000344 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000345 if sign == 0:
346 if context.rounding == ROUND_CEILING:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000347 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000348 return _dec_from_triple(sign, '9'*context.prec,
349 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000350 if sign == 1:
351 if context.rounding == ROUND_FLOOR:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +0000352 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000353 return _dec_from_triple(sign, '9'*context.prec,
354 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000355
356
357class Underflow(Inexact, Rounded, Subnormal):
358 """Numerical underflow with result rounded to 0.
359
360 This occurs and signals underflow if a result is inexact and the
361 adjusted exponent of the result would be smaller (more negative) than
362 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000363 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000364
365 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000366 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000367 in 0 with the sign of the intermediate result and an exponent of Etiny.
368
369 In all cases, Inexact, Rounded, and Subnormal will also be raised.
370 """
371
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000372# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000373_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000374 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000375
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000376# Map conditions (per the spec) to signals
377_condition_map = {ConversionSyntax:InvalidOperation,
378 DivisionImpossible:InvalidOperation,
379 DivisionUndefined:InvalidOperation,
380 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000381
Facundo Batista59c58842007-04-10 12:58:45 +0000382##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000383
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000384# The getcontext() and setcontext() function manage access to a thread-local
385# current context. Py2.4 offers direct support for thread locals. If that
386# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000387# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000388# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000389
390try:
391 import threading
392except ImportError:
393 # Python was compiled without threads; create a mock object instead
394 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000395 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000396 def local(self, sys=sys):
397 return sys.modules[__name__]
398 threading = MockThreading()
399 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000400
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000401try:
402 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000403
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000404except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000405
Facundo Batista59c58842007-04-10 12:58:45 +0000406 # To fix reloading, force it to create a new context
407 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000408 if hasattr(threading.currentThread(), '__decimal_context__'):
409 del threading.currentThread().__decimal_context__
410
411 def setcontext(context):
412 """Set this thread's context to context."""
413 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000414 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000415 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000416 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000417
418 def getcontext():
419 """Returns this thread's context.
420
421 If this thread does not yet have a context, returns
422 a new context and sets this thread's context.
423 New contexts are copies of DefaultContext.
424 """
425 try:
426 return threading.currentThread().__decimal_context__
427 except AttributeError:
428 context = Context()
429 threading.currentThread().__decimal_context__ = context
430 return context
431
432else:
433
434 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000435 if hasattr(local, '__decimal_context__'):
436 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000437
438 def getcontext(_local=local):
439 """Returns this thread's context.
440
441 If this thread does not yet have a context, returns
442 a new context and sets this thread's context.
443 New contexts are copies of DefaultContext.
444 """
445 try:
446 return _local.__decimal_context__
447 except AttributeError:
448 context = Context()
449 _local.__decimal_context__ = context
450 return context
451
452 def setcontext(context, _local=local):
453 """Set this thread's context to context."""
454 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000455 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000456 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000457 _local.__decimal_context__ = context
458
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000459 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000460
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000461def localcontext(ctx=None):
462 """Return a context manager for a copy of the supplied context
463
464 Uses a copy of the current context if no context is specified
465 The returned context manager creates a local decimal context
466 in a with statement:
467 def sin(x):
468 with localcontext() as ctx:
469 ctx.prec += 2
470 # Rest of sin calculation algorithm
471 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000472 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000473
474 def sin(x):
475 with localcontext(ExtendedContext):
476 # Rest of sin calculation algorithm
477 # uses the Extended Context from the
478 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000479 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000480
Facundo Batistaee340e52008-05-02 17:39:00 +0000481 >>> setcontext(DefaultContext)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000482 >>> print getcontext().prec
483 28
484 >>> with localcontext():
485 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000486 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000487 ... print ctx.prec
488 ...
489 30
490 >>> with localcontext(ExtendedContext):
491 ... print getcontext().prec
492 ...
493 9
494 >>> print getcontext().prec
495 28
496 """
Nick Coghlanced12182006-09-02 03:54:17 +0000497 if ctx is None: ctx = getcontext()
498 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000499
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000500
Facundo Batista59c58842007-04-10 12:58:45 +0000501##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000502
503class Decimal(object):
504 """Floating point class for decimal arithmetic."""
505
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000506 __slots__ = ('_exp','_int','_sign', '_is_special')
507 # Generally, the value of the Decimal instance is given by
508 # (-1)**_sign * _int * 10**_exp
509 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000510
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000511 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000512 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000513 """Create a decimal point instance.
514
515 >>> Decimal('3.14') # string input
Raymond Hettingerabe32372008-02-14 02:41:22 +0000516 Decimal('3.14')
Facundo Batista59c58842007-04-10 12:58:45 +0000517 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000518 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000519 >>> Decimal(314) # int or long
Raymond Hettingerabe32372008-02-14 02:41:22 +0000520 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000521 >>> Decimal(Decimal(314)) # another decimal instance
Raymond Hettingerabe32372008-02-14 02:41:22 +0000522 Decimal('314')
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000523 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Raymond Hettingerabe32372008-02-14 02:41:22 +0000524 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000525 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000526
Facundo Batista72bc54f2007-11-23 17:59:00 +0000527 # Note that the coefficient, self._int, is actually stored as
528 # a string rather than as a tuple of digits. This speeds up
529 # the "digits to integer" and "integer to digits" conversions
530 # that are used in almost every arithmetic operation on
531 # Decimals. This is an internal detail: the as_tuple function
532 # and the Decimal constructor still deal with tuples of
533 # digits.
534
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000535 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000536
Facundo Batista0d157a02007-11-30 17:15:25 +0000537 # From a string
538 # REs insist on real strings, so we can too.
539 if isinstance(value, basestring):
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000540 m = _parser(value.strip())
Facundo Batista0d157a02007-11-30 17:15:25 +0000541 if m is None:
542 if context is None:
543 context = getcontext()
544 return context._raise_error(ConversionSyntax,
545 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000546
Facundo Batista0d157a02007-11-30 17:15:25 +0000547 if m.group('sign') == "-":
548 self._sign = 1
549 else:
550 self._sign = 0
551 intpart = m.group('int')
552 if intpart is not None:
553 # finite number
554 fracpart = m.group('frac')
555 exp = int(m.group('exp') or '0')
556 if fracpart is not None:
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000557 self._int = str((intpart+fracpart).lstrip('0') or '0')
Facundo Batista0d157a02007-11-30 17:15:25 +0000558 self._exp = exp - len(fracpart)
559 else:
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000560 self._int = str(intpart.lstrip('0') or '0')
Facundo Batista0d157a02007-11-30 17:15:25 +0000561 self._exp = exp
562 self._is_special = False
563 else:
564 diag = m.group('diag')
565 if diag is not None:
566 # NaN
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000567 self._int = str(diag.lstrip('0'))
Facundo Batista0d157a02007-11-30 17:15:25 +0000568 if m.group('signal'):
569 self._exp = 'N'
570 else:
571 self._exp = 'n'
572 else:
573 # infinity
574 self._int = '0'
575 self._exp = 'F'
576 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000577 return self
578
579 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000580 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000581 if value >= 0:
582 self._sign = 0
583 else:
584 self._sign = 1
585 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000586 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000587 self._is_special = False
588 return self
589
590 # From another decimal
591 if isinstance(value, Decimal):
592 self._exp = value._exp
593 self._sign = value._sign
594 self._int = value._int
595 self._is_special = value._is_special
596 return self
597
598 # From an internal working value
599 if isinstance(value, _WorkRep):
600 self._sign = value.sign
601 self._int = str(value.int)
602 self._exp = int(value.exp)
603 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000604 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000605
606 # tuple/list conversion (possibly from as_tuple())
607 if isinstance(value, (list,tuple)):
608 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000609 raise ValueError('Invalid tuple size in creation of Decimal '
610 'from list or tuple. The list or tuple '
611 'should have exactly three elements.')
612 # process sign. The isinstance test rejects floats
613 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
614 raise ValueError("Invalid sign. The first value in the tuple "
615 "should be an integer; either 0 for a "
616 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000617 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000618 if value[2] == 'F':
619 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000620 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000621 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000622 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000623 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000624 # process and validate the digits in value[1]
625 digits = []
626 for digit in value[1]:
627 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
628 # skip leading zeros
629 if digits or digit != 0:
630 digits.append(digit)
631 else:
632 raise ValueError("The second value in the tuple must "
633 "be composed of integers in the range "
634 "0 through 9.")
635 if value[2] in ('n', 'N'):
636 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000637 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000638 self._exp = value[2]
639 self._is_special = True
640 elif isinstance(value[2], (int, long)):
641 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000642 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000643 self._exp = value[2]
644 self._is_special = False
645 else:
646 raise ValueError("The third value in the tuple must "
647 "be an integer, or one of the "
648 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000649 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000650
Raymond Hettingerbf440692004-07-10 14:14:37 +0000651 if isinstance(value, float):
652 raise TypeError("Cannot convert float to Decimal. " +
653 "First convert the float to a string")
654
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000655 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000656
Mark Dickinson6a961632009-01-04 21:10:56 +0000657 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
658 # don't use it (see notes on Py2.3 compatibility at top of file)
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000659 def from_float(cls, f):
660 """Converts a float to a decimal number, exactly.
661
662 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
663 Since 0.1 is not exactly representable in binary floating point, the
664 value is stored as the nearest representable value which is
665 0x1.999999999999ap-4. The exact equivalent of the value in decimal
666 is 0.1000000000000000055511151231257827021181583404541015625.
667
668 >>> Decimal.from_float(0.1)
669 Decimal('0.1000000000000000055511151231257827021181583404541015625')
670 >>> Decimal.from_float(float('nan'))
671 Decimal('NaN')
672 >>> Decimal.from_float(float('inf'))
673 Decimal('Infinity')
674 >>> Decimal.from_float(-float('inf'))
675 Decimal('-Infinity')
676 >>> Decimal.from_float(-0.0)
677 Decimal('-0')
678
679 """
680 if isinstance(f, (int, long)): # handle integer inputs
681 return cls(f)
682 if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
683 return cls(repr(f))
Mark Dickinson6a961632009-01-04 21:10:56 +0000684 if _math.copysign(1.0, f) == 1.0:
685 sign = 0
686 else:
687 sign = 1
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000688 n, d = abs(f).as_integer_ratio()
689 k = d.bit_length() - 1
690 result = _dec_from_triple(sign, str(n*5**k), -k)
Mark Dickinson6a961632009-01-04 21:10:56 +0000691 if cls is Decimal:
692 return result
693 else:
694 return cls(result)
695 from_float = classmethod(from_float)
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000696
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000697 def _isnan(self):
698 """Returns whether the number is not actually one.
699
700 0 if a number
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000701 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000702 2 if sNaN
703 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000704 if self._is_special:
705 exp = self._exp
706 if exp == 'n':
707 return 1
708 elif exp == 'N':
709 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000710 return 0
711
712 def _isinfinity(self):
713 """Returns whether the number is infinite
714
715 0 if finite or not a number
716 1 if +INF
717 -1 if -INF
718 """
719 if self._exp == 'F':
720 if self._sign:
721 return -1
722 return 1
723 return 0
724
Facundo Batista353750c2007-09-13 18:13:15 +0000725 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000726 """Returns whether the number is not actually one.
727
728 if self, other are sNaN, signal
729 if self, other are NaN return nan
730 return 0
731
732 Done before operations.
733 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000734
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000735 self_is_nan = self._isnan()
736 if other is None:
737 other_is_nan = False
738 else:
739 other_is_nan = other._isnan()
740
741 if self_is_nan or other_is_nan:
742 if context is None:
743 context = getcontext()
744
745 if self_is_nan == 2:
746 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000747 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000748 if other_is_nan == 2:
749 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000750 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000751 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000752 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000753
Facundo Batista353750c2007-09-13 18:13:15 +0000754 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000755 return 0
756
Mark Dickinson2fc92632008-02-06 22:10:50 +0000757 def _compare_check_nans(self, other, context):
758 """Version of _check_nans used for the signaling comparisons
759 compare_signal, __le__, __lt__, __ge__, __gt__.
760
761 Signal InvalidOperation if either self or other is a (quiet
762 or signaling) NaN. Signaling NaNs take precedence over quiet
763 NaNs.
764
765 Return 0 if neither operand is a NaN.
766
767 """
768 if context is None:
769 context = getcontext()
770
771 if self._is_special or other._is_special:
772 if self.is_snan():
773 return context._raise_error(InvalidOperation,
774 'comparison involving sNaN',
775 self)
776 elif other.is_snan():
777 return context._raise_error(InvalidOperation,
778 'comparison involving sNaN',
779 other)
780 elif self.is_qnan():
781 return context._raise_error(InvalidOperation,
782 'comparison involving NaN',
783 self)
784 elif other.is_qnan():
785 return context._raise_error(InvalidOperation,
786 'comparison involving NaN',
787 other)
788 return 0
789
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000790 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000791 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000792
Facundo Batista1a191df2007-10-02 17:01:24 +0000793 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000794 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000795 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000796
Mark Dickinson2fc92632008-02-06 22:10:50 +0000797 def _cmp(self, other):
798 """Compare the two non-NaN decimal instances self and other.
799
800 Returns -1 if self < other, 0 if self == other and 1
801 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000802
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000803 if self._is_special or other._is_special:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000804 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000805
Facundo Batista353750c2007-09-13 18:13:15 +0000806 # check for zeros; note that cmp(0, -0) should return 0
807 if not self:
808 if not other:
809 return 0
810 else:
811 return -((-1)**other._sign)
812 if not other:
813 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000814
Facundo Batista59c58842007-04-10 12:58:45 +0000815 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000816 if other._sign < self._sign:
817 return -1
818 if self._sign < other._sign:
819 return 1
820
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000821 self_adjusted = self.adjusted()
822 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000823 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000824 self_padded = self._int + '0'*(self._exp - other._exp)
825 other_padded = other._int + '0'*(other._exp - self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +0000826 return cmp(self_padded, other_padded) * (-1)**self._sign
827 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000828 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000829 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000830 return -((-1)**self._sign)
831
Mark Dickinson2fc92632008-02-06 22:10:50 +0000832 # Note: The Decimal standard doesn't cover rich comparisons for
833 # Decimals. In particular, the specification is silent on the
834 # subject of what should happen for a comparison involving a NaN.
835 # We take the following approach:
836 #
837 # == comparisons involving a NaN always return False
838 # != comparisons involving a NaN always return True
839 # <, >, <= and >= comparisons involving a (quiet or signaling)
840 # NaN signal InvalidOperation, and return False if the
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000841 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000842 #
843 # This behavior is designed to conform as closely as possible to
844 # that specified by IEEE 754.
845
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000846 def __eq__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000847 other = _convert_other(other)
848 if other is NotImplemented:
849 return other
850 if self.is_nan() or other.is_nan():
851 return False
852 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000853
854 def __ne__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000855 other = _convert_other(other)
856 if other is NotImplemented:
857 return other
858 if self.is_nan() or other.is_nan():
859 return True
860 return self._cmp(other) != 0
861
862 def __lt__(self, other, context=None):
863 other = _convert_other(other)
864 if other is NotImplemented:
865 return other
866 ans = self._compare_check_nans(other, context)
867 if ans:
868 return False
869 return self._cmp(other) < 0
870
871 def __le__(self, other, context=None):
872 other = _convert_other(other)
873 if other is NotImplemented:
874 return other
875 ans = self._compare_check_nans(other, context)
876 if ans:
877 return False
878 return self._cmp(other) <= 0
879
880 def __gt__(self, other, context=None):
881 other = _convert_other(other)
882 if other is NotImplemented:
883 return other
884 ans = self._compare_check_nans(other, context)
885 if ans:
886 return False
887 return self._cmp(other) > 0
888
889 def __ge__(self, other, context=None):
890 other = _convert_other(other)
891 if other is NotImplemented:
892 return other
893 ans = self._compare_check_nans(other, context)
894 if ans:
895 return False
896 return self._cmp(other) >= 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000897
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000898 def compare(self, other, context=None):
899 """Compares one to another.
900
901 -1 => a < b
902 0 => a = b
903 1 => a > b
904 NaN => one is NaN
905 Like __cmp__, but returns Decimal instances.
906 """
Facundo Batista353750c2007-09-13 18:13:15 +0000907 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000908
Facundo Batista59c58842007-04-10 12:58:45 +0000909 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000910 if (self._is_special or other and other._is_special):
911 ans = self._check_nans(other, context)
912 if ans:
913 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000914
Mark Dickinson2fc92632008-02-06 22:10:50 +0000915 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000916
917 def __hash__(self):
918 """x.__hash__() <==> hash(x)"""
919 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000920 #
921 # The hash of a nonspecial noninteger Decimal must depend only
922 # on the value of that Decimal, and not on its representation.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000923 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000924 if self._is_special:
925 if self._isnan():
926 raise TypeError('Cannot hash a NaN value.')
927 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000928 if not self:
929 return 0
930 if self._isinteger():
931 op = _WorkRep(self.to_integral_value())
932 # to make computation feasible for Decimals with large
933 # exponent, we use the fact that hash(n) == hash(m) for
934 # any two nonzero integers n and m such that (i) n and m
935 # have the same sign, and (ii) n is congruent to m modulo
936 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
937 # hash((-1)**s*c*pow(10, e, 2**64-1).
938 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000939 # The value of a nonzero nonspecial Decimal instance is
940 # faithfully represented by the triple consisting of its sign,
941 # its adjusted exponent, and its coefficient with trailing
942 # zeros removed.
943 return hash((self._sign,
944 self._exp+len(self._int),
945 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000946
947 def as_tuple(self):
948 """Represents the number as a triple tuple.
949
950 To show the internals exactly as they are.
951 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000952 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000953
954 def __repr__(self):
955 """Represents the number as an instance of Decimal."""
956 # Invariant: eval(repr(d)) == d
Raymond Hettingerabe32372008-02-14 02:41:22 +0000957 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000958
Facundo Batista353750c2007-09-13 18:13:15 +0000959 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000960 """Return string representation of the number in scientific notation.
961
962 Captures all of the information in the underlying representation.
963 """
964
Facundo Batista62edb712007-12-03 16:29:52 +0000965 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000966 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000967 if self._exp == 'F':
968 return sign + 'Infinity'
969 elif self._exp == 'n':
970 return sign + 'NaN' + self._int
971 else: # self._exp == 'N'
972 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000973
Facundo Batista62edb712007-12-03 16:29:52 +0000974 # number of digits of self._int to left of decimal point
975 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000976
Facundo Batista62edb712007-12-03 16:29:52 +0000977 # dotplace is number of digits of self._int to the left of the
978 # decimal point in the mantissa of the output string (that is,
979 # after adjusting the exponent)
980 if self._exp <= 0 and leftdigits > -6:
981 # no exponent required
982 dotplace = leftdigits
983 elif not eng:
984 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000985 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000986 elif self._int == '0':
987 # engineering notation, zero
988 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000989 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000990 # engineering notation, nonzero
991 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000992
Facundo Batista62edb712007-12-03 16:29:52 +0000993 if dotplace <= 0:
994 intpart = '0'
995 fracpart = '.' + '0'*(-dotplace) + self._int
996 elif dotplace >= len(self._int):
997 intpart = self._int+'0'*(dotplace-len(self._int))
998 fracpart = ''
999 else:
1000 intpart = self._int[:dotplace]
1001 fracpart = '.' + self._int[dotplace:]
1002 if leftdigits == dotplace:
1003 exp = ''
1004 else:
1005 if context is None:
1006 context = getcontext()
1007 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1008
1009 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001010
1011 def to_eng_string(self, context=None):
1012 """Convert to engineering-type string.
1013
1014 Engineering notation has an exponent which is a multiple of 3, so there
1015 are up to 3 digits left of the decimal place.
1016
1017 Same rules for when in exponential and when as a value as in __str__.
1018 """
Facundo Batista353750c2007-09-13 18:13:15 +00001019 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001020
1021 def __neg__(self, context=None):
1022 """Returns a copy with the sign switched.
1023
1024 Rounds, if it has reason.
1025 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001026 if self._is_special:
1027 ans = self._check_nans(context=context)
1028 if ans:
1029 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030
1031 if not self:
1032 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001033 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001035 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001036
1037 if context is None:
1038 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001039 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001040
1041 def __pos__(self, context=None):
1042 """Returns a copy, unless it is a sNaN.
1043
1044 Rounds the number (if more then precision digits)
1045 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001046 if self._is_special:
1047 ans = self._check_nans(context=context)
1048 if ans:
1049 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001050
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051 if not self:
1052 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001053 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +00001054 else:
1055 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001056
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001057 if context is None:
1058 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001059 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001060
Facundo Batistae64acfa2007-12-17 14:18:42 +00001061 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001062 """Returns the absolute value of self.
1063
Facundo Batistae64acfa2007-12-17 14:18:42 +00001064 If the keyword argument 'round' is false, do not round. The
1065 expression self.__abs__(round=False) is equivalent to
1066 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067 """
Facundo Batistae64acfa2007-12-17 14:18:42 +00001068 if not round:
1069 return self.copy_abs()
1070
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001071 if self._is_special:
1072 ans = self._check_nans(context=context)
1073 if ans:
1074 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001075
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001076 if self._sign:
1077 ans = self.__neg__(context=context)
1078 else:
1079 ans = self.__pos__(context=context)
1080
1081 return ans
1082
1083 def __add__(self, other, context=None):
1084 """Returns self + other.
1085
1086 -INF + INF (or the reverse) cause InvalidOperation errors.
1087 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001088 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001089 if other is NotImplemented:
1090 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001091
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092 if context is None:
1093 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001095 if self._is_special or other._is_special:
1096 ans = self._check_nans(other, context)
1097 if ans:
1098 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001099
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001100 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001101 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001102 if self._sign != other._sign and other._isinfinity():
1103 return context._raise_error(InvalidOperation, '-INF + INF')
1104 return Decimal(self)
1105 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001106 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001107
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001108 exp = min(self._exp, other._exp)
1109 negativezero = 0
1110 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001111 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001112 negativezero = 1
1113
1114 if not self and not other:
1115 sign = min(self._sign, other._sign)
1116 if negativezero:
1117 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001118 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001119 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001120 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001121 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001122 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001123 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001124 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001125 return ans
1126 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001127 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001128 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001129 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001130 return ans
1131
1132 op1 = _WorkRep(self)
1133 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001134 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135
1136 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001137 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001139 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001140 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001141 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001142 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001143 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001145 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001146 if op1.sign == 1:
1147 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001148 op1.sign, op2.sign = op2.sign, op1.sign
1149 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001150 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001151 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001152 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001153 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001154 op1.sign, op2.sign = (0, 0)
1155 else:
1156 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001157 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001158
Raymond Hettinger17931de2004-10-27 06:21:46 +00001159 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001160 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001162 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163
1164 result.exp = op1.exp
1165 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001166 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001167 return ans
1168
1169 __radd__ = __add__
1170
1171 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001172 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001173 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001174 if other is NotImplemented:
1175 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001177 if self._is_special or other._is_special:
1178 ans = self._check_nans(other, context=context)
1179 if ans:
1180 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001181
Facundo Batista353750c2007-09-13 18:13:15 +00001182 # self - other is computed as self + other.copy_negate()
1183 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184
1185 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001186 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001187 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001188 if other is NotImplemented:
1189 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001190
Facundo Batista353750c2007-09-13 18:13:15 +00001191 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001192
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001193 def __mul__(self, other, context=None):
1194 """Return self * other.
1195
1196 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1197 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001198 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001199 if other is NotImplemented:
1200 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001201
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202 if context is None:
1203 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001204
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001205 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001206
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001207 if self._is_special or other._is_special:
1208 ans = self._check_nans(other, context)
1209 if ans:
1210 return ans
1211
1212 if self._isinfinity():
1213 if not other:
1214 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001215 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001216
1217 if other._isinfinity():
1218 if not self:
1219 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001220 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001221
1222 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001223
1224 # Special case for multiplying by zero
1225 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001226 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001227 # Fixing in case the exponent is out of bounds
1228 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001229 return ans
1230
1231 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001232 if self._int == '1':
1233 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001234 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001235 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001236 if other._int == '1':
1237 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001238 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001239 return ans
1240
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001241 op1 = _WorkRep(self)
1242 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001243
Facundo Batista72bc54f2007-11-23 17:59:00 +00001244 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001245 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001246
1247 return ans
1248 __rmul__ = __mul__
1249
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001250 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001251 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001252 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001253 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001254 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001255
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001256 if context is None:
1257 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001258
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001259 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001260
1261 if self._is_special or other._is_special:
1262 ans = self._check_nans(other, context)
1263 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001264 return ans
1265
1266 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001267 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001268
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001269 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001270 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001271
1272 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001273 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001274 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001275
1276 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001277 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001278 if not self:
1279 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001280 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001281
Facundo Batistacce8df22007-09-18 16:53:18 +00001282 if not self:
1283 exp = self._exp - other._exp
1284 coeff = 0
1285 else:
1286 # OK, so neither = 0, INF or NaN
1287 shift = len(other._int) - len(self._int) + context.prec + 1
1288 exp = self._exp - other._exp - shift
1289 op1 = _WorkRep(self)
1290 op2 = _WorkRep(other)
1291 if shift >= 0:
1292 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1293 else:
1294 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1295 if remainder:
1296 # result is not exact; adjust to ensure correct rounding
1297 if coeff % 5 == 0:
1298 coeff += 1
1299 else:
1300 # result is exact; get as close to ideal exponent as possible
1301 ideal_exp = self._exp - other._exp
1302 while exp < ideal_exp and coeff % 10 == 0:
1303 coeff //= 10
1304 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001305
Facundo Batista72bc54f2007-11-23 17:59:00 +00001306 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001307 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001308
Facundo Batistacce8df22007-09-18 16:53:18 +00001309 def _divide(self, other, context):
1310 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001311
Facundo Batistacce8df22007-09-18 16:53:18 +00001312 Assumes that neither self nor other is a NaN, that self is not
1313 infinite and that other is nonzero.
1314 """
1315 sign = self._sign ^ other._sign
1316 if other._isinfinity():
1317 ideal_exp = self._exp
1318 else:
1319 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001320
Facundo Batistacce8df22007-09-18 16:53:18 +00001321 expdiff = self.adjusted() - other.adjusted()
1322 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001323 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001324 self._rescale(ideal_exp, context.rounding))
1325 if expdiff <= context.prec:
1326 op1 = _WorkRep(self)
1327 op2 = _WorkRep(other)
1328 if op1.exp >= op2.exp:
1329 op1.int *= 10**(op1.exp - op2.exp)
1330 else:
1331 op2.int *= 10**(op2.exp - op1.exp)
1332 q, r = divmod(op1.int, op2.int)
1333 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001334 return (_dec_from_triple(sign, str(q), 0),
1335 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001336
Facundo Batistacce8df22007-09-18 16:53:18 +00001337 # Here the quotient is too large to be representable
1338 ans = context._raise_error(DivisionImpossible,
1339 'quotient too large in //, % or divmod')
1340 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001341
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001342 def __rtruediv__(self, other, context=None):
1343 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001344 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001345 if other is NotImplemented:
1346 return other
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001347 return other.__truediv__(self, context=context)
1348
1349 __div__ = __truediv__
1350 __rdiv__ = __rtruediv__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001351
1352 def __divmod__(self, other, context=None):
1353 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001354 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001355 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001356 other = _convert_other(other)
1357 if other is NotImplemented:
1358 return other
1359
1360 if context is None:
1361 context = getcontext()
1362
1363 ans = self._check_nans(other, context)
1364 if ans:
1365 return (ans, ans)
1366
1367 sign = self._sign ^ other._sign
1368 if self._isinfinity():
1369 if other._isinfinity():
1370 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1371 return ans, ans
1372 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001373 return (_SignedInfinity[sign],
Facundo Batistacce8df22007-09-18 16:53:18 +00001374 context._raise_error(InvalidOperation, 'INF % x'))
1375
1376 if not other:
1377 if not self:
1378 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1379 return ans, ans
1380 else:
1381 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1382 context._raise_error(InvalidOperation, 'x % 0'))
1383
1384 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001385 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001386 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001387
1388 def __rdivmod__(self, other, context=None):
1389 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001390 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001391 if other is NotImplemented:
1392 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001393 return other.__divmod__(self, context=context)
1394
1395 def __mod__(self, other, context=None):
1396 """
1397 self % other
1398 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001399 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001400 if other is NotImplemented:
1401 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001402
Facundo Batistacce8df22007-09-18 16:53:18 +00001403 if context is None:
1404 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001405
Facundo Batistacce8df22007-09-18 16:53:18 +00001406 ans = self._check_nans(other, context)
1407 if ans:
1408 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001409
Facundo Batistacce8df22007-09-18 16:53:18 +00001410 if self._isinfinity():
1411 return context._raise_error(InvalidOperation, 'INF % x')
1412 elif not other:
1413 if self:
1414 return context._raise_error(InvalidOperation, 'x % 0')
1415 else:
1416 return context._raise_error(DivisionUndefined, '0 % 0')
1417
1418 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001419 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001420 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001421
1422 def __rmod__(self, other, context=None):
1423 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001424 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001425 if other is NotImplemented:
1426 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001427 return other.__mod__(self, context=context)
1428
1429 def remainder_near(self, other, context=None):
1430 """
1431 Remainder nearest to 0- abs(remainder-near) <= other/2
1432 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001433 if context is None:
1434 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001435
Facundo Batista353750c2007-09-13 18:13:15 +00001436 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001437
Facundo Batista353750c2007-09-13 18:13:15 +00001438 ans = self._check_nans(other, context)
1439 if ans:
1440 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001441
Facundo Batista353750c2007-09-13 18:13:15 +00001442 # self == +/-infinity -> InvalidOperation
1443 if self._isinfinity():
1444 return context._raise_error(InvalidOperation,
1445 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001446
Facundo Batista353750c2007-09-13 18:13:15 +00001447 # other == 0 -> either InvalidOperation or DivisionUndefined
1448 if not other:
1449 if self:
1450 return context._raise_error(InvalidOperation,
1451 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001452 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001453 return context._raise_error(DivisionUndefined,
1454 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001455
Facundo Batista353750c2007-09-13 18:13:15 +00001456 # other = +/-infinity -> remainder = self
1457 if other._isinfinity():
1458 ans = Decimal(self)
1459 return ans._fix(context)
1460
1461 # self = 0 -> remainder = self, with ideal exponent
1462 ideal_exponent = min(self._exp, other._exp)
1463 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001464 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001465 return ans._fix(context)
1466
1467 # catch most cases of large or small quotient
1468 expdiff = self.adjusted() - other.adjusted()
1469 if expdiff >= context.prec + 1:
1470 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001471 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001472 if expdiff <= -2:
1473 # expdiff <= -2 => abs(self/other) < 0.1
1474 ans = self._rescale(ideal_exponent, context.rounding)
1475 return ans._fix(context)
1476
1477 # adjust both arguments to have the same exponent, then divide
1478 op1 = _WorkRep(self)
1479 op2 = _WorkRep(other)
1480 if op1.exp >= op2.exp:
1481 op1.int *= 10**(op1.exp - op2.exp)
1482 else:
1483 op2.int *= 10**(op2.exp - op1.exp)
1484 q, r = divmod(op1.int, op2.int)
1485 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1486 # 10**ideal_exponent. Apply correction to ensure that
1487 # abs(remainder) <= abs(other)/2
1488 if 2*r + (q&1) > op2.int:
1489 r -= op2.int
1490 q += 1
1491
1492 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001493 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001494
1495 # result has same sign as self unless r is negative
1496 sign = self._sign
1497 if r < 0:
1498 sign = 1-sign
1499 r = -r
1500
Facundo Batista72bc54f2007-11-23 17:59:00 +00001501 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001502 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001503
1504 def __floordiv__(self, other, context=None):
1505 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001506 other = _convert_other(other)
1507 if other is NotImplemented:
1508 return other
1509
1510 if context is None:
1511 context = getcontext()
1512
1513 ans = self._check_nans(other, context)
1514 if ans:
1515 return ans
1516
1517 if self._isinfinity():
1518 if other._isinfinity():
1519 return context._raise_error(InvalidOperation, 'INF // INF')
1520 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001521 return _SignedInfinity[self._sign ^ other._sign]
Facundo Batistacce8df22007-09-18 16:53:18 +00001522
1523 if not other:
1524 if self:
1525 return context._raise_error(DivisionByZero, 'x // 0',
1526 self._sign ^ other._sign)
1527 else:
1528 return context._raise_error(DivisionUndefined, '0 // 0')
1529
1530 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001531
1532 def __rfloordiv__(self, other, context=None):
1533 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001534 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001535 if other is NotImplemented:
1536 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001537 return other.__floordiv__(self, context=context)
1538
1539 def __float__(self):
1540 """Float representation."""
1541 return float(str(self))
1542
1543 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001544 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001545 if self._is_special:
1546 if self._isnan():
1547 context = getcontext()
1548 return context._raise_error(InvalidContext)
1549 elif self._isinfinity():
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001550 raise OverflowError("Cannot convert infinity to int")
Facundo Batista353750c2007-09-13 18:13:15 +00001551 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001552 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001553 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001554 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001555 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001556
Raymond Hettinger5a053642008-01-24 19:05:29 +00001557 __trunc__ = __int__
1558
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001559 def real(self):
1560 return self
Mark Dickinson65808ff2009-01-04 21:22:02 +00001561 real = property(real)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001562
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001563 def imag(self):
1564 return Decimal(0)
Mark Dickinson65808ff2009-01-04 21:22:02 +00001565 imag = property(imag)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001566
1567 def conjugate(self):
1568 return self
1569
1570 def __complex__(self):
1571 return complex(float(self))
1572
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001573 def __long__(self):
1574 """Converts to a long.
1575
1576 Equivalent to long(int(self))
1577 """
1578 return long(self.__int__())
1579
Facundo Batista353750c2007-09-13 18:13:15 +00001580 def _fix_nan(self, context):
1581 """Decapitate the payload of a NaN to fit the context"""
1582 payload = self._int
1583
1584 # maximum length of payload is precision if _clamp=0,
1585 # precision-1 if _clamp=1.
1586 max_payload_len = context.prec - context._clamp
1587 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001588 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1589 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001590 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001591
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001592 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001593 """Round if it is necessary to keep self within prec precision.
1594
1595 Rounds and fixes the exponent. Does not raise on a sNaN.
1596
1597 Arguments:
1598 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001599 context - context used.
1600 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001601
Facundo Batista353750c2007-09-13 18:13:15 +00001602 if self._is_special:
1603 if self._isnan():
1604 # decapitate payload if necessary
1605 return self._fix_nan(context)
1606 else:
1607 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001608 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001609
Facundo Batista353750c2007-09-13 18:13:15 +00001610 # if self is zero then exponent should be between Etiny and
1611 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1612 Etiny = context.Etiny()
1613 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001614 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001615 exp_max = [context.Emax, Etop][context._clamp]
1616 new_exp = min(max(self._exp, Etiny), exp_max)
1617 if new_exp != self._exp:
1618 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001619 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001620 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001621 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001622
1623 # exp_min is the smallest allowable exponent of the result,
1624 # equal to max(self.adjusted()-context.prec+1, Etiny)
1625 exp_min = len(self._int) + self._exp - context.prec
1626 if exp_min > Etop:
1627 # overflow: exp_min > Etop iff self.adjusted() > Emax
1628 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001629 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001630 return context._raise_error(Overflow, 'above Emax', self._sign)
1631 self_is_subnormal = exp_min < Etiny
1632 if self_is_subnormal:
1633 context._raise_error(Subnormal)
1634 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001635
Facundo Batista353750c2007-09-13 18:13:15 +00001636 # round if self has too many digits
1637 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001638 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001639 digits = len(self._int) + self._exp - exp_min
1640 if digits < 0:
1641 self = _dec_from_triple(self._sign, '1', exp_min-1)
1642 digits = 0
1643 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1644 changed = this_function(digits)
1645 coeff = self._int[:digits] or '0'
1646 if changed == 1:
1647 coeff = str(int(coeff)+1)
1648 ans = _dec_from_triple(self._sign, coeff, exp_min)
1649
1650 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001651 context._raise_error(Inexact)
1652 if self_is_subnormal:
1653 context._raise_error(Underflow)
1654 if not ans:
1655 # raise Clamped on underflow to 0
1656 context._raise_error(Clamped)
1657 elif len(ans._int) == context.prec+1:
1658 # we get here only if rescaling rounds the
1659 # cofficient up to exactly 10**context.prec
1660 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001661 ans = _dec_from_triple(ans._sign,
1662 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001663 else:
1664 # Inexact and Rounded have already been raised
1665 ans = context._raise_error(Overflow, 'above Emax',
1666 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001667 return ans
1668
Facundo Batista353750c2007-09-13 18:13:15 +00001669 # fold down if _clamp == 1 and self has too few digits
1670 if context._clamp == 1 and self._exp > Etop:
1671 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001672 self_padded = self._int + '0'*(self._exp - Etop)
1673 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001674
Facundo Batista353750c2007-09-13 18:13:15 +00001675 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001676 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001677
1678 _pick_rounding_function = {}
1679
Facundo Batista353750c2007-09-13 18:13:15 +00001680 # for each of the rounding functions below:
1681 # self is a finite, nonzero Decimal
1682 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001683 #
1684 # each function returns either -1, 0, or 1, as follows:
1685 # 1 indicates that self should be rounded up (away from zero)
1686 # 0 indicates that self should be truncated, and that all the
1687 # digits to be truncated are zeros (so the value is unchanged)
1688 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001689
1690 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001691 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001692 if _all_zeros(self._int, prec):
1693 return 0
1694 else:
1695 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001696
Facundo Batista353750c2007-09-13 18:13:15 +00001697 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001698 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001699 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001700
Facundo Batista353750c2007-09-13 18:13:15 +00001701 def _round_half_up(self, prec):
1702 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001703 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001704 return 1
1705 elif _all_zeros(self._int, prec):
1706 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001707 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001708 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001709
1710 def _round_half_down(self, prec):
1711 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001712 if _exact_half(self._int, prec):
1713 return -1
1714 else:
1715 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001716
1717 def _round_half_even(self, prec):
1718 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001719 if _exact_half(self._int, prec) and \
1720 (prec == 0 or self._int[prec-1] in '02468'):
1721 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001722 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001723 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001724
1725 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001726 """Rounds up (not away from 0 if negative.)"""
1727 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001728 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001729 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001730 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001731
Facundo Batista353750c2007-09-13 18:13:15 +00001732 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001733 """Rounds down (not towards 0 if negative)"""
1734 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001735 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001736 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001737 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001738
Facundo Batista353750c2007-09-13 18:13:15 +00001739 def _round_05up(self, prec):
1740 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001741 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001742 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001743 else:
1744 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001745
Facundo Batista353750c2007-09-13 18:13:15 +00001746 def fma(self, other, third, context=None):
1747 """Fused multiply-add.
1748
1749 Returns self*other+third with no rounding of the intermediate
1750 product self*other.
1751
1752 self and other are multiplied together, with no rounding of
1753 the result. The third operand is then added to the result,
1754 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001755 """
Facundo Batista353750c2007-09-13 18:13:15 +00001756
1757 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001758
1759 # compute product; raise InvalidOperation if either operand is
1760 # a signaling NaN or if the product is zero times infinity.
1761 if self._is_special or other._is_special:
1762 if context is None:
1763 context = getcontext()
1764 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001765 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001766 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001767 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001768 if self._exp == 'n':
1769 product = self
1770 elif other._exp == 'n':
1771 product = other
1772 elif self._exp == 'F':
1773 if not other:
1774 return context._raise_error(InvalidOperation,
1775 'INF * 0 in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001776 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001777 elif other._exp == 'F':
1778 if not self:
1779 return context._raise_error(InvalidOperation,
1780 '0 * INF in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001781 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001782 else:
1783 product = _dec_from_triple(self._sign ^ other._sign,
1784 str(int(self._int) * int(other._int)),
1785 self._exp + other._exp)
1786
Facundo Batista353750c2007-09-13 18:13:15 +00001787 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001788 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001789
Facundo Batista353750c2007-09-13 18:13:15 +00001790 def _power_modulo(self, other, modulo, context=None):
1791 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001792
Facundo Batista353750c2007-09-13 18:13:15 +00001793 # if can't convert other and modulo to Decimal, raise
1794 # TypeError; there's no point returning NotImplemented (no
1795 # equivalent of __rpow__ for three argument pow)
1796 other = _convert_other(other, raiseit=True)
1797 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001798
Facundo Batista353750c2007-09-13 18:13:15 +00001799 if context is None:
1800 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001801
Facundo Batista353750c2007-09-13 18:13:15 +00001802 # deal with NaNs: if there are any sNaNs then first one wins,
1803 # (i.e. behaviour for NaNs is identical to that of fma)
1804 self_is_nan = self._isnan()
1805 other_is_nan = other._isnan()
1806 modulo_is_nan = modulo._isnan()
1807 if self_is_nan or other_is_nan or modulo_is_nan:
1808 if self_is_nan == 2:
1809 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001810 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001811 if other_is_nan == 2:
1812 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001813 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001814 if modulo_is_nan == 2:
1815 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001816 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001817 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001818 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001819 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001820 return other._fix_nan(context)
1821 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001822
Facundo Batista353750c2007-09-13 18:13:15 +00001823 # check inputs: we apply same restrictions as Python's pow()
1824 if not (self._isinteger() and
1825 other._isinteger() and
1826 modulo._isinteger()):
1827 return context._raise_error(InvalidOperation,
1828 'pow() 3rd argument not allowed '
1829 'unless all arguments are integers')
1830 if other < 0:
1831 return context._raise_error(InvalidOperation,
1832 'pow() 2nd argument cannot be '
1833 'negative when 3rd argument specified')
1834 if not modulo:
1835 return context._raise_error(InvalidOperation,
1836 'pow() 3rd argument cannot be 0')
1837
1838 # additional restriction for decimal: the modulus must be less
1839 # than 10**prec in absolute value
1840 if modulo.adjusted() >= context.prec:
1841 return context._raise_error(InvalidOperation,
1842 'insufficient precision: pow() 3rd '
1843 'argument must not have more than '
1844 'precision digits')
1845
1846 # define 0**0 == NaN, for consistency with two-argument pow
1847 # (even though it hurts!)
1848 if not other and not self:
1849 return context._raise_error(InvalidOperation,
1850 'at least one of pow() 1st argument '
1851 'and 2nd argument must be nonzero ;'
1852 '0**0 is not defined')
1853
1854 # compute sign of result
1855 if other._iseven():
1856 sign = 0
1857 else:
1858 sign = self._sign
1859
1860 # convert modulo to a Python integer, and self and other to
1861 # Decimal integers (i.e. force their exponents to be >= 0)
1862 modulo = abs(int(modulo))
1863 base = _WorkRep(self.to_integral_value())
1864 exponent = _WorkRep(other.to_integral_value())
1865
1866 # compute result using integer pow()
1867 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1868 for i in xrange(exponent.exp):
1869 base = pow(base, 10, modulo)
1870 base = pow(base, exponent.int, modulo)
1871
Facundo Batista72bc54f2007-11-23 17:59:00 +00001872 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001873
1874 def _power_exact(self, other, p):
1875 """Attempt to compute self**other exactly.
1876
1877 Given Decimals self and other and an integer p, attempt to
1878 compute an exact result for the power self**other, with p
1879 digits of precision. Return None if self**other is not
1880 exactly representable in p digits.
1881
1882 Assumes that elimination of special cases has already been
1883 performed: self and other must both be nonspecial; self must
1884 be positive and not numerically equal to 1; other must be
1885 nonzero. For efficiency, other._exp should not be too large,
1886 so that 10**abs(other._exp) is a feasible calculation."""
1887
1888 # In the comments below, we write x for the value of self and
1889 # y for the value of other. Write x = xc*10**xe and y =
1890 # yc*10**ye.
1891
1892 # The main purpose of this method is to identify the *failure*
1893 # of x**y to be exactly representable with as little effort as
1894 # possible. So we look for cheap and easy tests that
1895 # eliminate the possibility of x**y being exact. Only if all
1896 # these tests are passed do we go on to actually compute x**y.
1897
1898 # Here's the main idea. First normalize both x and y. We
1899 # express y as a rational m/n, with m and n relatively prime
1900 # and n>0. Then for x**y to be exactly representable (at
1901 # *any* precision), xc must be the nth power of a positive
1902 # integer and xe must be divisible by n. If m is negative
1903 # then additionally xc must be a power of either 2 or 5, hence
1904 # a power of 2**n or 5**n.
1905 #
1906 # There's a limit to how small |y| can be: if y=m/n as above
1907 # then:
1908 #
1909 # (1) if xc != 1 then for the result to be representable we
1910 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1911 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1912 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1913 # representable.
1914 #
1915 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1916 # |y| < 1/|xe| then the result is not representable.
1917 #
1918 # Note that since x is not equal to 1, at least one of (1) and
1919 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1920 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1921 #
1922 # There's also a limit to how large y can be, at least if it's
1923 # positive: the normalized result will have coefficient xc**y,
1924 # so if it's representable then xc**y < 10**p, and y <
1925 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1926 # not exactly representable.
1927
1928 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1929 # so |y| < 1/xe and the result is not representable.
1930 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1931 # < 1/nbits(xc).
1932
1933 x = _WorkRep(self)
1934 xc, xe = x.int, x.exp
1935 while xc % 10 == 0:
1936 xc //= 10
1937 xe += 1
1938
1939 y = _WorkRep(other)
1940 yc, ye = y.int, y.exp
1941 while yc % 10 == 0:
1942 yc //= 10
1943 ye += 1
1944
1945 # case where xc == 1: result is 10**(xe*y), with xe*y
1946 # required to be an integer
1947 if xc == 1:
1948 if ye >= 0:
1949 exponent = xe*yc*10**ye
1950 else:
1951 exponent, remainder = divmod(xe*yc, 10**-ye)
1952 if remainder:
1953 return None
1954 if y.sign == 1:
1955 exponent = -exponent
1956 # if other is a nonnegative integer, use ideal exponent
1957 if other._isinteger() and other._sign == 0:
1958 ideal_exponent = self._exp*int(other)
1959 zeros = min(exponent-ideal_exponent, p-1)
1960 else:
1961 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001962 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001963
1964 # case where y is negative: xc must be either a power
1965 # of 2 or a power of 5.
1966 if y.sign == 1:
1967 last_digit = xc % 10
1968 if last_digit in (2,4,6,8):
1969 # quick test for power of 2
1970 if xc & -xc != xc:
1971 return None
1972 # now xc is a power of 2; e is its exponent
1973 e = _nbits(xc)-1
1974 # find e*y and xe*y; both must be integers
1975 if ye >= 0:
1976 y_as_int = yc*10**ye
1977 e = e*y_as_int
1978 xe = xe*y_as_int
1979 else:
1980 ten_pow = 10**-ye
1981 e, remainder = divmod(e*yc, ten_pow)
1982 if remainder:
1983 return None
1984 xe, remainder = divmod(xe*yc, ten_pow)
1985 if remainder:
1986 return None
1987
1988 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1989 return None
1990 xc = 5**e
1991
1992 elif last_digit == 5:
1993 # e >= log_5(xc) if xc is a power of 5; we have
1994 # equality all the way up to xc=5**2658
1995 e = _nbits(xc)*28//65
1996 xc, remainder = divmod(5**e, xc)
1997 if remainder:
1998 return None
1999 while xc % 5 == 0:
2000 xc //= 5
2001 e -= 1
2002 if ye >= 0:
2003 y_as_integer = yc*10**ye
2004 e = e*y_as_integer
2005 xe = xe*y_as_integer
2006 else:
2007 ten_pow = 10**-ye
2008 e, remainder = divmod(e*yc, ten_pow)
2009 if remainder:
2010 return None
2011 xe, remainder = divmod(xe*yc, ten_pow)
2012 if remainder:
2013 return None
2014 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2015 return None
2016 xc = 2**e
2017 else:
2018 return None
2019
2020 if xc >= 10**p:
2021 return None
2022 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00002023 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00002024
2025 # now y is positive; find m and n such that y = m/n
2026 if ye >= 0:
2027 m, n = yc*10**ye, 1
2028 else:
2029 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2030 return None
2031 xc_bits = _nbits(xc)
2032 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2033 return None
2034 m, n = yc, 10**(-ye)
2035 while m % 2 == n % 2 == 0:
2036 m //= 2
2037 n //= 2
2038 while m % 5 == n % 5 == 0:
2039 m //= 5
2040 n //= 5
2041
2042 # compute nth root of xc*10**xe
2043 if n > 1:
2044 # if 1 < xc < 2**n then xc isn't an nth power
2045 if xc != 1 and xc_bits <= n:
2046 return None
2047
2048 xe, rem = divmod(xe, n)
2049 if rem != 0:
2050 return None
2051
2052 # compute nth root of xc using Newton's method
2053 a = 1L << -(-_nbits(xc)//n) # initial estimate
2054 while True:
2055 q, r = divmod(xc, a**(n-1))
2056 if a <= q:
2057 break
2058 else:
2059 a = (a*(n-1) + q)//n
2060 if not (a == q and r == 0):
2061 return None
2062 xc = a
2063
2064 # now xc*10**xe is the nth root of the original xc*10**xe
2065 # compute mth power of xc*10**xe
2066
2067 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2068 # 10**p and the result is not representable.
2069 if xc > 1 and m > p*100//_log10_lb(xc):
2070 return None
2071 xc = xc**m
2072 xe *= m
2073 if xc > 10**p:
2074 return None
2075
2076 # by this point the result *is* exactly representable
2077 # adjust the exponent to get as close as possible to the ideal
2078 # exponent, if necessary
2079 str_xc = str(xc)
2080 if other._isinteger() and other._sign == 0:
2081 ideal_exponent = self._exp*int(other)
2082 zeros = min(xe-ideal_exponent, p-len(str_xc))
2083 else:
2084 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002085 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002086
2087 def __pow__(self, other, modulo=None, context=None):
2088 """Return self ** other [ % modulo].
2089
2090 With two arguments, compute self**other.
2091
2092 With three arguments, compute (self**other) % modulo. For the
2093 three argument form, the following restrictions on the
2094 arguments hold:
2095
2096 - all three arguments must be integral
2097 - other must be nonnegative
2098 - either self or other (or both) must be nonzero
2099 - modulo must be nonzero and must have at most p digits,
2100 where p is the context precision.
2101
2102 If any of these restrictions is violated the InvalidOperation
2103 flag is raised.
2104
2105 The result of pow(self, other, modulo) is identical to the
2106 result that would be obtained by computing (self**other) %
2107 modulo with unbounded precision, but is computed more
2108 efficiently. It is always exact.
2109 """
2110
2111 if modulo is not None:
2112 return self._power_modulo(other, modulo, context)
2113
2114 other = _convert_other(other)
2115 if other is NotImplemented:
2116 return other
2117
2118 if context is None:
2119 context = getcontext()
2120
2121 # either argument is a NaN => result is NaN
2122 ans = self._check_nans(other, context)
2123 if ans:
2124 return ans
2125
2126 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2127 if not other:
2128 if not self:
2129 return context._raise_error(InvalidOperation, '0 ** 0')
2130 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002131 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002132
2133 # result has sign 1 iff self._sign is 1 and other is an odd integer
2134 result_sign = 0
2135 if self._sign == 1:
2136 if other._isinteger():
2137 if not other._iseven():
2138 result_sign = 1
2139 else:
2140 # -ve**noninteger = NaN
2141 # (-0)**noninteger = 0**noninteger
2142 if self:
2143 return context._raise_error(InvalidOperation,
2144 'x ** y with x negative and y not an integer')
2145 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002146 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002147
2148 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2149 if not self:
2150 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002151 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002152 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002153 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002154
2155 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002156 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002157 if other._sign == 0:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002158 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002159 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002160 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002161
Facundo Batista353750c2007-09-13 18:13:15 +00002162 # 1**other = 1, but the choice of exponent and the flags
2163 # depend on the exponent of self, and on whether other is a
2164 # positive integer, a negative integer, or neither
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002165 if self == _One:
Facundo Batista353750c2007-09-13 18:13:15 +00002166 if other._isinteger():
2167 # exp = max(self._exp*max(int(other), 0),
2168 # 1-context.prec) but evaluating int(other) directly
2169 # is dangerous until we know other is small (other
2170 # could be 1e999999999)
2171 if other._sign == 1:
2172 multiplier = 0
2173 elif other > context.prec:
2174 multiplier = context.prec
2175 else:
2176 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002177
Facundo Batista353750c2007-09-13 18:13:15 +00002178 exp = self._exp * multiplier
2179 if exp < 1-context.prec:
2180 exp = 1-context.prec
2181 context._raise_error(Rounded)
2182 else:
2183 context._raise_error(Inexact)
2184 context._raise_error(Rounded)
2185 exp = 1-context.prec
2186
Facundo Batista72bc54f2007-11-23 17:59:00 +00002187 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002188
2189 # compute adjusted exponent of self
2190 self_adj = self.adjusted()
2191
2192 # self ** infinity is infinity if self > 1, 0 if self < 1
2193 # self ** -infinity is infinity if self < 1, 0 if self > 1
2194 if other._isinfinity():
2195 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002196 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002197 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002198 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002199
2200 # from here on, the result always goes through the call
2201 # to _fix at the end of this function.
2202 ans = None
2203
2204 # crude test to catch cases of extreme overflow/underflow. If
2205 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2206 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2207 # self**other >= 10**(Emax+1), so overflow occurs. The test
2208 # for underflow is similar.
2209 bound = self._log10_exp_bound() + other.adjusted()
2210 if (self_adj >= 0) == (other._sign == 0):
2211 # self > 1 and other +ve, or self < 1 and other -ve
2212 # possibility of overflow
2213 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002214 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002215 else:
2216 # self > 1 and other -ve, or self < 1 and other +ve
2217 # possibility of underflow to 0
2218 Etiny = context.Etiny()
2219 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002220 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002221
2222 # try for an exact result with precision +1
2223 if ans is None:
2224 ans = self._power_exact(other, context.prec + 1)
2225 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002226 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002227
2228 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2229 if ans is None:
2230 p = context.prec
2231 x = _WorkRep(self)
2232 xc, xe = x.int, x.exp
2233 y = _WorkRep(other)
2234 yc, ye = y.int, y.exp
2235 if y.sign == 1:
2236 yc = -yc
2237
2238 # compute correctly rounded result: start with precision +3,
2239 # then increase precision until result is unambiguously roundable
2240 extra = 3
2241 while True:
2242 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2243 if coeff % (5*10**(len(str(coeff))-p-1)):
2244 break
2245 extra += 3
2246
Facundo Batista72bc54f2007-11-23 17:59:00 +00002247 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002248
2249 # the specification says that for non-integer other we need to
2250 # raise Inexact, even when the result is actually exact. In
2251 # the same way, we need to raise Underflow here if the result
2252 # is subnormal. (The call to _fix will take care of raising
2253 # Rounded and Subnormal, as usual.)
2254 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002255 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002256 # pad with zeros up to length context.prec+1 if necessary
2257 if len(ans._int) <= context.prec:
2258 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002259 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2260 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002261 if ans.adjusted() < context.Emin:
2262 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002263
Facundo Batista353750c2007-09-13 18:13:15 +00002264 # unlike exp, ln and log10, the power function respects the
2265 # rounding mode; no need to use ROUND_HALF_EVEN here
2266 ans = ans._fix(context)
2267 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002268
2269 def __rpow__(self, other, context=None):
2270 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002271 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002272 if other is NotImplemented:
2273 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002274 return other.__pow__(self, context=context)
2275
2276 def normalize(self, context=None):
2277 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002278
Facundo Batista353750c2007-09-13 18:13:15 +00002279 if context is None:
2280 context = getcontext()
2281
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002282 if self._is_special:
2283 ans = self._check_nans(context=context)
2284 if ans:
2285 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002286
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002287 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002288 if dup._isinfinity():
2289 return dup
2290
2291 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002292 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002293 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002294 end = len(dup._int)
2295 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002296 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002297 exp += 1
2298 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002299 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002300
Facundo Batistabd2fe832007-09-13 18:42:09 +00002301 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002302 """Quantize self so its exponent is the same as that of exp.
2303
2304 Similar to self._rescale(exp._exp) but with error checking.
2305 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002306 exp = _convert_other(exp, raiseit=True)
2307
Facundo Batista353750c2007-09-13 18:13:15 +00002308 if context is None:
2309 context = getcontext()
2310 if rounding is None:
2311 rounding = context.rounding
2312
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002313 if self._is_special or exp._is_special:
2314 ans = self._check_nans(exp, context)
2315 if ans:
2316 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002317
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002318 if exp._isinfinity() or self._isinfinity():
2319 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002320 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002321 return context._raise_error(InvalidOperation,
2322 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002323
Facundo Batistabd2fe832007-09-13 18:42:09 +00002324 # if we're not watching exponents, do a simple rescale
2325 if not watchexp:
2326 ans = self._rescale(exp._exp, rounding)
2327 # raise Inexact and Rounded where appropriate
2328 if ans._exp > self._exp:
2329 context._raise_error(Rounded)
2330 if ans != self:
2331 context._raise_error(Inexact)
2332 return ans
2333
Facundo Batista353750c2007-09-13 18:13:15 +00002334 # exp._exp should be between Etiny and Emax
2335 if not (context.Etiny() <= exp._exp <= context.Emax):
2336 return context._raise_error(InvalidOperation,
2337 'target exponent out of bounds in quantize')
2338
2339 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002340 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002341 return ans._fix(context)
2342
2343 self_adjusted = self.adjusted()
2344 if self_adjusted > context.Emax:
2345 return context._raise_error(InvalidOperation,
2346 'exponent of quantize result too large for current context')
2347 if self_adjusted - exp._exp + 1 > context.prec:
2348 return context._raise_error(InvalidOperation,
2349 'quantize result has too many digits for current context')
2350
2351 ans = self._rescale(exp._exp, rounding)
2352 if ans.adjusted() > context.Emax:
2353 return context._raise_error(InvalidOperation,
2354 'exponent of quantize result too large for current context')
2355 if len(ans._int) > context.prec:
2356 return context._raise_error(InvalidOperation,
2357 'quantize result has too many digits for current context')
2358
2359 # raise appropriate flags
2360 if ans._exp > self._exp:
2361 context._raise_error(Rounded)
2362 if ans != self:
2363 context._raise_error(Inexact)
2364 if ans and ans.adjusted() < context.Emin:
2365 context._raise_error(Subnormal)
2366
2367 # call to fix takes care of any necessary folddown
2368 ans = ans._fix(context)
2369 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002370
2371 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002372 """Return True if self and other have the same exponent; otherwise
2373 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002374
Facundo Batista1a191df2007-10-02 17:01:24 +00002375 If either operand is a special value, the following rules are used:
2376 * return True if both operands are infinities
2377 * return True if both operands are NaNs
2378 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002379 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002380 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002381 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002382 return (self.is_nan() and other.is_nan() or
2383 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002384 return self._exp == other._exp
2385
Facundo Batista353750c2007-09-13 18:13:15 +00002386 def _rescale(self, exp, rounding):
2387 """Rescale self so that the exponent is exp, either by padding with zeros
2388 or by truncating digits, using the given rounding mode.
2389
2390 Specials are returned without change. This operation is
2391 quiet: it raises no flags, and uses no information from the
2392 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002393
2394 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002395 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002396 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002397 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002398 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002399 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002400 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002401
Facundo Batista353750c2007-09-13 18:13:15 +00002402 if self._exp >= exp:
2403 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002404 return _dec_from_triple(self._sign,
2405 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002406
Facundo Batista353750c2007-09-13 18:13:15 +00002407 # too many digits; round and lose data. If self.adjusted() <
2408 # exp-1, replace self by 10**(exp-1) before rounding
2409 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002410 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002411 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002412 digits = 0
2413 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002414 changed = this_function(digits)
2415 coeff = self._int[:digits] or '0'
2416 if changed == 1:
2417 coeff = str(int(coeff)+1)
2418 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002419
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00002420 def _round(self, places, rounding):
2421 """Round a nonzero, nonspecial Decimal to a fixed number of
2422 significant figures, using the given rounding mode.
2423
2424 Infinities, NaNs and zeros are returned unaltered.
2425
2426 This operation is quiet: it raises no flags, and uses no
2427 information from the context.
2428
2429 """
2430 if places <= 0:
2431 raise ValueError("argument should be at least 1 in _round")
2432 if self._is_special or not self:
2433 return Decimal(self)
2434 ans = self._rescale(self.adjusted()+1-places, rounding)
2435 # it can happen that the rescale alters the adjusted exponent;
2436 # for example when rounding 99.97 to 3 significant figures.
2437 # When this happens we end up with an extra 0 at the end of
2438 # the number; a second rescale fixes this.
2439 if ans.adjusted() != self.adjusted():
2440 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2441 return ans
2442
Facundo Batista353750c2007-09-13 18:13:15 +00002443 def to_integral_exact(self, rounding=None, context=None):
2444 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002445
Facundo Batista353750c2007-09-13 18:13:15 +00002446 If no rounding mode is specified, take the rounding mode from
2447 the context. This method raises the Rounded and Inexact flags
2448 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002449
Facundo Batista353750c2007-09-13 18:13:15 +00002450 See also: to_integral_value, which does exactly the same as
2451 this method except that it doesn't raise Inexact or Rounded.
2452 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002453 if self._is_special:
2454 ans = self._check_nans(context=context)
2455 if ans:
2456 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002457 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002458 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002459 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002460 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002461 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002462 if context is None:
2463 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002464 if rounding is None:
2465 rounding = context.rounding
2466 context._raise_error(Rounded)
2467 ans = self._rescale(0, rounding)
2468 if ans != self:
2469 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002470 return ans
2471
Facundo Batista353750c2007-09-13 18:13:15 +00002472 def to_integral_value(self, rounding=None, context=None):
2473 """Rounds to the nearest integer, without raising inexact, rounded."""
2474 if context is None:
2475 context = getcontext()
2476 if rounding is None:
2477 rounding = context.rounding
2478 if self._is_special:
2479 ans = self._check_nans(context=context)
2480 if ans:
2481 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002482 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002483 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002484 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002485 else:
2486 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002487
Facundo Batista353750c2007-09-13 18:13:15 +00002488 # the method name changed, but we provide also the old one, for compatibility
2489 to_integral = to_integral_value
2490
2491 def sqrt(self, context=None):
2492 """Return the square root of self."""
Mark Dickinson3b24ccb2008-03-25 14:33:23 +00002493 if context is None:
2494 context = getcontext()
2495
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002496 if self._is_special:
2497 ans = self._check_nans(context=context)
2498 if ans:
2499 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002500
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002501 if self._isinfinity() and self._sign == 0:
2502 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002503
2504 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002505 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002506 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002507 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002508
2509 if self._sign == 1:
2510 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2511
Facundo Batista353750c2007-09-13 18:13:15 +00002512 # At this point self represents a positive number. Let p be
2513 # the desired precision and express self in the form c*100**e
2514 # with c a positive real number and e an integer, c and e
2515 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2516 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2517 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2518 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2519 # the closest integer to sqrt(c) with the even integer chosen
2520 # in the case of a tie.
2521 #
2522 # To ensure correct rounding in all cases, we use the
2523 # following trick: we compute the square root to an extra
2524 # place (precision p+1 instead of precision p), rounding down.
2525 # Then, if the result is inexact and its last digit is 0 or 5,
2526 # we increase the last digit to 1 or 6 respectively; if it's
2527 # exact we leave the last digit alone. Now the final round to
2528 # p places (or fewer in the case of underflow) will round
2529 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002530
Facundo Batista353750c2007-09-13 18:13:15 +00002531 # use an extra digit of precision
2532 prec = context.prec+1
2533
2534 # write argument in the form c*100**e where e = self._exp//2
2535 # is the 'ideal' exponent, to be used if the square root is
2536 # exactly representable. l is the number of 'digits' of c in
2537 # base 100, so that 100**(l-1) <= c < 100**l.
2538 op = _WorkRep(self)
2539 e = op.exp >> 1
2540 if op.exp & 1:
2541 c = op.int * 10
2542 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002543 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002544 c = op.int
2545 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002546
Facundo Batista353750c2007-09-13 18:13:15 +00002547 # rescale so that c has exactly prec base 100 'digits'
2548 shift = prec-l
2549 if shift >= 0:
2550 c *= 100**shift
2551 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002552 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002553 c, remainder = divmod(c, 100**-shift)
2554 exact = not remainder
2555 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002556
Facundo Batista353750c2007-09-13 18:13:15 +00002557 # find n = floor(sqrt(c)) using Newton's method
2558 n = 10**prec
2559 while True:
2560 q = c//n
2561 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002562 break
Facundo Batista353750c2007-09-13 18:13:15 +00002563 else:
2564 n = n + q >> 1
2565 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002566
Facundo Batista353750c2007-09-13 18:13:15 +00002567 if exact:
2568 # result is exact; rescale to use ideal exponent e
2569 if shift >= 0:
2570 # assert n % 10**shift == 0
2571 n //= 10**shift
2572 else:
2573 n *= 10**-shift
2574 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002575 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002576 # result is not exact; fix last digit as described above
2577 if n % 5 == 0:
2578 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002579
Facundo Batista72bc54f2007-11-23 17:59:00 +00002580 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002581
Facundo Batista353750c2007-09-13 18:13:15 +00002582 # round, and fit to current context
2583 context = context._shallow_copy()
2584 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002585 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002586 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002587
Facundo Batista353750c2007-09-13 18:13:15 +00002588 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002589
2590 def max(self, other, context=None):
2591 """Returns the larger value.
2592
Facundo Batista353750c2007-09-13 18:13:15 +00002593 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002594 NaN (and signals if one is sNaN). Also rounds.
2595 """
Facundo Batista353750c2007-09-13 18:13:15 +00002596 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002597
Facundo Batista6c398da2007-09-17 17:30:13 +00002598 if context is None:
2599 context = getcontext()
2600
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002601 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002602 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002603 # number is always returned
2604 sn = self._isnan()
2605 on = other._isnan()
2606 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002607 if on == 1 and sn == 0:
2608 return self._fix(context)
2609 if sn == 1 and on == 0:
2610 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002611 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002612
Mark Dickinson2fc92632008-02-06 22:10:50 +00002613 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002614 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002615 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002616 # then an ordering is applied:
2617 #
Facundo Batista59c58842007-04-10 12:58:45 +00002618 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002619 # positive sign and min returns the operand with the negative sign
2620 #
Facundo Batista59c58842007-04-10 12:58:45 +00002621 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002622 # the result. This is exactly the ordering used in compare_total.
2623 c = self.compare_total(other)
2624
2625 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002626 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002627 else:
2628 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002629
Facundo Batistae64acfa2007-12-17 14:18:42 +00002630 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002631
2632 def min(self, other, context=None):
2633 """Returns the smaller value.
2634
Facundo Batista59c58842007-04-10 12:58:45 +00002635 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002636 NaN (and signals if one is sNaN). Also rounds.
2637 """
Facundo Batista353750c2007-09-13 18:13:15 +00002638 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002639
Facundo Batista6c398da2007-09-17 17:30:13 +00002640 if context is None:
2641 context = getcontext()
2642
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002643 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002644 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002645 # number is always returned
2646 sn = self._isnan()
2647 on = other._isnan()
2648 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002649 if on == 1 and sn == 0:
2650 return self._fix(context)
2651 if sn == 1 and on == 0:
2652 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002653 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002654
Mark Dickinson2fc92632008-02-06 22:10:50 +00002655 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002656 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002657 c = self.compare_total(other)
2658
2659 if c == -1:
2660 ans = self
2661 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002662 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002663
Facundo Batistae64acfa2007-12-17 14:18:42 +00002664 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002665
2666 def _isinteger(self):
2667 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002668 if self._is_special:
2669 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002670 if self._exp >= 0:
2671 return True
2672 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002673 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002674
2675 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002676 """Returns True if self is even. Assumes self is an integer."""
2677 if not self or self._exp > 0:
2678 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002679 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002680
2681 def adjusted(self):
2682 """Return the adjusted exponent of self"""
2683 try:
2684 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002685 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002686 except TypeError:
2687 return 0
2688
Facundo Batista353750c2007-09-13 18:13:15 +00002689 def canonical(self, context=None):
2690 """Returns the same Decimal object.
2691
2692 As we do not have different encodings for the same number, the
2693 received object already is in its canonical form.
2694 """
2695 return self
2696
2697 def compare_signal(self, other, context=None):
2698 """Compares self to the other operand numerically.
2699
2700 It's pretty much like compare(), but all NaNs signal, with signaling
2701 NaNs taking precedence over quiet NaNs.
2702 """
Mark Dickinson2fc92632008-02-06 22:10:50 +00002703 other = _convert_other(other, raiseit = True)
2704 ans = self._compare_check_nans(other, context)
2705 if ans:
2706 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002707 return self.compare(other, context=context)
2708
2709 def compare_total(self, other):
2710 """Compares self to other using the abstract representations.
2711
2712 This is not like the standard compare, which use their numerical
2713 value. Note that a total ordering is defined for all possible abstract
2714 representations.
2715 """
2716 # if one is negative and the other is positive, it's easy
2717 if self._sign and not other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002718 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002719 if not self._sign and other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002720 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002721 sign = self._sign
2722
2723 # let's handle both NaN types
2724 self_nan = self._isnan()
2725 other_nan = other._isnan()
2726 if self_nan or other_nan:
2727 if self_nan == other_nan:
2728 if self._int < other._int:
2729 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002730 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002731 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002732 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002733 if self._int > other._int:
2734 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002735 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002736 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002737 return _One
2738 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002739
2740 if sign:
2741 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002742 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002743 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002744 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002745 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002746 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002747 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002748 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002749 else:
2750 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002751 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002752 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002753 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002754 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002755 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002756 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002757 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002758
2759 if self < other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002760 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002761 if self > other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002762 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002763
2764 if self._exp < other._exp:
2765 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002766 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002767 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002768 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002769 if self._exp > other._exp:
2770 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002771 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002772 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002773 return _One
2774 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002775
2776
2777 def compare_total_mag(self, other):
2778 """Compares self to other using abstract repr., ignoring sign.
2779
2780 Like compare_total, but with operand's sign ignored and assumed to be 0.
2781 """
2782 s = self.copy_abs()
2783 o = other.copy_abs()
2784 return s.compare_total(o)
2785
2786 def copy_abs(self):
2787 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002788 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002789
2790 def copy_negate(self):
2791 """Returns a copy with the sign inverted."""
2792 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002793 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002794 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002795 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002796
2797 def copy_sign(self, other):
2798 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002799 return _dec_from_triple(other._sign, self._int,
2800 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002801
2802 def exp(self, context=None):
2803 """Returns e ** self."""
2804
2805 if context is None:
2806 context = getcontext()
2807
2808 # exp(NaN) = NaN
2809 ans = self._check_nans(context=context)
2810 if ans:
2811 return ans
2812
2813 # exp(-Infinity) = 0
2814 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002815 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002816
2817 # exp(0) = 1
2818 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002819 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002820
2821 # exp(Infinity) = Infinity
2822 if self._isinfinity() == 1:
2823 return Decimal(self)
2824
2825 # the result is now guaranteed to be inexact (the true
2826 # mathematical result is transcendental). There's no need to
2827 # raise Rounded and Inexact here---they'll always be raised as
2828 # a result of the call to _fix.
2829 p = context.prec
2830 adj = self.adjusted()
2831
2832 # we only need to do any computation for quite a small range
2833 # of adjusted exponents---for example, -29 <= adj <= 10 for
2834 # the default context. For smaller exponent the result is
2835 # indistinguishable from 1 at the given precision, while for
2836 # larger exponent the result either overflows or underflows.
2837 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2838 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002839 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002840 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2841 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002842 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002843 elif self._sign == 0 and adj < -p:
2844 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002845 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002846 elif self._sign == 1 and adj < -p-1:
2847 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002848 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002849 # general case
2850 else:
2851 op = _WorkRep(self)
2852 c, e = op.int, op.exp
2853 if op.sign == 1:
2854 c = -c
2855
2856 # compute correctly rounded result: increase precision by
2857 # 3 digits at a time until we get an unambiguously
2858 # roundable result
2859 extra = 3
2860 while True:
2861 coeff, exp = _dexp(c, e, p+extra)
2862 if coeff % (5*10**(len(str(coeff))-p-1)):
2863 break
2864 extra += 3
2865
Facundo Batista72bc54f2007-11-23 17:59:00 +00002866 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002867
2868 # at this stage, ans should round correctly with *any*
2869 # rounding mode, not just with ROUND_HALF_EVEN
2870 context = context._shallow_copy()
2871 rounding = context._set_rounding(ROUND_HALF_EVEN)
2872 ans = ans._fix(context)
2873 context.rounding = rounding
2874
2875 return ans
2876
2877 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002878 """Return True if self is canonical; otherwise return False.
2879
2880 Currently, the encoding of a Decimal instance is always
2881 canonical, so this method returns True for any Decimal.
2882 """
2883 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002884
2885 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002886 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002887
Facundo Batista1a191df2007-10-02 17:01:24 +00002888 A Decimal instance is considered finite if it is neither
2889 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002890 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002891 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002892
2893 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002894 """Return True if self is infinite; otherwise return False."""
2895 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002896
2897 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002898 """Return True if self is a qNaN or sNaN; otherwise return False."""
2899 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002900
2901 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002902 """Return True if self is a normal number; otherwise return False."""
2903 if self._is_special or not self:
2904 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002905 if context is None:
2906 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002907 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002908
2909 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002910 """Return True if self is a quiet NaN; otherwise return False."""
2911 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002912
2913 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002914 """Return True if self is negative; otherwise return False."""
2915 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002916
2917 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002918 """Return True if self is a signaling NaN; otherwise return False."""
2919 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002920
2921 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002922 """Return True if self is subnormal; otherwise return False."""
2923 if self._is_special or not self:
2924 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002925 if context is None:
2926 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002927 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002928
2929 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002930 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002931 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002932
2933 def _ln_exp_bound(self):
2934 """Compute a lower bound for the adjusted exponent of self.ln().
2935 In other words, compute r such that self.ln() >= 10**r. Assumes
2936 that self is finite and positive and that self != 1.
2937 """
2938
2939 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2940 adj = self._exp + len(self._int) - 1
2941 if adj >= 1:
2942 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2943 return len(str(adj*23//10)) - 1
2944 if adj <= -2:
2945 # argument <= 0.1
2946 return len(str((-1-adj)*23//10)) - 1
2947 op = _WorkRep(self)
2948 c, e = op.int, op.exp
2949 if adj == 0:
2950 # 1 < self < 10
2951 num = str(c-10**-e)
2952 den = str(c)
2953 return len(num) - len(den) - (num < den)
2954 # adj == -1, 0.1 <= self < 1
2955 return e + len(str(10**-e - c)) - 1
2956
2957
2958 def ln(self, context=None):
2959 """Returns the natural (base e) logarithm of self."""
2960
2961 if context is None:
2962 context = getcontext()
2963
2964 # ln(NaN) = NaN
2965 ans = self._check_nans(context=context)
2966 if ans:
2967 return ans
2968
2969 # ln(0.0) == -Infinity
2970 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002971 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00002972
2973 # ln(Infinity) = Infinity
2974 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002975 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00002976
2977 # ln(1.0) == 0.0
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002978 if self == _One:
2979 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002980
2981 # ln(negative) raises InvalidOperation
2982 if self._sign == 1:
2983 return context._raise_error(InvalidOperation,
2984 'ln of a negative value')
2985
2986 # result is irrational, so necessarily inexact
2987 op = _WorkRep(self)
2988 c, e = op.int, op.exp
2989 p = context.prec
2990
2991 # correctly rounded result: repeatedly increase precision by 3
2992 # until we get an unambiguously roundable result
2993 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2994 while True:
2995 coeff = _dlog(c, e, places)
2996 # assert len(str(abs(coeff)))-p >= 1
2997 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2998 break
2999 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003000 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003001
3002 context = context._shallow_copy()
3003 rounding = context._set_rounding(ROUND_HALF_EVEN)
3004 ans = ans._fix(context)
3005 context.rounding = rounding
3006 return ans
3007
3008 def _log10_exp_bound(self):
3009 """Compute a lower bound for the adjusted exponent of self.log10().
3010 In other words, find r such that self.log10() >= 10**r.
3011 Assumes that self is finite and positive and that self != 1.
3012 """
3013
3014 # For x >= 10 or x < 0.1 we only need a bound on the integer
3015 # part of log10(self), and this comes directly from the
3016 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3017 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3018 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3019
3020 adj = self._exp + len(self._int) - 1
3021 if adj >= 1:
3022 # self >= 10
3023 return len(str(adj))-1
3024 if adj <= -2:
3025 # self < 0.1
3026 return len(str(-1-adj))-1
3027 op = _WorkRep(self)
3028 c, e = op.int, op.exp
3029 if adj == 0:
3030 # 1 < self < 10
3031 num = str(c-10**-e)
3032 den = str(231*c)
3033 return len(num) - len(den) - (num < den) + 2
3034 # adj == -1, 0.1 <= self < 1
3035 num = str(10**-e-c)
3036 return len(num) + e - (num < "231") - 1
3037
3038 def log10(self, context=None):
3039 """Returns the base 10 logarithm of self."""
3040
3041 if context is None:
3042 context = getcontext()
3043
3044 # log10(NaN) = NaN
3045 ans = self._check_nans(context=context)
3046 if ans:
3047 return ans
3048
3049 # log10(0.0) == -Infinity
3050 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003051 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003052
3053 # log10(Infinity) = Infinity
3054 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003055 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003056
3057 # log10(negative or -Infinity) raises InvalidOperation
3058 if self._sign == 1:
3059 return context._raise_error(InvalidOperation,
3060 'log10 of a negative value')
3061
3062 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00003063 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00003064 # answer may need rounding
3065 ans = Decimal(self._exp + len(self._int) - 1)
3066 else:
3067 # result is irrational, so necessarily inexact
3068 op = _WorkRep(self)
3069 c, e = op.int, op.exp
3070 p = context.prec
3071
3072 # correctly rounded result: repeatedly increase precision
3073 # until result is unambiguously roundable
3074 places = p-self._log10_exp_bound()+2
3075 while True:
3076 coeff = _dlog10(c, e, places)
3077 # assert len(str(abs(coeff)))-p >= 1
3078 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3079 break
3080 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003081 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003082
3083 context = context._shallow_copy()
3084 rounding = context._set_rounding(ROUND_HALF_EVEN)
3085 ans = ans._fix(context)
3086 context.rounding = rounding
3087 return ans
3088
3089 def logb(self, context=None):
3090 """ Returns the exponent of the magnitude of self's MSD.
3091
3092 The result is the integer which is the exponent of the magnitude
3093 of the most significant digit of self (as though it were truncated
3094 to a single digit while maintaining the value of that digit and
3095 without limiting the resulting exponent).
3096 """
3097 # logb(NaN) = NaN
3098 ans = self._check_nans(context=context)
3099 if ans:
3100 return ans
3101
3102 if context is None:
3103 context = getcontext()
3104
3105 # logb(+/-Inf) = +Inf
3106 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003107 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003108
3109 # logb(0) = -Inf, DivisionByZero
3110 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003111 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003112
3113 # otherwise, simply return the adjusted exponent of self, as a
3114 # Decimal. Note that no attempt is made to fit the result
3115 # into the current context.
3116 return Decimal(self.adjusted())
3117
3118 def _islogical(self):
3119 """Return True if self is a logical operand.
3120
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00003121 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00003122 an exponent of 0, and a coefficient whose digits must all be
3123 either 0 or 1.
3124 """
3125 if self._sign != 0 or self._exp != 0:
3126 return False
3127 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003128 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003129 return False
3130 return True
3131
3132 def _fill_logical(self, context, opa, opb):
3133 dif = context.prec - len(opa)
3134 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003135 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003136 elif dif < 0:
3137 opa = opa[-context.prec:]
3138 dif = context.prec - len(opb)
3139 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003140 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003141 elif dif < 0:
3142 opb = opb[-context.prec:]
3143 return opa, opb
3144
3145 def logical_and(self, other, context=None):
3146 """Applies an 'and' operation between self and other's digits."""
3147 if context is None:
3148 context = getcontext()
3149 if not self._islogical() or not other._islogical():
3150 return context._raise_error(InvalidOperation)
3151
3152 # fill to context.prec
3153 (opa, opb) = self._fill_logical(context, self._int, other._int)
3154
3155 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003156 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3157 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003158
3159 def logical_invert(self, context=None):
3160 """Invert all its digits."""
3161 if context is None:
3162 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003163 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3164 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003165
3166 def logical_or(self, other, context=None):
3167 """Applies an 'or' operation between self and other's digits."""
3168 if context is None:
3169 context = getcontext()
3170 if not self._islogical() or not other._islogical():
3171 return context._raise_error(InvalidOperation)
3172
3173 # fill to context.prec
3174 (opa, opb) = self._fill_logical(context, self._int, other._int)
3175
3176 # make the operation, and clean starting zeroes
Mark Dickinson65808ff2009-01-04 21:22:02 +00003177 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003178 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003179
3180 def logical_xor(self, other, context=None):
3181 """Applies an 'xor' operation between self and other's digits."""
3182 if context is None:
3183 context = getcontext()
3184 if not self._islogical() or not other._islogical():
3185 return context._raise_error(InvalidOperation)
3186
3187 # fill to context.prec
3188 (opa, opb) = self._fill_logical(context, self._int, other._int)
3189
3190 # make the operation, and clean starting zeroes
Mark Dickinson65808ff2009-01-04 21:22:02 +00003191 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003192 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003193
3194 def max_mag(self, other, context=None):
3195 """Compares the values numerically with their sign ignored."""
3196 other = _convert_other(other, raiseit=True)
3197
Facundo Batista6c398da2007-09-17 17:30:13 +00003198 if context is None:
3199 context = getcontext()
3200
Facundo Batista353750c2007-09-13 18:13:15 +00003201 if self._is_special or other._is_special:
3202 # If one operand is a quiet NaN and the other is number, then the
3203 # number is always returned
3204 sn = self._isnan()
3205 on = other._isnan()
3206 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003207 if on == 1 and sn == 0:
3208 return self._fix(context)
3209 if sn == 1 and on == 0:
3210 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003211 return self._check_nans(other, context)
3212
Mark Dickinson2fc92632008-02-06 22:10:50 +00003213 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003214 if c == 0:
3215 c = self.compare_total(other)
3216
3217 if c == -1:
3218 ans = other
3219 else:
3220 ans = self
3221
Facundo Batistae64acfa2007-12-17 14:18:42 +00003222 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003223
3224 def min_mag(self, other, context=None):
3225 """Compares the values numerically with their sign ignored."""
3226 other = _convert_other(other, raiseit=True)
3227
Facundo Batista6c398da2007-09-17 17:30:13 +00003228 if context is None:
3229 context = getcontext()
3230
Facundo Batista353750c2007-09-13 18:13:15 +00003231 if self._is_special or other._is_special:
3232 # If one operand is a quiet NaN and the other is number, then the
3233 # number is always returned
3234 sn = self._isnan()
3235 on = other._isnan()
3236 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003237 if on == 1 and sn == 0:
3238 return self._fix(context)
3239 if sn == 1 and on == 0:
3240 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003241 return self._check_nans(other, context)
3242
Mark Dickinson2fc92632008-02-06 22:10:50 +00003243 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003244 if c == 0:
3245 c = self.compare_total(other)
3246
3247 if c == -1:
3248 ans = self
3249 else:
3250 ans = other
3251
Facundo Batistae64acfa2007-12-17 14:18:42 +00003252 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003253
3254 def next_minus(self, context=None):
3255 """Returns the largest representable number smaller than itself."""
3256 if context is None:
3257 context = getcontext()
3258
3259 ans = self._check_nans(context=context)
3260 if ans:
3261 return ans
3262
3263 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003264 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003265 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003266 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003267
3268 context = context.copy()
3269 context._set_rounding(ROUND_FLOOR)
3270 context._ignore_all_flags()
3271 new_self = self._fix(context)
3272 if new_self != self:
3273 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003274 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3275 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003276
3277 def next_plus(self, context=None):
3278 """Returns the smallest representable number larger than itself."""
3279 if context is None:
3280 context = getcontext()
3281
3282 ans = self._check_nans(context=context)
3283 if ans:
3284 return ans
3285
3286 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003287 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003288 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003289 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003290
3291 context = context.copy()
3292 context._set_rounding(ROUND_CEILING)
3293 context._ignore_all_flags()
3294 new_self = self._fix(context)
3295 if new_self != self:
3296 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003297 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3298 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003299
3300 def next_toward(self, other, context=None):
3301 """Returns the number closest to self, in the direction towards other.
3302
3303 The result is the closest representable number to self
3304 (excluding self) that is in the direction towards other,
3305 unless both have the same value. If the two operands are
3306 numerically equal, then the result is a copy of self with the
3307 sign set to be the same as the sign of other.
3308 """
3309 other = _convert_other(other, raiseit=True)
3310
3311 if context is None:
3312 context = getcontext()
3313
3314 ans = self._check_nans(other, context)
3315 if ans:
3316 return ans
3317
Mark Dickinson2fc92632008-02-06 22:10:50 +00003318 comparison = self._cmp(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003319 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003320 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003321
3322 if comparison == -1:
3323 ans = self.next_plus(context)
3324 else: # comparison == 1
3325 ans = self.next_minus(context)
3326
3327 # decide which flags to raise using value of ans
3328 if ans._isinfinity():
3329 context._raise_error(Overflow,
3330 'Infinite result from next_toward',
3331 ans._sign)
3332 context._raise_error(Rounded)
3333 context._raise_error(Inexact)
3334 elif ans.adjusted() < context.Emin:
3335 context._raise_error(Underflow)
3336 context._raise_error(Subnormal)
3337 context._raise_error(Rounded)
3338 context._raise_error(Inexact)
3339 # if precision == 1 then we don't raise Clamped for a
3340 # result 0E-Etiny.
3341 if not ans:
3342 context._raise_error(Clamped)
3343
3344 return ans
3345
3346 def number_class(self, context=None):
3347 """Returns an indication of the class of self.
3348
3349 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003350 sNaN
3351 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003352 -Infinity
3353 -Normal
3354 -Subnormal
3355 -Zero
3356 +Zero
3357 +Subnormal
3358 +Normal
3359 +Infinity
3360 """
3361 if self.is_snan():
3362 return "sNaN"
3363 if self.is_qnan():
3364 return "NaN"
3365 inf = self._isinfinity()
3366 if inf == 1:
3367 return "+Infinity"
3368 if inf == -1:
3369 return "-Infinity"
3370 if self.is_zero():
3371 if self._sign:
3372 return "-Zero"
3373 else:
3374 return "+Zero"
3375 if context is None:
3376 context = getcontext()
3377 if self.is_subnormal(context=context):
3378 if self._sign:
3379 return "-Subnormal"
3380 else:
3381 return "+Subnormal"
3382 # just a normal, regular, boring number, :)
3383 if self._sign:
3384 return "-Normal"
3385 else:
3386 return "+Normal"
3387
3388 def radix(self):
3389 """Just returns 10, as this is Decimal, :)"""
3390 return Decimal(10)
3391
3392 def rotate(self, other, context=None):
3393 """Returns a rotated copy of self, value-of-other times."""
3394 if context is None:
3395 context = getcontext()
3396
3397 ans = self._check_nans(other, context)
3398 if ans:
3399 return ans
3400
3401 if other._exp != 0:
3402 return context._raise_error(InvalidOperation)
3403 if not (-context.prec <= int(other) <= context.prec):
3404 return context._raise_error(InvalidOperation)
3405
3406 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003407 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003408
3409 # get values, pad if necessary
3410 torot = int(other)
3411 rotdig = self._int
3412 topad = context.prec - len(rotdig)
3413 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003414 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003415
3416 # let's rotate!
3417 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003418 return _dec_from_triple(self._sign,
3419 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003420
3421 def scaleb (self, other, context=None):
3422 """Returns self operand after adding the second value to its exp."""
3423 if context is None:
3424 context = getcontext()
3425
3426 ans = self._check_nans(other, context)
3427 if ans:
3428 return ans
3429
3430 if other._exp != 0:
3431 return context._raise_error(InvalidOperation)
3432 liminf = -2 * (context.Emax + context.prec)
3433 limsup = 2 * (context.Emax + context.prec)
3434 if not (liminf <= int(other) <= limsup):
3435 return context._raise_error(InvalidOperation)
3436
3437 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003438 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003439
Facundo Batista72bc54f2007-11-23 17:59:00 +00003440 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003441 d = d._fix(context)
3442 return d
3443
3444 def shift(self, other, context=None):
3445 """Returns a shifted copy of self, value-of-other times."""
3446 if context is None:
3447 context = getcontext()
3448
3449 ans = self._check_nans(other, context)
3450 if ans:
3451 return ans
3452
3453 if other._exp != 0:
3454 return context._raise_error(InvalidOperation)
3455 if not (-context.prec <= int(other) <= context.prec):
3456 return context._raise_error(InvalidOperation)
3457
3458 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003459 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003460
3461 # get values, pad if necessary
3462 torot = int(other)
3463 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003464 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003465 rotdig = self._int
3466 topad = context.prec - len(rotdig)
3467 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003468 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003469
3470 # let's shift!
3471 if torot < 0:
3472 rotated = rotdig[:torot]
3473 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003474 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003475 rotated = rotated[-context.prec:]
3476
Facundo Batista72bc54f2007-11-23 17:59:00 +00003477 return _dec_from_triple(self._sign,
3478 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003479
Facundo Batista59c58842007-04-10 12:58:45 +00003480 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003481 def __reduce__(self):
3482 return (self.__class__, (str(self),))
3483
3484 def __copy__(self):
3485 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003486 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003487 return self.__class__(str(self))
3488
3489 def __deepcopy__(self, memo):
3490 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003491 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003492 return self.__class__(str(self))
3493
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003494 # PEP 3101 support. See also _parse_format_specifier and _format_align
3495 def __format__(self, specifier, context=None):
Mark Dickinsonf4da7772008-02-29 03:29:17 +00003496 """Format a Decimal instance according to the given specifier.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003497
3498 The specifier should be a standard format specifier, with the
3499 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3500 'F', 'g', 'G', and '%' are supported. If the formatting type
3501 is omitted it defaults to 'g' or 'G', depending on the value
3502 of context.capitals.
3503
3504 At this time the 'n' format specifier type (which is supposed
3505 to use the current locale) is not supported.
3506 """
3507
3508 # Note: PEP 3101 says that if the type is not present then
3509 # there should be at least one digit after the decimal point.
3510 # We take the liberty of ignoring this requirement for
3511 # Decimal---it's presumably there to make sure that
3512 # format(float, '') behaves similarly to str(float).
3513 if context is None:
3514 context = getcontext()
3515
3516 spec = _parse_format_specifier(specifier)
3517
3518 # special values don't care about the type or precision...
3519 if self._is_special:
3520 return _format_align(str(self), spec)
3521
3522 # a type of None defaults to 'g' or 'G', depending on context
3523 # if type is '%', adjust exponent of self accordingly
3524 if spec['type'] is None:
3525 spec['type'] = ['g', 'G'][context.capitals]
3526 elif spec['type'] == '%':
3527 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3528
3529 # round if necessary, taking rounding mode from the context
3530 rounding = context.rounding
3531 precision = spec['precision']
3532 if precision is not None:
3533 if spec['type'] in 'eE':
3534 self = self._round(precision+1, rounding)
3535 elif spec['type'] in 'gG':
3536 if len(self._int) > precision:
3537 self = self._round(precision, rounding)
3538 elif spec['type'] in 'fF%':
3539 self = self._rescale(-precision, rounding)
3540 # special case: zeros with a positive exponent can't be
3541 # represented in fixed point; rescale them to 0e0.
3542 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3543 self = self._rescale(0, rounding)
3544
3545 # figure out placement of the decimal point
3546 leftdigits = self._exp + len(self._int)
3547 if spec['type'] in 'fF%':
3548 dotplace = leftdigits
3549 elif spec['type'] in 'eE':
3550 if not self and precision is not None:
3551 dotplace = 1 - precision
3552 else:
3553 dotplace = 1
3554 elif spec['type'] in 'gG':
3555 if self._exp <= 0 and leftdigits > -6:
3556 dotplace = leftdigits
3557 else:
3558 dotplace = 1
3559
3560 # figure out main part of numeric string...
3561 if dotplace <= 0:
3562 num = '0.' + '0'*(-dotplace) + self._int
3563 elif dotplace >= len(self._int):
3564 # make sure we're not padding a '0' with extra zeros on the right
3565 assert dotplace==len(self._int) or self._int != '0'
3566 num = self._int + '0'*(dotplace-len(self._int))
3567 else:
3568 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3569
3570 # ...then the trailing exponent, or trailing '%'
3571 if leftdigits != dotplace or spec['type'] in 'eE':
3572 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3573 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3574 elif spec['type'] == '%':
3575 num = num + '%'
3576
3577 # add sign
3578 if self._sign == 1:
3579 num = '-' + num
3580 return _format_align(num, spec)
3581
3582
Facundo Batista72bc54f2007-11-23 17:59:00 +00003583def _dec_from_triple(sign, coefficient, exponent, special=False):
3584 """Create a decimal instance directly, without any validation,
3585 normalization (e.g. removal of leading zeros) or argument
3586 conversion.
3587
3588 This function is for *internal use only*.
3589 """
3590
3591 self = object.__new__(Decimal)
3592 self._sign = sign
3593 self._int = coefficient
3594 self._exp = exponent
3595 self._is_special = special
3596
3597 return self
3598
Facundo Batista59c58842007-04-10 12:58:45 +00003599##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003600
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003601
3602# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003603rounding_functions = [name for name in Decimal.__dict__.keys()
3604 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003605for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003606 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003607 globalname = name[1:].upper()
3608 val = globals()[globalname]
3609 Decimal._pick_rounding_function[val] = name
3610
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003611del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003612
Nick Coghlanced12182006-09-02 03:54:17 +00003613class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003614 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003615
Nick Coghlanced12182006-09-02 03:54:17 +00003616 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003617 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003618 """
3619 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003620 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003621 def __enter__(self):
3622 self.saved_context = getcontext()
3623 setcontext(self.new_context)
3624 return self.new_context
3625 def __exit__(self, t, v, tb):
3626 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003627
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003628class Context(object):
3629 """Contains the context for a Decimal instance.
3630
3631 Contains:
3632 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003633 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003634 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003635 raised when it is caused. Otherwise, a value is
3636 substituted in.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003637 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003638 (Whether or not the trap_enabler is set)
3639 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003640 Emin - Minimum exponent
3641 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003642 capitals - If 1, 1*10^1 is printed as 1E+1.
3643 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003644 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003645 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003646
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003647 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003648 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003649 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003650 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003651 _ignored_flags=None):
3652 if flags is None:
3653 flags = []
3654 if _ignored_flags is None:
3655 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003656 if not isinstance(flags, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003657 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003658 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003659 if traps is not None and not isinstance(traps, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003660 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003661 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003662 for name, val in locals().items():
3663 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003664 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003665 else:
3666 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003667 del self.self
3668
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003669 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003670 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003671 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003672 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3673 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3674 % vars(self))
3675 names = [f.__name__ for f, v in self.flags.items() if v]
3676 s.append('flags=[' + ', '.join(names) + ']')
3677 names = [t.__name__ for t, v in self.traps.items() if v]
3678 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003679 return ', '.join(s) + ')'
3680
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003681 def clear_flags(self):
3682 """Reset all flags to zero"""
3683 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003684 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003685
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003686 def _shallow_copy(self):
3687 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003688 nc = Context(self.prec, self.rounding, self.traps,
3689 self.flags, self.Emin, self.Emax,
3690 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003691 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003692
3693 def copy(self):
3694 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003695 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003696 self.flags.copy(), self.Emin, self.Emax,
3697 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003698 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003699 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003700
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003701 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003702 """Handles an error
3703
3704 If the flag is in _ignored_flags, returns the default response.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003705 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003706 trap_enabler is set, it reaises the exception. Otherwise, it returns
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003707 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003708 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003709 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003710 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003711 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003712 return error().handle(self, *args)
3713
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003714 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003715 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003716 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003717 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003718
3719 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003720 # self._ignored_flags = []
Mark Dickinson8aca9d02008-05-04 02:05:06 +00003721 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003722
3723 def _ignore_all_flags(self):
3724 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003725 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003726
3727 def _ignore_flags(self, *flags):
3728 """Ignore the flags, if they are raised"""
3729 # Do not mutate-- This way, copies of a context leave the original
3730 # alone.
3731 self._ignored_flags = (self._ignored_flags + list(flags))
3732 return list(flags)
3733
3734 def _regard_flags(self, *flags):
3735 """Stop ignoring the flags, if they are raised"""
3736 if flags and isinstance(flags[0], (tuple,list)):
3737 flags = flags[0]
3738 for flag in flags:
3739 self._ignored_flags.remove(flag)
3740
Nick Coghlan53663a62008-07-15 14:27:37 +00003741 # We inherit object.__hash__, so we must deny this explicitly
3742 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003743
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003744 def Etiny(self):
3745 """Returns Etiny (= Emin - prec + 1)"""
3746 return int(self.Emin - self.prec + 1)
3747
3748 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003749 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003750 return int(self.Emax - self.prec + 1)
3751
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003752 def _set_rounding(self, type):
3753 """Sets the rounding type.
3754
3755 Sets the rounding type, and returns the current (previous)
3756 rounding type. Often used like:
3757
3758 context = context.copy()
3759 # so you don't change the calling context
3760 # if an error occurs in the middle.
3761 rounding = context._set_rounding(ROUND_UP)
3762 val = self.__sub__(other, context=context)
3763 context._set_rounding(rounding)
3764
3765 This will make it round up for that operation.
3766 """
3767 rounding = self.rounding
3768 self.rounding= type
3769 return rounding
3770
Raymond Hettingerfed52962004-07-14 15:41:57 +00003771 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003772 """Creates a new Decimal instance but using self as context.
3773
3774 This method implements the to-number operation of the
3775 IBM Decimal specification."""
3776
3777 if isinstance(num, basestring) and num != num.strip():
3778 return self._raise_error(ConversionSyntax,
3779 "no trailing or leading whitespace is "
3780 "permitted.")
3781
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003782 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003783 if d._isnan() and len(d._int) > self.prec - self._clamp:
3784 return self._raise_error(ConversionSyntax,
3785 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003786 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003787
Raymond Hettingerf4d85972009-01-03 19:02:23 +00003788 def create_decimal_from_float(self, f):
3789 """Creates a new Decimal instance from a float but rounding using self
3790 as the context.
3791
3792 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3793 >>> context.create_decimal_from_float(3.1415926535897932)
3794 Decimal('3.1415')
3795 >>> context = Context(prec=5, traps=[Inexact])
3796 >>> context.create_decimal_from_float(3.1415926535897932)
3797 Traceback (most recent call last):
3798 ...
3799 Inexact: None
3800
3801 """
3802 d = Decimal.from_float(f) # An exact conversion
3803 return d._fix(self) # Apply the context rounding
3804
Facundo Batista59c58842007-04-10 12:58:45 +00003805 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003806 def abs(self, a):
3807 """Returns the absolute value of the operand.
3808
3809 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003810 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003811 the plus operation on the operand.
3812
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003813 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003814 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003815 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003816 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003817 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003818 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003819 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003820 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003821 """
3822 return a.__abs__(context=self)
3823
3824 def add(self, a, b):
3825 """Return the sum of the two operands.
3826
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003827 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003828 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003829 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003830 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003831 """
3832 return a.__add__(b, context=self)
3833
3834 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003835 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003836
Facundo Batista353750c2007-09-13 18:13:15 +00003837 def canonical(self, a):
3838 """Returns the same Decimal object.
3839
3840 As we do not have different encodings for the same number, the
3841 received object already is in its canonical form.
3842
3843 >>> ExtendedContext.canonical(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003844 Decimal('2.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003845 """
3846 return a.canonical(context=self)
3847
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003848 def compare(self, a, b):
3849 """Compares values numerically.
3850
3851 If the signs of the operands differ, a value representing each operand
3852 ('-1' if the operand is less than zero, '0' if the operand is zero or
3853 negative zero, or '1' if the operand is greater than zero) is used in
3854 place of that operand for the comparison instead of the actual
3855 operand.
3856
3857 The comparison is then effected by subtracting the second operand from
3858 the first and then returning a value according to the result of the
3859 subtraction: '-1' if the result is less than zero, '0' if the result is
3860 zero or negative zero, or '1' if the result is greater than zero.
3861
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003862 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003863 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003864 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003865 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003866 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003867 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003868 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003869 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003870 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003871 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003872 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003873 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003874 """
3875 return a.compare(b, context=self)
3876
Facundo Batista353750c2007-09-13 18:13:15 +00003877 def compare_signal(self, a, b):
3878 """Compares the values of the two operands numerically.
3879
3880 It's pretty much like compare(), but all NaNs signal, with signaling
3881 NaNs taking precedence over quiet NaNs.
3882
3883 >>> c = ExtendedContext
3884 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003885 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003886 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003887 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003888 >>> c.flags[InvalidOperation] = 0
3889 >>> print c.flags[InvalidOperation]
3890 0
3891 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003892 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003893 >>> print c.flags[InvalidOperation]
3894 1
3895 >>> c.flags[InvalidOperation] = 0
3896 >>> print c.flags[InvalidOperation]
3897 0
3898 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003899 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003900 >>> print c.flags[InvalidOperation]
3901 1
3902 """
3903 return a.compare_signal(b, context=self)
3904
3905 def compare_total(self, a, b):
3906 """Compares two operands using their abstract representation.
3907
3908 This is not like the standard compare, which use their numerical
3909 value. Note that a total ordering is defined for all possible abstract
3910 representations.
3911
3912 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003913 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003914 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003915 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003916 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003917 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003918 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003919 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003920 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003921 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00003922 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003923 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003924 """
3925 return a.compare_total(b)
3926
3927 def compare_total_mag(self, a, b):
3928 """Compares two operands using their abstract representation ignoring sign.
3929
3930 Like compare_total, but with operand's sign ignored and assumed to be 0.
3931 """
3932 return a.compare_total_mag(b)
3933
3934 def copy_abs(self, a):
3935 """Returns a copy of the operand with the sign set to 0.
3936
3937 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003938 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003939 >>> ExtendedContext.copy_abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003940 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00003941 """
3942 return a.copy_abs()
3943
3944 def copy_decimal(self, a):
3945 """Returns a copy of the decimal objet.
3946
3947 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003948 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003949 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003950 Decimal('-1.00')
Facundo Batista353750c2007-09-13 18:13:15 +00003951 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003952 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003953
3954 def copy_negate(self, a):
3955 """Returns a copy of the operand with the sign inverted.
3956
3957 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003958 Decimal('-101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003959 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003960 Decimal('101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003961 """
3962 return a.copy_negate()
3963
3964 def copy_sign(self, a, b):
3965 """Copies the second operand's sign to the first one.
3966
3967 In detail, it returns a copy of the first operand with the sign
3968 equal to the sign of the second operand.
3969
3970 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003971 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003972 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003973 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003974 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003975 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003976 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003977 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003978 """
3979 return a.copy_sign(b)
3980
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003981 def divide(self, a, b):
3982 """Decimal division in a specified context.
3983
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003984 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003985 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003986 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003987 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003988 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003989 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003990 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003991 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003992 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003993 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003994 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003995 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003996 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003997 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003998 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003999 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004000 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004001 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004002 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004003 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004004 """
4005 return a.__div__(b, context=self)
4006
4007 def divide_int(self, a, b):
4008 """Divides two numbers and returns the integer part of the result.
4009
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004010 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004011 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004012 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004013 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004014 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004015 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004016 """
4017 return a.__floordiv__(b, context=self)
4018
4019 def divmod(self, a, b):
4020 return a.__divmod__(b, context=self)
4021
Facundo Batista353750c2007-09-13 18:13:15 +00004022 def exp(self, a):
4023 """Returns e ** a.
4024
4025 >>> c = ExtendedContext.copy()
4026 >>> c.Emin = -999
4027 >>> c.Emax = 999
4028 >>> c.exp(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004029 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004030 >>> c.exp(Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004031 Decimal('0.367879441')
Facundo Batista353750c2007-09-13 18:13:15 +00004032 >>> c.exp(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004033 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004034 >>> c.exp(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004035 Decimal('2.71828183')
Facundo Batista353750c2007-09-13 18:13:15 +00004036 >>> c.exp(Decimal('0.693147181'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004037 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004038 >>> c.exp(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004039 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004040 """
4041 return a.exp(context=self)
4042
4043 def fma(self, a, b, c):
4044 """Returns a multiplied by b, plus c.
4045
4046 The first two operands are multiplied together, using multiply,
4047 the third operand is then added to the result of that
4048 multiplication, using add, all with only one final rounding.
4049
4050 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004051 Decimal('22')
Facundo Batista353750c2007-09-13 18:13:15 +00004052 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004053 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004054 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004055 Decimal('1.38435736E+12')
Facundo Batista353750c2007-09-13 18:13:15 +00004056 """
4057 return a.fma(b, c, context=self)
4058
4059 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004060 """Return True if the operand is canonical; otherwise return False.
4061
4062 Currently, the encoding of a Decimal instance is always
4063 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00004064
4065 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004066 True
Facundo Batista353750c2007-09-13 18:13:15 +00004067 """
Facundo Batista1a191df2007-10-02 17:01:24 +00004068 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00004069
4070 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004071 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004072
Facundo Batista1a191df2007-10-02 17:01:24 +00004073 A Decimal instance is considered finite if it is neither
4074 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00004075
4076 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004077 True
Facundo Batista353750c2007-09-13 18:13:15 +00004078 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004079 True
Facundo Batista353750c2007-09-13 18:13:15 +00004080 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004081 True
Facundo Batista353750c2007-09-13 18:13:15 +00004082 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004083 False
Facundo Batista353750c2007-09-13 18:13:15 +00004084 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004085 False
Facundo Batista353750c2007-09-13 18:13:15 +00004086 """
4087 return a.is_finite()
4088
4089 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004090 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004091
4092 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004093 False
Facundo Batista353750c2007-09-13 18:13:15 +00004094 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004095 True
Facundo Batista353750c2007-09-13 18:13:15 +00004096 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004097 False
Facundo Batista353750c2007-09-13 18:13:15 +00004098 """
4099 return a.is_infinite()
4100
4101 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004102 """Return True if the operand is a qNaN or sNaN;
4103 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004104
4105 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004106 False
Facundo Batista353750c2007-09-13 18:13:15 +00004107 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004108 True
Facundo Batista353750c2007-09-13 18:13:15 +00004109 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004110 True
Facundo Batista353750c2007-09-13 18:13:15 +00004111 """
4112 return a.is_nan()
4113
4114 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004115 """Return True if the operand is a normal number;
4116 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004117
4118 >>> c = ExtendedContext.copy()
4119 >>> c.Emin = -999
4120 >>> c.Emax = 999
4121 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004122 True
Facundo Batista353750c2007-09-13 18:13:15 +00004123 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004124 False
Facundo Batista353750c2007-09-13 18:13:15 +00004125 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004126 False
Facundo Batista353750c2007-09-13 18:13:15 +00004127 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004128 False
Facundo Batista353750c2007-09-13 18:13:15 +00004129 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004130 False
Facundo Batista353750c2007-09-13 18:13:15 +00004131 """
4132 return a.is_normal(context=self)
4133
4134 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004135 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004136
4137 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004138 False
Facundo Batista353750c2007-09-13 18:13:15 +00004139 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004140 True
Facundo Batista353750c2007-09-13 18:13:15 +00004141 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004142 False
Facundo Batista353750c2007-09-13 18:13:15 +00004143 """
4144 return a.is_qnan()
4145
4146 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004147 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004148
4149 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004150 False
Facundo Batista353750c2007-09-13 18:13:15 +00004151 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004152 True
Facundo Batista353750c2007-09-13 18:13:15 +00004153 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004154 True
Facundo Batista353750c2007-09-13 18:13:15 +00004155 """
4156 return a.is_signed()
4157
4158 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004159 """Return True if the operand is a signaling NaN;
4160 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004161
4162 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004163 False
Facundo Batista353750c2007-09-13 18:13:15 +00004164 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004165 False
Facundo Batista353750c2007-09-13 18:13:15 +00004166 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004167 True
Facundo Batista353750c2007-09-13 18:13:15 +00004168 """
4169 return a.is_snan()
4170
4171 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004172 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004173
4174 >>> c = ExtendedContext.copy()
4175 >>> c.Emin = -999
4176 >>> c.Emax = 999
4177 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004178 False
Facundo Batista353750c2007-09-13 18:13:15 +00004179 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004180 True
Facundo Batista353750c2007-09-13 18:13:15 +00004181 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004182 False
Facundo Batista353750c2007-09-13 18:13:15 +00004183 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004184 False
Facundo Batista353750c2007-09-13 18:13:15 +00004185 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004186 False
Facundo Batista353750c2007-09-13 18:13:15 +00004187 """
4188 return a.is_subnormal(context=self)
4189
4190 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004191 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004192
4193 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004194 True
Facundo Batista353750c2007-09-13 18:13:15 +00004195 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004196 False
Facundo Batista353750c2007-09-13 18:13:15 +00004197 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004198 True
Facundo Batista353750c2007-09-13 18:13:15 +00004199 """
4200 return a.is_zero()
4201
4202 def ln(self, a):
4203 """Returns the natural (base e) logarithm of the operand.
4204
4205 >>> c = ExtendedContext.copy()
4206 >>> c.Emin = -999
4207 >>> c.Emax = 999
4208 >>> c.ln(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004209 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004210 >>> c.ln(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004211 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004212 >>> c.ln(Decimal('2.71828183'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004213 Decimal('1.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004214 >>> c.ln(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004215 Decimal('2.30258509')
Facundo Batista353750c2007-09-13 18:13:15 +00004216 >>> c.ln(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004217 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004218 """
4219 return a.ln(context=self)
4220
4221 def log10(self, a):
4222 """Returns the base 10 logarithm of the operand.
4223
4224 >>> c = ExtendedContext.copy()
4225 >>> c.Emin = -999
4226 >>> c.Emax = 999
4227 >>> c.log10(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004228 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004229 >>> c.log10(Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004230 Decimal('-3')
Facundo Batista353750c2007-09-13 18:13:15 +00004231 >>> c.log10(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004232 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004233 >>> c.log10(Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004234 Decimal('0.301029996')
Facundo Batista353750c2007-09-13 18:13:15 +00004235 >>> c.log10(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004236 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004237 >>> c.log10(Decimal('70'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004238 Decimal('1.84509804')
Facundo Batista353750c2007-09-13 18:13:15 +00004239 >>> c.log10(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004240 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004241 """
4242 return a.log10(context=self)
4243
4244 def logb(self, a):
4245 """ Returns the exponent of the magnitude of the operand's MSD.
4246
4247 The result is the integer which is the exponent of the magnitude
4248 of the most significant digit of the operand (as though the
4249 operand were truncated to a single digit while maintaining the
4250 value of that digit and without limiting the resulting exponent).
4251
4252 >>> ExtendedContext.logb(Decimal('250'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004253 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004254 >>> ExtendedContext.logb(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004255 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004256 >>> ExtendedContext.logb(Decimal('0.03'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004257 Decimal('-2')
Facundo Batista353750c2007-09-13 18:13:15 +00004258 >>> ExtendedContext.logb(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004259 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004260 """
4261 return a.logb(context=self)
4262
4263 def logical_and(self, a, b):
4264 """Applies the logical operation 'and' between each operand's digits.
4265
4266 The operands must be both logical numbers.
4267
4268 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004269 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004270 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004271 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004272 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004273 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004274 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004275 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004276 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004277 Decimal('1000')
Facundo Batista353750c2007-09-13 18:13:15 +00004278 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004279 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004280 """
4281 return a.logical_and(b, context=self)
4282
4283 def logical_invert(self, a):
4284 """Invert all the digits in the operand.
4285
4286 The operand must be a logical number.
4287
4288 >>> ExtendedContext.logical_invert(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004289 Decimal('111111111')
Facundo Batista353750c2007-09-13 18:13:15 +00004290 >>> ExtendedContext.logical_invert(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004291 Decimal('111111110')
Facundo Batista353750c2007-09-13 18:13:15 +00004292 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004293 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004294 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004295 Decimal('10101010')
Facundo Batista353750c2007-09-13 18:13:15 +00004296 """
4297 return a.logical_invert(context=self)
4298
4299 def logical_or(self, a, b):
4300 """Applies the logical operation 'or' between each operand's digits.
4301
4302 The operands must be both logical numbers.
4303
4304 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004305 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004306 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004307 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004308 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004309 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004310 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004311 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004312 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004313 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004314 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004315 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004316 """
4317 return a.logical_or(b, context=self)
4318
4319 def logical_xor(self, a, b):
4320 """Applies the logical operation 'xor' between each operand's digits.
4321
4322 The operands must be both logical numbers.
4323
4324 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004325 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004326 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004327 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004328 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004329 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004330 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004331 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004332 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004333 Decimal('110')
Facundo Batista353750c2007-09-13 18:13:15 +00004334 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004335 Decimal('1101')
Facundo Batista353750c2007-09-13 18:13:15 +00004336 """
4337 return a.logical_xor(b, context=self)
4338
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004339 def max(self, a,b):
4340 """max compares two values numerically and returns the maximum.
4341
4342 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004343 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004344 operation. If they are numerically equal then the left-hand operand
4345 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004346 infinity) of the two operands is chosen as the result.
4347
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004348 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004349 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004350 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004351 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004352 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004353 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004354 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004355 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004356 """
4357 return a.max(b, context=self)
4358
Facundo Batista353750c2007-09-13 18:13:15 +00004359 def max_mag(self, a, b):
4360 """Compares the values numerically with their sign ignored."""
4361 return a.max_mag(b, context=self)
4362
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004363 def min(self, a,b):
4364 """min compares two values numerically and returns the minimum.
4365
4366 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004367 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004368 operation. If they are numerically equal then the left-hand operand
4369 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004370 infinity) of the two operands is chosen as the result.
4371
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004372 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004373 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004374 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004375 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004376 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004377 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004378 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004379 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004380 """
4381 return a.min(b, context=self)
4382
Facundo Batista353750c2007-09-13 18:13:15 +00004383 def min_mag(self, a, b):
4384 """Compares the values numerically with their sign ignored."""
4385 return a.min_mag(b, context=self)
4386
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004387 def minus(self, a):
4388 """Minus corresponds to unary prefix minus in Python.
4389
4390 The operation is evaluated using the same rules as subtract; the
4391 operation minus(a) is calculated as subtract('0', a) where the '0'
4392 has the same exponent as the operand.
4393
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004394 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004395 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004396 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004397 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004398 """
4399 return a.__neg__(context=self)
4400
4401 def multiply(self, a, b):
4402 """multiply multiplies two operands.
4403
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004404 If either operand is a special value then the general rules apply.
4405 Otherwise, the operands are multiplied together ('long multiplication'),
4406 resulting in a number which may be as long as the sum of the lengths
4407 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004408
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004409 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004410 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004411 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004412 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004413 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004414 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004415 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004416 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004417 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004418 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004419 """
4420 return a.__mul__(b, context=self)
4421
Facundo Batista353750c2007-09-13 18:13:15 +00004422 def next_minus(self, a):
4423 """Returns the largest representable number smaller than a.
4424
4425 >>> c = ExtendedContext.copy()
4426 >>> c.Emin = -999
4427 >>> c.Emax = 999
4428 >>> ExtendedContext.next_minus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004429 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004430 >>> c.next_minus(Decimal('1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004431 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004432 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004433 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004434 >>> c.next_minus(Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004435 Decimal('9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004436 """
4437 return a.next_minus(context=self)
4438
4439 def next_plus(self, a):
4440 """Returns the smallest representable number larger than a.
4441
4442 >>> c = ExtendedContext.copy()
4443 >>> c.Emin = -999
4444 >>> c.Emax = 999
4445 >>> ExtendedContext.next_plus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004446 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004447 >>> c.next_plus(Decimal('-1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004448 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004449 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004450 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004451 >>> c.next_plus(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004452 Decimal('-9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004453 """
4454 return a.next_plus(context=self)
4455
4456 def next_toward(self, a, b):
4457 """Returns the number closest to a, in direction towards b.
4458
4459 The result is the closest representable number from the first
4460 operand (but not the first operand) that is in the direction
4461 towards the second operand, unless the operands have the same
4462 value.
4463
4464 >>> c = ExtendedContext.copy()
4465 >>> c.Emin = -999
4466 >>> c.Emax = 999
4467 >>> c.next_toward(Decimal('1'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004468 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004469 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004470 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004471 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004472 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004473 >>> c.next_toward(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004474 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004475 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004476 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004477 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004478 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004479 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004480 Decimal('-0.00')
Facundo Batista353750c2007-09-13 18:13:15 +00004481 """
4482 return a.next_toward(b, context=self)
4483
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004484 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004485 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004486
4487 Essentially a plus operation with all trailing zeros removed from the
4488 result.
4489
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004490 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004491 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004492 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004493 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004494 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004495 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004496 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004497 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004498 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004499 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004500 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004501 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004502 """
4503 return a.normalize(context=self)
4504
Facundo Batista353750c2007-09-13 18:13:15 +00004505 def number_class(self, a):
4506 """Returns an indication of the class of the operand.
4507
4508 The class is one of the following strings:
4509 -sNaN
4510 -NaN
4511 -Infinity
4512 -Normal
4513 -Subnormal
4514 -Zero
4515 +Zero
4516 +Subnormal
4517 +Normal
4518 +Infinity
4519
4520 >>> c = Context(ExtendedContext)
4521 >>> c.Emin = -999
4522 >>> c.Emax = 999
4523 >>> c.number_class(Decimal('Infinity'))
4524 '+Infinity'
4525 >>> c.number_class(Decimal('1E-10'))
4526 '+Normal'
4527 >>> c.number_class(Decimal('2.50'))
4528 '+Normal'
4529 >>> c.number_class(Decimal('0.1E-999'))
4530 '+Subnormal'
4531 >>> c.number_class(Decimal('0'))
4532 '+Zero'
4533 >>> c.number_class(Decimal('-0'))
4534 '-Zero'
4535 >>> c.number_class(Decimal('-0.1E-999'))
4536 '-Subnormal'
4537 >>> c.number_class(Decimal('-1E-10'))
4538 '-Normal'
4539 >>> c.number_class(Decimal('-2.50'))
4540 '-Normal'
4541 >>> c.number_class(Decimal('-Infinity'))
4542 '-Infinity'
4543 >>> c.number_class(Decimal('NaN'))
4544 'NaN'
4545 >>> c.number_class(Decimal('-NaN'))
4546 'NaN'
4547 >>> c.number_class(Decimal('sNaN'))
4548 'sNaN'
4549 """
4550 return a.number_class(context=self)
4551
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004552 def plus(self, a):
4553 """Plus corresponds to unary prefix plus in Python.
4554
4555 The operation is evaluated using the same rules as add; the
4556 operation plus(a) is calculated as add('0', a) where the '0'
4557 has the same exponent as the operand.
4558
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004559 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004560 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004561 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004562 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004563 """
4564 return a.__pos__(context=self)
4565
4566 def power(self, a, b, modulo=None):
4567 """Raises a to the power of b, to modulo if given.
4568
Facundo Batista353750c2007-09-13 18:13:15 +00004569 With two arguments, compute a**b. If a is negative then b
4570 must be integral. The result will be inexact unless b is
4571 integral and the result is finite and can be expressed exactly
4572 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004573
Facundo Batista353750c2007-09-13 18:13:15 +00004574 With three arguments, compute (a**b) % modulo. For the
4575 three argument form, the following restrictions on the
4576 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004577
Facundo Batista353750c2007-09-13 18:13:15 +00004578 - all three arguments must be integral
4579 - b must be nonnegative
4580 - at least one of a or b must be nonzero
4581 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004582
Facundo Batista353750c2007-09-13 18:13:15 +00004583 The result of pow(a, b, modulo) is identical to the result
4584 that would be obtained by computing (a**b) % modulo with
4585 unbounded precision, but is computed more efficiently. It is
4586 always exact.
4587
4588 >>> c = ExtendedContext.copy()
4589 >>> c.Emin = -999
4590 >>> c.Emax = 999
4591 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004592 Decimal('8')
Facundo Batista353750c2007-09-13 18:13:15 +00004593 >>> c.power(Decimal('-2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004594 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004595 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004596 Decimal('0.125')
Facundo Batista353750c2007-09-13 18:13:15 +00004597 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004598 Decimal('69.7575744')
Facundo Batista353750c2007-09-13 18:13:15 +00004599 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004600 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004601 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004602 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004603 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004604 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004605 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004606 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004607 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004608 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004609 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004610 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004611 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004612 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004613 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004614 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004615 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004616 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00004617
4618 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004619 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004620 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004621 Decimal('-11')
Facundo Batista353750c2007-09-13 18:13:15 +00004622 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004623 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004624 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004625 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004626 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004627 Decimal('11729830')
Facundo Batista353750c2007-09-13 18:13:15 +00004628 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004629 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004630 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004631 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004632 """
4633 return a.__pow__(b, modulo, context=self)
4634
4635 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004636 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004637
4638 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004639 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004640 exponent is being increased), multiplied by a positive power of ten (if
4641 the exponent is being decreased), or is unchanged (if the exponent is
4642 already equal to that of the right-hand operand).
4643
4644 Unlike other operations, if the length of the coefficient after the
4645 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004646 operation condition is raised. This guarantees that, unless there is
4647 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648 equal to that of the right-hand operand.
4649
4650 Also unlike other operations, quantize will never raise Underflow, even
4651 if the result is subnormal and inexact.
4652
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004653 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004654 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004655 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004656 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004657 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004658 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004659 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004660 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004661 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004662 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004663 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004664 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004665 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004666 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004667 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004668 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004669 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004670 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004671 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004672 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004673 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004674 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004675 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004676 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004677 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004678 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004679 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004680 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004681 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004682 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004683 """
4684 return a.quantize(b, context=self)
4685
Facundo Batista353750c2007-09-13 18:13:15 +00004686 def radix(self):
4687 """Just returns 10, as this is Decimal, :)
4688
4689 >>> ExtendedContext.radix()
Raymond Hettingerabe32372008-02-14 02:41:22 +00004690 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004691 """
4692 return Decimal(10)
4693
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004694 def remainder(self, a, b):
4695 """Returns the remainder from integer division.
4696
4697 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004698 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004699 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004700 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004701
4702 This operation will fail under the same conditions as integer division
4703 (that is, if integer division on the same two operands would fail, the
4704 remainder cannot be calculated).
4705
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004706 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004707 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004708 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004709 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004710 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004711 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004712 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004713 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004714 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004715 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004716 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004717 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004718 """
4719 return a.__mod__(b, context=self)
4720
4721 def remainder_near(self, a, b):
4722 """Returns to be "a - b * n", where n is the integer nearest the exact
4723 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004724 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004725 sign of a.
4726
4727 This operation will fail under the same conditions as integer division
4728 (that is, if integer division on the same two operands would fail, the
4729 remainder cannot be calculated).
4730
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004731 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004732 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004733 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004734 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004735 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004736 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004737 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004738 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004739 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004740 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004741 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004742 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004743 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004744 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004745 """
4746 return a.remainder_near(b, context=self)
4747
Facundo Batista353750c2007-09-13 18:13:15 +00004748 def rotate(self, a, b):
4749 """Returns a rotated copy of a, b times.
4750
4751 The coefficient of the result is a rotated copy of the digits in
4752 the coefficient of the first operand. The number of places of
4753 rotation is taken from the absolute value of the second operand,
4754 with the rotation being to the left if the second operand is
4755 positive or to the right otherwise.
4756
4757 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004758 Decimal('400000003')
Facundo Batista353750c2007-09-13 18:13:15 +00004759 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004760 Decimal('12')
Facundo Batista353750c2007-09-13 18:13:15 +00004761 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004762 Decimal('891234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004763 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004764 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004765 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004766 Decimal('345678912')
Facundo Batista353750c2007-09-13 18:13:15 +00004767 """
4768 return a.rotate(b, context=self)
4769
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004770 def same_quantum(self, a, b):
4771 """Returns True if the two operands have the same exponent.
4772
4773 The result is never affected by either the sign or the coefficient of
4774 either operand.
4775
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004776 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004777 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004778 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004779 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004780 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004781 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004782 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004783 True
4784 """
4785 return a.same_quantum(b)
4786
Facundo Batista353750c2007-09-13 18:13:15 +00004787 def scaleb (self, a, b):
4788 """Returns the first operand after adding the second value its exp.
4789
4790 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004791 Decimal('0.0750')
Facundo Batista353750c2007-09-13 18:13:15 +00004792 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004793 Decimal('7.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004794 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004795 Decimal('7.50E+3')
Facundo Batista353750c2007-09-13 18:13:15 +00004796 """
4797 return a.scaleb (b, context=self)
4798
4799 def shift(self, a, b):
4800 """Returns a shifted copy of a, b times.
4801
4802 The coefficient of the result is a shifted copy of the digits
4803 in the coefficient of the first operand. The number of places
4804 to shift is taken from the absolute value of the second operand,
4805 with the shift being to the left if the second operand is
4806 positive or to the right otherwise. Digits shifted into the
4807 coefficient are zeros.
4808
4809 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004810 Decimal('400000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004811 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004812 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004813 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004814 Decimal('1234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004815 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004816 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004817 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004818 Decimal('345678900')
Facundo Batista353750c2007-09-13 18:13:15 +00004819 """
4820 return a.shift(b, context=self)
4821
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004822 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004823 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004824
4825 If the result must be inexact, it is rounded using the round-half-even
4826 algorithm.
4827
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004828 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004829 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004830 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004831 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004832 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004833 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004834 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004835 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004836 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004837 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004838 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004839 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004840 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004841 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004842 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004843 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004844 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004845 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004846 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004847 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004848 """
4849 return a.sqrt(context=self)
4850
4851 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004852 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004853
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004854 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004855 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004856 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004857 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004858 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004859 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004860 """
4861 return a.__sub__(b, context=self)
4862
4863 def to_eng_string(self, a):
4864 """Converts a number to a string, using scientific notation.
4865
4866 The operation is not affected by the context.
4867 """
4868 return a.to_eng_string(context=self)
4869
4870 def to_sci_string(self, a):
4871 """Converts a number to a string, using scientific notation.
4872
4873 The operation is not affected by the context.
4874 """
4875 return a.__str__(context=self)
4876
Facundo Batista353750c2007-09-13 18:13:15 +00004877 def to_integral_exact(self, a):
4878 """Rounds to an integer.
4879
4880 When the operand has a negative exponent, the result is the same
4881 as using the quantize() operation using the given operand as the
4882 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4883 of the operand as the precision setting; Inexact and Rounded flags
4884 are allowed in this operation. The rounding mode is taken from the
4885 context.
4886
4887 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004888 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004889 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004890 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004891 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004892 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004893 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004894 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004895 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004896 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004897 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004898 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004899 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004900 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004901 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004902 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004903 """
4904 return a.to_integral_exact(context=self)
4905
4906 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004907 """Rounds to an integer.
4908
4909 When the operand has a negative exponent, the result is the same
4910 as using the quantize() operation using the given operand as the
4911 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4912 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004913 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004914
Facundo Batista353750c2007-09-13 18:13:15 +00004915 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004916 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004917 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004918 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004919 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004920 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004921 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004922 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004923 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004924 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004925 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004926 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004927 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004928 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004929 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004930 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004931 """
Facundo Batista353750c2007-09-13 18:13:15 +00004932 return a.to_integral_value(context=self)
4933
4934 # the method name changed, but we provide also the old one, for compatibility
4935 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004936
4937class _WorkRep(object):
4938 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004939 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004940 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004941 # exp: None, int, or string
4942
4943 def __init__(self, value=None):
4944 if value is None:
4945 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004946 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004947 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004948 elif isinstance(value, Decimal):
4949 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004950 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004951 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004952 else:
4953 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004954 self.sign = value[0]
4955 self.int = value[1]
4956 self.exp = value[2]
4957
4958 def __repr__(self):
4959 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4960
4961 __str__ = __repr__
4962
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004963
4964
Facundo Batistae64acfa2007-12-17 14:18:42 +00004965def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004966 """Normalizes op1, op2 to have the same exp and length of coefficient.
4967
4968 Done during addition.
4969 """
Facundo Batista353750c2007-09-13 18:13:15 +00004970 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004971 tmp = op2
4972 other = op1
4973 else:
4974 tmp = op1
4975 other = op2
4976
Facundo Batista353750c2007-09-13 18:13:15 +00004977 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4978 # Then adding 10**exp to tmp has the same effect (after rounding)
4979 # as adding any positive quantity smaller than 10**exp; similarly
4980 # for subtraction. So if other is smaller than 10**exp we replace
4981 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004982 tmp_len = len(str(tmp.int))
4983 other_len = len(str(other.int))
4984 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4985 if other_len + other.exp - 1 < exp:
4986 other.int = 1
4987 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004988
Facundo Batista353750c2007-09-13 18:13:15 +00004989 tmp.int *= 10 ** (tmp.exp - other.exp)
4990 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004991 return op1, op2
4992
Facundo Batista353750c2007-09-13 18:13:15 +00004993##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4994
4995# This function from Tim Peters was taken from here:
4996# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4997# The correction being in the function definition is for speed, and
4998# the whole function is not resolved with math.log because of avoiding
4999# the use of floats.
5000def _nbits(n, correction = {
5001 '0': 4, '1': 3, '2': 2, '3': 2,
5002 '4': 1, '5': 1, '6': 1, '7': 1,
5003 '8': 0, '9': 0, 'a': 0, 'b': 0,
5004 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5005 """Number of bits in binary representation of the positive integer n,
5006 or 0 if n == 0.
5007 """
5008 if n < 0:
5009 raise ValueError("The argument to _nbits should be nonnegative.")
5010 hex_n = "%x" % n
5011 return 4*len(hex_n) - correction[hex_n[0]]
5012
5013def _sqrt_nearest(n, a):
5014 """Closest integer to the square root of the positive integer n. a is
5015 an initial approximation to the square root. Any positive integer
5016 will do for a, but the closer a is to the square root of n the
5017 faster convergence will be.
5018
5019 """
5020 if n <= 0 or a <= 0:
5021 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5022
5023 b=0
5024 while a != b:
5025 b, a = a, a--n//a>>1
5026 return a
5027
5028def _rshift_nearest(x, shift):
5029 """Given an integer x and a nonnegative integer shift, return closest
5030 integer to x / 2**shift; use round-to-even in case of a tie.
5031
5032 """
5033 b, q = 1L << shift, x >> shift
5034 return q + (2*(x & (b-1)) + (q&1) > b)
5035
5036def _div_nearest(a, b):
5037 """Closest integer to a/b, a and b positive integers; rounds to even
5038 in the case of a tie.
5039
5040 """
5041 q, r = divmod(a, b)
5042 return q + (2*r + (q&1) > b)
5043
5044def _ilog(x, M, L = 8):
5045 """Integer approximation to M*log(x/M), with absolute error boundable
5046 in terms only of x/M.
5047
5048 Given positive integers x and M, return an integer approximation to
5049 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5050 between the approximation and the exact result is at most 22. For
5051 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5052 both cases these are upper bounds on the error; it will usually be
5053 much smaller."""
5054
5055 # The basic algorithm is the following: let log1p be the function
5056 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5057 # the reduction
5058 #
5059 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5060 #
5061 # repeatedly until the argument to log1p is small (< 2**-L in
5062 # absolute value). For small y we can use the Taylor series
5063 # expansion
5064 #
5065 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5066 #
5067 # truncating at T such that y**T is small enough. The whole
5068 # computation is carried out in a form of fixed-point arithmetic,
5069 # with a real number z being represented by an integer
5070 # approximation to z*M. To avoid loss of precision, the y below
5071 # is actually an integer approximation to 2**R*y*M, where R is the
5072 # number of reductions performed so far.
5073
5074 y = x-M
5075 # argument reduction; R = number of reductions performed
5076 R = 0
5077 while (R <= L and long(abs(y)) << L-R >= M or
5078 R > L and abs(y) >> R-L >= M):
5079 y = _div_nearest(long(M*y) << 1,
5080 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5081 R += 1
5082
5083 # Taylor series with T terms
5084 T = -int(-10*len(str(M))//(3*L))
5085 yshift = _rshift_nearest(y, R)
5086 w = _div_nearest(M, T)
5087 for k in xrange(T-1, 0, -1):
5088 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5089
5090 return _div_nearest(w*y, M)
5091
5092def _dlog10(c, e, p):
5093 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5094 approximation to 10**p * log10(c*10**e), with an absolute error of
5095 at most 1. Assumes that c*10**e is not exactly 1."""
5096
5097 # increase precision by 2; compensate for this by dividing
5098 # final result by 100
5099 p += 2
5100
5101 # write c*10**e as d*10**f with either:
5102 # f >= 0 and 1 <= d <= 10, or
5103 # f <= 0 and 0.1 <= d <= 1.
5104 # Thus for c*10**e close to 1, f = 0
5105 l = len(str(c))
5106 f = e+l - (e+l >= 1)
5107
5108 if p > 0:
5109 M = 10**p
5110 k = e+p-f
5111 if k >= 0:
5112 c *= 10**k
5113 else:
5114 c = _div_nearest(c, 10**-k)
5115
5116 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005117 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005118 log_d = _div_nearest(log_d*M, log_10)
5119 log_tenpower = f*M # exact
5120 else:
5121 log_d = 0 # error < 2.31
Neal Norwitz18aa3882008-08-24 05:04:52 +00005122 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Facundo Batista353750c2007-09-13 18:13:15 +00005123
5124 return _div_nearest(log_tenpower+log_d, 100)
5125
5126def _dlog(c, e, p):
5127 """Given integers c, e and p with c > 0, compute an integer
5128 approximation to 10**p * log(c*10**e), with an absolute error of
5129 at most 1. Assumes that c*10**e is not exactly 1."""
5130
5131 # Increase precision by 2. The precision increase is compensated
5132 # for at the end with a division by 100.
5133 p += 2
5134
5135 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5136 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5137 # as 10**p * log(d) + 10**p*f * log(10).
5138 l = len(str(c))
5139 f = e+l - (e+l >= 1)
5140
5141 # compute approximation to 10**p*log(d), with error < 27
5142 if p > 0:
5143 k = e+p-f
5144 if k >= 0:
5145 c *= 10**k
5146 else:
5147 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5148
5149 # _ilog magnifies existing error in c by a factor of at most 10
5150 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5151 else:
5152 # p <= 0: just approximate the whole thing by 0; error < 2.31
5153 log_d = 0
5154
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005155 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00005156 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005157 extra = len(str(abs(f)))-1
5158 if p + extra >= 0:
5159 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5160 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5161 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00005162 else:
5163 f_log_ten = 0
5164 else:
5165 f_log_ten = 0
5166
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005167 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005168 return _div_nearest(f_log_ten + log_d, 100)
5169
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005170class _Log10Memoize(object):
5171 """Class to compute, store, and allow retrieval of, digits of the
5172 constant log(10) = 2.302585.... This constant is needed by
5173 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5174 def __init__(self):
5175 self.digits = "23025850929940456840179914546843642076011014886"
5176
5177 def getdigits(self, p):
5178 """Given an integer p >= 0, return floor(10**p)*log(10).
5179
5180 For example, self.getdigits(3) returns 2302.
5181 """
5182 # digits are stored as a string, for quick conversion to
5183 # integer in the case that we've already computed enough
5184 # digits; the stored digits should always be correct
5185 # (truncated, not rounded to nearest).
5186 if p < 0:
5187 raise ValueError("p should be nonnegative")
5188
5189 if p >= len(self.digits):
5190 # compute p+3, p+6, p+9, ... digits; continue until at
5191 # least one of the extra digits is nonzero
5192 extra = 3
5193 while True:
5194 # compute p+extra digits, correct to within 1ulp
5195 M = 10**(p+extra+2)
5196 digits = str(_div_nearest(_ilog(10*M, M), 100))
5197 if digits[-extra:] != '0'*extra:
5198 break
5199 extra += 3
5200 # keep all reliable digits so far; remove trailing zeros
5201 # and next nonzero digit
5202 self.digits = digits.rstrip('0')[:-1]
5203 return int(self.digits[:p+1])
5204
5205_log10_digits = _Log10Memoize().getdigits
5206
Facundo Batista353750c2007-09-13 18:13:15 +00005207def _iexp(x, M, L=8):
5208 """Given integers x and M, M > 0, such that x/M is small in absolute
5209 value, compute an integer approximation to M*exp(x/M). For 0 <=
5210 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5211 is usually much smaller)."""
5212
5213 # Algorithm: to compute exp(z) for a real number z, first divide z
5214 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5215 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5216 # series
5217 #
5218 # expm1(x) = x + x**2/2! + x**3/3! + ...
5219 #
5220 # Now use the identity
5221 #
5222 # expm1(2x) = expm1(x)*(expm1(x)+2)
5223 #
5224 # R times to compute the sequence expm1(z/2**R),
5225 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5226
5227 # Find R such that x/2**R/M <= 2**-L
5228 R = _nbits((long(x)<<L)//M)
5229
5230 # Taylor series. (2**L)**T > M
5231 T = -int(-10*len(str(M))//(3*L))
5232 y = _div_nearest(x, T)
5233 Mshift = long(M)<<R
5234 for i in xrange(T-1, 0, -1):
5235 y = _div_nearest(x*(Mshift + y), Mshift * i)
5236
5237 # Expansion
5238 for k in xrange(R-1, -1, -1):
5239 Mshift = long(M)<<(k+2)
5240 y = _div_nearest(y*(y+Mshift), Mshift)
5241
5242 return M+y
5243
5244def _dexp(c, e, p):
5245 """Compute an approximation to exp(c*10**e), with p decimal places of
5246 precision.
5247
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005248 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005249
5250 10**(p-1) <= d <= 10**p, and
5251 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5252
5253 In other words, d*10**f is an approximation to exp(c*10**e) with p
5254 digits of precision, and with an error in d of at most 1. This is
5255 almost, but not quite, the same as the error being < 1ulp: when d
5256 = 10**(p-1) the error could be up to 10 ulp."""
5257
5258 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5259 p += 2
5260
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005261 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005262 extra = max(0, e + len(str(c)) - 1)
5263 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005264
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005265 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005266 # rounding down
5267 shift = e+q
5268 if shift >= 0:
5269 cshift = c*10**shift
5270 else:
5271 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005272 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005273
5274 # reduce remainder back to original precision
5275 rem = _div_nearest(rem, 10**extra)
5276
5277 # error in result of _iexp < 120; error after division < 0.62
5278 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5279
5280def _dpower(xc, xe, yc, ye, p):
5281 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5282 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5283
5284 10**(p-1) <= c <= 10**p, and
5285 (c-1)*10**e < x**y < (c+1)*10**e
5286
5287 in other words, c*10**e is an approximation to x**y with p digits
5288 of precision, and with an error in c of at most 1. (This is
5289 almost, but not quite, the same as the error being < 1ulp: when c
5290 == 10**(p-1) we can only guarantee error < 10ulp.)
5291
5292 We assume that: x is positive and not equal to 1, and y is nonzero.
5293 """
5294
5295 # Find b such that 10**(b-1) <= |y| <= 10**b
5296 b = len(str(abs(yc))) + ye
5297
5298 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5299 lxc = _dlog(xc, xe, p+b+1)
5300
5301 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5302 shift = ye-b
5303 if shift >= 0:
5304 pc = lxc*yc*10**shift
5305 else:
5306 pc = _div_nearest(lxc*yc, 10**-shift)
5307
5308 if pc == 0:
5309 # we prefer a result that isn't exactly 1; this makes it
5310 # easier to compute a correctly rounded result in __pow__
5311 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5312 coeff, exp = 10**(p-1)+1, 1-p
5313 else:
5314 coeff, exp = 10**p-1, -p
5315 else:
5316 coeff, exp = _dexp(pc, -(p+1), p+1)
5317 coeff = _div_nearest(coeff, 10)
5318 exp += 1
5319
5320 return coeff, exp
5321
5322def _log10_lb(c, correction = {
5323 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5324 '6': 23, '7': 16, '8': 10, '9': 5}):
5325 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5326 if c <= 0:
5327 raise ValueError("The argument to _log10_lb should be nonnegative.")
5328 str_c = str(c)
5329 return 100*len(str_c) - correction[str_c[0]]
5330
Facundo Batista59c58842007-04-10 12:58:45 +00005331##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005332
Facundo Batista353750c2007-09-13 18:13:15 +00005333def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005334 """Convert other to Decimal.
5335
5336 Verifies that it's ok to use in an implicit construction.
5337 """
5338 if isinstance(other, Decimal):
5339 return other
5340 if isinstance(other, (int, long)):
5341 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005342 if raiseit:
5343 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005344 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005345
Facundo Batista59c58842007-04-10 12:58:45 +00005346##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005347
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005348# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005349# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005350
5351DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005352 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005353 traps=[DivisionByZero, Overflow, InvalidOperation],
5354 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005355 Emax=999999999,
5356 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005357 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005358)
5359
5360# Pre-made alternate contexts offered by the specification
5361# Don't change these; the user should be able to select these
5362# contexts and be able to reproduce results from other implementations
5363# of the spec.
5364
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005365BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005366 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005367 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5368 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005369)
5370
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005371ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005372 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005373 traps=[],
5374 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005375)
5376
5377
Facundo Batista72bc54f2007-11-23 17:59:00 +00005378##### crud for parsing strings #############################################
Mark Dickinson6a123cb2008-02-24 18:12:36 +00005379#
Facundo Batista72bc54f2007-11-23 17:59:00 +00005380# Regular expression used for parsing numeric strings. Additional
5381# comments:
5382#
5383# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5384# whitespace. But note that the specification disallows whitespace in
5385# a numeric string.
5386#
5387# 2. For finite numbers (not infinities and NaNs) the body of the
5388# number between the optional sign and the optional exponent must have
5389# at least one decimal digit, possibly after the decimal point. The
5390# lookahead expression '(?=\d|\.\d)' checks this.
5391#
5392# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5393# other meaning for \d than the numbers [0-9].
5394
5395import re
Mark Dickinson70c32892008-07-02 09:37:01 +00005396_parser = re.compile(r""" # A numeric string consists of:
Facundo Batista72bc54f2007-11-23 17:59:00 +00005397# \s*
Mark Dickinson70c32892008-07-02 09:37:01 +00005398 (?P<sign>[-+])? # an optional sign, followed by either...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005399 (
Mark Dickinson70c32892008-07-02 09:37:01 +00005400 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5401 (?P<int>[0-9]*) # having a (possibly empty) integer part
5402 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5403 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005404 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005405 Inf(inity)? # ...an infinity, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005406 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005407 (?P<signal>s)? # ...an (optionally signaling)
5408 NaN # NaN
5409 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005410 )
5411# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005412 \Z
Facundo Batista72bc54f2007-11-23 17:59:00 +00005413""", re.VERBOSE | re.IGNORECASE).match
5414
Facundo Batista2ec74152007-12-03 17:55:00 +00005415_all_zeros = re.compile('0*$').match
5416_exact_half = re.compile('50*$').match
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005417
5418##### PEP3101 support functions ##############################################
5419# The functions parse_format_specifier and format_align have little to do
5420# with the Decimal class, and could potentially be reused for other pure
5421# Python numeric classes that want to implement __format__
5422#
5423# A format specifier for Decimal looks like:
5424#
5425# [[fill]align][sign][0][minimumwidth][.precision][type]
5426#
5427
5428_parse_format_specifier_regex = re.compile(r"""\A
5429(?:
5430 (?P<fill>.)?
5431 (?P<align>[<>=^])
5432)?
5433(?P<sign>[-+ ])?
5434(?P<zeropad>0)?
5435(?P<minimumwidth>(?!0)\d+)?
5436(?:\.(?P<precision>0|(?!0)\d+))?
5437(?P<type>[eEfFgG%])?
5438\Z
5439""", re.VERBOSE)
5440
Facundo Batista72bc54f2007-11-23 17:59:00 +00005441del re
5442
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005443def _parse_format_specifier(format_spec):
5444 """Parse and validate a format specifier.
5445
5446 Turns a standard numeric format specifier into a dict, with the
5447 following entries:
5448
5449 fill: fill character to pad field to minimum width
5450 align: alignment type, either '<', '>', '=' or '^'
5451 sign: either '+', '-' or ' '
5452 minimumwidth: nonnegative integer giving minimum width
5453 precision: nonnegative integer giving precision, or None
5454 type: one of the characters 'eEfFgG%', or None
5455 unicode: either True or False (always True for Python 3.x)
5456
5457 """
5458 m = _parse_format_specifier_regex.match(format_spec)
5459 if m is None:
5460 raise ValueError("Invalid format specifier: " + format_spec)
5461
5462 # get the dictionary
5463 format_dict = m.groupdict()
5464
5465 # defaults for fill and alignment
5466 fill = format_dict['fill']
5467 align = format_dict['align']
5468 if format_dict.pop('zeropad') is not None:
5469 # in the face of conflict, refuse the temptation to guess
5470 if fill is not None and fill != '0':
5471 raise ValueError("Fill character conflicts with '0'"
5472 " in format specifier: " + format_spec)
5473 if align is not None and align != '=':
5474 raise ValueError("Alignment conflicts with '0' in "
5475 "format specifier: " + format_spec)
5476 fill = '0'
5477 align = '='
5478 format_dict['fill'] = fill or ' '
5479 format_dict['align'] = align or '<'
5480
5481 if format_dict['sign'] is None:
5482 format_dict['sign'] = '-'
5483
5484 # turn minimumwidth and precision entries into integers.
5485 # minimumwidth defaults to 0; precision remains None if not given
5486 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5487 if format_dict['precision'] is not None:
5488 format_dict['precision'] = int(format_dict['precision'])
5489
5490 # if format type is 'g' or 'G' then a precision of 0 makes little
5491 # sense; convert it to 1. Same if format type is unspecified.
5492 if format_dict['precision'] == 0:
5493 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5494 format_dict['precision'] = 1
5495
5496 # record whether return type should be str or unicode
5497 format_dict['unicode'] = isinstance(format_spec, unicode)
5498
5499 return format_dict
5500
5501def _format_align(body, spec_dict):
5502 """Given an unpadded, non-aligned numeric string, add padding and
5503 aligment to conform with the given format specifier dictionary (as
5504 output from parse_format_specifier).
5505
5506 It's assumed that if body is negative then it starts with '-'.
5507 Any leading sign ('-' or '+') is stripped from the body before
5508 applying the alignment and padding rules, and replaced in the
5509 appropriate position.
5510
5511 """
5512 # figure out the sign; we only examine the first character, so if
5513 # body has leading whitespace the results may be surprising.
5514 if len(body) > 0 and body[0] in '-+':
5515 sign = body[0]
5516 body = body[1:]
5517 else:
5518 sign = ''
5519
5520 if sign != '-':
5521 if spec_dict['sign'] in ' +':
5522 sign = spec_dict['sign']
5523 else:
5524 sign = ''
5525
5526 # how much extra space do we have to play with?
5527 minimumwidth = spec_dict['minimumwidth']
5528 fill = spec_dict['fill']
5529 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5530
5531 align = spec_dict['align']
5532 if align == '<':
5533 result = padding + sign + body
5534 elif align == '>':
5535 result = sign + body + padding
5536 elif align == '=':
5537 result = sign + padding + body
5538 else: #align == '^'
5539 half = len(padding)//2
5540 result = padding[:half] + sign + body + padding[half:]
5541
5542 # make sure that result is unicode if necessary
5543 if spec_dict['unicode']:
5544 result = unicode(result)
5545
5546 return result
Facundo Batista72bc54f2007-11-23 17:59:00 +00005547
Facundo Batista59c58842007-04-10 12:58:45 +00005548##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005549
Facundo Batista59c58842007-04-10 12:58:45 +00005550# Reusable defaults
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00005551_Infinity = Decimal('Inf')
5552_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonc5de0962009-01-02 23:07:08 +00005553_NaN = Decimal('NaN')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00005554_Zero = Decimal(0)
5555_One = Decimal(1)
5556_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005557
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00005558# _SignedInfinity[sign] is infinity w/ that sign
5559_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005560
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005561
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005562
5563if __name__ == '__main__':
5564 import doctest, sys
5565 doctest.testmod(sys.modules[__name__])