blob: 88e9bc80195aa79065bae1dae2f101d02db2d192 [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
Raymond Hettingerf4d85972009-01-03 19:02:23 +0000657 @classmethod
658 def from_float(cls, f):
659 """Converts a float to a decimal number, exactly.
660
661 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
662 Since 0.1 is not exactly representable in binary floating point, the
663 value is stored as the nearest representable value which is
664 0x1.999999999999ap-4. The exact equivalent of the value in decimal
665 is 0.1000000000000000055511151231257827021181583404541015625.
666
667 >>> Decimal.from_float(0.1)
668 Decimal('0.1000000000000000055511151231257827021181583404541015625')
669 >>> Decimal.from_float(float('nan'))
670 Decimal('NaN')
671 >>> Decimal.from_float(float('inf'))
672 Decimal('Infinity')
673 >>> Decimal.from_float(-float('inf'))
674 Decimal('-Infinity')
675 >>> Decimal.from_float(-0.0)
676 Decimal('-0')
677
678 """
679 if isinstance(f, (int, long)): # handle integer inputs
680 return cls(f)
681 if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
682 return cls(repr(f))
683 sign = 0 if _math.copysign(1.0, f) == 1.0 else 1
684 n, d = abs(f).as_integer_ratio()
685 k = d.bit_length() - 1
686 result = _dec_from_triple(sign, str(n*5**k), -k)
687 return result if cls is Decimal else cls(result)
688
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000689 def _isnan(self):
690 """Returns whether the number is not actually one.
691
692 0 if a number
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000693 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000694 2 if sNaN
695 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000696 if self._is_special:
697 exp = self._exp
698 if exp == 'n':
699 return 1
700 elif exp == 'N':
701 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000702 return 0
703
704 def _isinfinity(self):
705 """Returns whether the number is infinite
706
707 0 if finite or not a number
708 1 if +INF
709 -1 if -INF
710 """
711 if self._exp == 'F':
712 if self._sign:
713 return -1
714 return 1
715 return 0
716
Facundo Batista353750c2007-09-13 18:13:15 +0000717 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000718 """Returns whether the number is not actually one.
719
720 if self, other are sNaN, signal
721 if self, other are NaN return nan
722 return 0
723
724 Done before operations.
725 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000726
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000727 self_is_nan = self._isnan()
728 if other is None:
729 other_is_nan = False
730 else:
731 other_is_nan = other._isnan()
732
733 if self_is_nan or other_is_nan:
734 if context is None:
735 context = getcontext()
736
737 if self_is_nan == 2:
738 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000739 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000740 if other_is_nan == 2:
741 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000742 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000743 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000744 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000745
Facundo Batista353750c2007-09-13 18:13:15 +0000746 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000747 return 0
748
Mark Dickinson2fc92632008-02-06 22:10:50 +0000749 def _compare_check_nans(self, other, context):
750 """Version of _check_nans used for the signaling comparisons
751 compare_signal, __le__, __lt__, __ge__, __gt__.
752
753 Signal InvalidOperation if either self or other is a (quiet
754 or signaling) NaN. Signaling NaNs take precedence over quiet
755 NaNs.
756
757 Return 0 if neither operand is a NaN.
758
759 """
760 if context is None:
761 context = getcontext()
762
763 if self._is_special or other._is_special:
764 if self.is_snan():
765 return context._raise_error(InvalidOperation,
766 'comparison involving sNaN',
767 self)
768 elif other.is_snan():
769 return context._raise_error(InvalidOperation,
770 'comparison involving sNaN',
771 other)
772 elif self.is_qnan():
773 return context._raise_error(InvalidOperation,
774 'comparison involving NaN',
775 self)
776 elif other.is_qnan():
777 return context._raise_error(InvalidOperation,
778 'comparison involving NaN',
779 other)
780 return 0
781
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000782 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000783 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000784
Facundo Batista1a191df2007-10-02 17:01:24 +0000785 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000786 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000787 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000788
Mark Dickinson2fc92632008-02-06 22:10:50 +0000789 def _cmp(self, other):
790 """Compare the two non-NaN decimal instances self and other.
791
792 Returns -1 if self < other, 0 if self == other and 1
793 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000794
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000795 if self._is_special or other._is_special:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000796 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000797
Facundo Batista353750c2007-09-13 18:13:15 +0000798 # check for zeros; note that cmp(0, -0) should return 0
799 if not self:
800 if not other:
801 return 0
802 else:
803 return -((-1)**other._sign)
804 if not other:
805 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000806
Facundo Batista59c58842007-04-10 12:58:45 +0000807 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000808 if other._sign < self._sign:
809 return -1
810 if self._sign < other._sign:
811 return 1
812
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000813 self_adjusted = self.adjusted()
814 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000815 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000816 self_padded = self._int + '0'*(self._exp - other._exp)
817 other_padded = other._int + '0'*(other._exp - self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +0000818 return cmp(self_padded, other_padded) * (-1)**self._sign
819 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000820 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000821 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000822 return -((-1)**self._sign)
823
Mark Dickinson2fc92632008-02-06 22:10:50 +0000824 # Note: The Decimal standard doesn't cover rich comparisons for
825 # Decimals. In particular, the specification is silent on the
826 # subject of what should happen for a comparison involving a NaN.
827 # We take the following approach:
828 #
829 # == comparisons involving a NaN always return False
830 # != comparisons involving a NaN always return True
831 # <, >, <= and >= comparisons involving a (quiet or signaling)
832 # NaN signal InvalidOperation, and return False if the
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000833 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000834 #
835 # This behavior is designed to conform as closely as possible to
836 # that specified by IEEE 754.
837
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000838 def __eq__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000839 other = _convert_other(other)
840 if other is NotImplemented:
841 return other
842 if self.is_nan() or other.is_nan():
843 return False
844 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000845
846 def __ne__(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 True
852 return self._cmp(other) != 0
853
854 def __lt__(self, other, context=None):
855 other = _convert_other(other)
856 if other is NotImplemented:
857 return other
858 ans = self._compare_check_nans(other, context)
859 if ans:
860 return False
861 return self._cmp(other) < 0
862
863 def __le__(self, other, context=None):
864 other = _convert_other(other)
865 if other is NotImplemented:
866 return other
867 ans = self._compare_check_nans(other, context)
868 if ans:
869 return False
870 return self._cmp(other) <= 0
871
872 def __gt__(self, other, context=None):
873 other = _convert_other(other)
874 if other is NotImplemented:
875 return other
876 ans = self._compare_check_nans(other, context)
877 if ans:
878 return False
879 return self._cmp(other) > 0
880
881 def __ge__(self, other, context=None):
882 other = _convert_other(other)
883 if other is NotImplemented:
884 return other
885 ans = self._compare_check_nans(other, context)
886 if ans:
887 return False
888 return self._cmp(other) >= 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000889
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000890 def compare(self, other, context=None):
891 """Compares one to another.
892
893 -1 => a < b
894 0 => a = b
895 1 => a > b
896 NaN => one is NaN
897 Like __cmp__, but returns Decimal instances.
898 """
Facundo Batista353750c2007-09-13 18:13:15 +0000899 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000900
Facundo Batista59c58842007-04-10 12:58:45 +0000901 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000902 if (self._is_special or other and other._is_special):
903 ans = self._check_nans(other, context)
904 if ans:
905 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000906
Mark Dickinson2fc92632008-02-06 22:10:50 +0000907 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000908
909 def __hash__(self):
910 """x.__hash__() <==> hash(x)"""
911 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000912 #
913 # The hash of a nonspecial noninteger Decimal must depend only
914 # on the value of that Decimal, and not on its representation.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000915 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000916 if self._is_special:
917 if self._isnan():
918 raise TypeError('Cannot hash a NaN value.')
919 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000920 if not self:
921 return 0
922 if self._isinteger():
923 op = _WorkRep(self.to_integral_value())
924 # to make computation feasible for Decimals with large
925 # exponent, we use the fact that hash(n) == hash(m) for
926 # any two nonzero integers n and m such that (i) n and m
927 # have the same sign, and (ii) n is congruent to m modulo
928 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
929 # hash((-1)**s*c*pow(10, e, 2**64-1).
930 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000931 # The value of a nonzero nonspecial Decimal instance is
932 # faithfully represented by the triple consisting of its sign,
933 # its adjusted exponent, and its coefficient with trailing
934 # zeros removed.
935 return hash((self._sign,
936 self._exp+len(self._int),
937 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000938
939 def as_tuple(self):
940 """Represents the number as a triple tuple.
941
942 To show the internals exactly as they are.
943 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000944 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000945
946 def __repr__(self):
947 """Represents the number as an instance of Decimal."""
948 # Invariant: eval(repr(d)) == d
Raymond Hettingerabe32372008-02-14 02:41:22 +0000949 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000950
Facundo Batista353750c2007-09-13 18:13:15 +0000951 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000952 """Return string representation of the number in scientific notation.
953
954 Captures all of the information in the underlying representation.
955 """
956
Facundo Batista62edb712007-12-03 16:29:52 +0000957 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000958 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000959 if self._exp == 'F':
960 return sign + 'Infinity'
961 elif self._exp == 'n':
962 return sign + 'NaN' + self._int
963 else: # self._exp == 'N'
964 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000965
Facundo Batista62edb712007-12-03 16:29:52 +0000966 # number of digits of self._int to left of decimal point
967 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000968
Facundo Batista62edb712007-12-03 16:29:52 +0000969 # dotplace is number of digits of self._int to the left of the
970 # decimal point in the mantissa of the output string (that is,
971 # after adjusting the exponent)
972 if self._exp <= 0 and leftdigits > -6:
973 # no exponent required
974 dotplace = leftdigits
975 elif not eng:
976 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000977 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000978 elif self._int == '0':
979 # engineering notation, zero
980 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000981 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000982 # engineering notation, nonzero
983 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000984
Facundo Batista62edb712007-12-03 16:29:52 +0000985 if dotplace <= 0:
986 intpart = '0'
987 fracpart = '.' + '0'*(-dotplace) + self._int
988 elif dotplace >= len(self._int):
989 intpart = self._int+'0'*(dotplace-len(self._int))
990 fracpart = ''
991 else:
992 intpart = self._int[:dotplace]
993 fracpart = '.' + self._int[dotplace:]
994 if leftdigits == dotplace:
995 exp = ''
996 else:
997 if context is None:
998 context = getcontext()
999 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1000
1001 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001002
1003 def to_eng_string(self, context=None):
1004 """Convert to engineering-type string.
1005
1006 Engineering notation has an exponent which is a multiple of 3, so there
1007 are up to 3 digits left of the decimal place.
1008
1009 Same rules for when in exponential and when as a value as in __str__.
1010 """
Facundo Batista353750c2007-09-13 18:13:15 +00001011 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001012
1013 def __neg__(self, context=None):
1014 """Returns a copy with the sign switched.
1015
1016 Rounds, if it has reason.
1017 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001018 if self._is_special:
1019 ans = self._check_nans(context=context)
1020 if ans:
1021 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022
1023 if not self:
1024 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001025 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001026 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001027 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001028
1029 if context is None:
1030 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001031 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001032
1033 def __pos__(self, context=None):
1034 """Returns a copy, unless it is a sNaN.
1035
1036 Rounds the number (if more then precision digits)
1037 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001038 if self._is_special:
1039 ans = self._check_nans(context=context)
1040 if ans:
1041 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001042
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001043 if not self:
1044 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001045 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +00001046 else:
1047 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001048
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001049 if context is None:
1050 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001051 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001052
Facundo Batistae64acfa2007-12-17 14:18:42 +00001053 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001054 """Returns the absolute value of self.
1055
Facundo Batistae64acfa2007-12-17 14:18:42 +00001056 If the keyword argument 'round' is false, do not round. The
1057 expression self.__abs__(round=False) is equivalent to
1058 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001059 """
Facundo Batistae64acfa2007-12-17 14:18:42 +00001060 if not round:
1061 return self.copy_abs()
1062
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001063 if self._is_special:
1064 ans = self._check_nans(context=context)
1065 if ans:
1066 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068 if self._sign:
1069 ans = self.__neg__(context=context)
1070 else:
1071 ans = self.__pos__(context=context)
1072
1073 return ans
1074
1075 def __add__(self, other, context=None):
1076 """Returns self + other.
1077
1078 -INF + INF (or the reverse) cause InvalidOperation errors.
1079 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001080 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001081 if other is NotImplemented:
1082 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001083
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084 if context is None:
1085 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001086
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001087 if self._is_special or other._is_special:
1088 ans = self._check_nans(other, context)
1089 if ans:
1090 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001091
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001092 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001093 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001094 if self._sign != other._sign and other._isinfinity():
1095 return context._raise_error(InvalidOperation, '-INF + INF')
1096 return Decimal(self)
1097 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001098 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001099
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100 exp = min(self._exp, other._exp)
1101 negativezero = 0
1102 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001103 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001104 negativezero = 1
1105
1106 if not self and not other:
1107 sign = min(self._sign, other._sign)
1108 if negativezero:
1109 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001110 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001111 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001112 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001113 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001114 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001115 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001116 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001117 return ans
1118 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001119 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001120 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001121 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001122 return ans
1123
1124 op1 = _WorkRep(self)
1125 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001126 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001127
1128 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001130 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001131 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001132 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001133 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001134 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001135 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001136 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001137 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001138 if op1.sign == 1:
1139 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140 op1.sign, op2.sign = op2.sign, op1.sign
1141 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001142 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001143 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001144 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001145 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001146 op1.sign, op2.sign = (0, 0)
1147 else:
1148 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001149 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001150
Raymond Hettinger17931de2004-10-27 06:21:46 +00001151 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001152 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001153 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001154 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001155
1156 result.exp = op1.exp
1157 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001158 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001159 return ans
1160
1161 __radd__ = __add__
1162
1163 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001164 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001165 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001166 if other is NotImplemented:
1167 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001168
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001169 if self._is_special or other._is_special:
1170 ans = self._check_nans(other, context=context)
1171 if ans:
1172 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173
Facundo Batista353750c2007-09-13 18:13:15 +00001174 # self - other is computed as self + other.copy_negate()
1175 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001176
1177 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001178 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001179 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001180 if other is NotImplemented:
1181 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001182
Facundo Batista353750c2007-09-13 18:13:15 +00001183 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001185 def __mul__(self, other, context=None):
1186 """Return self * other.
1187
1188 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1189 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001190 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001191 if other is NotImplemented:
1192 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001193
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194 if context is None:
1195 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001196
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001197 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001198
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001199 if self._is_special or other._is_special:
1200 ans = self._check_nans(other, context)
1201 if ans:
1202 return ans
1203
1204 if self._isinfinity():
1205 if not other:
1206 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001207 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001208
1209 if other._isinfinity():
1210 if not self:
1211 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001212 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001213
1214 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001215
1216 # Special case for multiplying by zero
1217 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001218 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001219 # Fixing in case the exponent is out of bounds
1220 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001221 return ans
1222
1223 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001224 if self._int == '1':
1225 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001226 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001227 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001228 if other._int == '1':
1229 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001230 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001231 return ans
1232
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001233 op1 = _WorkRep(self)
1234 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001235
Facundo Batista72bc54f2007-11-23 17:59:00 +00001236 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001237 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001238
1239 return ans
1240 __rmul__ = __mul__
1241
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001242 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001243 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001244 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001245 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001246 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001247
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001248 if context is None:
1249 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001250
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001251 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001252
1253 if self._is_special or other._is_special:
1254 ans = self._check_nans(other, context)
1255 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001256 return ans
1257
1258 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001259 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001260
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001261 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001262 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001263
1264 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001265 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001266 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001267
1268 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001269 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001270 if not self:
1271 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001272 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273
Facundo Batistacce8df22007-09-18 16:53:18 +00001274 if not self:
1275 exp = self._exp - other._exp
1276 coeff = 0
1277 else:
1278 # OK, so neither = 0, INF or NaN
1279 shift = len(other._int) - len(self._int) + context.prec + 1
1280 exp = self._exp - other._exp - shift
1281 op1 = _WorkRep(self)
1282 op2 = _WorkRep(other)
1283 if shift >= 0:
1284 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1285 else:
1286 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1287 if remainder:
1288 # result is not exact; adjust to ensure correct rounding
1289 if coeff % 5 == 0:
1290 coeff += 1
1291 else:
1292 # result is exact; get as close to ideal exponent as possible
1293 ideal_exp = self._exp - other._exp
1294 while exp < ideal_exp and coeff % 10 == 0:
1295 coeff //= 10
1296 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001297
Facundo Batista72bc54f2007-11-23 17:59:00 +00001298 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001299 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001300
Facundo Batistacce8df22007-09-18 16:53:18 +00001301 def _divide(self, other, context):
1302 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001303
Facundo Batistacce8df22007-09-18 16:53:18 +00001304 Assumes that neither self nor other is a NaN, that self is not
1305 infinite and that other is nonzero.
1306 """
1307 sign = self._sign ^ other._sign
1308 if other._isinfinity():
1309 ideal_exp = self._exp
1310 else:
1311 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312
Facundo Batistacce8df22007-09-18 16:53:18 +00001313 expdiff = self.adjusted() - other.adjusted()
1314 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001315 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001316 self._rescale(ideal_exp, context.rounding))
1317 if expdiff <= context.prec:
1318 op1 = _WorkRep(self)
1319 op2 = _WorkRep(other)
1320 if op1.exp >= op2.exp:
1321 op1.int *= 10**(op1.exp - op2.exp)
1322 else:
1323 op2.int *= 10**(op2.exp - op1.exp)
1324 q, r = divmod(op1.int, op2.int)
1325 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001326 return (_dec_from_triple(sign, str(q), 0),
1327 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001328
Facundo Batistacce8df22007-09-18 16:53:18 +00001329 # Here the quotient is too large to be representable
1330 ans = context._raise_error(DivisionImpossible,
1331 'quotient too large in //, % or divmod')
1332 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001333
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001334 def __rtruediv__(self, other, context=None):
1335 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001336 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001337 if other is NotImplemented:
1338 return other
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001339 return other.__truediv__(self, context=context)
1340
1341 __div__ = __truediv__
1342 __rdiv__ = __rtruediv__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001343
1344 def __divmod__(self, other, context=None):
1345 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001346 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001347 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001348 other = _convert_other(other)
1349 if other is NotImplemented:
1350 return other
1351
1352 if context is None:
1353 context = getcontext()
1354
1355 ans = self._check_nans(other, context)
1356 if ans:
1357 return (ans, ans)
1358
1359 sign = self._sign ^ other._sign
1360 if self._isinfinity():
1361 if other._isinfinity():
1362 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1363 return ans, ans
1364 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001365 return (_SignedInfinity[sign],
Facundo Batistacce8df22007-09-18 16:53:18 +00001366 context._raise_error(InvalidOperation, 'INF % x'))
1367
1368 if not other:
1369 if not self:
1370 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1371 return ans, ans
1372 else:
1373 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1374 context._raise_error(InvalidOperation, 'x % 0'))
1375
1376 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001377 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001378 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001379
1380 def __rdivmod__(self, other, context=None):
1381 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001382 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001383 if other is NotImplemented:
1384 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001385 return other.__divmod__(self, context=context)
1386
1387 def __mod__(self, other, context=None):
1388 """
1389 self % other
1390 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001391 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001392 if other is NotImplemented:
1393 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001394
Facundo Batistacce8df22007-09-18 16:53:18 +00001395 if context is None:
1396 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001397
Facundo Batistacce8df22007-09-18 16:53:18 +00001398 ans = self._check_nans(other, context)
1399 if ans:
1400 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001401
Facundo Batistacce8df22007-09-18 16:53:18 +00001402 if self._isinfinity():
1403 return context._raise_error(InvalidOperation, 'INF % x')
1404 elif not other:
1405 if self:
1406 return context._raise_error(InvalidOperation, 'x % 0')
1407 else:
1408 return context._raise_error(DivisionUndefined, '0 % 0')
1409
1410 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001411 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001412 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001413
1414 def __rmod__(self, other, context=None):
1415 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001416 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001417 if other is NotImplemented:
1418 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001419 return other.__mod__(self, context=context)
1420
1421 def remainder_near(self, other, context=None):
1422 """
1423 Remainder nearest to 0- abs(remainder-near) <= other/2
1424 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001425 if context is None:
1426 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001427
Facundo Batista353750c2007-09-13 18:13:15 +00001428 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001429
Facundo Batista353750c2007-09-13 18:13:15 +00001430 ans = self._check_nans(other, context)
1431 if ans:
1432 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001433
Facundo Batista353750c2007-09-13 18:13:15 +00001434 # self == +/-infinity -> InvalidOperation
1435 if self._isinfinity():
1436 return context._raise_error(InvalidOperation,
1437 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001438
Facundo Batista353750c2007-09-13 18:13:15 +00001439 # other == 0 -> either InvalidOperation or DivisionUndefined
1440 if not other:
1441 if self:
1442 return context._raise_error(InvalidOperation,
1443 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001444 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001445 return context._raise_error(DivisionUndefined,
1446 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001447
Facundo Batista353750c2007-09-13 18:13:15 +00001448 # other = +/-infinity -> remainder = self
1449 if other._isinfinity():
1450 ans = Decimal(self)
1451 return ans._fix(context)
1452
1453 # self = 0 -> remainder = self, with ideal exponent
1454 ideal_exponent = min(self._exp, other._exp)
1455 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001456 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001457 return ans._fix(context)
1458
1459 # catch most cases of large or small quotient
1460 expdiff = self.adjusted() - other.adjusted()
1461 if expdiff >= context.prec + 1:
1462 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001463 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001464 if expdiff <= -2:
1465 # expdiff <= -2 => abs(self/other) < 0.1
1466 ans = self._rescale(ideal_exponent, context.rounding)
1467 return ans._fix(context)
1468
1469 # adjust both arguments to have the same exponent, then divide
1470 op1 = _WorkRep(self)
1471 op2 = _WorkRep(other)
1472 if op1.exp >= op2.exp:
1473 op1.int *= 10**(op1.exp - op2.exp)
1474 else:
1475 op2.int *= 10**(op2.exp - op1.exp)
1476 q, r = divmod(op1.int, op2.int)
1477 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1478 # 10**ideal_exponent. Apply correction to ensure that
1479 # abs(remainder) <= abs(other)/2
1480 if 2*r + (q&1) > op2.int:
1481 r -= op2.int
1482 q += 1
1483
1484 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001485 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001486
1487 # result has same sign as self unless r is negative
1488 sign = self._sign
1489 if r < 0:
1490 sign = 1-sign
1491 r = -r
1492
Facundo Batista72bc54f2007-11-23 17:59:00 +00001493 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001494 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001495
1496 def __floordiv__(self, other, context=None):
1497 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001498 other = _convert_other(other)
1499 if other is NotImplemented:
1500 return other
1501
1502 if context is None:
1503 context = getcontext()
1504
1505 ans = self._check_nans(other, context)
1506 if ans:
1507 return ans
1508
1509 if self._isinfinity():
1510 if other._isinfinity():
1511 return context._raise_error(InvalidOperation, 'INF // INF')
1512 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001513 return _SignedInfinity[self._sign ^ other._sign]
Facundo Batistacce8df22007-09-18 16:53:18 +00001514
1515 if not other:
1516 if self:
1517 return context._raise_error(DivisionByZero, 'x // 0',
1518 self._sign ^ other._sign)
1519 else:
1520 return context._raise_error(DivisionUndefined, '0 // 0')
1521
1522 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001523
1524 def __rfloordiv__(self, other, context=None):
1525 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001526 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001527 if other is NotImplemented:
1528 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001529 return other.__floordiv__(self, context=context)
1530
1531 def __float__(self):
1532 """Float representation."""
1533 return float(str(self))
1534
1535 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001536 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001537 if self._is_special:
1538 if self._isnan():
1539 context = getcontext()
1540 return context._raise_error(InvalidContext)
1541 elif self._isinfinity():
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001542 raise OverflowError("Cannot convert infinity to int")
Facundo Batista353750c2007-09-13 18:13:15 +00001543 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001544 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001545 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001546 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001547 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001548
Raymond Hettinger5a053642008-01-24 19:05:29 +00001549 __trunc__ = __int__
1550
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001551 @property
1552 def real(self):
1553 return self
1554
1555 @property
1556 def imag(self):
1557 return Decimal(0)
1558
1559 def conjugate(self):
1560 return self
1561
1562 def __complex__(self):
1563 return complex(float(self))
1564
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001565 def __long__(self):
1566 """Converts to a long.
1567
1568 Equivalent to long(int(self))
1569 """
1570 return long(self.__int__())
1571
Facundo Batista353750c2007-09-13 18:13:15 +00001572 def _fix_nan(self, context):
1573 """Decapitate the payload of a NaN to fit the context"""
1574 payload = self._int
1575
1576 # maximum length of payload is precision if _clamp=0,
1577 # precision-1 if _clamp=1.
1578 max_payload_len = context.prec - context._clamp
1579 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001580 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1581 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001582 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001583
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001584 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001585 """Round if it is necessary to keep self within prec precision.
1586
1587 Rounds and fixes the exponent. Does not raise on a sNaN.
1588
1589 Arguments:
1590 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001591 context - context used.
1592 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001593
Facundo Batista353750c2007-09-13 18:13:15 +00001594 if self._is_special:
1595 if self._isnan():
1596 # decapitate payload if necessary
1597 return self._fix_nan(context)
1598 else:
1599 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001600 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001601
Facundo Batista353750c2007-09-13 18:13:15 +00001602 # if self is zero then exponent should be between Etiny and
1603 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1604 Etiny = context.Etiny()
1605 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001606 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001607 exp_max = [context.Emax, Etop][context._clamp]
1608 new_exp = min(max(self._exp, Etiny), exp_max)
1609 if new_exp != self._exp:
1610 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001611 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001612 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001613 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001614
1615 # exp_min is the smallest allowable exponent of the result,
1616 # equal to max(self.adjusted()-context.prec+1, Etiny)
1617 exp_min = len(self._int) + self._exp - context.prec
1618 if exp_min > Etop:
1619 # overflow: exp_min > Etop iff self.adjusted() > Emax
1620 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001621 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001622 return context._raise_error(Overflow, 'above Emax', self._sign)
1623 self_is_subnormal = exp_min < Etiny
1624 if self_is_subnormal:
1625 context._raise_error(Subnormal)
1626 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001627
Facundo Batista353750c2007-09-13 18:13:15 +00001628 # round if self has too many digits
1629 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001630 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001631 digits = len(self._int) + self._exp - exp_min
1632 if digits < 0:
1633 self = _dec_from_triple(self._sign, '1', exp_min-1)
1634 digits = 0
1635 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1636 changed = this_function(digits)
1637 coeff = self._int[:digits] or '0'
1638 if changed == 1:
1639 coeff = str(int(coeff)+1)
1640 ans = _dec_from_triple(self._sign, coeff, exp_min)
1641
1642 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001643 context._raise_error(Inexact)
1644 if self_is_subnormal:
1645 context._raise_error(Underflow)
1646 if not ans:
1647 # raise Clamped on underflow to 0
1648 context._raise_error(Clamped)
1649 elif len(ans._int) == context.prec+1:
1650 # we get here only if rescaling rounds the
1651 # cofficient up to exactly 10**context.prec
1652 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001653 ans = _dec_from_triple(ans._sign,
1654 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001655 else:
1656 # Inexact and Rounded have already been raised
1657 ans = context._raise_error(Overflow, 'above Emax',
1658 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001659 return ans
1660
Facundo Batista353750c2007-09-13 18:13:15 +00001661 # fold down if _clamp == 1 and self has too few digits
1662 if context._clamp == 1 and self._exp > Etop:
1663 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001664 self_padded = self._int + '0'*(self._exp - Etop)
1665 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001666
Facundo Batista353750c2007-09-13 18:13:15 +00001667 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001668 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001669
1670 _pick_rounding_function = {}
1671
Facundo Batista353750c2007-09-13 18:13:15 +00001672 # for each of the rounding functions below:
1673 # self is a finite, nonzero Decimal
1674 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001675 #
1676 # each function returns either -1, 0, or 1, as follows:
1677 # 1 indicates that self should be rounded up (away from zero)
1678 # 0 indicates that self should be truncated, and that all the
1679 # digits to be truncated are zeros (so the value is unchanged)
1680 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001681
1682 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001683 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001684 if _all_zeros(self._int, prec):
1685 return 0
1686 else:
1687 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001688
Facundo Batista353750c2007-09-13 18:13:15 +00001689 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001690 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001691 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001692
Facundo Batista353750c2007-09-13 18:13:15 +00001693 def _round_half_up(self, prec):
1694 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001695 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001696 return 1
1697 elif _all_zeros(self._int, prec):
1698 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001699 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001700 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001701
1702 def _round_half_down(self, prec):
1703 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001704 if _exact_half(self._int, prec):
1705 return -1
1706 else:
1707 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001708
1709 def _round_half_even(self, prec):
1710 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001711 if _exact_half(self._int, prec) and \
1712 (prec == 0 or self._int[prec-1] in '02468'):
1713 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001714 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001715 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001716
1717 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001718 """Rounds up (not away from 0 if negative.)"""
1719 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001720 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001721 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001722 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001723
Facundo Batista353750c2007-09-13 18:13:15 +00001724 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001725 """Rounds down (not towards 0 if negative)"""
1726 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001727 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001728 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001729 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001730
Facundo Batista353750c2007-09-13 18:13:15 +00001731 def _round_05up(self, prec):
1732 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001733 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001734 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001735 else:
1736 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001737
Facundo Batista353750c2007-09-13 18:13:15 +00001738 def fma(self, other, third, context=None):
1739 """Fused multiply-add.
1740
1741 Returns self*other+third with no rounding of the intermediate
1742 product self*other.
1743
1744 self and other are multiplied together, with no rounding of
1745 the result. The third operand is then added to the result,
1746 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001747 """
Facundo Batista353750c2007-09-13 18:13:15 +00001748
1749 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001750
1751 # compute product; raise InvalidOperation if either operand is
1752 # a signaling NaN or if the product is zero times infinity.
1753 if self._is_special or other._is_special:
1754 if context is None:
1755 context = getcontext()
1756 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001757 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001758 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001759 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001760 if self._exp == 'n':
1761 product = self
1762 elif other._exp == 'n':
1763 product = other
1764 elif self._exp == 'F':
1765 if not other:
1766 return context._raise_error(InvalidOperation,
1767 'INF * 0 in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001768 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001769 elif other._exp == 'F':
1770 if not self:
1771 return context._raise_error(InvalidOperation,
1772 '0 * INF in fma')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00001773 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001774 else:
1775 product = _dec_from_triple(self._sign ^ other._sign,
1776 str(int(self._int) * int(other._int)),
1777 self._exp + other._exp)
1778
Facundo Batista353750c2007-09-13 18:13:15 +00001779 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001780 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001781
Facundo Batista353750c2007-09-13 18:13:15 +00001782 def _power_modulo(self, other, modulo, context=None):
1783 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001784
Facundo Batista353750c2007-09-13 18:13:15 +00001785 # if can't convert other and modulo to Decimal, raise
1786 # TypeError; there's no point returning NotImplemented (no
1787 # equivalent of __rpow__ for three argument pow)
1788 other = _convert_other(other, raiseit=True)
1789 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001790
Facundo Batista353750c2007-09-13 18:13:15 +00001791 if context is None:
1792 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001793
Facundo Batista353750c2007-09-13 18:13:15 +00001794 # deal with NaNs: if there are any sNaNs then first one wins,
1795 # (i.e. behaviour for NaNs is identical to that of fma)
1796 self_is_nan = self._isnan()
1797 other_is_nan = other._isnan()
1798 modulo_is_nan = modulo._isnan()
1799 if self_is_nan or other_is_nan or modulo_is_nan:
1800 if self_is_nan == 2:
1801 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001802 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001803 if other_is_nan == 2:
1804 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001805 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001806 if modulo_is_nan == 2:
1807 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001808 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001809 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001810 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001811 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001812 return other._fix_nan(context)
1813 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001814
Facundo Batista353750c2007-09-13 18:13:15 +00001815 # check inputs: we apply same restrictions as Python's pow()
1816 if not (self._isinteger() and
1817 other._isinteger() and
1818 modulo._isinteger()):
1819 return context._raise_error(InvalidOperation,
1820 'pow() 3rd argument not allowed '
1821 'unless all arguments are integers')
1822 if other < 0:
1823 return context._raise_error(InvalidOperation,
1824 'pow() 2nd argument cannot be '
1825 'negative when 3rd argument specified')
1826 if not modulo:
1827 return context._raise_error(InvalidOperation,
1828 'pow() 3rd argument cannot be 0')
1829
1830 # additional restriction for decimal: the modulus must be less
1831 # than 10**prec in absolute value
1832 if modulo.adjusted() >= context.prec:
1833 return context._raise_error(InvalidOperation,
1834 'insufficient precision: pow() 3rd '
1835 'argument must not have more than '
1836 'precision digits')
1837
1838 # define 0**0 == NaN, for consistency with two-argument pow
1839 # (even though it hurts!)
1840 if not other and not self:
1841 return context._raise_error(InvalidOperation,
1842 'at least one of pow() 1st argument '
1843 'and 2nd argument must be nonzero ;'
1844 '0**0 is not defined')
1845
1846 # compute sign of result
1847 if other._iseven():
1848 sign = 0
1849 else:
1850 sign = self._sign
1851
1852 # convert modulo to a Python integer, and self and other to
1853 # Decimal integers (i.e. force their exponents to be >= 0)
1854 modulo = abs(int(modulo))
1855 base = _WorkRep(self.to_integral_value())
1856 exponent = _WorkRep(other.to_integral_value())
1857
1858 # compute result using integer pow()
1859 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1860 for i in xrange(exponent.exp):
1861 base = pow(base, 10, modulo)
1862 base = pow(base, exponent.int, modulo)
1863
Facundo Batista72bc54f2007-11-23 17:59:00 +00001864 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001865
1866 def _power_exact(self, other, p):
1867 """Attempt to compute self**other exactly.
1868
1869 Given Decimals self and other and an integer p, attempt to
1870 compute an exact result for the power self**other, with p
1871 digits of precision. Return None if self**other is not
1872 exactly representable in p digits.
1873
1874 Assumes that elimination of special cases has already been
1875 performed: self and other must both be nonspecial; self must
1876 be positive and not numerically equal to 1; other must be
1877 nonzero. For efficiency, other._exp should not be too large,
1878 so that 10**abs(other._exp) is a feasible calculation."""
1879
1880 # In the comments below, we write x for the value of self and
1881 # y for the value of other. Write x = xc*10**xe and y =
1882 # yc*10**ye.
1883
1884 # The main purpose of this method is to identify the *failure*
1885 # of x**y to be exactly representable with as little effort as
1886 # possible. So we look for cheap and easy tests that
1887 # eliminate the possibility of x**y being exact. Only if all
1888 # these tests are passed do we go on to actually compute x**y.
1889
1890 # Here's the main idea. First normalize both x and y. We
1891 # express y as a rational m/n, with m and n relatively prime
1892 # and n>0. Then for x**y to be exactly representable (at
1893 # *any* precision), xc must be the nth power of a positive
1894 # integer and xe must be divisible by n. If m is negative
1895 # then additionally xc must be a power of either 2 or 5, hence
1896 # a power of 2**n or 5**n.
1897 #
1898 # There's a limit to how small |y| can be: if y=m/n as above
1899 # then:
1900 #
1901 # (1) if xc != 1 then for the result to be representable we
1902 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1903 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1904 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1905 # representable.
1906 #
1907 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1908 # |y| < 1/|xe| then the result is not representable.
1909 #
1910 # Note that since x is not equal to 1, at least one of (1) and
1911 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1912 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1913 #
1914 # There's also a limit to how large y can be, at least if it's
1915 # positive: the normalized result will have coefficient xc**y,
1916 # so if it's representable then xc**y < 10**p, and y <
1917 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1918 # not exactly representable.
1919
1920 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1921 # so |y| < 1/xe and the result is not representable.
1922 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1923 # < 1/nbits(xc).
1924
1925 x = _WorkRep(self)
1926 xc, xe = x.int, x.exp
1927 while xc % 10 == 0:
1928 xc //= 10
1929 xe += 1
1930
1931 y = _WorkRep(other)
1932 yc, ye = y.int, y.exp
1933 while yc % 10 == 0:
1934 yc //= 10
1935 ye += 1
1936
1937 # case where xc == 1: result is 10**(xe*y), with xe*y
1938 # required to be an integer
1939 if xc == 1:
1940 if ye >= 0:
1941 exponent = xe*yc*10**ye
1942 else:
1943 exponent, remainder = divmod(xe*yc, 10**-ye)
1944 if remainder:
1945 return None
1946 if y.sign == 1:
1947 exponent = -exponent
1948 # if other is a nonnegative integer, use ideal exponent
1949 if other._isinteger() and other._sign == 0:
1950 ideal_exponent = self._exp*int(other)
1951 zeros = min(exponent-ideal_exponent, p-1)
1952 else:
1953 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001954 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001955
1956 # case where y is negative: xc must be either a power
1957 # of 2 or a power of 5.
1958 if y.sign == 1:
1959 last_digit = xc % 10
1960 if last_digit in (2,4,6,8):
1961 # quick test for power of 2
1962 if xc & -xc != xc:
1963 return None
1964 # now xc is a power of 2; e is its exponent
1965 e = _nbits(xc)-1
1966 # find e*y and xe*y; both must be integers
1967 if ye >= 0:
1968 y_as_int = yc*10**ye
1969 e = e*y_as_int
1970 xe = xe*y_as_int
1971 else:
1972 ten_pow = 10**-ye
1973 e, remainder = divmod(e*yc, ten_pow)
1974 if remainder:
1975 return None
1976 xe, remainder = divmod(xe*yc, ten_pow)
1977 if remainder:
1978 return None
1979
1980 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1981 return None
1982 xc = 5**e
1983
1984 elif last_digit == 5:
1985 # e >= log_5(xc) if xc is a power of 5; we have
1986 # equality all the way up to xc=5**2658
1987 e = _nbits(xc)*28//65
1988 xc, remainder = divmod(5**e, xc)
1989 if remainder:
1990 return None
1991 while xc % 5 == 0:
1992 xc //= 5
1993 e -= 1
1994 if ye >= 0:
1995 y_as_integer = yc*10**ye
1996 e = e*y_as_integer
1997 xe = xe*y_as_integer
1998 else:
1999 ten_pow = 10**-ye
2000 e, remainder = divmod(e*yc, ten_pow)
2001 if remainder:
2002 return None
2003 xe, remainder = divmod(xe*yc, ten_pow)
2004 if remainder:
2005 return None
2006 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2007 return None
2008 xc = 2**e
2009 else:
2010 return None
2011
2012 if xc >= 10**p:
2013 return None
2014 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00002015 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00002016
2017 # now y is positive; find m and n such that y = m/n
2018 if ye >= 0:
2019 m, n = yc*10**ye, 1
2020 else:
2021 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2022 return None
2023 xc_bits = _nbits(xc)
2024 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2025 return None
2026 m, n = yc, 10**(-ye)
2027 while m % 2 == n % 2 == 0:
2028 m //= 2
2029 n //= 2
2030 while m % 5 == n % 5 == 0:
2031 m //= 5
2032 n //= 5
2033
2034 # compute nth root of xc*10**xe
2035 if n > 1:
2036 # if 1 < xc < 2**n then xc isn't an nth power
2037 if xc != 1 and xc_bits <= n:
2038 return None
2039
2040 xe, rem = divmod(xe, n)
2041 if rem != 0:
2042 return None
2043
2044 # compute nth root of xc using Newton's method
2045 a = 1L << -(-_nbits(xc)//n) # initial estimate
2046 while True:
2047 q, r = divmod(xc, a**(n-1))
2048 if a <= q:
2049 break
2050 else:
2051 a = (a*(n-1) + q)//n
2052 if not (a == q and r == 0):
2053 return None
2054 xc = a
2055
2056 # now xc*10**xe is the nth root of the original xc*10**xe
2057 # compute mth power of xc*10**xe
2058
2059 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2060 # 10**p and the result is not representable.
2061 if xc > 1 and m > p*100//_log10_lb(xc):
2062 return None
2063 xc = xc**m
2064 xe *= m
2065 if xc > 10**p:
2066 return None
2067
2068 # by this point the result *is* exactly representable
2069 # adjust the exponent to get as close as possible to the ideal
2070 # exponent, if necessary
2071 str_xc = str(xc)
2072 if other._isinteger() and other._sign == 0:
2073 ideal_exponent = self._exp*int(other)
2074 zeros = min(xe-ideal_exponent, p-len(str_xc))
2075 else:
2076 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002077 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002078
2079 def __pow__(self, other, modulo=None, context=None):
2080 """Return self ** other [ % modulo].
2081
2082 With two arguments, compute self**other.
2083
2084 With three arguments, compute (self**other) % modulo. For the
2085 three argument form, the following restrictions on the
2086 arguments hold:
2087
2088 - all three arguments must be integral
2089 - other must be nonnegative
2090 - either self or other (or both) must be nonzero
2091 - modulo must be nonzero and must have at most p digits,
2092 where p is the context precision.
2093
2094 If any of these restrictions is violated the InvalidOperation
2095 flag is raised.
2096
2097 The result of pow(self, other, modulo) is identical to the
2098 result that would be obtained by computing (self**other) %
2099 modulo with unbounded precision, but is computed more
2100 efficiently. It is always exact.
2101 """
2102
2103 if modulo is not None:
2104 return self._power_modulo(other, modulo, context)
2105
2106 other = _convert_other(other)
2107 if other is NotImplemented:
2108 return other
2109
2110 if context is None:
2111 context = getcontext()
2112
2113 # either argument is a NaN => result is NaN
2114 ans = self._check_nans(other, context)
2115 if ans:
2116 return ans
2117
2118 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2119 if not other:
2120 if not self:
2121 return context._raise_error(InvalidOperation, '0 ** 0')
2122 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002123 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002124
2125 # result has sign 1 iff self._sign is 1 and other is an odd integer
2126 result_sign = 0
2127 if self._sign == 1:
2128 if other._isinteger():
2129 if not other._iseven():
2130 result_sign = 1
2131 else:
2132 # -ve**noninteger = NaN
2133 # (-0)**noninteger = 0**noninteger
2134 if self:
2135 return context._raise_error(InvalidOperation,
2136 'x ** y with x negative and y not an integer')
2137 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002138 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002139
2140 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2141 if not self:
2142 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002143 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002144 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002145 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002146
2147 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002148 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002149 if other._sign == 0:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002150 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002151 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002152 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002153
Facundo Batista353750c2007-09-13 18:13:15 +00002154 # 1**other = 1, but the choice of exponent and the flags
2155 # depend on the exponent of self, and on whether other is a
2156 # positive integer, a negative integer, or neither
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002157 if self == _One:
Facundo Batista353750c2007-09-13 18:13:15 +00002158 if other._isinteger():
2159 # exp = max(self._exp*max(int(other), 0),
2160 # 1-context.prec) but evaluating int(other) directly
2161 # is dangerous until we know other is small (other
2162 # could be 1e999999999)
2163 if other._sign == 1:
2164 multiplier = 0
2165 elif other > context.prec:
2166 multiplier = context.prec
2167 else:
2168 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002169
Facundo Batista353750c2007-09-13 18:13:15 +00002170 exp = self._exp * multiplier
2171 if exp < 1-context.prec:
2172 exp = 1-context.prec
2173 context._raise_error(Rounded)
2174 else:
2175 context._raise_error(Inexact)
2176 context._raise_error(Rounded)
2177 exp = 1-context.prec
2178
Facundo Batista72bc54f2007-11-23 17:59:00 +00002179 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002180
2181 # compute adjusted exponent of self
2182 self_adj = self.adjusted()
2183
2184 # self ** infinity is infinity if self > 1, 0 if self < 1
2185 # self ** -infinity is infinity if self < 1, 0 if self > 1
2186 if other._isinfinity():
2187 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002188 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002189 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002190 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002191
2192 # from here on, the result always goes through the call
2193 # to _fix at the end of this function.
2194 ans = None
2195
2196 # crude test to catch cases of extreme overflow/underflow. If
2197 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2198 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2199 # self**other >= 10**(Emax+1), so overflow occurs. The test
2200 # for underflow is similar.
2201 bound = self._log10_exp_bound() + other.adjusted()
2202 if (self_adj >= 0) == (other._sign == 0):
2203 # self > 1 and other +ve, or self < 1 and other -ve
2204 # possibility of overflow
2205 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002206 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002207 else:
2208 # self > 1 and other -ve, or self < 1 and other +ve
2209 # possibility of underflow to 0
2210 Etiny = context.Etiny()
2211 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002212 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002213
2214 # try for an exact result with precision +1
2215 if ans is None:
2216 ans = self._power_exact(other, context.prec + 1)
2217 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002218 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002219
2220 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2221 if ans is None:
2222 p = context.prec
2223 x = _WorkRep(self)
2224 xc, xe = x.int, x.exp
2225 y = _WorkRep(other)
2226 yc, ye = y.int, y.exp
2227 if y.sign == 1:
2228 yc = -yc
2229
2230 # compute correctly rounded result: start with precision +3,
2231 # then increase precision until result is unambiguously roundable
2232 extra = 3
2233 while True:
2234 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2235 if coeff % (5*10**(len(str(coeff))-p-1)):
2236 break
2237 extra += 3
2238
Facundo Batista72bc54f2007-11-23 17:59:00 +00002239 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002240
2241 # the specification says that for non-integer other we need to
2242 # raise Inexact, even when the result is actually exact. In
2243 # the same way, we need to raise Underflow here if the result
2244 # is subnormal. (The call to _fix will take care of raising
2245 # Rounded and Subnormal, as usual.)
2246 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002247 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002248 # pad with zeros up to length context.prec+1 if necessary
2249 if len(ans._int) <= context.prec:
2250 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002251 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2252 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002253 if ans.adjusted() < context.Emin:
2254 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002255
Facundo Batista353750c2007-09-13 18:13:15 +00002256 # unlike exp, ln and log10, the power function respects the
2257 # rounding mode; no need to use ROUND_HALF_EVEN here
2258 ans = ans._fix(context)
2259 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002260
2261 def __rpow__(self, other, context=None):
2262 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002263 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002264 if other is NotImplemented:
2265 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002266 return other.__pow__(self, context=context)
2267
2268 def normalize(self, context=None):
2269 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002270
Facundo Batista353750c2007-09-13 18:13:15 +00002271 if context is None:
2272 context = getcontext()
2273
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002274 if self._is_special:
2275 ans = self._check_nans(context=context)
2276 if ans:
2277 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002278
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002279 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002280 if dup._isinfinity():
2281 return dup
2282
2283 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002284 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002285 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002286 end = len(dup._int)
2287 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002288 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002289 exp += 1
2290 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002291 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002292
Facundo Batistabd2fe832007-09-13 18:42:09 +00002293 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002294 """Quantize self so its exponent is the same as that of exp.
2295
2296 Similar to self._rescale(exp._exp) but with error checking.
2297 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002298 exp = _convert_other(exp, raiseit=True)
2299
Facundo Batista353750c2007-09-13 18:13:15 +00002300 if context is None:
2301 context = getcontext()
2302 if rounding is None:
2303 rounding = context.rounding
2304
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002305 if self._is_special or exp._is_special:
2306 ans = self._check_nans(exp, context)
2307 if ans:
2308 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002309
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002310 if exp._isinfinity() or self._isinfinity():
2311 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002312 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002313 return context._raise_error(InvalidOperation,
2314 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002315
Facundo Batistabd2fe832007-09-13 18:42:09 +00002316 # if we're not watching exponents, do a simple rescale
2317 if not watchexp:
2318 ans = self._rescale(exp._exp, rounding)
2319 # raise Inexact and Rounded where appropriate
2320 if ans._exp > self._exp:
2321 context._raise_error(Rounded)
2322 if ans != self:
2323 context._raise_error(Inexact)
2324 return ans
2325
Facundo Batista353750c2007-09-13 18:13:15 +00002326 # exp._exp should be between Etiny and Emax
2327 if not (context.Etiny() <= exp._exp <= context.Emax):
2328 return context._raise_error(InvalidOperation,
2329 'target exponent out of bounds in quantize')
2330
2331 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002332 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002333 return ans._fix(context)
2334
2335 self_adjusted = self.adjusted()
2336 if self_adjusted > context.Emax:
2337 return context._raise_error(InvalidOperation,
2338 'exponent of quantize result too large for current context')
2339 if self_adjusted - exp._exp + 1 > context.prec:
2340 return context._raise_error(InvalidOperation,
2341 'quantize result has too many digits for current context')
2342
2343 ans = self._rescale(exp._exp, rounding)
2344 if ans.adjusted() > context.Emax:
2345 return context._raise_error(InvalidOperation,
2346 'exponent of quantize result too large for current context')
2347 if len(ans._int) > context.prec:
2348 return context._raise_error(InvalidOperation,
2349 'quantize result has too many digits for current context')
2350
2351 # raise appropriate flags
2352 if ans._exp > self._exp:
2353 context._raise_error(Rounded)
2354 if ans != self:
2355 context._raise_error(Inexact)
2356 if ans and ans.adjusted() < context.Emin:
2357 context._raise_error(Subnormal)
2358
2359 # call to fix takes care of any necessary folddown
2360 ans = ans._fix(context)
2361 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002362
2363 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002364 """Return True if self and other have the same exponent; otherwise
2365 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002366
Facundo Batista1a191df2007-10-02 17:01:24 +00002367 If either operand is a special value, the following rules are used:
2368 * return True if both operands are infinities
2369 * return True if both operands are NaNs
2370 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002371 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002372 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002373 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002374 return (self.is_nan() and other.is_nan() or
2375 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002376 return self._exp == other._exp
2377
Facundo Batista353750c2007-09-13 18:13:15 +00002378 def _rescale(self, exp, rounding):
2379 """Rescale self so that the exponent is exp, either by padding with zeros
2380 or by truncating digits, using the given rounding mode.
2381
2382 Specials are returned without change. This operation is
2383 quiet: it raises no flags, and uses no information from the
2384 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002385
2386 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002387 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002388 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002389 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002390 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002391 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002392 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002393
Facundo Batista353750c2007-09-13 18:13:15 +00002394 if self._exp >= exp:
2395 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002396 return _dec_from_triple(self._sign,
2397 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002398
Facundo Batista353750c2007-09-13 18:13:15 +00002399 # too many digits; round and lose data. If self.adjusted() <
2400 # exp-1, replace self by 10**(exp-1) before rounding
2401 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002402 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002403 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002404 digits = 0
2405 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002406 changed = this_function(digits)
2407 coeff = self._int[:digits] or '0'
2408 if changed == 1:
2409 coeff = str(int(coeff)+1)
2410 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002411
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00002412 def _round(self, places, rounding):
2413 """Round a nonzero, nonspecial Decimal to a fixed number of
2414 significant figures, using the given rounding mode.
2415
2416 Infinities, NaNs and zeros are returned unaltered.
2417
2418 This operation is quiet: it raises no flags, and uses no
2419 information from the context.
2420
2421 """
2422 if places <= 0:
2423 raise ValueError("argument should be at least 1 in _round")
2424 if self._is_special or not self:
2425 return Decimal(self)
2426 ans = self._rescale(self.adjusted()+1-places, rounding)
2427 # it can happen that the rescale alters the adjusted exponent;
2428 # for example when rounding 99.97 to 3 significant figures.
2429 # When this happens we end up with an extra 0 at the end of
2430 # the number; a second rescale fixes this.
2431 if ans.adjusted() != self.adjusted():
2432 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2433 return ans
2434
Facundo Batista353750c2007-09-13 18:13:15 +00002435 def to_integral_exact(self, rounding=None, context=None):
2436 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002437
Facundo Batista353750c2007-09-13 18:13:15 +00002438 If no rounding mode is specified, take the rounding mode from
2439 the context. This method raises the Rounded and Inexact flags
2440 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002441
Facundo Batista353750c2007-09-13 18:13:15 +00002442 See also: to_integral_value, which does exactly the same as
2443 this method except that it doesn't raise Inexact or Rounded.
2444 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002445 if self._is_special:
2446 ans = self._check_nans(context=context)
2447 if ans:
2448 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002449 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002450 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002451 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002452 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002453 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002454 if context is None:
2455 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002456 if rounding is None:
2457 rounding = context.rounding
2458 context._raise_error(Rounded)
2459 ans = self._rescale(0, rounding)
2460 if ans != self:
2461 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002462 return ans
2463
Facundo Batista353750c2007-09-13 18:13:15 +00002464 def to_integral_value(self, rounding=None, context=None):
2465 """Rounds to the nearest integer, without raising inexact, rounded."""
2466 if context is None:
2467 context = getcontext()
2468 if rounding is None:
2469 rounding = context.rounding
2470 if self._is_special:
2471 ans = self._check_nans(context=context)
2472 if ans:
2473 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002474 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002475 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002476 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002477 else:
2478 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002479
Facundo Batista353750c2007-09-13 18:13:15 +00002480 # the method name changed, but we provide also the old one, for compatibility
2481 to_integral = to_integral_value
2482
2483 def sqrt(self, context=None):
2484 """Return the square root of self."""
Mark Dickinson3b24ccb2008-03-25 14:33:23 +00002485 if context is None:
2486 context = getcontext()
2487
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002488 if self._is_special:
2489 ans = self._check_nans(context=context)
2490 if ans:
2491 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002492
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002493 if self._isinfinity() and self._sign == 0:
2494 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002495
2496 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002497 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002498 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002499 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002500
2501 if self._sign == 1:
2502 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2503
Facundo Batista353750c2007-09-13 18:13:15 +00002504 # At this point self represents a positive number. Let p be
2505 # the desired precision and express self in the form c*100**e
2506 # with c a positive real number and e an integer, c and e
2507 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2508 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2509 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2510 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2511 # the closest integer to sqrt(c) with the even integer chosen
2512 # in the case of a tie.
2513 #
2514 # To ensure correct rounding in all cases, we use the
2515 # following trick: we compute the square root to an extra
2516 # place (precision p+1 instead of precision p), rounding down.
2517 # Then, if the result is inexact and its last digit is 0 or 5,
2518 # we increase the last digit to 1 or 6 respectively; if it's
2519 # exact we leave the last digit alone. Now the final round to
2520 # p places (or fewer in the case of underflow) will round
2521 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002522
Facundo Batista353750c2007-09-13 18:13:15 +00002523 # use an extra digit of precision
2524 prec = context.prec+1
2525
2526 # write argument in the form c*100**e where e = self._exp//2
2527 # is the 'ideal' exponent, to be used if the square root is
2528 # exactly representable. l is the number of 'digits' of c in
2529 # base 100, so that 100**(l-1) <= c < 100**l.
2530 op = _WorkRep(self)
2531 e = op.exp >> 1
2532 if op.exp & 1:
2533 c = op.int * 10
2534 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002535 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002536 c = op.int
2537 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002538
Facundo Batista353750c2007-09-13 18:13:15 +00002539 # rescale so that c has exactly prec base 100 'digits'
2540 shift = prec-l
2541 if shift >= 0:
2542 c *= 100**shift
2543 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002544 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002545 c, remainder = divmod(c, 100**-shift)
2546 exact = not remainder
2547 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002548
Facundo Batista353750c2007-09-13 18:13:15 +00002549 # find n = floor(sqrt(c)) using Newton's method
2550 n = 10**prec
2551 while True:
2552 q = c//n
2553 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002554 break
Facundo Batista353750c2007-09-13 18:13:15 +00002555 else:
2556 n = n + q >> 1
2557 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002558
Facundo Batista353750c2007-09-13 18:13:15 +00002559 if exact:
2560 # result is exact; rescale to use ideal exponent e
2561 if shift >= 0:
2562 # assert n % 10**shift == 0
2563 n //= 10**shift
2564 else:
2565 n *= 10**-shift
2566 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002567 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002568 # result is not exact; fix last digit as described above
2569 if n % 5 == 0:
2570 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002571
Facundo Batista72bc54f2007-11-23 17:59:00 +00002572 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002573
Facundo Batista353750c2007-09-13 18:13:15 +00002574 # round, and fit to current context
2575 context = context._shallow_copy()
2576 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002577 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002578 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002579
Facundo Batista353750c2007-09-13 18:13:15 +00002580 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002581
2582 def max(self, other, context=None):
2583 """Returns the larger value.
2584
Facundo Batista353750c2007-09-13 18:13:15 +00002585 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002586 NaN (and signals if one is sNaN). Also rounds.
2587 """
Facundo Batista353750c2007-09-13 18:13:15 +00002588 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002589
Facundo Batista6c398da2007-09-17 17:30:13 +00002590 if context is None:
2591 context = getcontext()
2592
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002593 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002594 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002595 # number is always returned
2596 sn = self._isnan()
2597 on = other._isnan()
2598 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002599 if on == 1 and sn == 0:
2600 return self._fix(context)
2601 if sn == 1 and on == 0:
2602 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002603 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002604
Mark Dickinson2fc92632008-02-06 22:10:50 +00002605 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002606 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002607 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002608 # then an ordering is applied:
2609 #
Facundo Batista59c58842007-04-10 12:58:45 +00002610 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002611 # positive sign and min returns the operand with the negative sign
2612 #
Facundo Batista59c58842007-04-10 12:58:45 +00002613 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002614 # the result. This is exactly the ordering used in compare_total.
2615 c = self.compare_total(other)
2616
2617 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002618 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002619 else:
2620 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002621
Facundo Batistae64acfa2007-12-17 14:18:42 +00002622 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002623
2624 def min(self, other, context=None):
2625 """Returns the smaller value.
2626
Facundo Batista59c58842007-04-10 12:58:45 +00002627 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002628 NaN (and signals if one is sNaN). Also rounds.
2629 """
Facundo Batista353750c2007-09-13 18:13:15 +00002630 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002631
Facundo Batista6c398da2007-09-17 17:30:13 +00002632 if context is None:
2633 context = getcontext()
2634
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002635 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002636 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002637 # number is always returned
2638 sn = self._isnan()
2639 on = other._isnan()
2640 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00002641 if on == 1 and sn == 0:
2642 return self._fix(context)
2643 if sn == 1 and on == 0:
2644 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002645 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002646
Mark Dickinson2fc92632008-02-06 22:10:50 +00002647 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002648 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002649 c = self.compare_total(other)
2650
2651 if c == -1:
2652 ans = self
2653 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002654 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002655
Facundo Batistae64acfa2007-12-17 14:18:42 +00002656 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002657
2658 def _isinteger(self):
2659 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002660 if self._is_special:
2661 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002662 if self._exp >= 0:
2663 return True
2664 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002665 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002666
2667 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002668 """Returns True if self is even. Assumes self is an integer."""
2669 if not self or self._exp > 0:
2670 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002671 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002672
2673 def adjusted(self):
2674 """Return the adjusted exponent of self"""
2675 try:
2676 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002677 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002678 except TypeError:
2679 return 0
2680
Facundo Batista353750c2007-09-13 18:13:15 +00002681 def canonical(self, context=None):
2682 """Returns the same Decimal object.
2683
2684 As we do not have different encodings for the same number, the
2685 received object already is in its canonical form.
2686 """
2687 return self
2688
2689 def compare_signal(self, other, context=None):
2690 """Compares self to the other operand numerically.
2691
2692 It's pretty much like compare(), but all NaNs signal, with signaling
2693 NaNs taking precedence over quiet NaNs.
2694 """
Mark Dickinson2fc92632008-02-06 22:10:50 +00002695 other = _convert_other(other, raiseit = True)
2696 ans = self._compare_check_nans(other, context)
2697 if ans:
2698 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002699 return self.compare(other, context=context)
2700
2701 def compare_total(self, other):
2702 """Compares self to other using the abstract representations.
2703
2704 This is not like the standard compare, which use their numerical
2705 value. Note that a total ordering is defined for all possible abstract
2706 representations.
2707 """
2708 # if one is negative and the other is positive, it's easy
2709 if self._sign and not other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002710 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002711 if not self._sign and other._sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002712 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002713 sign = self._sign
2714
2715 # let's handle both NaN types
2716 self_nan = self._isnan()
2717 other_nan = other._isnan()
2718 if self_nan or other_nan:
2719 if self_nan == other_nan:
2720 if self._int < other._int:
2721 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002722 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002723 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002724 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002725 if self._int > other._int:
2726 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002727 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002728 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002729 return _One
2730 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002731
2732 if sign:
2733 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002734 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002735 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002736 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002737 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002738 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002739 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002740 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002741 else:
2742 if self_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002743 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002744 if other_nan == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002745 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002746 if self_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002747 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002748 if other_nan == 2:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002749 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002750
2751 if self < other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002752 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002753 if self > other:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002754 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002755
2756 if self._exp < other._exp:
2757 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002758 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002759 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002760 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002761 if self._exp > other._exp:
2762 if sign:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002763 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002764 else:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002765 return _One
2766 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002767
2768
2769 def compare_total_mag(self, other):
2770 """Compares self to other using abstract repr., ignoring sign.
2771
2772 Like compare_total, but with operand's sign ignored and assumed to be 0.
2773 """
2774 s = self.copy_abs()
2775 o = other.copy_abs()
2776 return s.compare_total(o)
2777
2778 def copy_abs(self):
2779 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002780 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002781
2782 def copy_negate(self):
2783 """Returns a copy with the sign inverted."""
2784 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002785 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002786 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002787 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002788
2789 def copy_sign(self, other):
2790 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002791 return _dec_from_triple(other._sign, self._int,
2792 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002793
2794 def exp(self, context=None):
2795 """Returns e ** self."""
2796
2797 if context is None:
2798 context = getcontext()
2799
2800 # exp(NaN) = NaN
2801 ans = self._check_nans(context=context)
2802 if ans:
2803 return ans
2804
2805 # exp(-Infinity) = 0
2806 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002807 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002808
2809 # exp(0) = 1
2810 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002811 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002812
2813 # exp(Infinity) = Infinity
2814 if self._isinfinity() == 1:
2815 return Decimal(self)
2816
2817 # the result is now guaranteed to be inexact (the true
2818 # mathematical result is transcendental). There's no need to
2819 # raise Rounded and Inexact here---they'll always be raised as
2820 # a result of the call to _fix.
2821 p = context.prec
2822 adj = self.adjusted()
2823
2824 # we only need to do any computation for quite a small range
2825 # of adjusted exponents---for example, -29 <= adj <= 10 for
2826 # the default context. For smaller exponent the result is
2827 # indistinguishable from 1 at the given precision, while for
2828 # larger exponent the result either overflows or underflows.
2829 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2830 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002831 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002832 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2833 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002834 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002835 elif self._sign == 0 and adj < -p:
2836 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002837 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002838 elif self._sign == 1 and adj < -p-1:
2839 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002840 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002841 # general case
2842 else:
2843 op = _WorkRep(self)
2844 c, e = op.int, op.exp
2845 if op.sign == 1:
2846 c = -c
2847
2848 # compute correctly rounded result: increase precision by
2849 # 3 digits at a time until we get an unambiguously
2850 # roundable result
2851 extra = 3
2852 while True:
2853 coeff, exp = _dexp(c, e, p+extra)
2854 if coeff % (5*10**(len(str(coeff))-p-1)):
2855 break
2856 extra += 3
2857
Facundo Batista72bc54f2007-11-23 17:59:00 +00002858 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002859
2860 # at this stage, ans should round correctly with *any*
2861 # rounding mode, not just with ROUND_HALF_EVEN
2862 context = context._shallow_copy()
2863 rounding = context._set_rounding(ROUND_HALF_EVEN)
2864 ans = ans._fix(context)
2865 context.rounding = rounding
2866
2867 return ans
2868
2869 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002870 """Return True if self is canonical; otherwise return False.
2871
2872 Currently, the encoding of a Decimal instance is always
2873 canonical, so this method returns True for any Decimal.
2874 """
2875 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002876
2877 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002878 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002879
Facundo Batista1a191df2007-10-02 17:01:24 +00002880 A Decimal instance is considered finite if it is neither
2881 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002882 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002883 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002884
2885 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002886 """Return True if self is infinite; otherwise return False."""
2887 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002888
2889 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002890 """Return True if self is a qNaN or sNaN; otherwise return False."""
2891 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002892
2893 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002894 """Return True if self is a normal number; otherwise return False."""
2895 if self._is_special or not self:
2896 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002897 if context is None:
2898 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002899 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002900
2901 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002902 """Return True if self is a quiet NaN; otherwise return False."""
2903 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002904
2905 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002906 """Return True if self is negative; otherwise return False."""
2907 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002908
2909 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002910 """Return True if self is a signaling NaN; otherwise return False."""
2911 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002912
2913 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002914 """Return True if self is subnormal; otherwise return False."""
2915 if self._is_special or not self:
2916 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002917 if context is None:
2918 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002919 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002920
2921 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002922 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002923 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002924
2925 def _ln_exp_bound(self):
2926 """Compute a lower bound for the adjusted exponent of self.ln().
2927 In other words, compute r such that self.ln() >= 10**r. Assumes
2928 that self is finite and positive and that self != 1.
2929 """
2930
2931 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2932 adj = self._exp + len(self._int) - 1
2933 if adj >= 1:
2934 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2935 return len(str(adj*23//10)) - 1
2936 if adj <= -2:
2937 # argument <= 0.1
2938 return len(str((-1-adj)*23//10)) - 1
2939 op = _WorkRep(self)
2940 c, e = op.int, op.exp
2941 if adj == 0:
2942 # 1 < self < 10
2943 num = str(c-10**-e)
2944 den = str(c)
2945 return len(num) - len(den) - (num < den)
2946 # adj == -1, 0.1 <= self < 1
2947 return e + len(str(10**-e - c)) - 1
2948
2949
2950 def ln(self, context=None):
2951 """Returns the natural (base e) logarithm of self."""
2952
2953 if context is None:
2954 context = getcontext()
2955
2956 # ln(NaN) = NaN
2957 ans = self._check_nans(context=context)
2958 if ans:
2959 return ans
2960
2961 # ln(0.0) == -Infinity
2962 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002963 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00002964
2965 # ln(Infinity) = Infinity
2966 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002967 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00002968
2969 # ln(1.0) == 0.0
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00002970 if self == _One:
2971 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002972
2973 # ln(negative) raises InvalidOperation
2974 if self._sign == 1:
2975 return context._raise_error(InvalidOperation,
2976 'ln of a negative value')
2977
2978 # result is irrational, so necessarily inexact
2979 op = _WorkRep(self)
2980 c, e = op.int, op.exp
2981 p = context.prec
2982
2983 # correctly rounded result: repeatedly increase precision by 3
2984 # until we get an unambiguously roundable result
2985 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2986 while True:
2987 coeff = _dlog(c, e, places)
2988 # assert len(str(abs(coeff)))-p >= 1
2989 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2990 break
2991 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002992 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002993
2994 context = context._shallow_copy()
2995 rounding = context._set_rounding(ROUND_HALF_EVEN)
2996 ans = ans._fix(context)
2997 context.rounding = rounding
2998 return ans
2999
3000 def _log10_exp_bound(self):
3001 """Compute a lower bound for the adjusted exponent of self.log10().
3002 In other words, find r such that self.log10() >= 10**r.
3003 Assumes that self is finite and positive and that self != 1.
3004 """
3005
3006 # For x >= 10 or x < 0.1 we only need a bound on the integer
3007 # part of log10(self), and this comes directly from the
3008 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3009 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3010 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3011
3012 adj = self._exp + len(self._int) - 1
3013 if adj >= 1:
3014 # self >= 10
3015 return len(str(adj))-1
3016 if adj <= -2:
3017 # self < 0.1
3018 return len(str(-1-adj))-1
3019 op = _WorkRep(self)
3020 c, e = op.int, op.exp
3021 if adj == 0:
3022 # 1 < self < 10
3023 num = str(c-10**-e)
3024 den = str(231*c)
3025 return len(num) - len(den) - (num < den) + 2
3026 # adj == -1, 0.1 <= self < 1
3027 num = str(10**-e-c)
3028 return len(num) + e - (num < "231") - 1
3029
3030 def log10(self, context=None):
3031 """Returns the base 10 logarithm of self."""
3032
3033 if context is None:
3034 context = getcontext()
3035
3036 # log10(NaN) = NaN
3037 ans = self._check_nans(context=context)
3038 if ans:
3039 return ans
3040
3041 # log10(0.0) == -Infinity
3042 if not self:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003043 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003044
3045 # log10(Infinity) = Infinity
3046 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003047 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003048
3049 # log10(negative or -Infinity) raises InvalidOperation
3050 if self._sign == 1:
3051 return context._raise_error(InvalidOperation,
3052 'log10 of a negative value')
3053
3054 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00003055 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00003056 # answer may need rounding
3057 ans = Decimal(self._exp + len(self._int) - 1)
3058 else:
3059 # result is irrational, so necessarily inexact
3060 op = _WorkRep(self)
3061 c, e = op.int, op.exp
3062 p = context.prec
3063
3064 # correctly rounded result: repeatedly increase precision
3065 # until result is unambiguously roundable
3066 places = p-self._log10_exp_bound()+2
3067 while True:
3068 coeff = _dlog10(c, e, places)
3069 # assert len(str(abs(coeff)))-p >= 1
3070 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3071 break
3072 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003073 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003074
3075 context = context._shallow_copy()
3076 rounding = context._set_rounding(ROUND_HALF_EVEN)
3077 ans = ans._fix(context)
3078 context.rounding = rounding
3079 return ans
3080
3081 def logb(self, context=None):
3082 """ Returns the exponent of the magnitude of self's MSD.
3083
3084 The result is the integer which is the exponent of the magnitude
3085 of the most significant digit of self (as though it were truncated
3086 to a single digit while maintaining the value of that digit and
3087 without limiting the resulting exponent).
3088 """
3089 # logb(NaN) = NaN
3090 ans = self._check_nans(context=context)
3091 if ans:
3092 return ans
3093
3094 if context is None:
3095 context = getcontext()
3096
3097 # logb(+/-Inf) = +Inf
3098 if self._isinfinity():
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003099 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003100
3101 # logb(0) = -Inf, DivisionByZero
3102 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003103 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003104
3105 # otherwise, simply return the adjusted exponent of self, as a
3106 # Decimal. Note that no attempt is made to fit the result
3107 # into the current context.
3108 return Decimal(self.adjusted())
3109
3110 def _islogical(self):
3111 """Return True if self is a logical operand.
3112
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00003113 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00003114 an exponent of 0, and a coefficient whose digits must all be
3115 either 0 or 1.
3116 """
3117 if self._sign != 0 or self._exp != 0:
3118 return False
3119 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003120 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003121 return False
3122 return True
3123
3124 def _fill_logical(self, context, opa, opb):
3125 dif = context.prec - len(opa)
3126 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003127 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003128 elif dif < 0:
3129 opa = opa[-context.prec:]
3130 dif = context.prec - len(opb)
3131 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003132 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003133 elif dif < 0:
3134 opb = opb[-context.prec:]
3135 return opa, opb
3136
3137 def logical_and(self, other, context=None):
3138 """Applies an 'and' operation between self and other's digits."""
3139 if context is None:
3140 context = getcontext()
3141 if not self._islogical() or not other._islogical():
3142 return context._raise_error(InvalidOperation)
3143
3144 # fill to context.prec
3145 (opa, opb) = self._fill_logical(context, self._int, other._int)
3146
3147 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003148 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3149 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003150
3151 def logical_invert(self, context=None):
3152 """Invert all its digits."""
3153 if context is None:
3154 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003155 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3156 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003157
3158 def logical_or(self, other, context=None):
3159 """Applies an 'or' operation between self and other's digits."""
3160 if context is None:
3161 context = getcontext()
3162 if not self._islogical() or not other._islogical():
3163 return context._raise_error(InvalidOperation)
3164
3165 # fill to context.prec
3166 (opa, opb) = self._fill_logical(context, self._int, other._int)
3167
3168 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003169 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3170 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003171
3172 def logical_xor(self, other, context=None):
3173 """Applies an 'xor' operation between self and other's digits."""
3174 if context is None:
3175 context = getcontext()
3176 if not self._islogical() or not other._islogical():
3177 return context._raise_error(InvalidOperation)
3178
3179 # fill to context.prec
3180 (opa, opb) = self._fill_logical(context, self._int, other._int)
3181
3182 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003183 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3184 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003185
3186 def max_mag(self, other, context=None):
3187 """Compares the values numerically with their sign ignored."""
3188 other = _convert_other(other, raiseit=True)
3189
Facundo Batista6c398da2007-09-17 17:30:13 +00003190 if context is None:
3191 context = getcontext()
3192
Facundo Batista353750c2007-09-13 18:13:15 +00003193 if self._is_special or other._is_special:
3194 # If one operand is a quiet NaN and the other is number, then the
3195 # number is always returned
3196 sn = self._isnan()
3197 on = other._isnan()
3198 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003199 if on == 1 and sn == 0:
3200 return self._fix(context)
3201 if sn == 1 and on == 0:
3202 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003203 return self._check_nans(other, context)
3204
Mark Dickinson2fc92632008-02-06 22:10:50 +00003205 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003206 if c == 0:
3207 c = self.compare_total(other)
3208
3209 if c == -1:
3210 ans = other
3211 else:
3212 ans = self
3213
Facundo Batistae64acfa2007-12-17 14:18:42 +00003214 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003215
3216 def min_mag(self, other, context=None):
3217 """Compares the values numerically with their sign ignored."""
3218 other = _convert_other(other, raiseit=True)
3219
Facundo Batista6c398da2007-09-17 17:30:13 +00003220 if context is None:
3221 context = getcontext()
3222
Facundo Batista353750c2007-09-13 18:13:15 +00003223 if self._is_special or other._is_special:
3224 # If one operand is a quiet NaN and the other is number, then the
3225 # number is always returned
3226 sn = self._isnan()
3227 on = other._isnan()
3228 if sn or on:
Facundo Batistae29d4352008-12-11 04:19:46 +00003229 if on == 1 and sn == 0:
3230 return self._fix(context)
3231 if sn == 1 and on == 0:
3232 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003233 return self._check_nans(other, context)
3234
Mark Dickinson2fc92632008-02-06 22:10:50 +00003235 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003236 if c == 0:
3237 c = self.compare_total(other)
3238
3239 if c == -1:
3240 ans = self
3241 else:
3242 ans = other
3243
Facundo Batistae64acfa2007-12-17 14:18:42 +00003244 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003245
3246 def next_minus(self, context=None):
3247 """Returns the largest representable number smaller than itself."""
3248 if context is None:
3249 context = getcontext()
3250
3251 ans = self._check_nans(context=context)
3252 if ans:
3253 return ans
3254
3255 if self._isinfinity() == -1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003256 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003257 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003258 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003259
3260 context = context.copy()
3261 context._set_rounding(ROUND_FLOOR)
3262 context._ignore_all_flags()
3263 new_self = self._fix(context)
3264 if new_self != self:
3265 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003266 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3267 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003268
3269 def next_plus(self, context=None):
3270 """Returns the smallest representable number larger than itself."""
3271 if context is None:
3272 context = getcontext()
3273
3274 ans = self._check_nans(context=context)
3275 if ans:
3276 return ans
3277
3278 if self._isinfinity() == 1:
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00003279 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003280 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003281 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003282
3283 context = context.copy()
3284 context._set_rounding(ROUND_CEILING)
3285 context._ignore_all_flags()
3286 new_self = self._fix(context)
3287 if new_self != self:
3288 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003289 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3290 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003291
3292 def next_toward(self, other, context=None):
3293 """Returns the number closest to self, in the direction towards other.
3294
3295 The result is the closest representable number to self
3296 (excluding self) that is in the direction towards other,
3297 unless both have the same value. If the two operands are
3298 numerically equal, then the result is a copy of self with the
3299 sign set to be the same as the sign of other.
3300 """
3301 other = _convert_other(other, raiseit=True)
3302
3303 if context is None:
3304 context = getcontext()
3305
3306 ans = self._check_nans(other, context)
3307 if ans:
3308 return ans
3309
Mark Dickinson2fc92632008-02-06 22:10:50 +00003310 comparison = self._cmp(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003311 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003312 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003313
3314 if comparison == -1:
3315 ans = self.next_plus(context)
3316 else: # comparison == 1
3317 ans = self.next_minus(context)
3318
3319 # decide which flags to raise using value of ans
3320 if ans._isinfinity():
3321 context._raise_error(Overflow,
3322 'Infinite result from next_toward',
3323 ans._sign)
3324 context._raise_error(Rounded)
3325 context._raise_error(Inexact)
3326 elif ans.adjusted() < context.Emin:
3327 context._raise_error(Underflow)
3328 context._raise_error(Subnormal)
3329 context._raise_error(Rounded)
3330 context._raise_error(Inexact)
3331 # if precision == 1 then we don't raise Clamped for a
3332 # result 0E-Etiny.
3333 if not ans:
3334 context._raise_error(Clamped)
3335
3336 return ans
3337
3338 def number_class(self, context=None):
3339 """Returns an indication of the class of self.
3340
3341 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003342 sNaN
3343 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003344 -Infinity
3345 -Normal
3346 -Subnormal
3347 -Zero
3348 +Zero
3349 +Subnormal
3350 +Normal
3351 +Infinity
3352 """
3353 if self.is_snan():
3354 return "sNaN"
3355 if self.is_qnan():
3356 return "NaN"
3357 inf = self._isinfinity()
3358 if inf == 1:
3359 return "+Infinity"
3360 if inf == -1:
3361 return "-Infinity"
3362 if self.is_zero():
3363 if self._sign:
3364 return "-Zero"
3365 else:
3366 return "+Zero"
3367 if context is None:
3368 context = getcontext()
3369 if self.is_subnormal(context=context):
3370 if self._sign:
3371 return "-Subnormal"
3372 else:
3373 return "+Subnormal"
3374 # just a normal, regular, boring number, :)
3375 if self._sign:
3376 return "-Normal"
3377 else:
3378 return "+Normal"
3379
3380 def radix(self):
3381 """Just returns 10, as this is Decimal, :)"""
3382 return Decimal(10)
3383
3384 def rotate(self, other, context=None):
3385 """Returns a rotated copy of self, value-of-other times."""
3386 if context is None:
3387 context = getcontext()
3388
3389 ans = self._check_nans(other, context)
3390 if ans:
3391 return ans
3392
3393 if other._exp != 0:
3394 return context._raise_error(InvalidOperation)
3395 if not (-context.prec <= int(other) <= context.prec):
3396 return context._raise_error(InvalidOperation)
3397
3398 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003399 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003400
3401 # get values, pad if necessary
3402 torot = int(other)
3403 rotdig = self._int
3404 topad = context.prec - len(rotdig)
3405 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003406 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003407
3408 # let's rotate!
3409 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003410 return _dec_from_triple(self._sign,
3411 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003412
3413 def scaleb (self, other, context=None):
3414 """Returns self operand after adding the second value to its exp."""
3415 if context is None:
3416 context = getcontext()
3417
3418 ans = self._check_nans(other, context)
3419 if ans:
3420 return ans
3421
3422 if other._exp != 0:
3423 return context._raise_error(InvalidOperation)
3424 liminf = -2 * (context.Emax + context.prec)
3425 limsup = 2 * (context.Emax + context.prec)
3426 if not (liminf <= int(other) <= limsup):
3427 return context._raise_error(InvalidOperation)
3428
3429 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003430 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003431
Facundo Batista72bc54f2007-11-23 17:59:00 +00003432 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003433 d = d._fix(context)
3434 return d
3435
3436 def shift(self, other, context=None):
3437 """Returns a shifted copy of self, value-of-other times."""
3438 if context is None:
3439 context = getcontext()
3440
3441 ans = self._check_nans(other, context)
3442 if ans:
3443 return ans
3444
3445 if other._exp != 0:
3446 return context._raise_error(InvalidOperation)
3447 if not (-context.prec <= int(other) <= context.prec):
3448 return context._raise_error(InvalidOperation)
3449
3450 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003451 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003452
3453 # get values, pad if necessary
3454 torot = int(other)
3455 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003456 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003457 rotdig = self._int
3458 topad = context.prec - len(rotdig)
3459 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003460 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003461
3462 # let's shift!
3463 if torot < 0:
3464 rotated = rotdig[:torot]
3465 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003466 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003467 rotated = rotated[-context.prec:]
3468
Facundo Batista72bc54f2007-11-23 17:59:00 +00003469 return _dec_from_triple(self._sign,
3470 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003471
Facundo Batista59c58842007-04-10 12:58:45 +00003472 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003473 def __reduce__(self):
3474 return (self.__class__, (str(self),))
3475
3476 def __copy__(self):
3477 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003478 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003479 return self.__class__(str(self))
3480
3481 def __deepcopy__(self, memo):
3482 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003483 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003484 return self.__class__(str(self))
3485
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003486 # PEP 3101 support. See also _parse_format_specifier and _format_align
3487 def __format__(self, specifier, context=None):
Mark Dickinsonf4da7772008-02-29 03:29:17 +00003488 """Format a Decimal instance according to the given specifier.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003489
3490 The specifier should be a standard format specifier, with the
3491 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3492 'F', 'g', 'G', and '%' are supported. If the formatting type
3493 is omitted it defaults to 'g' or 'G', depending on the value
3494 of context.capitals.
3495
3496 At this time the 'n' format specifier type (which is supposed
3497 to use the current locale) is not supported.
3498 """
3499
3500 # Note: PEP 3101 says that if the type is not present then
3501 # there should be at least one digit after the decimal point.
3502 # We take the liberty of ignoring this requirement for
3503 # Decimal---it's presumably there to make sure that
3504 # format(float, '') behaves similarly to str(float).
3505 if context is None:
3506 context = getcontext()
3507
3508 spec = _parse_format_specifier(specifier)
3509
3510 # special values don't care about the type or precision...
3511 if self._is_special:
3512 return _format_align(str(self), spec)
3513
3514 # a type of None defaults to 'g' or 'G', depending on context
3515 # if type is '%', adjust exponent of self accordingly
3516 if spec['type'] is None:
3517 spec['type'] = ['g', 'G'][context.capitals]
3518 elif spec['type'] == '%':
3519 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3520
3521 # round if necessary, taking rounding mode from the context
3522 rounding = context.rounding
3523 precision = spec['precision']
3524 if precision is not None:
3525 if spec['type'] in 'eE':
3526 self = self._round(precision+1, rounding)
3527 elif spec['type'] in 'gG':
3528 if len(self._int) > precision:
3529 self = self._round(precision, rounding)
3530 elif spec['type'] in 'fF%':
3531 self = self._rescale(-precision, rounding)
3532 # special case: zeros with a positive exponent can't be
3533 # represented in fixed point; rescale them to 0e0.
3534 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3535 self = self._rescale(0, rounding)
3536
3537 # figure out placement of the decimal point
3538 leftdigits = self._exp + len(self._int)
3539 if spec['type'] in 'fF%':
3540 dotplace = leftdigits
3541 elif spec['type'] in 'eE':
3542 if not self and precision is not None:
3543 dotplace = 1 - precision
3544 else:
3545 dotplace = 1
3546 elif spec['type'] in 'gG':
3547 if self._exp <= 0 and leftdigits > -6:
3548 dotplace = leftdigits
3549 else:
3550 dotplace = 1
3551
3552 # figure out main part of numeric string...
3553 if dotplace <= 0:
3554 num = '0.' + '0'*(-dotplace) + self._int
3555 elif dotplace >= len(self._int):
3556 # make sure we're not padding a '0' with extra zeros on the right
3557 assert dotplace==len(self._int) or self._int != '0'
3558 num = self._int + '0'*(dotplace-len(self._int))
3559 else:
3560 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3561
3562 # ...then the trailing exponent, or trailing '%'
3563 if leftdigits != dotplace or spec['type'] in 'eE':
3564 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3565 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3566 elif spec['type'] == '%':
3567 num = num + '%'
3568
3569 # add sign
3570 if self._sign == 1:
3571 num = '-' + num
3572 return _format_align(num, spec)
3573
3574
Facundo Batista72bc54f2007-11-23 17:59:00 +00003575def _dec_from_triple(sign, coefficient, exponent, special=False):
3576 """Create a decimal instance directly, without any validation,
3577 normalization (e.g. removal of leading zeros) or argument
3578 conversion.
3579
3580 This function is for *internal use only*.
3581 """
3582
3583 self = object.__new__(Decimal)
3584 self._sign = sign
3585 self._int = coefficient
3586 self._exp = exponent
3587 self._is_special = special
3588
3589 return self
3590
Facundo Batista59c58842007-04-10 12:58:45 +00003591##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003592
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003593
3594# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003595rounding_functions = [name for name in Decimal.__dict__.keys()
3596 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003597for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003598 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003599 globalname = name[1:].upper()
3600 val = globals()[globalname]
3601 Decimal._pick_rounding_function[val] = name
3602
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003603del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003604
Nick Coghlanced12182006-09-02 03:54:17 +00003605class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003606 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003607
Nick Coghlanced12182006-09-02 03:54:17 +00003608 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003609 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003610 """
3611 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003612 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003613 def __enter__(self):
3614 self.saved_context = getcontext()
3615 setcontext(self.new_context)
3616 return self.new_context
3617 def __exit__(self, t, v, tb):
3618 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003619
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003620class Context(object):
3621 """Contains the context for a Decimal instance.
3622
3623 Contains:
3624 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003625 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003626 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003627 raised when it is caused. Otherwise, a value is
3628 substituted in.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003629 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003630 (Whether or not the trap_enabler is set)
3631 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003632 Emin - Minimum exponent
3633 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003634 capitals - If 1, 1*10^1 is printed as 1E+1.
3635 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003636 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003637 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003638
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003639 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003640 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003641 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003642 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003643 _ignored_flags=None):
3644 if flags is None:
3645 flags = []
3646 if _ignored_flags is None:
3647 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003648 if not isinstance(flags, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003649 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003650 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003651 if traps is not None and not isinstance(traps, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003652 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003653 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003654 for name, val in locals().items():
3655 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003656 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003657 else:
3658 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003659 del self.self
3660
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003661 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003662 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003663 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003664 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3665 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3666 % vars(self))
3667 names = [f.__name__ for f, v in self.flags.items() if v]
3668 s.append('flags=[' + ', '.join(names) + ']')
3669 names = [t.__name__ for t, v in self.traps.items() if v]
3670 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003671 return ', '.join(s) + ')'
3672
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003673 def clear_flags(self):
3674 """Reset all flags to zero"""
3675 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003676 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003677
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003678 def _shallow_copy(self):
3679 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003680 nc = Context(self.prec, self.rounding, self.traps,
3681 self.flags, self.Emin, self.Emax,
3682 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003683 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003684
3685 def copy(self):
3686 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003687 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003688 self.flags.copy(), self.Emin, self.Emax,
3689 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003690 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003691 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003692
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003693 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003694 """Handles an error
3695
3696 If the flag is in _ignored_flags, returns the default response.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003697 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003698 trap_enabler is set, it reaises the exception. Otherwise, it returns
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003699 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003700 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003701 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003702 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003703 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003704 return error().handle(self, *args)
3705
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003706 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003707 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003708 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003709 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003710
3711 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003712 # self._ignored_flags = []
Mark Dickinson8aca9d02008-05-04 02:05:06 +00003713 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003714
3715 def _ignore_all_flags(self):
3716 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003717 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003718
3719 def _ignore_flags(self, *flags):
3720 """Ignore the flags, if they are raised"""
3721 # Do not mutate-- This way, copies of a context leave the original
3722 # alone.
3723 self._ignored_flags = (self._ignored_flags + list(flags))
3724 return list(flags)
3725
3726 def _regard_flags(self, *flags):
3727 """Stop ignoring the flags, if they are raised"""
3728 if flags and isinstance(flags[0], (tuple,list)):
3729 flags = flags[0]
3730 for flag in flags:
3731 self._ignored_flags.remove(flag)
3732
Nick Coghlan53663a62008-07-15 14:27:37 +00003733 # We inherit object.__hash__, so we must deny this explicitly
3734 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003735
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003736 def Etiny(self):
3737 """Returns Etiny (= Emin - prec + 1)"""
3738 return int(self.Emin - self.prec + 1)
3739
3740 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003741 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003742 return int(self.Emax - self.prec + 1)
3743
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003744 def _set_rounding(self, type):
3745 """Sets the rounding type.
3746
3747 Sets the rounding type, and returns the current (previous)
3748 rounding type. Often used like:
3749
3750 context = context.copy()
3751 # so you don't change the calling context
3752 # if an error occurs in the middle.
3753 rounding = context._set_rounding(ROUND_UP)
3754 val = self.__sub__(other, context=context)
3755 context._set_rounding(rounding)
3756
3757 This will make it round up for that operation.
3758 """
3759 rounding = self.rounding
3760 self.rounding= type
3761 return rounding
3762
Raymond Hettingerfed52962004-07-14 15:41:57 +00003763 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003764 """Creates a new Decimal instance but using self as context.
3765
3766 This method implements the to-number operation of the
3767 IBM Decimal specification."""
3768
3769 if isinstance(num, basestring) and num != num.strip():
3770 return self._raise_error(ConversionSyntax,
3771 "no trailing or leading whitespace is "
3772 "permitted.")
3773
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003774 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003775 if d._isnan() and len(d._int) > self.prec - self._clamp:
3776 return self._raise_error(ConversionSyntax,
3777 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003778 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003779
Raymond Hettingerf4d85972009-01-03 19:02:23 +00003780 def create_decimal_from_float(self, f):
3781 """Creates a new Decimal instance from a float but rounding using self
3782 as the context.
3783
3784 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3785 >>> context.create_decimal_from_float(3.1415926535897932)
3786 Decimal('3.1415')
3787 >>> context = Context(prec=5, traps=[Inexact])
3788 >>> context.create_decimal_from_float(3.1415926535897932)
3789 Traceback (most recent call last):
3790 ...
3791 Inexact: None
3792
3793 """
3794 d = Decimal.from_float(f) # An exact conversion
3795 return d._fix(self) # Apply the context rounding
3796
Facundo Batista59c58842007-04-10 12:58:45 +00003797 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003798 def abs(self, a):
3799 """Returns the absolute value of the operand.
3800
3801 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003802 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003803 the plus operation on the operand.
3804
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003805 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003806 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003807 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003808 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003809 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003810 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003811 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003812 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003813 """
3814 return a.__abs__(context=self)
3815
3816 def add(self, a, b):
3817 """Return the sum of the two operands.
3818
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003819 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003820 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003821 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003822 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003823 """
3824 return a.__add__(b, context=self)
3825
3826 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003827 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003828
Facundo Batista353750c2007-09-13 18:13:15 +00003829 def canonical(self, a):
3830 """Returns the same Decimal object.
3831
3832 As we do not have different encodings for the same number, the
3833 received object already is in its canonical form.
3834
3835 >>> ExtendedContext.canonical(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003836 Decimal('2.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003837 """
3838 return a.canonical(context=self)
3839
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003840 def compare(self, a, b):
3841 """Compares values numerically.
3842
3843 If the signs of the operands differ, a value representing each operand
3844 ('-1' if the operand is less than zero, '0' if the operand is zero or
3845 negative zero, or '1' if the operand is greater than zero) is used in
3846 place of that operand for the comparison instead of the actual
3847 operand.
3848
3849 The comparison is then effected by subtracting the second operand from
3850 the first and then returning a value according to the result of the
3851 subtraction: '-1' if the result is less than zero, '0' if the result is
3852 zero or negative zero, or '1' if the result is greater than zero.
3853
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003854 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003855 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003856 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003857 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003858 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003859 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003860 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003861 Decimal('1')
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('-3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003865 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003866 """
3867 return a.compare(b, context=self)
3868
Facundo Batista353750c2007-09-13 18:13:15 +00003869 def compare_signal(self, a, b):
3870 """Compares the values of the two operands numerically.
3871
3872 It's pretty much like compare(), but all NaNs signal, with signaling
3873 NaNs taking precedence over quiet NaNs.
3874
3875 >>> c = ExtendedContext
3876 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003877 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003878 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003879 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003880 >>> c.flags[InvalidOperation] = 0
3881 >>> print c.flags[InvalidOperation]
3882 0
3883 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003884 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003885 >>> print c.flags[InvalidOperation]
3886 1
3887 >>> c.flags[InvalidOperation] = 0
3888 >>> print c.flags[InvalidOperation]
3889 0
3890 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003891 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003892 >>> print c.flags[InvalidOperation]
3893 1
3894 """
3895 return a.compare_signal(b, context=self)
3896
3897 def compare_total(self, a, b):
3898 """Compares two operands using their abstract representation.
3899
3900 This is not like the standard compare, which use their numerical
3901 value. Note that a total ordering is defined for all possible abstract
3902 representations.
3903
3904 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003905 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003906 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003907 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003908 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003909 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003910 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003911 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003912 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003913 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00003914 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003915 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003916 """
3917 return a.compare_total(b)
3918
3919 def compare_total_mag(self, a, b):
3920 """Compares two operands using their abstract representation ignoring sign.
3921
3922 Like compare_total, but with operand's sign ignored and assumed to be 0.
3923 """
3924 return a.compare_total_mag(b)
3925
3926 def copy_abs(self, a):
3927 """Returns a copy of the operand with the sign set to 0.
3928
3929 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003930 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003931 >>> ExtendedContext.copy_abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003932 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00003933 """
3934 return a.copy_abs()
3935
3936 def copy_decimal(self, a):
3937 """Returns a copy of the decimal objet.
3938
3939 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003940 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003941 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003942 Decimal('-1.00')
Facundo Batista353750c2007-09-13 18:13:15 +00003943 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003944 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003945
3946 def copy_negate(self, a):
3947 """Returns a copy of the operand with the sign inverted.
3948
3949 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003950 Decimal('-101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003951 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003952 Decimal('101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003953 """
3954 return a.copy_negate()
3955
3956 def copy_sign(self, a, b):
3957 """Copies the second operand's sign to the first one.
3958
3959 In detail, it returns a copy of the first operand with the sign
3960 equal to the sign of the second operand.
3961
3962 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003963 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003964 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003965 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003966 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003967 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003968 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003969 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003970 """
3971 return a.copy_sign(b)
3972
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003973 def divide(self, a, b):
3974 """Decimal division in a specified context.
3975
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003976 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003977 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003978 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003979 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003980 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003981 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003982 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003983 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003984 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003985 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003986 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003987 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003988 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003989 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003990 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003991 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003992 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003993 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003994 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003995 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003996 """
3997 return a.__div__(b, context=self)
3998
3999 def divide_int(self, a, b):
4000 """Divides two numbers and returns the integer part of the result.
4001
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004002 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004003 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004004 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004005 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004006 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004007 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004008 """
4009 return a.__floordiv__(b, context=self)
4010
4011 def divmod(self, a, b):
4012 return a.__divmod__(b, context=self)
4013
Facundo Batista353750c2007-09-13 18:13:15 +00004014 def exp(self, a):
4015 """Returns e ** a.
4016
4017 >>> c = ExtendedContext.copy()
4018 >>> c.Emin = -999
4019 >>> c.Emax = 999
4020 >>> c.exp(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004021 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004022 >>> c.exp(Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004023 Decimal('0.367879441')
Facundo Batista353750c2007-09-13 18:13:15 +00004024 >>> c.exp(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004025 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004026 >>> c.exp(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004027 Decimal('2.71828183')
Facundo Batista353750c2007-09-13 18:13:15 +00004028 >>> c.exp(Decimal('0.693147181'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004029 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004030 >>> c.exp(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004031 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004032 """
4033 return a.exp(context=self)
4034
4035 def fma(self, a, b, c):
4036 """Returns a multiplied by b, plus c.
4037
4038 The first two operands are multiplied together, using multiply,
4039 the third operand is then added to the result of that
4040 multiplication, using add, all with only one final rounding.
4041
4042 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004043 Decimal('22')
Facundo Batista353750c2007-09-13 18:13:15 +00004044 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004045 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004046 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004047 Decimal('1.38435736E+12')
Facundo Batista353750c2007-09-13 18:13:15 +00004048 """
4049 return a.fma(b, c, context=self)
4050
4051 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004052 """Return True if the operand is canonical; otherwise return False.
4053
4054 Currently, the encoding of a Decimal instance is always
4055 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00004056
4057 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004058 True
Facundo Batista353750c2007-09-13 18:13:15 +00004059 """
Facundo Batista1a191df2007-10-02 17:01:24 +00004060 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00004061
4062 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004063 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004064
Facundo Batista1a191df2007-10-02 17:01:24 +00004065 A Decimal instance is considered finite if it is neither
4066 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00004067
4068 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004069 True
Facundo Batista353750c2007-09-13 18:13:15 +00004070 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004071 True
Facundo Batista353750c2007-09-13 18:13:15 +00004072 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004073 True
Facundo Batista353750c2007-09-13 18:13:15 +00004074 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004075 False
Facundo Batista353750c2007-09-13 18:13:15 +00004076 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004077 False
Facundo Batista353750c2007-09-13 18:13:15 +00004078 """
4079 return a.is_finite()
4080
4081 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004082 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004083
4084 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004085 False
Facundo Batista353750c2007-09-13 18:13:15 +00004086 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004087 True
Facundo Batista353750c2007-09-13 18:13:15 +00004088 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004089 False
Facundo Batista353750c2007-09-13 18:13:15 +00004090 """
4091 return a.is_infinite()
4092
4093 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004094 """Return True if the operand is a qNaN or sNaN;
4095 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004096
4097 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004098 False
Facundo Batista353750c2007-09-13 18:13:15 +00004099 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004100 True
Facundo Batista353750c2007-09-13 18:13:15 +00004101 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004102 True
Facundo Batista353750c2007-09-13 18:13:15 +00004103 """
4104 return a.is_nan()
4105
4106 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004107 """Return True if the operand is a normal number;
4108 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004109
4110 >>> c = ExtendedContext.copy()
4111 >>> c.Emin = -999
4112 >>> c.Emax = 999
4113 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004114 True
Facundo Batista353750c2007-09-13 18:13:15 +00004115 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004116 False
Facundo Batista353750c2007-09-13 18:13:15 +00004117 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004118 False
Facundo Batista353750c2007-09-13 18:13:15 +00004119 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004120 False
Facundo Batista353750c2007-09-13 18:13:15 +00004121 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004122 False
Facundo Batista353750c2007-09-13 18:13:15 +00004123 """
4124 return a.is_normal(context=self)
4125
4126 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004127 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004128
4129 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004130 False
Facundo Batista353750c2007-09-13 18:13:15 +00004131 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004132 True
Facundo Batista353750c2007-09-13 18:13:15 +00004133 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004134 False
Facundo Batista353750c2007-09-13 18:13:15 +00004135 """
4136 return a.is_qnan()
4137
4138 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004139 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004140
4141 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004142 False
Facundo Batista353750c2007-09-13 18:13:15 +00004143 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004144 True
Facundo Batista353750c2007-09-13 18:13:15 +00004145 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004146 True
Facundo Batista353750c2007-09-13 18:13:15 +00004147 """
4148 return a.is_signed()
4149
4150 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004151 """Return True if the operand is a signaling NaN;
4152 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004153
4154 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004155 False
Facundo Batista353750c2007-09-13 18:13:15 +00004156 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004157 False
Facundo Batista353750c2007-09-13 18:13:15 +00004158 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004159 True
Facundo Batista353750c2007-09-13 18:13:15 +00004160 """
4161 return a.is_snan()
4162
4163 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004164 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004165
4166 >>> c = ExtendedContext.copy()
4167 >>> c.Emin = -999
4168 >>> c.Emax = 999
4169 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004170 False
Facundo Batista353750c2007-09-13 18:13:15 +00004171 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004172 True
Facundo Batista353750c2007-09-13 18:13:15 +00004173 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004174 False
Facundo Batista353750c2007-09-13 18:13:15 +00004175 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004176 False
Facundo Batista353750c2007-09-13 18:13:15 +00004177 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004178 False
Facundo Batista353750c2007-09-13 18:13:15 +00004179 """
4180 return a.is_subnormal(context=self)
4181
4182 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004183 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004184
4185 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004186 True
Facundo Batista353750c2007-09-13 18:13:15 +00004187 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004188 False
Facundo Batista353750c2007-09-13 18:13:15 +00004189 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004190 True
Facundo Batista353750c2007-09-13 18:13:15 +00004191 """
4192 return a.is_zero()
4193
4194 def ln(self, a):
4195 """Returns the natural (base e) logarithm of the operand.
4196
4197 >>> c = ExtendedContext.copy()
4198 >>> c.Emin = -999
4199 >>> c.Emax = 999
4200 >>> c.ln(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004201 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004202 >>> c.ln(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004203 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004204 >>> c.ln(Decimal('2.71828183'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004205 Decimal('1.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004206 >>> c.ln(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004207 Decimal('2.30258509')
Facundo Batista353750c2007-09-13 18:13:15 +00004208 >>> c.ln(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004209 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004210 """
4211 return a.ln(context=self)
4212
4213 def log10(self, a):
4214 """Returns the base 10 logarithm of the operand.
4215
4216 >>> c = ExtendedContext.copy()
4217 >>> c.Emin = -999
4218 >>> c.Emax = 999
4219 >>> c.log10(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004220 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004221 >>> c.log10(Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004222 Decimal('-3')
Facundo Batista353750c2007-09-13 18:13:15 +00004223 >>> c.log10(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004224 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004225 >>> c.log10(Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004226 Decimal('0.301029996')
Facundo Batista353750c2007-09-13 18:13:15 +00004227 >>> c.log10(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004228 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004229 >>> c.log10(Decimal('70'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004230 Decimal('1.84509804')
Facundo Batista353750c2007-09-13 18:13:15 +00004231 >>> c.log10(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004232 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004233 """
4234 return a.log10(context=self)
4235
4236 def logb(self, a):
4237 """ Returns the exponent of the magnitude of the operand's MSD.
4238
4239 The result is the integer which is the exponent of the magnitude
4240 of the most significant digit of the operand (as though the
4241 operand were truncated to a single digit while maintaining the
4242 value of that digit and without limiting the resulting exponent).
4243
4244 >>> ExtendedContext.logb(Decimal('250'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004245 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004246 >>> ExtendedContext.logb(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004247 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004248 >>> ExtendedContext.logb(Decimal('0.03'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004249 Decimal('-2')
Facundo Batista353750c2007-09-13 18:13:15 +00004250 >>> ExtendedContext.logb(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004251 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004252 """
4253 return a.logb(context=self)
4254
4255 def logical_and(self, a, b):
4256 """Applies the logical operation 'and' between each operand's digits.
4257
4258 The operands must be both logical numbers.
4259
4260 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004261 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004262 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004263 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004264 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004265 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004266 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004267 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004268 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004269 Decimal('1000')
Facundo Batista353750c2007-09-13 18:13:15 +00004270 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004271 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004272 """
4273 return a.logical_and(b, context=self)
4274
4275 def logical_invert(self, a):
4276 """Invert all the digits in the operand.
4277
4278 The operand must be a logical number.
4279
4280 >>> ExtendedContext.logical_invert(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004281 Decimal('111111111')
Facundo Batista353750c2007-09-13 18:13:15 +00004282 >>> ExtendedContext.logical_invert(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004283 Decimal('111111110')
Facundo Batista353750c2007-09-13 18:13:15 +00004284 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004285 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004286 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004287 Decimal('10101010')
Facundo Batista353750c2007-09-13 18:13:15 +00004288 """
4289 return a.logical_invert(context=self)
4290
4291 def logical_or(self, a, b):
4292 """Applies the logical operation 'or' between each operand's digits.
4293
4294 The operands must be both logical numbers.
4295
4296 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004297 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004298 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004299 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004300 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004301 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004302 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004303 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004304 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004305 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004306 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004307 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004308 """
4309 return a.logical_or(b, context=self)
4310
4311 def logical_xor(self, a, b):
4312 """Applies the logical operation 'xor' between each operand's digits.
4313
4314 The operands must be both logical numbers.
4315
4316 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004317 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004318 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004319 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004320 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004321 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004322 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004323 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004324 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004325 Decimal('110')
Facundo Batista353750c2007-09-13 18:13:15 +00004326 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004327 Decimal('1101')
Facundo Batista353750c2007-09-13 18:13:15 +00004328 """
4329 return a.logical_xor(b, context=self)
4330
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004331 def max(self, a,b):
4332 """max compares two values numerically and returns the maximum.
4333
4334 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004335 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004336 operation. If they are numerically equal then the left-hand operand
4337 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004338 infinity) of the two operands is chosen as the result.
4339
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004340 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004341 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004342 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004343 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004344 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004345 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004346 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004347 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004348 """
4349 return a.max(b, context=self)
4350
Facundo Batista353750c2007-09-13 18:13:15 +00004351 def max_mag(self, a, b):
4352 """Compares the values numerically with their sign ignored."""
4353 return a.max_mag(b, context=self)
4354
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004355 def min(self, a,b):
4356 """min compares two values numerically and returns the minimum.
4357
4358 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004359 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004360 operation. If they are numerically equal then the left-hand operand
4361 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004362 infinity) of the two operands is chosen as the result.
4363
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004364 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004365 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004366 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004367 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004368 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004369 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004370 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004371 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004372 """
4373 return a.min(b, context=self)
4374
Facundo Batista353750c2007-09-13 18:13:15 +00004375 def min_mag(self, a, b):
4376 """Compares the values numerically with their sign ignored."""
4377 return a.min_mag(b, context=self)
4378
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004379 def minus(self, a):
4380 """Minus corresponds to unary prefix minus in Python.
4381
4382 The operation is evaluated using the same rules as subtract; the
4383 operation minus(a) is calculated as subtract('0', a) where the '0'
4384 has the same exponent as the operand.
4385
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004386 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004387 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004388 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004389 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004390 """
4391 return a.__neg__(context=self)
4392
4393 def multiply(self, a, b):
4394 """multiply multiplies two operands.
4395
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004396 If either operand is a special value then the general rules apply.
4397 Otherwise, the operands are multiplied together ('long multiplication'),
4398 resulting in a number which may be as long as the sum of the lengths
4399 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004400
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004401 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004402 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004403 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004404 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004405 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004406 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004407 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004408 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004409 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004410 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004411 """
4412 return a.__mul__(b, context=self)
4413
Facundo Batista353750c2007-09-13 18:13:15 +00004414 def next_minus(self, a):
4415 """Returns the largest representable number smaller than a.
4416
4417 >>> c = ExtendedContext.copy()
4418 >>> c.Emin = -999
4419 >>> c.Emax = 999
4420 >>> ExtendedContext.next_minus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004421 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004422 >>> c.next_minus(Decimal('1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004423 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004424 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004425 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004426 >>> c.next_minus(Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004427 Decimal('9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004428 """
4429 return a.next_minus(context=self)
4430
4431 def next_plus(self, a):
4432 """Returns the smallest representable number larger than a.
4433
4434 >>> c = ExtendedContext.copy()
4435 >>> c.Emin = -999
4436 >>> c.Emax = 999
4437 >>> ExtendedContext.next_plus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004438 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004439 >>> c.next_plus(Decimal('-1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004440 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004441 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004442 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004443 >>> c.next_plus(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004444 Decimal('-9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004445 """
4446 return a.next_plus(context=self)
4447
4448 def next_toward(self, a, b):
4449 """Returns the number closest to a, in direction towards b.
4450
4451 The result is the closest representable number from the first
4452 operand (but not the first operand) that is in the direction
4453 towards the second operand, unless the operands have the same
4454 value.
4455
4456 >>> c = ExtendedContext.copy()
4457 >>> c.Emin = -999
4458 >>> c.Emax = 999
4459 >>> c.next_toward(Decimal('1'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004460 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004461 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004462 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004463 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004464 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004465 >>> c.next_toward(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004466 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004467 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004468 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004469 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004470 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004471 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004472 Decimal('-0.00')
Facundo Batista353750c2007-09-13 18:13:15 +00004473 """
4474 return a.next_toward(b, context=self)
4475
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004476 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004477 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004478
4479 Essentially a plus operation with all trailing zeros removed from the
4480 result.
4481
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004482 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004483 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004484 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004485 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004486 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004487 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004488 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004489 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004490 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004491 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004492 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004493 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 """
4495 return a.normalize(context=self)
4496
Facundo Batista353750c2007-09-13 18:13:15 +00004497 def number_class(self, a):
4498 """Returns an indication of the class of the operand.
4499
4500 The class is one of the following strings:
4501 -sNaN
4502 -NaN
4503 -Infinity
4504 -Normal
4505 -Subnormal
4506 -Zero
4507 +Zero
4508 +Subnormal
4509 +Normal
4510 +Infinity
4511
4512 >>> c = Context(ExtendedContext)
4513 >>> c.Emin = -999
4514 >>> c.Emax = 999
4515 >>> c.number_class(Decimal('Infinity'))
4516 '+Infinity'
4517 >>> c.number_class(Decimal('1E-10'))
4518 '+Normal'
4519 >>> c.number_class(Decimal('2.50'))
4520 '+Normal'
4521 >>> c.number_class(Decimal('0.1E-999'))
4522 '+Subnormal'
4523 >>> c.number_class(Decimal('0'))
4524 '+Zero'
4525 >>> c.number_class(Decimal('-0'))
4526 '-Zero'
4527 >>> c.number_class(Decimal('-0.1E-999'))
4528 '-Subnormal'
4529 >>> c.number_class(Decimal('-1E-10'))
4530 '-Normal'
4531 >>> c.number_class(Decimal('-2.50'))
4532 '-Normal'
4533 >>> c.number_class(Decimal('-Infinity'))
4534 '-Infinity'
4535 >>> c.number_class(Decimal('NaN'))
4536 'NaN'
4537 >>> c.number_class(Decimal('-NaN'))
4538 'NaN'
4539 >>> c.number_class(Decimal('sNaN'))
4540 'sNaN'
4541 """
4542 return a.number_class(context=self)
4543
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004544 def plus(self, a):
4545 """Plus corresponds to unary prefix plus in Python.
4546
4547 The operation is evaluated using the same rules as add; the
4548 operation plus(a) is calculated as add('0', a) where the '0'
4549 has the same exponent as the operand.
4550
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004551 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004552 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004553 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004554 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004555 """
4556 return a.__pos__(context=self)
4557
4558 def power(self, a, b, modulo=None):
4559 """Raises a to the power of b, to modulo if given.
4560
Facundo Batista353750c2007-09-13 18:13:15 +00004561 With two arguments, compute a**b. If a is negative then b
4562 must be integral. The result will be inexact unless b is
4563 integral and the result is finite and can be expressed exactly
4564 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004565
Facundo Batista353750c2007-09-13 18:13:15 +00004566 With three arguments, compute (a**b) % modulo. For the
4567 three argument form, the following restrictions on the
4568 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004569
Facundo Batista353750c2007-09-13 18:13:15 +00004570 - all three arguments must be integral
4571 - b must be nonnegative
4572 - at least one of a or b must be nonzero
4573 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004574
Facundo Batista353750c2007-09-13 18:13:15 +00004575 The result of pow(a, b, modulo) is identical to the result
4576 that would be obtained by computing (a**b) % modulo with
4577 unbounded precision, but is computed more efficiently. It is
4578 always exact.
4579
4580 >>> c = ExtendedContext.copy()
4581 >>> c.Emin = -999
4582 >>> c.Emax = 999
4583 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004584 Decimal('8')
Facundo Batista353750c2007-09-13 18:13:15 +00004585 >>> c.power(Decimal('-2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004586 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004587 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004588 Decimal('0.125')
Facundo Batista353750c2007-09-13 18:13:15 +00004589 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004590 Decimal('69.7575744')
Facundo Batista353750c2007-09-13 18:13:15 +00004591 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004592 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004593 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004594 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004595 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004596 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004597 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004598 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004599 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004600 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004601 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004602 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004603 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004604 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004605 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004606 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004607 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004608 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00004609
4610 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004611 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004612 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004613 Decimal('-11')
Facundo Batista353750c2007-09-13 18:13:15 +00004614 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004615 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004616 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004617 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004618 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004619 Decimal('11729830')
Facundo Batista353750c2007-09-13 18:13:15 +00004620 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004621 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004622 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004623 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004624 """
4625 return a.__pow__(b, modulo, context=self)
4626
4627 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004628 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004629
4630 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004631 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004632 exponent is being increased), multiplied by a positive power of ten (if
4633 the exponent is being decreased), or is unchanged (if the exponent is
4634 already equal to that of the right-hand operand).
4635
4636 Unlike other operations, if the length of the coefficient after the
4637 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004638 operation condition is raised. This guarantees that, unless there is
4639 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004640 equal to that of the right-hand operand.
4641
4642 Also unlike other operations, quantize will never raise Underflow, even
4643 if the result is subnormal and inexact.
4644
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004645 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004646 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004647 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004648 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004649 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004650 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004651 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004652 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004653 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004654 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004655 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004656 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004657 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004658 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004659 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004660 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004661 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004662 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004663 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004664 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004665 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004666 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004667 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004668 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004669 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004670 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004671 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004672 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004673 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004674 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004675 """
4676 return a.quantize(b, context=self)
4677
Facundo Batista353750c2007-09-13 18:13:15 +00004678 def radix(self):
4679 """Just returns 10, as this is Decimal, :)
4680
4681 >>> ExtendedContext.radix()
Raymond Hettingerabe32372008-02-14 02:41:22 +00004682 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004683 """
4684 return Decimal(10)
4685
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004686 def remainder(self, a, b):
4687 """Returns the remainder from integer division.
4688
4689 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004690 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004691 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004692 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004693
4694 This operation will fail under the same conditions as integer division
4695 (that is, if integer division on the same two operands would fail, the
4696 remainder cannot be calculated).
4697
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004698 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004699 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004700 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004701 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004702 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004703 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004704 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004705 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004706 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004707 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004708 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004709 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004710 """
4711 return a.__mod__(b, context=self)
4712
4713 def remainder_near(self, a, b):
4714 """Returns to be "a - b * n", where n is the integer nearest the exact
4715 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004716 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004717 sign of a.
4718
4719 This operation will fail under the same conditions as integer division
4720 (that is, if integer division on the same two operands would fail, the
4721 remainder cannot be calculated).
4722
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004723 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004724 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004725 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004726 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004727 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004728 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004729 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004730 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004731 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004732 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004733 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004734 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004735 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004736 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004737 """
4738 return a.remainder_near(b, context=self)
4739
Facundo Batista353750c2007-09-13 18:13:15 +00004740 def rotate(self, a, b):
4741 """Returns a rotated copy of a, b times.
4742
4743 The coefficient of the result is a rotated copy of the digits in
4744 the coefficient of the first operand. The number of places of
4745 rotation is taken from the absolute value of the second operand,
4746 with the rotation being to the left if the second operand is
4747 positive or to the right otherwise.
4748
4749 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004750 Decimal('400000003')
Facundo Batista353750c2007-09-13 18:13:15 +00004751 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004752 Decimal('12')
Facundo Batista353750c2007-09-13 18:13:15 +00004753 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004754 Decimal('891234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004755 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004756 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004757 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004758 Decimal('345678912')
Facundo Batista353750c2007-09-13 18:13:15 +00004759 """
4760 return a.rotate(b, context=self)
4761
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004762 def same_quantum(self, a, b):
4763 """Returns True if the two operands have the same exponent.
4764
4765 The result is never affected by either the sign or the coefficient of
4766 either operand.
4767
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004768 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004769 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004770 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004771 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004772 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004773 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004774 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004775 True
4776 """
4777 return a.same_quantum(b)
4778
Facundo Batista353750c2007-09-13 18:13:15 +00004779 def scaleb (self, a, b):
4780 """Returns the first operand after adding the second value its exp.
4781
4782 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004783 Decimal('0.0750')
Facundo Batista353750c2007-09-13 18:13:15 +00004784 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004785 Decimal('7.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004786 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004787 Decimal('7.50E+3')
Facundo Batista353750c2007-09-13 18:13:15 +00004788 """
4789 return a.scaleb (b, context=self)
4790
4791 def shift(self, a, b):
4792 """Returns a shifted copy of a, b times.
4793
4794 The coefficient of the result is a shifted copy of the digits
4795 in the coefficient of the first operand. The number of places
4796 to shift is taken from the absolute value of the second operand,
4797 with the shift being to the left if the second operand is
4798 positive or to the right otherwise. Digits shifted into the
4799 coefficient are zeros.
4800
4801 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004802 Decimal('400000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004803 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004804 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004805 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004806 Decimal('1234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004807 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004808 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004809 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004810 Decimal('345678900')
Facundo Batista353750c2007-09-13 18:13:15 +00004811 """
4812 return a.shift(b, context=self)
4813
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004814 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004815 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004816
4817 If the result must be inexact, it is rounded using the round-half-even
4818 algorithm.
4819
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004820 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004821 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004822 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004823 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004824 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004825 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004826 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004827 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004828 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004829 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004830 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004831 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004832 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004833 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004834 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004835 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004836 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004837 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004838 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004839 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004840 """
4841 return a.sqrt(context=self)
4842
4843 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004844 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004845
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004846 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004847 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004848 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004849 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004850 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004851 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004852 """
4853 return a.__sub__(b, context=self)
4854
4855 def to_eng_string(self, a):
4856 """Converts a number to a string, using scientific notation.
4857
4858 The operation is not affected by the context.
4859 """
4860 return a.to_eng_string(context=self)
4861
4862 def to_sci_string(self, a):
4863 """Converts a number to a string, using scientific notation.
4864
4865 The operation is not affected by the context.
4866 """
4867 return a.__str__(context=self)
4868
Facundo Batista353750c2007-09-13 18:13:15 +00004869 def to_integral_exact(self, a):
4870 """Rounds to an integer.
4871
4872 When the operand has a negative exponent, the result is the same
4873 as using the quantize() operation using the given operand as the
4874 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4875 of the operand as the precision setting; Inexact and Rounded flags
4876 are allowed in this operation. The rounding mode is taken from the
4877 context.
4878
4879 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004880 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004881 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004882 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004883 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004884 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004885 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004886 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004887 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004888 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004889 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004890 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004891 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004892 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004893 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004894 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004895 """
4896 return a.to_integral_exact(context=self)
4897
4898 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004899 """Rounds to an integer.
4900
4901 When the operand has a negative exponent, the result is the same
4902 as using the quantize() operation using the given operand as the
4903 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4904 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004905 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004906
Facundo Batista353750c2007-09-13 18:13:15 +00004907 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004908 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004909 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004910 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004911 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004912 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004913 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004914 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004915 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004916 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004917 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004918 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004919 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004920 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004921 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004922 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004923 """
Facundo Batista353750c2007-09-13 18:13:15 +00004924 return a.to_integral_value(context=self)
4925
4926 # the method name changed, but we provide also the old one, for compatibility
4927 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004928
4929class _WorkRep(object):
4930 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004931 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004932 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004933 # exp: None, int, or string
4934
4935 def __init__(self, value=None):
4936 if value is None:
4937 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004938 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004939 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004940 elif isinstance(value, Decimal):
4941 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004942 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004943 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004944 else:
4945 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004946 self.sign = value[0]
4947 self.int = value[1]
4948 self.exp = value[2]
4949
4950 def __repr__(self):
4951 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4952
4953 __str__ = __repr__
4954
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004955
4956
Facundo Batistae64acfa2007-12-17 14:18:42 +00004957def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004958 """Normalizes op1, op2 to have the same exp and length of coefficient.
4959
4960 Done during addition.
4961 """
Facundo Batista353750c2007-09-13 18:13:15 +00004962 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004963 tmp = op2
4964 other = op1
4965 else:
4966 tmp = op1
4967 other = op2
4968
Facundo Batista353750c2007-09-13 18:13:15 +00004969 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4970 # Then adding 10**exp to tmp has the same effect (after rounding)
4971 # as adding any positive quantity smaller than 10**exp; similarly
4972 # for subtraction. So if other is smaller than 10**exp we replace
4973 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004974 tmp_len = len(str(tmp.int))
4975 other_len = len(str(other.int))
4976 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4977 if other_len + other.exp - 1 < exp:
4978 other.int = 1
4979 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004980
Facundo Batista353750c2007-09-13 18:13:15 +00004981 tmp.int *= 10 ** (tmp.exp - other.exp)
4982 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004983 return op1, op2
4984
Facundo Batista353750c2007-09-13 18:13:15 +00004985##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4986
4987# This function from Tim Peters was taken from here:
4988# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4989# The correction being in the function definition is for speed, and
4990# the whole function is not resolved with math.log because of avoiding
4991# the use of floats.
4992def _nbits(n, correction = {
4993 '0': 4, '1': 3, '2': 2, '3': 2,
4994 '4': 1, '5': 1, '6': 1, '7': 1,
4995 '8': 0, '9': 0, 'a': 0, 'b': 0,
4996 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4997 """Number of bits in binary representation of the positive integer n,
4998 or 0 if n == 0.
4999 """
5000 if n < 0:
5001 raise ValueError("The argument to _nbits should be nonnegative.")
5002 hex_n = "%x" % n
5003 return 4*len(hex_n) - correction[hex_n[0]]
5004
5005def _sqrt_nearest(n, a):
5006 """Closest integer to the square root of the positive integer n. a is
5007 an initial approximation to the square root. Any positive integer
5008 will do for a, but the closer a is to the square root of n the
5009 faster convergence will be.
5010
5011 """
5012 if n <= 0 or a <= 0:
5013 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5014
5015 b=0
5016 while a != b:
5017 b, a = a, a--n//a>>1
5018 return a
5019
5020def _rshift_nearest(x, shift):
5021 """Given an integer x and a nonnegative integer shift, return closest
5022 integer to x / 2**shift; use round-to-even in case of a tie.
5023
5024 """
5025 b, q = 1L << shift, x >> shift
5026 return q + (2*(x & (b-1)) + (q&1) > b)
5027
5028def _div_nearest(a, b):
5029 """Closest integer to a/b, a and b positive integers; rounds to even
5030 in the case of a tie.
5031
5032 """
5033 q, r = divmod(a, b)
5034 return q + (2*r + (q&1) > b)
5035
5036def _ilog(x, M, L = 8):
5037 """Integer approximation to M*log(x/M), with absolute error boundable
5038 in terms only of x/M.
5039
5040 Given positive integers x and M, return an integer approximation to
5041 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5042 between the approximation and the exact result is at most 22. For
5043 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5044 both cases these are upper bounds on the error; it will usually be
5045 much smaller."""
5046
5047 # The basic algorithm is the following: let log1p be the function
5048 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5049 # the reduction
5050 #
5051 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5052 #
5053 # repeatedly until the argument to log1p is small (< 2**-L in
5054 # absolute value). For small y we can use the Taylor series
5055 # expansion
5056 #
5057 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5058 #
5059 # truncating at T such that y**T is small enough. The whole
5060 # computation is carried out in a form of fixed-point arithmetic,
5061 # with a real number z being represented by an integer
5062 # approximation to z*M. To avoid loss of precision, the y below
5063 # is actually an integer approximation to 2**R*y*M, where R is the
5064 # number of reductions performed so far.
5065
5066 y = x-M
5067 # argument reduction; R = number of reductions performed
5068 R = 0
5069 while (R <= L and long(abs(y)) << L-R >= M or
5070 R > L and abs(y) >> R-L >= M):
5071 y = _div_nearest(long(M*y) << 1,
5072 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5073 R += 1
5074
5075 # Taylor series with T terms
5076 T = -int(-10*len(str(M))//(3*L))
5077 yshift = _rshift_nearest(y, R)
5078 w = _div_nearest(M, T)
5079 for k in xrange(T-1, 0, -1):
5080 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5081
5082 return _div_nearest(w*y, M)
5083
5084def _dlog10(c, e, p):
5085 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5086 approximation to 10**p * log10(c*10**e), with an absolute error of
5087 at most 1. Assumes that c*10**e is not exactly 1."""
5088
5089 # increase precision by 2; compensate for this by dividing
5090 # final result by 100
5091 p += 2
5092
5093 # write c*10**e as d*10**f with either:
5094 # f >= 0 and 1 <= d <= 10, or
5095 # f <= 0 and 0.1 <= d <= 1.
5096 # Thus for c*10**e close to 1, f = 0
5097 l = len(str(c))
5098 f = e+l - (e+l >= 1)
5099
5100 if p > 0:
5101 M = 10**p
5102 k = e+p-f
5103 if k >= 0:
5104 c *= 10**k
5105 else:
5106 c = _div_nearest(c, 10**-k)
5107
5108 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005109 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005110 log_d = _div_nearest(log_d*M, log_10)
5111 log_tenpower = f*M # exact
5112 else:
5113 log_d = 0 # error < 2.31
Neal Norwitz18aa3882008-08-24 05:04:52 +00005114 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Facundo Batista353750c2007-09-13 18:13:15 +00005115
5116 return _div_nearest(log_tenpower+log_d, 100)
5117
5118def _dlog(c, e, p):
5119 """Given integers c, e and p with c > 0, compute an integer
5120 approximation to 10**p * log(c*10**e), with an absolute error of
5121 at most 1. Assumes that c*10**e is not exactly 1."""
5122
5123 # Increase precision by 2. The precision increase is compensated
5124 # for at the end with a division by 100.
5125 p += 2
5126
5127 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5128 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5129 # as 10**p * log(d) + 10**p*f * log(10).
5130 l = len(str(c))
5131 f = e+l - (e+l >= 1)
5132
5133 # compute approximation to 10**p*log(d), with error < 27
5134 if p > 0:
5135 k = e+p-f
5136 if k >= 0:
5137 c *= 10**k
5138 else:
5139 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5140
5141 # _ilog magnifies existing error in c by a factor of at most 10
5142 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5143 else:
5144 # p <= 0: just approximate the whole thing by 0; error < 2.31
5145 log_d = 0
5146
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005147 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00005148 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005149 extra = len(str(abs(f)))-1
5150 if p + extra >= 0:
5151 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5152 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5153 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00005154 else:
5155 f_log_ten = 0
5156 else:
5157 f_log_ten = 0
5158
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005159 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005160 return _div_nearest(f_log_ten + log_d, 100)
5161
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005162class _Log10Memoize(object):
5163 """Class to compute, store, and allow retrieval of, digits of the
5164 constant log(10) = 2.302585.... This constant is needed by
5165 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5166 def __init__(self):
5167 self.digits = "23025850929940456840179914546843642076011014886"
5168
5169 def getdigits(self, p):
5170 """Given an integer p >= 0, return floor(10**p)*log(10).
5171
5172 For example, self.getdigits(3) returns 2302.
5173 """
5174 # digits are stored as a string, for quick conversion to
5175 # integer in the case that we've already computed enough
5176 # digits; the stored digits should always be correct
5177 # (truncated, not rounded to nearest).
5178 if p < 0:
5179 raise ValueError("p should be nonnegative")
5180
5181 if p >= len(self.digits):
5182 # compute p+3, p+6, p+9, ... digits; continue until at
5183 # least one of the extra digits is nonzero
5184 extra = 3
5185 while True:
5186 # compute p+extra digits, correct to within 1ulp
5187 M = 10**(p+extra+2)
5188 digits = str(_div_nearest(_ilog(10*M, M), 100))
5189 if digits[-extra:] != '0'*extra:
5190 break
5191 extra += 3
5192 # keep all reliable digits so far; remove trailing zeros
5193 # and next nonzero digit
5194 self.digits = digits.rstrip('0')[:-1]
5195 return int(self.digits[:p+1])
5196
5197_log10_digits = _Log10Memoize().getdigits
5198
Facundo Batista353750c2007-09-13 18:13:15 +00005199def _iexp(x, M, L=8):
5200 """Given integers x and M, M > 0, such that x/M is small in absolute
5201 value, compute an integer approximation to M*exp(x/M). For 0 <=
5202 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5203 is usually much smaller)."""
5204
5205 # Algorithm: to compute exp(z) for a real number z, first divide z
5206 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5207 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5208 # series
5209 #
5210 # expm1(x) = x + x**2/2! + x**3/3! + ...
5211 #
5212 # Now use the identity
5213 #
5214 # expm1(2x) = expm1(x)*(expm1(x)+2)
5215 #
5216 # R times to compute the sequence expm1(z/2**R),
5217 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5218
5219 # Find R such that x/2**R/M <= 2**-L
5220 R = _nbits((long(x)<<L)//M)
5221
5222 # Taylor series. (2**L)**T > M
5223 T = -int(-10*len(str(M))//(3*L))
5224 y = _div_nearest(x, T)
5225 Mshift = long(M)<<R
5226 for i in xrange(T-1, 0, -1):
5227 y = _div_nearest(x*(Mshift + y), Mshift * i)
5228
5229 # Expansion
5230 for k in xrange(R-1, -1, -1):
5231 Mshift = long(M)<<(k+2)
5232 y = _div_nearest(y*(y+Mshift), Mshift)
5233
5234 return M+y
5235
5236def _dexp(c, e, p):
5237 """Compute an approximation to exp(c*10**e), with p decimal places of
5238 precision.
5239
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005240 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005241
5242 10**(p-1) <= d <= 10**p, and
5243 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5244
5245 In other words, d*10**f is an approximation to exp(c*10**e) with p
5246 digits of precision, and with an error in d of at most 1. This is
5247 almost, but not quite, the same as the error being < 1ulp: when d
5248 = 10**(p-1) the error could be up to 10 ulp."""
5249
5250 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5251 p += 2
5252
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005253 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005254 extra = max(0, e + len(str(c)) - 1)
5255 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005256
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005257 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005258 # rounding down
5259 shift = e+q
5260 if shift >= 0:
5261 cshift = c*10**shift
5262 else:
5263 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005264 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005265
5266 # reduce remainder back to original precision
5267 rem = _div_nearest(rem, 10**extra)
5268
5269 # error in result of _iexp < 120; error after division < 0.62
5270 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5271
5272def _dpower(xc, xe, yc, ye, p):
5273 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5274 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5275
5276 10**(p-1) <= c <= 10**p, and
5277 (c-1)*10**e < x**y < (c+1)*10**e
5278
5279 in other words, c*10**e is an approximation to x**y with p digits
5280 of precision, and with an error in c of at most 1. (This is
5281 almost, but not quite, the same as the error being < 1ulp: when c
5282 == 10**(p-1) we can only guarantee error < 10ulp.)
5283
5284 We assume that: x is positive and not equal to 1, and y is nonzero.
5285 """
5286
5287 # Find b such that 10**(b-1) <= |y| <= 10**b
5288 b = len(str(abs(yc))) + ye
5289
5290 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5291 lxc = _dlog(xc, xe, p+b+1)
5292
5293 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5294 shift = ye-b
5295 if shift >= 0:
5296 pc = lxc*yc*10**shift
5297 else:
5298 pc = _div_nearest(lxc*yc, 10**-shift)
5299
5300 if pc == 0:
5301 # we prefer a result that isn't exactly 1; this makes it
5302 # easier to compute a correctly rounded result in __pow__
5303 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5304 coeff, exp = 10**(p-1)+1, 1-p
5305 else:
5306 coeff, exp = 10**p-1, -p
5307 else:
5308 coeff, exp = _dexp(pc, -(p+1), p+1)
5309 coeff = _div_nearest(coeff, 10)
5310 exp += 1
5311
5312 return coeff, exp
5313
5314def _log10_lb(c, correction = {
5315 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5316 '6': 23, '7': 16, '8': 10, '9': 5}):
5317 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5318 if c <= 0:
5319 raise ValueError("The argument to _log10_lb should be nonnegative.")
5320 str_c = str(c)
5321 return 100*len(str_c) - correction[str_c[0]]
5322
Facundo Batista59c58842007-04-10 12:58:45 +00005323##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005324
Facundo Batista353750c2007-09-13 18:13:15 +00005325def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005326 """Convert other to Decimal.
5327
5328 Verifies that it's ok to use in an implicit construction.
5329 """
5330 if isinstance(other, Decimal):
5331 return other
5332 if isinstance(other, (int, long)):
5333 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005334 if raiseit:
5335 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005336 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005337
Facundo Batista59c58842007-04-10 12:58:45 +00005338##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005339
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005340# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005341# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005342
5343DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005344 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005345 traps=[DivisionByZero, Overflow, InvalidOperation],
5346 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005347 Emax=999999999,
5348 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005349 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005350)
5351
5352# Pre-made alternate contexts offered by the specification
5353# Don't change these; the user should be able to select these
5354# contexts and be able to reproduce results from other implementations
5355# of the spec.
5356
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005357BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005358 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005359 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5360 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005361)
5362
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005363ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005364 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005365 traps=[],
5366 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005367)
5368
5369
Facundo Batista72bc54f2007-11-23 17:59:00 +00005370##### crud for parsing strings #############################################
Mark Dickinson6a123cb2008-02-24 18:12:36 +00005371#
Facundo Batista72bc54f2007-11-23 17:59:00 +00005372# Regular expression used for parsing numeric strings. Additional
5373# comments:
5374#
5375# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5376# whitespace. But note that the specification disallows whitespace in
5377# a numeric string.
5378#
5379# 2. For finite numbers (not infinities and NaNs) the body of the
5380# number between the optional sign and the optional exponent must have
5381# at least one decimal digit, possibly after the decimal point. The
5382# lookahead expression '(?=\d|\.\d)' checks this.
5383#
5384# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5385# other meaning for \d than the numbers [0-9].
5386
5387import re
Mark Dickinson70c32892008-07-02 09:37:01 +00005388_parser = re.compile(r""" # A numeric string consists of:
Facundo Batista72bc54f2007-11-23 17:59:00 +00005389# \s*
Mark Dickinson70c32892008-07-02 09:37:01 +00005390 (?P<sign>[-+])? # an optional sign, followed by either...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005391 (
Mark Dickinson70c32892008-07-02 09:37:01 +00005392 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5393 (?P<int>[0-9]*) # having a (possibly empty) integer part
5394 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5395 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005396 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005397 Inf(inity)? # ...an infinity, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005398 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005399 (?P<signal>s)? # ...an (optionally signaling)
5400 NaN # NaN
5401 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005402 )
5403# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005404 \Z
Facundo Batista72bc54f2007-11-23 17:59:00 +00005405""", re.VERBOSE | re.IGNORECASE).match
5406
Facundo Batista2ec74152007-12-03 17:55:00 +00005407_all_zeros = re.compile('0*$').match
5408_exact_half = re.compile('50*$').match
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005409
5410##### PEP3101 support functions ##############################################
5411# The functions parse_format_specifier and format_align have little to do
5412# with the Decimal class, and could potentially be reused for other pure
5413# Python numeric classes that want to implement __format__
5414#
5415# A format specifier for Decimal looks like:
5416#
5417# [[fill]align][sign][0][minimumwidth][.precision][type]
5418#
5419
5420_parse_format_specifier_regex = re.compile(r"""\A
5421(?:
5422 (?P<fill>.)?
5423 (?P<align>[<>=^])
5424)?
5425(?P<sign>[-+ ])?
5426(?P<zeropad>0)?
5427(?P<minimumwidth>(?!0)\d+)?
5428(?:\.(?P<precision>0|(?!0)\d+))?
5429(?P<type>[eEfFgG%])?
5430\Z
5431""", re.VERBOSE)
5432
Facundo Batista72bc54f2007-11-23 17:59:00 +00005433del re
5434
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005435def _parse_format_specifier(format_spec):
5436 """Parse and validate a format specifier.
5437
5438 Turns a standard numeric format specifier into a dict, with the
5439 following entries:
5440
5441 fill: fill character to pad field to minimum width
5442 align: alignment type, either '<', '>', '=' or '^'
5443 sign: either '+', '-' or ' '
5444 minimumwidth: nonnegative integer giving minimum width
5445 precision: nonnegative integer giving precision, or None
5446 type: one of the characters 'eEfFgG%', or None
5447 unicode: either True or False (always True for Python 3.x)
5448
5449 """
5450 m = _parse_format_specifier_regex.match(format_spec)
5451 if m is None:
5452 raise ValueError("Invalid format specifier: " + format_spec)
5453
5454 # get the dictionary
5455 format_dict = m.groupdict()
5456
5457 # defaults for fill and alignment
5458 fill = format_dict['fill']
5459 align = format_dict['align']
5460 if format_dict.pop('zeropad') is not None:
5461 # in the face of conflict, refuse the temptation to guess
5462 if fill is not None and fill != '0':
5463 raise ValueError("Fill character conflicts with '0'"
5464 " in format specifier: " + format_spec)
5465 if align is not None and align != '=':
5466 raise ValueError("Alignment conflicts with '0' in "
5467 "format specifier: " + format_spec)
5468 fill = '0'
5469 align = '='
5470 format_dict['fill'] = fill or ' '
5471 format_dict['align'] = align or '<'
5472
5473 if format_dict['sign'] is None:
5474 format_dict['sign'] = '-'
5475
5476 # turn minimumwidth and precision entries into integers.
5477 # minimumwidth defaults to 0; precision remains None if not given
5478 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5479 if format_dict['precision'] is not None:
5480 format_dict['precision'] = int(format_dict['precision'])
5481
5482 # if format type is 'g' or 'G' then a precision of 0 makes little
5483 # sense; convert it to 1. Same if format type is unspecified.
5484 if format_dict['precision'] == 0:
5485 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5486 format_dict['precision'] = 1
5487
5488 # record whether return type should be str or unicode
5489 format_dict['unicode'] = isinstance(format_spec, unicode)
5490
5491 return format_dict
5492
5493def _format_align(body, spec_dict):
5494 """Given an unpadded, non-aligned numeric string, add padding and
5495 aligment to conform with the given format specifier dictionary (as
5496 output from parse_format_specifier).
5497
5498 It's assumed that if body is negative then it starts with '-'.
5499 Any leading sign ('-' or '+') is stripped from the body before
5500 applying the alignment and padding rules, and replaced in the
5501 appropriate position.
5502
5503 """
5504 # figure out the sign; we only examine the first character, so if
5505 # body has leading whitespace the results may be surprising.
5506 if len(body) > 0 and body[0] in '-+':
5507 sign = body[0]
5508 body = body[1:]
5509 else:
5510 sign = ''
5511
5512 if sign != '-':
5513 if spec_dict['sign'] in ' +':
5514 sign = spec_dict['sign']
5515 else:
5516 sign = ''
5517
5518 # how much extra space do we have to play with?
5519 minimumwidth = spec_dict['minimumwidth']
5520 fill = spec_dict['fill']
5521 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5522
5523 align = spec_dict['align']
5524 if align == '<':
5525 result = padding + sign + body
5526 elif align == '>':
5527 result = sign + body + padding
5528 elif align == '=':
5529 result = sign + padding + body
5530 else: #align == '^'
5531 half = len(padding)//2
5532 result = padding[:half] + sign + body + padding[half:]
5533
5534 # make sure that result is unicode if necessary
5535 if spec_dict['unicode']:
5536 result = unicode(result)
5537
5538 return result
Facundo Batista72bc54f2007-11-23 17:59:00 +00005539
Facundo Batista59c58842007-04-10 12:58:45 +00005540##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005541
Facundo Batista59c58842007-04-10 12:58:45 +00005542# Reusable defaults
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00005543_Infinity = Decimal('Inf')
5544_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonc5de0962009-01-02 23:07:08 +00005545_NaN = Decimal('NaN')
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00005546_Zero = Decimal(0)
5547_One = Decimal(1)
5548_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005549
Raymond Hettingerb7e835b2009-01-03 19:08:10 +00005550# _SignedInfinity[sign] is infinity w/ that sign
5551_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005552
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005553
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005554
5555if __name__ == '__main__':
5556 import doctest, sys
5557 doctest.testmod(sys.modules[__name__])