blob: a1662bbd6713609635793daaa7cab78440551340 [file] [log] [blame]
Stefan Krahb578f8a2014-09-10 17:58:15 +02001# 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>
7# and Aahz <aahz at pobox.com>
8# and Tim Peters
9
10# This module should be kept in sync with the latest updates of the
11# IBM specification as it evolves. Those updates will be treated
12# as bug fixes (deviation from the spec is a compatibility, usability
13# bug) and will be backported. At this point the spec is stabilizing
14# and the updates are becoming fewer, smaller, and less significant.
15
16"""
17This is an implementation of decimal floating point arithmetic based on
18the General Decimal Arithmetic Specification:
19
20 http://speleotrove.com/decimal/decarith.html
21
22and IEEE standard 854-1987:
23
24 http://en.wikipedia.org/wiki/IEEE_854-1987
25
26Decimal floating point has finite precision with arbitrarily large bounds.
27
28The purpose of this module is to support arithmetic using familiar
29"schoolhouse" rules and to avoid some of the tricky representation
30issues associated with binary floating point. The package is especially
31useful for financial applications or for contexts where users have
32expectations that are at odds with binary floating point (for instance,
33in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
34of 0.0; Decimal('1.00') % Decimal('0.1') returns the expected
35Decimal('0.00')).
36
37Here are some examples of using the decimal module:
38
39>>> from decimal import *
40>>> setcontext(ExtendedContext)
41>>> Decimal(0)
42Decimal('0')
43>>> Decimal('1')
44Decimal('1')
45>>> Decimal('-.0123')
46Decimal('-0.0123')
47>>> Decimal(123456)
48Decimal('123456')
49>>> Decimal('123.45e12345678')
50Decimal('1.2345E+12345680')
51>>> Decimal('1.33') + Decimal('1.27')
52Decimal('2.60')
53>>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
54Decimal('-2.20')
55>>> dig = Decimal(1)
56>>> print(dig / Decimal(3))
570.333333333
58>>> getcontext().prec = 18
59>>> print(dig / Decimal(3))
600.333333333333333333
61>>> print(dig.sqrt())
621
63>>> print(Decimal(3).sqrt())
641.73205080756887729
65>>> print(Decimal(3) ** 123)
664.85192780976896427E+58
67>>> inf = Decimal(1) / Decimal(0)
68>>> print(inf)
69Infinity
70>>> neginf = Decimal(-1) / Decimal(0)
71>>> print(neginf)
72-Infinity
73>>> print(neginf + inf)
74NaN
75>>> print(neginf * inf)
76-Infinity
77>>> print(dig / 0)
78Infinity
79>>> getcontext().traps[DivisionByZero] = 1
80>>> print(dig / 0)
81Traceback (most recent call last):
82 ...
83 ...
84 ...
85decimal.DivisionByZero: x / 0
86>>> c = Context()
87>>> c.traps[InvalidOperation] = 0
88>>> print(c.flags[InvalidOperation])
890
90>>> c.divide(Decimal(0), Decimal(0))
91Decimal('NaN')
92>>> c.traps[InvalidOperation] = 1
93>>> print(c.flags[InvalidOperation])
941
95>>> c.flags[InvalidOperation] = 0
96>>> print(c.flags[InvalidOperation])
970
98>>> print(c.divide(Decimal(0), Decimal(0)))
99Traceback (most recent call last):
100 ...
101 ...
102 ...
103decimal.InvalidOperation: 0 / 0
104>>> print(c.flags[InvalidOperation])
1051
106>>> c.flags[InvalidOperation] = 0
107>>> c.traps[InvalidOperation] = 0
108>>> print(c.divide(Decimal(0), Decimal(0)))
109NaN
110>>> print(c.flags[InvalidOperation])
1111
112>>>
113"""
114
115__all__ = [
116 # Two major classes
117 'Decimal', 'Context',
118
119 # Named tuple representation
120 'DecimalTuple',
121
122 # Contexts
123 'DefaultContext', 'BasicContext', 'ExtendedContext',
124
125 # Exceptions
126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
128 'FloatOperation',
129
130 # Exceptional conditions that trigger InvalidOperation
131 'DivisionImpossible', 'InvalidContext', 'ConversionSyntax', 'DivisionUndefined',
132
133 # Constants for use in setting up contexts
134 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
135 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
136
137 # Functions for manipulating contexts
138 'setcontext', 'getcontext', 'localcontext',
139
140 # Limits for the C version for compatibility
141 'MAX_PREC', 'MAX_EMAX', 'MIN_EMIN', 'MIN_ETINY',
142
143 # C version: compile time choice that enables the thread local context
144 'HAVE_THREADS'
145]
146
Stefan Krahbca45ed2014-10-12 13:29:15 +0200147__xname__ = __name__ # sys.modules lookup (--without-threads)
Stefan Krahb578f8a2014-09-10 17:58:15 +0200148__name__ = 'decimal' # For pickling
149__version__ = '1.70' # Highest version of the spec this complies with
150 # See http://speleotrove.com/decimal/
Stefan Krah66e9d032016-03-23 20:50:10 +0100151__libmpdec_version__ = "2.4.2" # compatible libmpdec version
Stefan Krahb578f8a2014-09-10 17:58:15 +0200152
153import math as _math
154import numbers as _numbers
155import sys
156
157try:
158 from collections import namedtuple as _namedtuple
159 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
160except ImportError:
161 DecimalTuple = lambda *args: args
162
163# Rounding
164ROUND_DOWN = 'ROUND_DOWN'
165ROUND_HALF_UP = 'ROUND_HALF_UP'
166ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
167ROUND_CEILING = 'ROUND_CEILING'
168ROUND_FLOOR = 'ROUND_FLOOR'
169ROUND_UP = 'ROUND_UP'
170ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
171ROUND_05UP = 'ROUND_05UP'
172
173# Compatibility with the C version
174HAVE_THREADS = True
175if sys.maxsize == 2**63-1:
176 MAX_PREC = 999999999999999999
177 MAX_EMAX = 999999999999999999
178 MIN_EMIN = -999999999999999999
179else:
180 MAX_PREC = 425000000
181 MAX_EMAX = 425000000
182 MIN_EMIN = -425000000
183
184MIN_ETINY = MIN_EMIN - (MAX_PREC-1)
185
186# Errors
187
188class DecimalException(ArithmeticError):
189 """Base exception class.
190
191 Used exceptions derive from this.
192 If an exception derives from another exception besides this (such as
193 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
194 called if the others are present. This isn't actually used for
195 anything, though.
196
197 handle -- Called when context._raise_error is called and the
198 trap_enabler is not set. First argument is self, second is the
199 context. More arguments can be given, those being after
200 the explanation in _raise_error (For example,
201 context._raise_error(NewError, '(-x)!', self._sign) would
202 call NewError().handle(context, self._sign).)
203
204 To define a new exception, it should be sufficient to have it derive
205 from DecimalException.
206 """
207 def handle(self, context, *args):
208 pass
209
210
211class Clamped(DecimalException):
212 """Exponent of a 0 changed to fit bounds.
213
214 This occurs and signals clamped if the exponent of a result has been
215 altered in order to fit the constraints of a specific concrete
216 representation. This may occur when the exponent of a zero result would
217 be outside the bounds of a representation, or when a large normal
218 number would have an encoded exponent that cannot be represented. In
219 this latter case, the exponent is reduced to fit and the corresponding
220 number of zero digits are appended to the coefficient ("fold-down").
221 """
222
223class InvalidOperation(DecimalException):
224 """An invalid operation was performed.
225
226 Various bad things cause this:
227
228 Something creates a signaling NaN
229 -INF + INF
230 0 * (+-)INF
231 (+-)INF / (+-)INF
232 x % 0
233 (+-)INF % x
234 x._rescale( non-integer )
235 sqrt(-x) , x > 0
236 0 ** 0
237 x ** (non-integer)
238 x ** (+-)INF
239 An operand is invalid
240
241 The result of the operation after these is a quiet positive NaN,
242 except when the cause is a signaling NaN, in which case the result is
243 also a quiet NaN, but with the original sign, and an optional
244 diagnostic information.
245 """
246 def handle(self, context, *args):
247 if args:
248 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
249 return ans._fix_nan(context)
250 return _NaN
251
252class ConversionSyntax(InvalidOperation):
253 """Trying to convert badly formed string.
254
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +0300255 This occurs and signals invalid-operation if a string is being
Stefan Krahb578f8a2014-09-10 17:58:15 +0200256 converted to a number and it does not conform to the numeric string
257 syntax. The result is [0,qNaN].
258 """
259 def handle(self, context, *args):
260 return _NaN
261
262class DivisionByZero(DecimalException, ZeroDivisionError):
263 """Division by 0.
264
265 This occurs and signals division-by-zero if division of a finite number
266 by zero was attempted (during a divide-integer or divide operation, or a
267 power operation with negative right-hand operand), and the dividend was
268 not zero.
269
270 The result of the operation is [sign,inf], where sign is the exclusive
271 or of the signs of the operands for divide, or is 1 for an odd power of
272 -0, for power.
273 """
274
275 def handle(self, context, sign, *args):
276 return _SignedInfinity[sign]
277
278class DivisionImpossible(InvalidOperation):
279 """Cannot perform the division adequately.
280
281 This occurs and signals invalid-operation if the integer result of a
282 divide-integer or remainder operation had too many digits (would be
283 longer than precision). The result is [0,qNaN].
284 """
285
286 def handle(self, context, *args):
287 return _NaN
288
289class DivisionUndefined(InvalidOperation, ZeroDivisionError):
290 """Undefined result of division.
291
292 This occurs and signals invalid-operation if division by zero was
293 attempted (during a divide-integer, divide, or remainder operation), and
294 the dividend is also zero. The result is [0,qNaN].
295 """
296
297 def handle(self, context, *args):
298 return _NaN
299
300class Inexact(DecimalException):
301 """Had to round, losing information.
302
303 This occurs and signals inexact whenever the result of an operation is
304 not exact (that is, it needed to be rounded and any discarded digits
305 were non-zero), or if an overflow or underflow condition occurs. The
306 result in all cases is unchanged.
307
308 The inexact signal may be tested (or trapped) to determine if a given
309 operation (or sequence of operations) was inexact.
310 """
311
312class InvalidContext(InvalidOperation):
313 """Invalid context. Unknown rounding, for example.
314
315 This occurs and signals invalid-operation if an invalid context was
316 detected during an operation. This can occur if contexts are not checked
317 on creation and either the precision exceeds the capability of the
318 underlying concrete representation or an unknown or unsupported rounding
319 was specified. These aspects of the context need only be checked when
320 the values are required to be used. The result is [0,qNaN].
321 """
322
323 def handle(self, context, *args):
324 return _NaN
325
326class Rounded(DecimalException):
327 """Number got rounded (not necessarily changed during rounding).
328
329 This occurs and signals rounded whenever the result of an operation is
330 rounded (that is, some zero or non-zero digits were discarded from the
331 coefficient), or if an overflow or underflow condition occurs. The
332 result in all cases is unchanged.
333
334 The rounded signal may be tested (or trapped) to determine if a given
335 operation (or sequence of operations) caused a loss of precision.
336 """
337
338class Subnormal(DecimalException):
339 """Exponent < Emin before rounding.
340
341 This occurs and signals subnormal whenever the result of a conversion or
342 operation is subnormal (that is, its adjusted exponent is less than
343 Emin, before any rounding). The result in all cases is unchanged.
344
345 The subnormal signal may be tested (or trapped) to determine if a given
346 or operation (or sequence of operations) yielded a subnormal result.
347 """
348
349class Overflow(Inexact, Rounded):
350 """Numerical overflow.
351
352 This occurs and signals overflow if the adjusted exponent of a result
353 (from a conversion or from an operation that is not an attempt to divide
354 by zero), after rounding, would be greater than the largest value that
355 can be handled by the implementation (the value Emax).
356
357 The result depends on the rounding mode:
358
359 For round-half-up and round-half-even (and for round-half-down and
360 round-up, if implemented), the result of the operation is [sign,inf],
361 where sign is the sign of the intermediate result. For round-down, the
362 result is the largest finite number that can be represented in the
363 current precision, with the sign of the intermediate result. For
364 round-ceiling, the result is the same as for round-down if the sign of
365 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
366 the result is the same as for round-down if the sign of the intermediate
367 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
368 will also be raised.
369 """
370
371 def handle(self, context, sign, *args):
372 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
373 ROUND_HALF_DOWN, ROUND_UP):
374 return _SignedInfinity[sign]
375 if sign == 0:
376 if context.rounding == ROUND_CEILING:
377 return _SignedInfinity[sign]
378 return _dec_from_triple(sign, '9'*context.prec,
379 context.Emax-context.prec+1)
380 if sign == 1:
381 if context.rounding == ROUND_FLOOR:
382 return _SignedInfinity[sign]
383 return _dec_from_triple(sign, '9'*context.prec,
384 context.Emax-context.prec+1)
385
386
387class Underflow(Inexact, Rounded, Subnormal):
388 """Numerical underflow with result rounded to 0.
389
390 This occurs and signals underflow if a result is inexact and the
391 adjusted exponent of the result would be smaller (more negative) than
392 the smallest value that can be handled by the implementation (the value
393 Emin). That is, the result is both inexact and subnormal.
394
395 The result after an underflow will be a subnormal number rounded, if
396 necessary, so that its exponent is not less than Etiny. This may result
397 in 0 with the sign of the intermediate result and an exponent of Etiny.
398
399 In all cases, Inexact, Rounded, and Subnormal will also be raised.
400 """
401
402class FloatOperation(DecimalException, TypeError):
403 """Enable stricter semantics for mixing floats and Decimals.
404
405 If the signal is not trapped (default), mixing floats and Decimals is
406 permitted in the Decimal() constructor, context.create_decimal() and
407 all comparison operators. Both conversion and comparisons are exact.
408 Any occurrence of a mixed operation is silently recorded by setting
409 FloatOperation in the context flags. Explicit conversions with
410 Decimal.from_float() or context.create_decimal_from_float() do not
411 set the flag.
412
413 Otherwise (the signal is trapped), only equality comparisons and explicit
414 conversions are silent. All other mixed operations raise FloatOperation.
415 """
416
417# List of public traps and flags
418_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
419 Underflow, InvalidOperation, Subnormal, FloatOperation]
420
421# Map conditions (per the spec) to signals
422_condition_map = {ConversionSyntax:InvalidOperation,
423 DivisionImpossible:InvalidOperation,
424 DivisionUndefined:InvalidOperation,
425 InvalidContext:InvalidOperation}
426
427# Valid rounding modes
428_rounding_modes = (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_CEILING,
429 ROUND_FLOOR, ROUND_UP, ROUND_HALF_DOWN, ROUND_05UP)
430
431##### Context Functions ##################################################
432
433# The getcontext() and setcontext() function manage access to a thread-local
Antoine Pitrou88c60c92017-09-18 23:50:44 +0200434# current context.
Stefan Krahb578f8a2014-09-10 17:58:15 +0200435
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200436import threading
Stefan Krahb578f8a2014-09-10 17:58:15 +0200437
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200438local = threading.local()
439if hasattr(local, '__decimal_context__'):
440 del local.__decimal_context__
Stefan Krahb578f8a2014-09-10 17:58:15 +0200441
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200442def getcontext(_local=local):
443 """Returns this thread's context.
Stefan Krahb578f8a2014-09-10 17:58:15 +0200444
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200445 If this thread does not yet have a context, returns
446 a new context and sets this thread's context.
447 New contexts are copies of DefaultContext.
448 """
449 try:
450 return _local.__decimal_context__
451 except AttributeError:
452 context = Context()
Stefan Krahb578f8a2014-09-10 17:58:15 +0200453 _local.__decimal_context__ = context
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200454 return context
Stefan Krahb578f8a2014-09-10 17:58:15 +0200455
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200456def setcontext(context, _local=local):
457 """Set this thread's context to context."""
458 if context in (DefaultContext, BasicContext, ExtendedContext):
459 context = context.copy()
460 context.clear_flags()
461 _local.__decimal_context__ = context
462
463del threading, local # Don't contaminate the namespace
Stefan Krahb578f8a2014-09-10 17:58:15 +0200464
465def localcontext(ctx=None):
466 """Return a context manager for a copy of the supplied context
467
468 Uses a copy of the current context if no context is specified
469 The returned context manager creates a local decimal context
470 in a with statement:
471 def sin(x):
472 with localcontext() as ctx:
473 ctx.prec += 2
474 # Rest of sin calculation algorithm
475 # uses a precision 2 greater than normal
476 return +s # Convert result to normal precision
477
478 def sin(x):
479 with localcontext(ExtendedContext):
480 # Rest of sin calculation algorithm
481 # uses the Extended Context from the
482 # General Decimal Arithmetic Specification
483 return +s # Convert result to normal context
484
485 >>> setcontext(DefaultContext)
486 >>> print(getcontext().prec)
487 28
488 >>> with localcontext():
489 ... ctx = getcontext()
490 ... ctx.prec += 2
491 ... print(ctx.prec)
492 ...
493 30
494 >>> with localcontext(ExtendedContext):
495 ... print(getcontext().prec)
496 ...
497 9
498 >>> print(getcontext().prec)
499 28
500 """
501 if ctx is None: ctx = getcontext()
502 return _ContextManager(ctx)
503
504
505##### Decimal class #######################################################
506
507# Do not subclass Decimal from numbers.Real and do not register it as such
508# (because Decimals are not interoperable with floats). See the notes in
509# numbers.py for more detail.
510
511class Decimal(object):
512 """Floating point class for decimal arithmetic."""
513
514 __slots__ = ('_exp','_int','_sign', '_is_special')
515 # Generally, the value of the Decimal instance is given by
516 # (-1)**_sign * _int * 10**_exp
517 # Special values are signified by _is_special == True
518
519 # We're immutable, so use __new__ not __init__
520 def __new__(cls, value="0", context=None):
521 """Create a decimal point instance.
522
523 >>> Decimal('3.14') # string input
524 Decimal('3.14')
525 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
526 Decimal('3.14')
527 >>> Decimal(314) # int
528 Decimal('314')
529 >>> Decimal(Decimal(314)) # another decimal instance
530 Decimal('314')
531 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
532 Decimal('3.14')
533 """
534
535 # Note that the coefficient, self._int, is actually stored as
536 # a string rather than as a tuple of digits. This speeds up
537 # the "digits to integer" and "integer to digits" conversions
538 # that are used in almost every arithmetic operation on
539 # Decimals. This is an internal detail: the as_tuple function
540 # and the Decimal constructor still deal with tuples of
541 # digits.
542
543 self = object.__new__(cls)
544
545 # From a string
546 # REs insist on real strings, so we can too.
547 if isinstance(value, str):
Brett Cannona721aba2016-09-09 14:57:09 -0700548 m = _parser(value.strip().replace("_", ""))
Stefan Krahb578f8a2014-09-10 17:58:15 +0200549 if m is None:
550 if context is None:
551 context = getcontext()
552 return context._raise_error(ConversionSyntax,
553 "Invalid literal for Decimal: %r" % value)
554
555 if m.group('sign') == "-":
556 self._sign = 1
557 else:
558 self._sign = 0
559 intpart = m.group('int')
560 if intpart is not None:
561 # finite number
562 fracpart = m.group('frac') or ''
563 exp = int(m.group('exp') or '0')
564 self._int = str(int(intpart+fracpart))
565 self._exp = exp - len(fracpart)
566 self._is_special = False
567 else:
568 diag = m.group('diag')
569 if diag is not None:
570 # NaN
571 self._int = str(int(diag or '0')).lstrip('0')
572 if m.group('signal'):
573 self._exp = 'N'
574 else:
575 self._exp = 'n'
576 else:
577 # infinity
578 self._int = '0'
579 self._exp = 'F'
580 self._is_special = True
581 return self
582
583 # From an integer
584 if isinstance(value, int):
585 if value >= 0:
586 self._sign = 0
587 else:
588 self._sign = 1
589 self._exp = 0
590 self._int = str(abs(value))
591 self._is_special = False
592 return self
593
594 # From another decimal
595 if isinstance(value, Decimal):
596 self._exp = value._exp
597 self._sign = value._sign
598 self._int = value._int
599 self._is_special = value._is_special
600 return self
601
602 # From an internal working value
603 if isinstance(value, _WorkRep):
604 self._sign = value.sign
605 self._int = str(value.int)
606 self._exp = int(value.exp)
607 self._is_special = False
608 return self
609
610 # tuple/list conversion (possibly from as_tuple())
611 if isinstance(value, (list,tuple)):
612 if len(value) != 3:
613 raise ValueError('Invalid tuple size in creation of Decimal '
614 'from list or tuple. The list or tuple '
615 'should have exactly three elements.')
616 # process sign. The isinstance test rejects floats
617 if not (isinstance(value[0], int) and value[0] in (0,1)):
618 raise ValueError("Invalid sign. The first value in the tuple "
619 "should be an integer; either 0 for a "
620 "positive number or 1 for a negative number.")
621 self._sign = value[0]
622 if value[2] == 'F':
623 # infinity: value[1] is ignored
624 self._int = '0'
625 self._exp = value[2]
626 self._is_special = True
627 else:
628 # process and validate the digits in value[1]
629 digits = []
630 for digit in value[1]:
631 if isinstance(digit, int) and 0 <= digit <= 9:
632 # skip leading zeros
633 if digits or digit != 0:
634 digits.append(digit)
635 else:
636 raise ValueError("The second value in the tuple must "
637 "be composed of integers in the range "
638 "0 through 9.")
639 if value[2] in ('n', 'N'):
640 # NaN: digits form the diagnostic
641 self._int = ''.join(map(str, digits))
642 self._exp = value[2]
643 self._is_special = True
644 elif isinstance(value[2], int):
645 # finite number: digits give the coefficient
646 self._int = ''.join(map(str, digits or [0]))
647 self._exp = value[2]
648 self._is_special = False
649 else:
650 raise ValueError("The third value in the tuple must "
651 "be an integer, or one of the "
652 "strings 'F', 'n', 'N'.")
653 return self
654
655 if isinstance(value, float):
656 if context is None:
657 context = getcontext()
658 context._raise_error(FloatOperation,
659 "strict semantics for mixing floats and Decimals are "
660 "enabled")
661 value = Decimal.from_float(value)
662 self._exp = value._exp
663 self._sign = value._sign
664 self._int = value._int
665 self._is_special = value._is_special
666 return self
667
668 raise TypeError("Cannot convert %r to Decimal" % value)
669
670 @classmethod
671 def from_float(cls, f):
672 """Converts a float to a decimal number, exactly.
673
674 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
675 Since 0.1 is not exactly representable in binary floating point, the
676 value is stored as the nearest representable value which is
677 0x1.999999999999ap-4. The exact equivalent of the value in decimal
678 is 0.1000000000000000055511151231257827021181583404541015625.
679
680 >>> Decimal.from_float(0.1)
681 Decimal('0.1000000000000000055511151231257827021181583404541015625')
682 >>> Decimal.from_float(float('nan'))
683 Decimal('NaN')
684 >>> Decimal.from_float(float('inf'))
685 Decimal('Infinity')
686 >>> Decimal.from_float(-float('inf'))
687 Decimal('-Infinity')
688 >>> Decimal.from_float(-0.0)
689 Decimal('-0')
690
691 """
692 if isinstance(f, int): # handle integer inputs
Andrew Nester6d1dece2017-02-14 21:22:55 +0300693 sign = 0 if f >= 0 else 1
694 k = 0
695 coeff = str(abs(f))
696 elif isinstance(f, float):
697 if _math.isinf(f) or _math.isnan(f):
698 return cls(repr(f))
699 if _math.copysign(1.0, f) == 1.0:
700 sign = 0
701 else:
702 sign = 1
703 n, d = abs(f).as_integer_ratio()
704 k = d.bit_length() - 1
705 coeff = str(n*5**k)
Stefan Krahb578f8a2014-09-10 17:58:15 +0200706 else:
Andrew Nester6d1dece2017-02-14 21:22:55 +0300707 raise TypeError("argument must be int or float.")
708
709 result = _dec_from_triple(sign, coeff, -k)
Stefan Krahb578f8a2014-09-10 17:58:15 +0200710 if cls is Decimal:
711 return result
712 else:
713 return cls(result)
714
715 def _isnan(self):
716 """Returns whether the number is not actually one.
717
718 0 if a number
719 1 if NaN
720 2 if sNaN
721 """
722 if self._is_special:
723 exp = self._exp
724 if exp == 'n':
725 return 1
726 elif exp == 'N':
727 return 2
728 return 0
729
730 def _isinfinity(self):
731 """Returns whether the number is infinite
732
733 0 if finite or not a number
734 1 if +INF
735 -1 if -INF
736 """
737 if self._exp == 'F':
738 if self._sign:
739 return -1
740 return 1
741 return 0
742
743 def _check_nans(self, other=None, context=None):
744 """Returns whether the number is not actually one.
745
746 if self, other are sNaN, signal
747 if self, other are NaN return nan
748 return 0
749
750 Done before operations.
751 """
752
753 self_is_nan = self._isnan()
754 if other is None:
755 other_is_nan = False
756 else:
757 other_is_nan = other._isnan()
758
759 if self_is_nan or other_is_nan:
760 if context is None:
761 context = getcontext()
762
763 if self_is_nan == 2:
764 return context._raise_error(InvalidOperation, 'sNaN',
765 self)
766 if other_is_nan == 2:
767 return context._raise_error(InvalidOperation, 'sNaN',
768 other)
769 if self_is_nan:
770 return self._fix_nan(context)
771
772 return other._fix_nan(context)
773 return 0
774
775 def _compare_check_nans(self, other, context):
776 """Version of _check_nans used for the signaling comparisons
777 compare_signal, __le__, __lt__, __ge__, __gt__.
778
779 Signal InvalidOperation if either self or other is a (quiet
780 or signaling) NaN. Signaling NaNs take precedence over quiet
781 NaNs.
782
783 Return 0 if neither operand is a NaN.
784
785 """
786 if context is None:
787 context = getcontext()
788
789 if self._is_special or other._is_special:
790 if self.is_snan():
791 return context._raise_error(InvalidOperation,
792 'comparison involving sNaN',
793 self)
794 elif other.is_snan():
795 return context._raise_error(InvalidOperation,
796 'comparison involving sNaN',
797 other)
798 elif self.is_qnan():
799 return context._raise_error(InvalidOperation,
800 'comparison involving NaN',
801 self)
802 elif other.is_qnan():
803 return context._raise_error(InvalidOperation,
804 'comparison involving NaN',
805 other)
806 return 0
807
808 def __bool__(self):
809 """Return True if self is nonzero; otherwise return False.
810
811 NaNs and infinities are considered nonzero.
812 """
813 return self._is_special or self._int != '0'
814
815 def _cmp(self, other):
816 """Compare the two non-NaN decimal instances self and other.
817
818 Returns -1 if self < other, 0 if self == other and 1
819 if self > other. This routine is for internal use only."""
820
821 if self._is_special or other._is_special:
822 self_inf = self._isinfinity()
823 other_inf = other._isinfinity()
824 if self_inf == other_inf:
825 return 0
826 elif self_inf < other_inf:
827 return -1
828 else:
829 return 1
830
831 # check for zeros; Decimal('0') == Decimal('-0')
832 if not self:
833 if not other:
834 return 0
835 else:
836 return -((-1)**other._sign)
837 if not other:
838 return (-1)**self._sign
839
840 # If different signs, neg one is less
841 if other._sign < self._sign:
842 return -1
843 if self._sign < other._sign:
844 return 1
845
846 self_adjusted = self.adjusted()
847 other_adjusted = other.adjusted()
848 if self_adjusted == other_adjusted:
849 self_padded = self._int + '0'*(self._exp - other._exp)
850 other_padded = other._int + '0'*(other._exp - self._exp)
851 if self_padded == other_padded:
852 return 0
853 elif self_padded < other_padded:
854 return -(-1)**self._sign
855 else:
856 return (-1)**self._sign
857 elif self_adjusted > other_adjusted:
858 return (-1)**self._sign
859 else: # self_adjusted < other_adjusted
860 return -((-1)**self._sign)
861
862 # Note: The Decimal standard doesn't cover rich comparisons for
863 # Decimals. In particular, the specification is silent on the
864 # subject of what should happen for a comparison involving a NaN.
865 # We take the following approach:
866 #
867 # == comparisons involving a quiet NaN always return False
868 # != comparisons involving a quiet NaN always return True
869 # == or != comparisons involving a signaling NaN signal
870 # InvalidOperation, and return False or True as above if the
871 # InvalidOperation is not trapped.
872 # <, >, <= and >= comparisons involving a (quiet or signaling)
873 # NaN signal InvalidOperation, and return False if the
874 # InvalidOperation is not trapped.
875 #
876 # This behavior is designed to conform as closely as possible to
877 # that specified by IEEE 754.
878
879 def __eq__(self, other, context=None):
880 self, other = _convert_for_comparison(self, other, equality_op=True)
881 if other is NotImplemented:
882 return other
883 if self._check_nans(other, context):
884 return False
885 return self._cmp(other) == 0
886
Stefan Krahb578f8a2014-09-10 17:58:15 +0200887 def __lt__(self, other, context=None):
888 self, other = _convert_for_comparison(self, other)
889 if other is NotImplemented:
890 return other
891 ans = self._compare_check_nans(other, context)
892 if ans:
893 return False
894 return self._cmp(other) < 0
895
896 def __le__(self, other, context=None):
897 self, other = _convert_for_comparison(self, other)
898 if other is NotImplemented:
899 return other
900 ans = self._compare_check_nans(other, context)
901 if ans:
902 return False
903 return self._cmp(other) <= 0
904
905 def __gt__(self, other, context=None):
906 self, other = _convert_for_comparison(self, other)
907 if other is NotImplemented:
908 return other
909 ans = self._compare_check_nans(other, context)
910 if ans:
911 return False
912 return self._cmp(other) > 0
913
914 def __ge__(self, other, context=None):
915 self, other = _convert_for_comparison(self, other)
916 if other is NotImplemented:
917 return other
918 ans = self._compare_check_nans(other, context)
919 if ans:
920 return False
921 return self._cmp(other) >= 0
922
923 def compare(self, other, context=None):
Serhiy Storchakac2ccce72015-03-12 22:01:30 +0200924 """Compare self to other. Return a decimal value:
Stefan Krahb578f8a2014-09-10 17:58:15 +0200925
Serhiy Storchakac2ccce72015-03-12 22:01:30 +0200926 a or b is a NaN ==> Decimal('NaN')
927 a < b ==> Decimal('-1')
928 a == b ==> Decimal('0')
929 a > b ==> Decimal('1')
Stefan Krahb578f8a2014-09-10 17:58:15 +0200930 """
931 other = _convert_other(other, raiseit=True)
932
933 # Compare(NaN, NaN) = NaN
934 if (self._is_special or other and other._is_special):
935 ans = self._check_nans(other, context)
936 if ans:
937 return ans
938
939 return Decimal(self._cmp(other))
940
941 def __hash__(self):
942 """x.__hash__() <==> hash(x)"""
943
944 # In order to make sure that the hash of a Decimal instance
945 # agrees with the hash of a numerically equal integer, float
946 # or Fraction, we follow the rules for numeric hashes outlined
947 # in the documentation. (See library docs, 'Built-in Types').
948 if self._is_special:
949 if self.is_snan():
950 raise TypeError('Cannot hash a signaling NaN value.')
951 elif self.is_nan():
952 return _PyHASH_NAN
953 else:
954 if self._sign:
955 return -_PyHASH_INF
956 else:
957 return _PyHASH_INF
958
959 if self._exp >= 0:
960 exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
961 else:
962 exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
963 hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
964 ans = hash_ if self >= 0 else -hash_
965 return -2 if ans == -1 else ans
966
967 def as_tuple(self):
968 """Represents the number as a triple tuple.
969
970 To show the internals exactly as they are.
971 """
972 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
973
Stefan Krah53f2e0a2015-12-28 23:02:02 +0100974 def as_integer_ratio(self):
975 """Express a finite Decimal instance in the form n / d.
976
977 Returns a pair (n, d) of integers. When called on an infinity
978 or NaN, raises OverflowError or ValueError respectively.
979
980 >>> Decimal('3.14').as_integer_ratio()
981 (157, 50)
982 >>> Decimal('-123e5').as_integer_ratio()
983 (-12300000, 1)
984 >>> Decimal('0.00').as_integer_ratio()
985 (0, 1)
986
987 """
988 if self._is_special:
989 if self.is_nan():
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +0200990 raise ValueError("cannot convert NaN to integer ratio")
Stefan Krah53f2e0a2015-12-28 23:02:02 +0100991 else:
Serhiy Storchaka0d250bc2015-12-29 22:34:23 +0200992 raise OverflowError("cannot convert Infinity to integer ratio")
Stefan Krah53f2e0a2015-12-28 23:02:02 +0100993
994 if not self:
995 return 0, 1
996
997 # Find n, d in lowest terms such that abs(self) == n / d;
998 # we'll deal with the sign later.
999 n = int(self._int)
1000 if self._exp >= 0:
1001 # self is an integer.
1002 n, d = n * 10**self._exp, 1
1003 else:
1004 # Find d2, d5 such that abs(self) = n / (2**d2 * 5**d5).
1005 d5 = -self._exp
1006 while d5 > 0 and n % 5 == 0:
1007 n //= 5
1008 d5 -= 1
1009
1010 # (n & -n).bit_length() - 1 counts trailing zeros in binary
1011 # representation of n (provided n is nonzero).
1012 d2 = -self._exp
1013 shift2 = min((n & -n).bit_length() - 1, d2)
1014 if shift2:
1015 n >>= shift2
1016 d2 -= shift2
1017
1018 d = 5**d5 << d2
1019
1020 if self._sign:
1021 n = -n
1022 return n, d
1023
Stefan Krahb578f8a2014-09-10 17:58:15 +02001024 def __repr__(self):
1025 """Represents the number as an instance of Decimal."""
1026 # Invariant: eval(repr(d)) == d
1027 return "Decimal('%s')" % str(self)
1028
1029 def __str__(self, eng=False, context=None):
1030 """Return string representation of the number in scientific notation.
1031
1032 Captures all of the information in the underlying representation.
1033 """
1034
1035 sign = ['', '-'][self._sign]
1036 if self._is_special:
1037 if self._exp == 'F':
1038 return sign + 'Infinity'
1039 elif self._exp == 'n':
1040 return sign + 'NaN' + self._int
1041 else: # self._exp == 'N'
1042 return sign + 'sNaN' + self._int
1043
1044 # number of digits of self._int to left of decimal point
1045 leftdigits = self._exp + len(self._int)
1046
1047 # dotplace is number of digits of self._int to the left of the
1048 # decimal point in the mantissa of the output string (that is,
1049 # after adjusting the exponent)
1050 if self._exp <= 0 and leftdigits > -6:
1051 # no exponent required
1052 dotplace = leftdigits
1053 elif not eng:
1054 # usual scientific notation: 1 digit on left of the point
1055 dotplace = 1
1056 elif self._int == '0':
1057 # engineering notation, zero
1058 dotplace = (leftdigits + 1) % 3 - 1
1059 else:
1060 # engineering notation, nonzero
1061 dotplace = (leftdigits - 1) % 3 + 1
1062
1063 if dotplace <= 0:
1064 intpart = '0'
1065 fracpart = '.' + '0'*(-dotplace) + self._int
1066 elif dotplace >= len(self._int):
1067 intpart = self._int+'0'*(dotplace-len(self._int))
1068 fracpart = ''
1069 else:
1070 intpart = self._int[:dotplace]
1071 fracpart = '.' + self._int[dotplace:]
1072 if leftdigits == dotplace:
1073 exp = ''
1074 else:
1075 if context is None:
1076 context = getcontext()
1077 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1078
1079 return sign + intpart + fracpart + exp
1080
1081 def to_eng_string(self, context=None):
Raymond Hettingerf6ffa982016-08-13 11:15:34 -07001082 """Convert to a string, using engineering notation if an exponent is needed.
Stefan Krahb578f8a2014-09-10 17:58:15 +02001083
Raymond Hettingerf6ffa982016-08-13 11:15:34 -07001084 Engineering notation has an exponent which is a multiple of 3. This
1085 can leave up to 3 digits to the left of the decimal place and may
1086 require the addition of either one or two trailing zeros.
Stefan Krahb578f8a2014-09-10 17:58:15 +02001087 """
1088 return self.__str__(eng=True, context=context)
1089
1090 def __neg__(self, context=None):
1091 """Returns a copy with the sign switched.
1092
1093 Rounds, if it has reason.
1094 """
1095 if self._is_special:
1096 ans = self._check_nans(context=context)
1097 if ans:
1098 return ans
1099
1100 if context is None:
1101 context = getcontext()
1102
1103 if not self and context.rounding != ROUND_FLOOR:
1104 # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
1105 # in ROUND_FLOOR rounding mode.
1106 ans = self.copy_abs()
1107 else:
1108 ans = self.copy_negate()
1109
1110 return ans._fix(context)
1111
1112 def __pos__(self, context=None):
1113 """Returns a copy, unless it is a sNaN.
1114
Martin Pantere26da7c2016-06-02 10:07:09 +00001115 Rounds the number (if more than precision digits)
Stefan Krahb578f8a2014-09-10 17:58:15 +02001116 """
1117 if self._is_special:
1118 ans = self._check_nans(context=context)
1119 if ans:
1120 return ans
1121
1122 if context is None:
1123 context = getcontext()
1124
1125 if not self and context.rounding != ROUND_FLOOR:
1126 # + (-0) = 0, except in ROUND_FLOOR rounding mode.
1127 ans = self.copy_abs()
1128 else:
1129 ans = Decimal(self)
1130
1131 return ans._fix(context)
1132
1133 def __abs__(self, round=True, context=None):
1134 """Returns the absolute value of self.
1135
1136 If the keyword argument 'round' is false, do not round. The
1137 expression self.__abs__(round=False) is equivalent to
1138 self.copy_abs().
1139 """
1140 if not round:
1141 return self.copy_abs()
1142
1143 if self._is_special:
1144 ans = self._check_nans(context=context)
1145 if ans:
1146 return ans
1147
1148 if self._sign:
1149 ans = self.__neg__(context=context)
1150 else:
1151 ans = self.__pos__(context=context)
1152
1153 return ans
1154
1155 def __add__(self, other, context=None):
1156 """Returns self + other.
1157
1158 -INF + INF (or the reverse) cause InvalidOperation errors.
1159 """
1160 other = _convert_other(other)
1161 if other is NotImplemented:
1162 return other
1163
1164 if context is None:
1165 context = getcontext()
1166
1167 if self._is_special or other._is_special:
1168 ans = self._check_nans(other, context)
1169 if ans:
1170 return ans
1171
1172 if self._isinfinity():
1173 # If both INF, same sign => same as both, opposite => error.
1174 if self._sign != other._sign and other._isinfinity():
1175 return context._raise_error(InvalidOperation, '-INF + INF')
1176 return Decimal(self)
1177 if other._isinfinity():
1178 return Decimal(other) # Can't both be infinity here
1179
1180 exp = min(self._exp, other._exp)
1181 negativezero = 0
1182 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
1183 # If the answer is 0, the sign should be negative, in this case.
1184 negativezero = 1
1185
1186 if not self and not other:
1187 sign = min(self._sign, other._sign)
1188 if negativezero:
1189 sign = 1
1190 ans = _dec_from_triple(sign, '0', exp)
1191 ans = ans._fix(context)
1192 return ans
1193 if not self:
1194 exp = max(exp, other._exp - context.prec-1)
1195 ans = other._rescale(exp, context.rounding)
1196 ans = ans._fix(context)
1197 return ans
1198 if not other:
1199 exp = max(exp, self._exp - context.prec-1)
1200 ans = self._rescale(exp, context.rounding)
1201 ans = ans._fix(context)
1202 return ans
1203
1204 op1 = _WorkRep(self)
1205 op2 = _WorkRep(other)
1206 op1, op2 = _normalize(op1, op2, context.prec)
1207
1208 result = _WorkRep()
1209 if op1.sign != op2.sign:
1210 # Equal and opposite
1211 if op1.int == op2.int:
1212 ans = _dec_from_triple(negativezero, '0', exp)
1213 ans = ans._fix(context)
1214 return ans
1215 if op1.int < op2.int:
1216 op1, op2 = op2, op1
1217 # OK, now abs(op1) > abs(op2)
1218 if op1.sign == 1:
1219 result.sign = 1
1220 op1.sign, op2.sign = op2.sign, op1.sign
1221 else:
1222 result.sign = 0
1223 # So we know the sign, and op1 > 0.
1224 elif op1.sign == 1:
1225 result.sign = 1
1226 op1.sign, op2.sign = (0, 0)
1227 else:
1228 result.sign = 0
1229 # Now, op1 > abs(op2) > 0
1230
1231 if op2.sign == 0:
1232 result.int = op1.int + op2.int
1233 else:
1234 result.int = op1.int - op2.int
1235
1236 result.exp = op1.exp
1237 ans = Decimal(result)
1238 ans = ans._fix(context)
1239 return ans
1240
1241 __radd__ = __add__
1242
1243 def __sub__(self, other, context=None):
1244 """Return self - other"""
1245 other = _convert_other(other)
1246 if other is NotImplemented:
1247 return other
1248
1249 if self._is_special or other._is_special:
1250 ans = self._check_nans(other, context=context)
1251 if ans:
1252 return ans
1253
1254 # self - other is computed as self + other.copy_negate()
1255 return self.__add__(other.copy_negate(), context=context)
1256
1257 def __rsub__(self, other, context=None):
1258 """Return other - self"""
1259 other = _convert_other(other)
1260 if other is NotImplemented:
1261 return other
1262
1263 return other.__sub__(self, context=context)
1264
1265 def __mul__(self, other, context=None):
1266 """Return self * other.
1267
1268 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1269 """
1270 other = _convert_other(other)
1271 if other is NotImplemented:
1272 return other
1273
1274 if context is None:
1275 context = getcontext()
1276
1277 resultsign = self._sign ^ other._sign
1278
1279 if self._is_special or other._is_special:
1280 ans = self._check_nans(other, context)
1281 if ans:
1282 return ans
1283
1284 if self._isinfinity():
1285 if not other:
1286 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1287 return _SignedInfinity[resultsign]
1288
1289 if other._isinfinity():
1290 if not self:
1291 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1292 return _SignedInfinity[resultsign]
1293
1294 resultexp = self._exp + other._exp
1295
1296 # Special case for multiplying by zero
1297 if not self or not other:
1298 ans = _dec_from_triple(resultsign, '0', resultexp)
1299 # Fixing in case the exponent is out of bounds
1300 ans = ans._fix(context)
1301 return ans
1302
1303 # Special case for multiplying by power of 10
1304 if self._int == '1':
1305 ans = _dec_from_triple(resultsign, other._int, resultexp)
1306 ans = ans._fix(context)
1307 return ans
1308 if other._int == '1':
1309 ans = _dec_from_triple(resultsign, self._int, resultexp)
1310 ans = ans._fix(context)
1311 return ans
1312
1313 op1 = _WorkRep(self)
1314 op2 = _WorkRep(other)
1315
1316 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
1317 ans = ans._fix(context)
1318
1319 return ans
1320 __rmul__ = __mul__
1321
1322 def __truediv__(self, other, context=None):
1323 """Return self / other."""
1324 other = _convert_other(other)
1325 if other is NotImplemented:
1326 return NotImplemented
1327
1328 if context is None:
1329 context = getcontext()
1330
1331 sign = self._sign ^ other._sign
1332
1333 if self._is_special or other._is_special:
1334 ans = self._check_nans(other, context)
1335 if ans:
1336 return ans
1337
1338 if self._isinfinity() and other._isinfinity():
1339 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
1340
1341 if self._isinfinity():
1342 return _SignedInfinity[sign]
1343
1344 if other._isinfinity():
1345 context._raise_error(Clamped, 'Division by infinity')
1346 return _dec_from_triple(sign, '0', context.Etiny())
1347
1348 # Special cases for zeroes
1349 if not other:
1350 if not self:
1351 return context._raise_error(DivisionUndefined, '0 / 0')
1352 return context._raise_error(DivisionByZero, 'x / 0', sign)
1353
1354 if not self:
1355 exp = self._exp - other._exp
1356 coeff = 0
1357 else:
1358 # OK, so neither = 0, INF or NaN
1359 shift = len(other._int) - len(self._int) + context.prec + 1
1360 exp = self._exp - other._exp - shift
1361 op1 = _WorkRep(self)
1362 op2 = _WorkRep(other)
1363 if shift >= 0:
1364 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1365 else:
1366 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1367 if remainder:
1368 # result is not exact; adjust to ensure correct rounding
1369 if coeff % 5 == 0:
1370 coeff += 1
1371 else:
1372 # result is exact; get as close to ideal exponent as possible
1373 ideal_exp = self._exp - other._exp
1374 while exp < ideal_exp and coeff % 10 == 0:
1375 coeff //= 10
1376 exp += 1
1377
1378 ans = _dec_from_triple(sign, str(coeff), exp)
1379 return ans._fix(context)
1380
1381 def _divide(self, other, context):
1382 """Return (self // other, self % other), to context.prec precision.
1383
1384 Assumes that neither self nor other is a NaN, that self is not
1385 infinite and that other is nonzero.
1386 """
1387 sign = self._sign ^ other._sign
1388 if other._isinfinity():
1389 ideal_exp = self._exp
1390 else:
1391 ideal_exp = min(self._exp, other._exp)
1392
1393 expdiff = self.adjusted() - other.adjusted()
1394 if not self or other._isinfinity() or expdiff <= -2:
1395 return (_dec_from_triple(sign, '0', 0),
1396 self._rescale(ideal_exp, context.rounding))
1397 if expdiff <= context.prec:
1398 op1 = _WorkRep(self)
1399 op2 = _WorkRep(other)
1400 if op1.exp >= op2.exp:
1401 op1.int *= 10**(op1.exp - op2.exp)
1402 else:
1403 op2.int *= 10**(op2.exp - op1.exp)
1404 q, r = divmod(op1.int, op2.int)
1405 if q < 10**context.prec:
1406 return (_dec_from_triple(sign, str(q), 0),
1407 _dec_from_triple(self._sign, str(r), ideal_exp))
1408
1409 # Here the quotient is too large to be representable
1410 ans = context._raise_error(DivisionImpossible,
1411 'quotient too large in //, % or divmod')
1412 return ans, ans
1413
1414 def __rtruediv__(self, other, context=None):
1415 """Swaps self/other and returns __truediv__."""
1416 other = _convert_other(other)
1417 if other is NotImplemented:
1418 return other
1419 return other.__truediv__(self, context=context)
1420
1421 def __divmod__(self, other, context=None):
1422 """
1423 Return (self // other, self % other)
1424 """
1425 other = _convert_other(other)
1426 if other is NotImplemented:
1427 return other
1428
1429 if context is None:
1430 context = getcontext()
1431
1432 ans = self._check_nans(other, context)
1433 if ans:
1434 return (ans, ans)
1435
1436 sign = self._sign ^ other._sign
1437 if self._isinfinity():
1438 if other._isinfinity():
1439 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1440 return ans, ans
1441 else:
1442 return (_SignedInfinity[sign],
1443 context._raise_error(InvalidOperation, 'INF % x'))
1444
1445 if not other:
1446 if not self:
1447 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1448 return ans, ans
1449 else:
1450 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1451 context._raise_error(InvalidOperation, 'x % 0'))
1452
1453 quotient, remainder = self._divide(other, context)
1454 remainder = remainder._fix(context)
1455 return quotient, remainder
1456
1457 def __rdivmod__(self, other, context=None):
1458 """Swaps self/other and returns __divmod__."""
1459 other = _convert_other(other)
1460 if other is NotImplemented:
1461 return other
1462 return other.__divmod__(self, context=context)
1463
1464 def __mod__(self, other, context=None):
1465 """
1466 self % other
1467 """
1468 other = _convert_other(other)
1469 if other is NotImplemented:
1470 return other
1471
1472 if context is None:
1473 context = getcontext()
1474
1475 ans = self._check_nans(other, context)
1476 if ans:
1477 return ans
1478
1479 if self._isinfinity():
1480 return context._raise_error(InvalidOperation, 'INF % x')
1481 elif not other:
1482 if self:
1483 return context._raise_error(InvalidOperation, 'x % 0')
1484 else:
1485 return context._raise_error(DivisionUndefined, '0 % 0')
1486
1487 remainder = self._divide(other, context)[1]
1488 remainder = remainder._fix(context)
1489 return remainder
1490
1491 def __rmod__(self, other, context=None):
1492 """Swaps self/other and returns __mod__."""
1493 other = _convert_other(other)
1494 if other is NotImplemented:
1495 return other
1496 return other.__mod__(self, context=context)
1497
1498 def remainder_near(self, other, context=None):
1499 """
1500 Remainder nearest to 0- abs(remainder-near) <= other/2
1501 """
1502 if context is None:
1503 context = getcontext()
1504
1505 other = _convert_other(other, raiseit=True)
1506
1507 ans = self._check_nans(other, context)
1508 if ans:
1509 return ans
1510
1511 # self == +/-infinity -> InvalidOperation
1512 if self._isinfinity():
1513 return context._raise_error(InvalidOperation,
1514 'remainder_near(infinity, x)')
1515
1516 # other == 0 -> either InvalidOperation or DivisionUndefined
1517 if not other:
1518 if self:
1519 return context._raise_error(InvalidOperation,
1520 'remainder_near(x, 0)')
1521 else:
1522 return context._raise_error(DivisionUndefined,
1523 'remainder_near(0, 0)')
1524
1525 # other = +/-infinity -> remainder = self
1526 if other._isinfinity():
1527 ans = Decimal(self)
1528 return ans._fix(context)
1529
1530 # self = 0 -> remainder = self, with ideal exponent
1531 ideal_exponent = min(self._exp, other._exp)
1532 if not self:
1533 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
1534 return ans._fix(context)
1535
1536 # catch most cases of large or small quotient
1537 expdiff = self.adjusted() - other.adjusted()
1538 if expdiff >= context.prec + 1:
1539 # expdiff >= prec+1 => abs(self/other) > 10**prec
1540 return context._raise_error(DivisionImpossible)
1541 if expdiff <= -2:
1542 # expdiff <= -2 => abs(self/other) < 0.1
1543 ans = self._rescale(ideal_exponent, context.rounding)
1544 return ans._fix(context)
1545
1546 # adjust both arguments to have the same exponent, then divide
1547 op1 = _WorkRep(self)
1548 op2 = _WorkRep(other)
1549 if op1.exp >= op2.exp:
1550 op1.int *= 10**(op1.exp - op2.exp)
1551 else:
1552 op2.int *= 10**(op2.exp - op1.exp)
1553 q, r = divmod(op1.int, op2.int)
1554 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1555 # 10**ideal_exponent. Apply correction to ensure that
1556 # abs(remainder) <= abs(other)/2
1557 if 2*r + (q&1) > op2.int:
1558 r -= op2.int
1559 q += 1
1560
1561 if q >= 10**context.prec:
1562 return context._raise_error(DivisionImpossible)
1563
1564 # result has same sign as self unless r is negative
1565 sign = self._sign
1566 if r < 0:
1567 sign = 1-sign
1568 r = -r
1569
1570 ans = _dec_from_triple(sign, str(r), ideal_exponent)
1571 return ans._fix(context)
1572
1573 def __floordiv__(self, other, context=None):
1574 """self // other"""
1575 other = _convert_other(other)
1576 if other is NotImplemented:
1577 return other
1578
1579 if context is None:
1580 context = getcontext()
1581
1582 ans = self._check_nans(other, context)
1583 if ans:
1584 return ans
1585
1586 if self._isinfinity():
1587 if other._isinfinity():
1588 return context._raise_error(InvalidOperation, 'INF // INF')
1589 else:
1590 return _SignedInfinity[self._sign ^ other._sign]
1591
1592 if not other:
1593 if self:
1594 return context._raise_error(DivisionByZero, 'x // 0',
1595 self._sign ^ other._sign)
1596 else:
1597 return context._raise_error(DivisionUndefined, '0 // 0')
1598
1599 return self._divide(other, context)[0]
1600
1601 def __rfloordiv__(self, other, context=None):
1602 """Swaps self/other and returns __floordiv__."""
1603 other = _convert_other(other)
1604 if other is NotImplemented:
1605 return other
1606 return other.__floordiv__(self, context=context)
1607
1608 def __float__(self):
1609 """Float representation."""
1610 if self._isnan():
1611 if self.is_snan():
1612 raise ValueError("Cannot convert signaling NaN to float")
1613 s = "-nan" if self._sign else "nan"
1614 else:
1615 s = str(self)
1616 return float(s)
1617
1618 def __int__(self):
1619 """Converts self to an int, truncating if necessary."""
1620 if self._is_special:
1621 if self._isnan():
1622 raise ValueError("Cannot convert NaN to integer")
1623 elif self._isinfinity():
1624 raise OverflowError("Cannot convert infinity to integer")
1625 s = (-1)**self._sign
1626 if self._exp >= 0:
1627 return s*int(self._int)*10**self._exp
1628 else:
1629 return s*int(self._int[:self._exp] or '0')
1630
1631 __trunc__ = __int__
1632
Serhiy Storchakabdf6b912017-03-19 08:40:32 +02001633 @property
Stefan Krahb578f8a2014-09-10 17:58:15 +02001634 def real(self):
1635 return self
Stefan Krahb578f8a2014-09-10 17:58:15 +02001636
Serhiy Storchakabdf6b912017-03-19 08:40:32 +02001637 @property
Stefan Krahb578f8a2014-09-10 17:58:15 +02001638 def imag(self):
1639 return Decimal(0)
Stefan Krahb578f8a2014-09-10 17:58:15 +02001640
1641 def conjugate(self):
1642 return self
1643
1644 def __complex__(self):
1645 return complex(float(self))
1646
1647 def _fix_nan(self, context):
1648 """Decapitate the payload of a NaN to fit the context"""
1649 payload = self._int
1650
1651 # maximum length of payload is precision if clamp=0,
1652 # precision-1 if clamp=1.
1653 max_payload_len = context.prec - context.clamp
1654 if len(payload) > max_payload_len:
1655 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1656 return _dec_from_triple(self._sign, payload, self._exp, True)
1657 return Decimal(self)
1658
1659 def _fix(self, context):
1660 """Round if it is necessary to keep self within prec precision.
1661
1662 Rounds and fixes the exponent. Does not raise on a sNaN.
1663
1664 Arguments:
1665 self - Decimal instance
1666 context - context used.
1667 """
1668
1669 if self._is_special:
1670 if self._isnan():
1671 # decapitate payload if necessary
1672 return self._fix_nan(context)
1673 else:
1674 # self is +/-Infinity; return unaltered
1675 return Decimal(self)
1676
1677 # if self is zero then exponent should be between Etiny and
1678 # Emax if clamp==0, and between Etiny and Etop if clamp==1.
1679 Etiny = context.Etiny()
1680 Etop = context.Etop()
1681 if not self:
1682 exp_max = [context.Emax, Etop][context.clamp]
1683 new_exp = min(max(self._exp, Etiny), exp_max)
1684 if new_exp != self._exp:
1685 context._raise_error(Clamped)
1686 return _dec_from_triple(self._sign, '0', new_exp)
1687 else:
1688 return Decimal(self)
1689
1690 # exp_min is the smallest allowable exponent of the result,
1691 # equal to max(self.adjusted()-context.prec+1, Etiny)
1692 exp_min = len(self._int) + self._exp - context.prec
1693 if exp_min > Etop:
1694 # overflow: exp_min > Etop iff self.adjusted() > Emax
1695 ans = context._raise_error(Overflow, 'above Emax', self._sign)
1696 context._raise_error(Inexact)
1697 context._raise_error(Rounded)
1698 return ans
1699
1700 self_is_subnormal = exp_min < Etiny
1701 if self_is_subnormal:
1702 exp_min = Etiny
1703
1704 # round if self has too many digits
1705 if self._exp < exp_min:
1706 digits = len(self._int) + self._exp - exp_min
1707 if digits < 0:
1708 self = _dec_from_triple(self._sign, '1', exp_min-1)
1709 digits = 0
1710 rounding_method = self._pick_rounding_function[context.rounding]
1711 changed = rounding_method(self, digits)
1712 coeff = self._int[:digits] or '0'
1713 if changed > 0:
1714 coeff = str(int(coeff)+1)
1715 if len(coeff) > context.prec:
1716 coeff = coeff[:-1]
1717 exp_min += 1
1718
1719 # check whether the rounding pushed the exponent out of range
1720 if exp_min > Etop:
1721 ans = context._raise_error(Overflow, 'above Emax', self._sign)
1722 else:
1723 ans = _dec_from_triple(self._sign, coeff, exp_min)
1724
1725 # raise the appropriate signals, taking care to respect
1726 # the precedence described in the specification
1727 if changed and self_is_subnormal:
1728 context._raise_error(Underflow)
1729 if self_is_subnormal:
1730 context._raise_error(Subnormal)
1731 if changed:
1732 context._raise_error(Inexact)
1733 context._raise_error(Rounded)
1734 if not ans:
1735 # raise Clamped on underflow to 0
1736 context._raise_error(Clamped)
1737 return ans
1738
1739 if self_is_subnormal:
1740 context._raise_error(Subnormal)
1741
1742 # fold down if clamp == 1 and self has too few digits
1743 if context.clamp == 1 and self._exp > Etop:
1744 context._raise_error(Clamped)
1745 self_padded = self._int + '0'*(self._exp - Etop)
1746 return _dec_from_triple(self._sign, self_padded, Etop)
1747
1748 # here self was representable to begin with; return unchanged
1749 return Decimal(self)
1750
1751 # for each of the rounding functions below:
1752 # self is a finite, nonzero Decimal
1753 # prec is an integer satisfying 0 <= prec < len(self._int)
1754 #
1755 # each function returns either -1, 0, or 1, as follows:
1756 # 1 indicates that self should be rounded up (away from zero)
1757 # 0 indicates that self should be truncated, and that all the
1758 # digits to be truncated are zeros (so the value is unchanged)
1759 # -1 indicates that there are nonzero digits to be truncated
1760
1761 def _round_down(self, prec):
1762 """Also known as round-towards-0, truncate."""
1763 if _all_zeros(self._int, prec):
1764 return 0
1765 else:
1766 return -1
1767
1768 def _round_up(self, prec):
1769 """Rounds away from 0."""
1770 return -self._round_down(prec)
1771
1772 def _round_half_up(self, prec):
1773 """Rounds 5 up (away from 0)"""
1774 if self._int[prec] in '56789':
1775 return 1
1776 elif _all_zeros(self._int, prec):
1777 return 0
1778 else:
1779 return -1
1780
1781 def _round_half_down(self, prec):
1782 """Round 5 down"""
1783 if _exact_half(self._int, prec):
1784 return -1
1785 else:
1786 return self._round_half_up(prec)
1787
1788 def _round_half_even(self, prec):
1789 """Round 5 to even, rest to nearest."""
1790 if _exact_half(self._int, prec) and \
1791 (prec == 0 or self._int[prec-1] in '02468'):
1792 return -1
1793 else:
1794 return self._round_half_up(prec)
1795
1796 def _round_ceiling(self, prec):
1797 """Rounds up (not away from 0 if negative.)"""
1798 if self._sign:
1799 return self._round_down(prec)
1800 else:
1801 return -self._round_down(prec)
1802
1803 def _round_floor(self, prec):
1804 """Rounds down (not towards 0 if negative)"""
1805 if not self._sign:
1806 return self._round_down(prec)
1807 else:
1808 return -self._round_down(prec)
1809
1810 def _round_05up(self, prec):
1811 """Round down unless digit prec-1 is 0 or 5."""
1812 if prec and self._int[prec-1] not in '05':
1813 return self._round_down(prec)
1814 else:
1815 return -self._round_down(prec)
1816
1817 _pick_rounding_function = dict(
1818 ROUND_DOWN = _round_down,
1819 ROUND_UP = _round_up,
1820 ROUND_HALF_UP = _round_half_up,
1821 ROUND_HALF_DOWN = _round_half_down,
1822 ROUND_HALF_EVEN = _round_half_even,
1823 ROUND_CEILING = _round_ceiling,
1824 ROUND_FLOOR = _round_floor,
1825 ROUND_05UP = _round_05up,
1826 )
1827
1828 def __round__(self, n=None):
1829 """Round self to the nearest integer, or to a given precision.
1830
1831 If only one argument is supplied, round a finite Decimal
1832 instance self to the nearest integer. If self is infinite or
1833 a NaN then a Python exception is raised. If self is finite
1834 and lies exactly halfway between two integers then it is
1835 rounded to the integer with even last digit.
1836
1837 >>> round(Decimal('123.456'))
1838 123
1839 >>> round(Decimal('-456.789'))
1840 -457
1841 >>> round(Decimal('-3.0'))
1842 -3
1843 >>> round(Decimal('2.5'))
1844 2
1845 >>> round(Decimal('3.5'))
1846 4
1847 >>> round(Decimal('Inf'))
1848 Traceback (most recent call last):
1849 ...
1850 OverflowError: cannot round an infinity
1851 >>> round(Decimal('NaN'))
1852 Traceback (most recent call last):
1853 ...
1854 ValueError: cannot round a NaN
1855
1856 If a second argument n is supplied, self is rounded to n
1857 decimal places using the rounding mode for the current
1858 context.
1859
1860 For an integer n, round(self, -n) is exactly equivalent to
1861 self.quantize(Decimal('1En')).
1862
1863 >>> round(Decimal('123.456'), 0)
1864 Decimal('123')
1865 >>> round(Decimal('123.456'), 2)
1866 Decimal('123.46')
1867 >>> round(Decimal('123.456'), -2)
1868 Decimal('1E+2')
1869 >>> round(Decimal('-Infinity'), 37)
1870 Decimal('NaN')
1871 >>> round(Decimal('sNaN123'), 0)
1872 Decimal('NaN123')
1873
1874 """
1875 if n is not None:
1876 # two-argument form: use the equivalent quantize call
1877 if not isinstance(n, int):
1878 raise TypeError('Second argument to round should be integral')
1879 exp = _dec_from_triple(0, '1', -n)
1880 return self.quantize(exp)
1881
1882 # one-argument form
1883 if self._is_special:
1884 if self.is_nan():
1885 raise ValueError("cannot round a NaN")
1886 else:
1887 raise OverflowError("cannot round an infinity")
1888 return int(self._rescale(0, ROUND_HALF_EVEN))
1889
1890 def __floor__(self):
1891 """Return the floor of self, as an integer.
1892
1893 For a finite Decimal instance self, return the greatest
1894 integer n such that n <= self. If self is infinite or a NaN
1895 then a Python exception is raised.
1896
1897 """
1898 if self._is_special:
1899 if self.is_nan():
1900 raise ValueError("cannot round a NaN")
1901 else:
1902 raise OverflowError("cannot round an infinity")
1903 return int(self._rescale(0, ROUND_FLOOR))
1904
1905 def __ceil__(self):
1906 """Return the ceiling of self, as an integer.
1907
1908 For a finite Decimal instance self, return the least integer n
1909 such that n >= self. If self is infinite or a NaN then a
1910 Python exception is raised.
1911
1912 """
1913 if self._is_special:
1914 if self.is_nan():
1915 raise ValueError("cannot round a NaN")
1916 else:
1917 raise OverflowError("cannot round an infinity")
1918 return int(self._rescale(0, ROUND_CEILING))
1919
1920 def fma(self, other, third, context=None):
1921 """Fused multiply-add.
1922
1923 Returns self*other+third with no rounding of the intermediate
1924 product self*other.
1925
1926 self and other are multiplied together, with no rounding of
1927 the result. The third operand is then added to the result,
1928 and a single final rounding is performed.
1929 """
1930
1931 other = _convert_other(other, raiseit=True)
1932 third = _convert_other(third, raiseit=True)
1933
1934 # compute product; raise InvalidOperation if either operand is
1935 # a signaling NaN or if the product is zero times infinity.
1936 if self._is_special or other._is_special:
1937 if context is None:
1938 context = getcontext()
1939 if self._exp == 'N':
1940 return context._raise_error(InvalidOperation, 'sNaN', self)
1941 if other._exp == 'N':
1942 return context._raise_error(InvalidOperation, 'sNaN', other)
1943 if self._exp == 'n':
1944 product = self
1945 elif other._exp == 'n':
1946 product = other
1947 elif self._exp == 'F':
1948 if not other:
1949 return context._raise_error(InvalidOperation,
1950 'INF * 0 in fma')
1951 product = _SignedInfinity[self._sign ^ other._sign]
1952 elif other._exp == 'F':
1953 if not self:
1954 return context._raise_error(InvalidOperation,
1955 '0 * INF in fma')
1956 product = _SignedInfinity[self._sign ^ other._sign]
1957 else:
1958 product = _dec_from_triple(self._sign ^ other._sign,
1959 str(int(self._int) * int(other._int)),
1960 self._exp + other._exp)
1961
1962 return product.__add__(third, context)
1963
1964 def _power_modulo(self, other, modulo, context=None):
1965 """Three argument version of __pow__"""
1966
1967 other = _convert_other(other)
1968 if other is NotImplemented:
1969 return other
1970 modulo = _convert_other(modulo)
1971 if modulo is NotImplemented:
1972 return modulo
1973
1974 if context is None:
1975 context = getcontext()
1976
1977 # deal with NaNs: if there are any sNaNs then first one wins,
1978 # (i.e. behaviour for NaNs is identical to that of fma)
1979 self_is_nan = self._isnan()
1980 other_is_nan = other._isnan()
1981 modulo_is_nan = modulo._isnan()
1982 if self_is_nan or other_is_nan or modulo_is_nan:
1983 if self_is_nan == 2:
1984 return context._raise_error(InvalidOperation, 'sNaN',
1985 self)
1986 if other_is_nan == 2:
1987 return context._raise_error(InvalidOperation, 'sNaN',
1988 other)
1989 if modulo_is_nan == 2:
1990 return context._raise_error(InvalidOperation, 'sNaN',
1991 modulo)
1992 if self_is_nan:
1993 return self._fix_nan(context)
1994 if other_is_nan:
1995 return other._fix_nan(context)
1996 return modulo._fix_nan(context)
1997
1998 # check inputs: we apply same restrictions as Python's pow()
1999 if not (self._isinteger() and
2000 other._isinteger() and
2001 modulo._isinteger()):
2002 return context._raise_error(InvalidOperation,
2003 'pow() 3rd argument not allowed '
2004 'unless all arguments are integers')
2005 if other < 0:
2006 return context._raise_error(InvalidOperation,
2007 'pow() 2nd argument cannot be '
2008 'negative when 3rd argument specified')
2009 if not modulo:
2010 return context._raise_error(InvalidOperation,
2011 'pow() 3rd argument cannot be 0')
2012
2013 # additional restriction for decimal: the modulus must be less
2014 # than 10**prec in absolute value
2015 if modulo.adjusted() >= context.prec:
2016 return context._raise_error(InvalidOperation,
2017 'insufficient precision: pow() 3rd '
2018 'argument must not have more than '
2019 'precision digits')
2020
2021 # define 0**0 == NaN, for consistency with two-argument pow
2022 # (even though it hurts!)
2023 if not other and not self:
2024 return context._raise_error(InvalidOperation,
2025 'at least one of pow() 1st argument '
2026 'and 2nd argument must be nonzero ;'
2027 '0**0 is not defined')
2028
2029 # compute sign of result
2030 if other._iseven():
2031 sign = 0
2032 else:
2033 sign = self._sign
2034
2035 # convert modulo to a Python integer, and self and other to
2036 # Decimal integers (i.e. force their exponents to be >= 0)
2037 modulo = abs(int(modulo))
2038 base = _WorkRep(self.to_integral_value())
2039 exponent = _WorkRep(other.to_integral_value())
2040
2041 # compute result using integer pow()
2042 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
2043 for i in range(exponent.exp):
2044 base = pow(base, 10, modulo)
2045 base = pow(base, exponent.int, modulo)
2046
2047 return _dec_from_triple(sign, str(base), 0)
2048
2049 def _power_exact(self, other, p):
2050 """Attempt to compute self**other exactly.
2051
2052 Given Decimals self and other and an integer p, attempt to
2053 compute an exact result for the power self**other, with p
2054 digits of precision. Return None if self**other is not
2055 exactly representable in p digits.
2056
2057 Assumes that elimination of special cases has already been
2058 performed: self and other must both be nonspecial; self must
2059 be positive and not numerically equal to 1; other must be
2060 nonzero. For efficiency, other._exp should not be too large,
2061 so that 10**abs(other._exp) is a feasible calculation."""
2062
2063 # In the comments below, we write x for the value of self and y for the
2064 # value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
2065 # and yc positive integers not divisible by 10.
2066
2067 # The main purpose of this method is to identify the *failure*
2068 # of x**y to be exactly representable with as little effort as
2069 # possible. So we look for cheap and easy tests that
2070 # eliminate the possibility of x**y being exact. Only if all
2071 # these tests are passed do we go on to actually compute x**y.
2072
2073 # Here's the main idea. Express y as a rational number m/n, with m and
2074 # n relatively prime and n>0. Then for x**y to be exactly
2075 # representable (at *any* precision), xc must be the nth power of a
2076 # positive integer and xe must be divisible by n. If y is negative
2077 # then additionally xc must be a power of either 2 or 5, hence a power
2078 # of 2**n or 5**n.
2079 #
2080 # There's a limit to how small |y| can be: if y=m/n as above
2081 # then:
2082 #
2083 # (1) if xc != 1 then for the result to be representable we
2084 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2085 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2086 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
2087 # representable.
2088 #
2089 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2090 # |y| < 1/|xe| then the result is not representable.
2091 #
2092 # Note that since x is not equal to 1, at least one of (1) and
2093 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2094 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2095 #
2096 # There's also a limit to how large y can be, at least if it's
2097 # positive: the normalized result will have coefficient xc**y,
2098 # so if it's representable then xc**y < 10**p, and y <
2099 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
2100 # not exactly representable.
2101
2102 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2103 # so |y| < 1/xe and the result is not representable.
2104 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2105 # < 1/nbits(xc).
2106
2107 x = _WorkRep(self)
2108 xc, xe = x.int, x.exp
2109 while xc % 10 == 0:
2110 xc //= 10
2111 xe += 1
2112
2113 y = _WorkRep(other)
2114 yc, ye = y.int, y.exp
2115 while yc % 10 == 0:
2116 yc //= 10
2117 ye += 1
2118
2119 # case where xc == 1: result is 10**(xe*y), with xe*y
2120 # required to be an integer
2121 if xc == 1:
2122 xe *= yc
2123 # result is now 10**(xe * 10**ye); xe * 10**ye must be integral
2124 while xe % 10 == 0:
2125 xe //= 10
2126 ye += 1
2127 if ye < 0:
2128 return None
2129 exponent = xe * 10**ye
2130 if y.sign == 1:
2131 exponent = -exponent
2132 # if other is a nonnegative integer, use ideal exponent
2133 if other._isinteger() and other._sign == 0:
2134 ideal_exponent = self._exp*int(other)
2135 zeros = min(exponent-ideal_exponent, p-1)
2136 else:
2137 zeros = 0
2138 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
2139
2140 # case where y is negative: xc must be either a power
2141 # of 2 or a power of 5.
2142 if y.sign == 1:
2143 last_digit = xc % 10
2144 if last_digit in (2,4,6,8):
2145 # quick test for power of 2
2146 if xc & -xc != xc:
2147 return None
2148 # now xc is a power of 2; e is its exponent
2149 e = _nbits(xc)-1
2150
2151 # We now have:
2152 #
2153 # x = 2**e * 10**xe, e > 0, and y < 0.
2154 #
2155 # The exact result is:
2156 #
2157 # x**y = 5**(-e*y) * 10**(e*y + xe*y)
2158 #
2159 # provided that both e*y and xe*y are integers. Note that if
2160 # 5**(-e*y) >= 10**p, then the result can't be expressed
2161 # exactly with p digits of precision.
2162 #
2163 # Using the above, we can guard against large values of ye.
2164 # 93/65 is an upper bound for log(10)/log(5), so if
2165 #
2166 # ye >= len(str(93*p//65))
2167 #
2168 # then
2169 #
2170 # -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
2171 #
2172 # so 5**(-e*y) >= 10**p, and the coefficient of the result
2173 # can't be expressed in p digits.
2174
2175 # emax >= largest e such that 5**e < 10**p.
2176 emax = p*93//65
2177 if ye >= len(str(emax)):
2178 return None
2179
2180 # Find -e*y and -xe*y; both must be integers
2181 e = _decimal_lshift_exact(e * yc, ye)
2182 xe = _decimal_lshift_exact(xe * yc, ye)
2183 if e is None or xe is None:
2184 return None
2185
2186 if e > emax:
2187 return None
2188 xc = 5**e
2189
2190 elif last_digit == 5:
2191 # e >= log_5(xc) if xc is a power of 5; we have
2192 # equality all the way up to xc=5**2658
2193 e = _nbits(xc)*28//65
2194 xc, remainder = divmod(5**e, xc)
2195 if remainder:
2196 return None
2197 while xc % 5 == 0:
2198 xc //= 5
2199 e -= 1
2200
2201 # Guard against large values of ye, using the same logic as in
2202 # the 'xc is a power of 2' branch. 10/3 is an upper bound for
2203 # log(10)/log(2).
2204 emax = p*10//3
2205 if ye >= len(str(emax)):
2206 return None
2207
2208 e = _decimal_lshift_exact(e * yc, ye)
2209 xe = _decimal_lshift_exact(xe * yc, ye)
2210 if e is None or xe is None:
2211 return None
2212
2213 if e > emax:
2214 return None
2215 xc = 2**e
2216 else:
2217 return None
2218
2219 if xc >= 10**p:
2220 return None
2221 xe = -e-xe
2222 return _dec_from_triple(0, str(xc), xe)
2223
2224 # now y is positive; find m and n such that y = m/n
2225 if ye >= 0:
2226 m, n = yc*10**ye, 1
2227 else:
2228 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2229 return None
2230 xc_bits = _nbits(xc)
2231 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2232 return None
2233 m, n = yc, 10**(-ye)
2234 while m % 2 == n % 2 == 0:
2235 m //= 2
2236 n //= 2
2237 while m % 5 == n % 5 == 0:
2238 m //= 5
2239 n //= 5
2240
2241 # compute nth root of xc*10**xe
2242 if n > 1:
2243 # if 1 < xc < 2**n then xc isn't an nth power
2244 if xc != 1 and xc_bits <= n:
2245 return None
2246
2247 xe, rem = divmod(xe, n)
2248 if rem != 0:
2249 return None
2250
2251 # compute nth root of xc using Newton's method
2252 a = 1 << -(-_nbits(xc)//n) # initial estimate
2253 while True:
2254 q, r = divmod(xc, a**(n-1))
2255 if a <= q:
2256 break
2257 else:
2258 a = (a*(n-1) + q)//n
2259 if not (a == q and r == 0):
2260 return None
2261 xc = a
2262
2263 # now xc*10**xe is the nth root of the original xc*10**xe
2264 # compute mth power of xc*10**xe
2265
2266 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2267 # 10**p and the result is not representable.
2268 if xc > 1 and m > p*100//_log10_lb(xc):
2269 return None
2270 xc = xc**m
2271 xe *= m
2272 if xc > 10**p:
2273 return None
2274
2275 # by this point the result *is* exactly representable
2276 # adjust the exponent to get as close as possible to the ideal
2277 # exponent, if necessary
2278 str_xc = str(xc)
2279 if other._isinteger() and other._sign == 0:
2280 ideal_exponent = self._exp*int(other)
2281 zeros = min(xe-ideal_exponent, p-len(str_xc))
2282 else:
2283 zeros = 0
2284 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
2285
2286 def __pow__(self, other, modulo=None, context=None):
2287 """Return self ** other [ % modulo].
2288
2289 With two arguments, compute self**other.
2290
2291 With three arguments, compute (self**other) % modulo. For the
2292 three argument form, the following restrictions on the
2293 arguments hold:
2294
2295 - all three arguments must be integral
2296 - other must be nonnegative
2297 - either self or other (or both) must be nonzero
2298 - modulo must be nonzero and must have at most p digits,
2299 where p is the context precision.
2300
2301 If any of these restrictions is violated the InvalidOperation
2302 flag is raised.
2303
2304 The result of pow(self, other, modulo) is identical to the
2305 result that would be obtained by computing (self**other) %
2306 modulo with unbounded precision, but is computed more
2307 efficiently. It is always exact.
2308 """
2309
2310 if modulo is not None:
2311 return self._power_modulo(other, modulo, context)
2312
2313 other = _convert_other(other)
2314 if other is NotImplemented:
2315 return other
2316
2317 if context is None:
2318 context = getcontext()
2319
2320 # either argument is a NaN => result is NaN
2321 ans = self._check_nans(other, context)
2322 if ans:
2323 return ans
2324
2325 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2326 if not other:
2327 if not self:
2328 return context._raise_error(InvalidOperation, '0 ** 0')
2329 else:
2330 return _One
2331
2332 # result has sign 1 iff self._sign is 1 and other is an odd integer
2333 result_sign = 0
2334 if self._sign == 1:
2335 if other._isinteger():
2336 if not other._iseven():
2337 result_sign = 1
2338 else:
2339 # -ve**noninteger = NaN
2340 # (-0)**noninteger = 0**noninteger
2341 if self:
2342 return context._raise_error(InvalidOperation,
2343 'x ** y with x negative and y not an integer')
2344 # negate self, without doing any unwanted rounding
2345 self = self.copy_negate()
2346
2347 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2348 if not self:
2349 if other._sign == 0:
2350 return _dec_from_triple(result_sign, '0', 0)
2351 else:
2352 return _SignedInfinity[result_sign]
2353
2354 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2355 if self._isinfinity():
2356 if other._sign == 0:
2357 return _SignedInfinity[result_sign]
2358 else:
2359 return _dec_from_triple(result_sign, '0', 0)
2360
2361 # 1**other = 1, but the choice of exponent and the flags
2362 # depend on the exponent of self, and on whether other is a
2363 # positive integer, a negative integer, or neither
2364 if self == _One:
2365 if other._isinteger():
2366 # exp = max(self._exp*max(int(other), 0),
2367 # 1-context.prec) but evaluating int(other) directly
2368 # is dangerous until we know other is small (other
2369 # could be 1e999999999)
2370 if other._sign == 1:
2371 multiplier = 0
2372 elif other > context.prec:
2373 multiplier = context.prec
2374 else:
2375 multiplier = int(other)
2376
2377 exp = self._exp * multiplier
2378 if exp < 1-context.prec:
2379 exp = 1-context.prec
2380 context._raise_error(Rounded)
2381 else:
2382 context._raise_error(Inexact)
2383 context._raise_error(Rounded)
2384 exp = 1-context.prec
2385
2386 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
2387
2388 # compute adjusted exponent of self
2389 self_adj = self.adjusted()
2390
2391 # self ** infinity is infinity if self > 1, 0 if self < 1
2392 # self ** -infinity is infinity if self < 1, 0 if self > 1
2393 if other._isinfinity():
2394 if (other._sign == 0) == (self_adj < 0):
2395 return _dec_from_triple(result_sign, '0', 0)
2396 else:
2397 return _SignedInfinity[result_sign]
2398
2399 # from here on, the result always goes through the call
2400 # to _fix at the end of this function.
2401 ans = None
2402 exact = False
2403
2404 # crude test to catch cases of extreme overflow/underflow. If
2405 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2406 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2407 # self**other >= 10**(Emax+1), so overflow occurs. The test
2408 # for underflow is similar.
2409 bound = self._log10_exp_bound() + other.adjusted()
2410 if (self_adj >= 0) == (other._sign == 0):
2411 # self > 1 and other +ve, or self < 1 and other -ve
2412 # possibility of overflow
2413 if bound >= len(str(context.Emax)):
2414 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
2415 else:
2416 # self > 1 and other -ve, or self < 1 and other +ve
2417 # possibility of underflow to 0
2418 Etiny = context.Etiny()
2419 if bound >= len(str(-Etiny)):
2420 ans = _dec_from_triple(result_sign, '1', Etiny-1)
2421
2422 # try for an exact result with precision +1
2423 if ans is None:
2424 ans = self._power_exact(other, context.prec + 1)
2425 if ans is not None:
2426 if result_sign == 1:
2427 ans = _dec_from_triple(1, ans._int, ans._exp)
2428 exact = True
2429
2430 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2431 if ans is None:
2432 p = context.prec
2433 x = _WorkRep(self)
2434 xc, xe = x.int, x.exp
2435 y = _WorkRep(other)
2436 yc, ye = y.int, y.exp
2437 if y.sign == 1:
2438 yc = -yc
2439
2440 # compute correctly rounded result: start with precision +3,
2441 # then increase precision until result is unambiguously roundable
2442 extra = 3
2443 while True:
2444 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2445 if coeff % (5*10**(len(str(coeff))-p-1)):
2446 break
2447 extra += 3
2448
2449 ans = _dec_from_triple(result_sign, str(coeff), exp)
2450
2451 # unlike exp, ln and log10, the power function respects the
2452 # rounding mode; no need to switch to ROUND_HALF_EVEN here
2453
2454 # There's a difficulty here when 'other' is not an integer and
2455 # the result is exact. In this case, the specification
2456 # requires that the Inexact flag be raised (in spite of
2457 # exactness), but since the result is exact _fix won't do this
2458 # for us. (Correspondingly, the Underflow signal should also
2459 # be raised for subnormal results.) We can't directly raise
2460 # these signals either before or after calling _fix, since
2461 # that would violate the precedence for signals. So we wrap
2462 # the ._fix call in a temporary context, and reraise
2463 # afterwards.
2464 if exact and not other._isinteger():
2465 # pad with zeros up to length context.prec+1 if necessary; this
2466 # ensures that the Rounded signal will be raised.
2467 if len(ans._int) <= context.prec:
2468 expdiff = context.prec + 1 - len(ans._int)
2469 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2470 ans._exp-expdiff)
2471
2472 # create a copy of the current context, with cleared flags/traps
2473 newcontext = context.copy()
2474 newcontext.clear_flags()
2475 for exception in _signals:
2476 newcontext.traps[exception] = 0
2477
2478 # round in the new context
2479 ans = ans._fix(newcontext)
2480
2481 # raise Inexact, and if necessary, Underflow
2482 newcontext._raise_error(Inexact)
2483 if newcontext.flags[Subnormal]:
2484 newcontext._raise_error(Underflow)
2485
2486 # propagate signals to the original context; _fix could
2487 # have raised any of Overflow, Underflow, Subnormal,
2488 # Inexact, Rounded, Clamped. Overflow needs the correct
2489 # arguments. Note that the order of the exceptions is
2490 # important here.
2491 if newcontext.flags[Overflow]:
2492 context._raise_error(Overflow, 'above Emax', ans._sign)
2493 for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
2494 if newcontext.flags[exception]:
2495 context._raise_error(exception)
2496
2497 else:
2498 ans = ans._fix(context)
2499
2500 return ans
2501
2502 def __rpow__(self, other, context=None):
2503 """Swaps self/other and returns __pow__."""
2504 other = _convert_other(other)
2505 if other is NotImplemented:
2506 return other
2507 return other.__pow__(self, context=context)
2508
2509 def normalize(self, context=None):
2510 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2511
2512 if context is None:
2513 context = getcontext()
2514
2515 if self._is_special:
2516 ans = self._check_nans(context=context)
2517 if ans:
2518 return ans
2519
2520 dup = self._fix(context)
2521 if dup._isinfinity():
2522 return dup
2523
2524 if not dup:
2525 return _dec_from_triple(dup._sign, '0', 0)
2526 exp_max = [context.Emax, context.Etop()][context.clamp]
2527 end = len(dup._int)
2528 exp = dup._exp
2529 while dup._int[end-1] == '0' and exp < exp_max:
2530 exp += 1
2531 end -= 1
2532 return _dec_from_triple(dup._sign, dup._int[:end], exp)
2533
2534 def quantize(self, exp, rounding=None, context=None):
2535 """Quantize self so its exponent is the same as that of exp.
2536
2537 Similar to self._rescale(exp._exp) but with error checking.
2538 """
2539 exp = _convert_other(exp, raiseit=True)
2540
2541 if context is None:
2542 context = getcontext()
2543 if rounding is None:
2544 rounding = context.rounding
2545
2546 if self._is_special or exp._is_special:
2547 ans = self._check_nans(exp, context)
2548 if ans:
2549 return ans
2550
2551 if exp._isinfinity() or self._isinfinity():
2552 if exp._isinfinity() and self._isinfinity():
2553 return Decimal(self) # if both are inf, it is OK
2554 return context._raise_error(InvalidOperation,
2555 'quantize with one INF')
2556
2557 # exp._exp should be between Etiny and Emax
2558 if not (context.Etiny() <= exp._exp <= context.Emax):
2559 return context._raise_error(InvalidOperation,
2560 'target exponent out of bounds in quantize')
2561
2562 if not self:
2563 ans = _dec_from_triple(self._sign, '0', exp._exp)
2564 return ans._fix(context)
2565
2566 self_adjusted = self.adjusted()
2567 if self_adjusted > context.Emax:
2568 return context._raise_error(InvalidOperation,
2569 'exponent of quantize result too large for current context')
2570 if self_adjusted - exp._exp + 1 > context.prec:
2571 return context._raise_error(InvalidOperation,
2572 'quantize result has too many digits for current context')
2573
2574 ans = self._rescale(exp._exp, rounding)
2575 if ans.adjusted() > context.Emax:
2576 return context._raise_error(InvalidOperation,
2577 'exponent of quantize result too large for current context')
2578 if len(ans._int) > context.prec:
2579 return context._raise_error(InvalidOperation,
2580 'quantize result has too many digits for current context')
2581
2582 # raise appropriate flags
2583 if ans and ans.adjusted() < context.Emin:
2584 context._raise_error(Subnormal)
2585 if ans._exp > self._exp:
2586 if ans != self:
2587 context._raise_error(Inexact)
2588 context._raise_error(Rounded)
2589
2590 # call to fix takes care of any necessary folddown, and
2591 # signals Clamped if necessary
2592 ans = ans._fix(context)
2593 return ans
2594
2595 def same_quantum(self, other, context=None):
2596 """Return True if self and other have the same exponent; otherwise
2597 return False.
2598
2599 If either operand is a special value, the following rules are used:
2600 * return True if both operands are infinities
2601 * return True if both operands are NaNs
2602 * otherwise, return False.
2603 """
2604 other = _convert_other(other, raiseit=True)
2605 if self._is_special or other._is_special:
2606 return (self.is_nan() and other.is_nan() or
2607 self.is_infinite() and other.is_infinite())
2608 return self._exp == other._exp
2609
2610 def _rescale(self, exp, rounding):
2611 """Rescale self so that the exponent is exp, either by padding with zeros
2612 or by truncating digits, using the given rounding mode.
2613
2614 Specials are returned without change. This operation is
2615 quiet: it raises no flags, and uses no information from the
2616 context.
2617
2618 exp = exp to scale to (an integer)
2619 rounding = rounding mode
2620 """
2621 if self._is_special:
2622 return Decimal(self)
2623 if not self:
2624 return _dec_from_triple(self._sign, '0', exp)
2625
2626 if self._exp >= exp:
2627 # pad answer with zeros if necessary
2628 return _dec_from_triple(self._sign,
2629 self._int + '0'*(self._exp - exp), exp)
2630
2631 # too many digits; round and lose data. If self.adjusted() <
2632 # exp-1, replace self by 10**(exp-1) before rounding
2633 digits = len(self._int) + self._exp - exp
2634 if digits < 0:
2635 self = _dec_from_triple(self._sign, '1', exp-1)
2636 digits = 0
2637 this_function = self._pick_rounding_function[rounding]
2638 changed = this_function(self, digits)
2639 coeff = self._int[:digits] or '0'
2640 if changed == 1:
2641 coeff = str(int(coeff)+1)
2642 return _dec_from_triple(self._sign, coeff, exp)
2643
2644 def _round(self, places, rounding):
2645 """Round a nonzero, nonspecial Decimal to a fixed number of
2646 significant figures, using the given rounding mode.
2647
2648 Infinities, NaNs and zeros are returned unaltered.
2649
2650 This operation is quiet: it raises no flags, and uses no
2651 information from the context.
2652
2653 """
2654 if places <= 0:
2655 raise ValueError("argument should be at least 1 in _round")
2656 if self._is_special or not self:
2657 return Decimal(self)
2658 ans = self._rescale(self.adjusted()+1-places, rounding)
2659 # it can happen that the rescale alters the adjusted exponent;
2660 # for example when rounding 99.97 to 3 significant figures.
2661 # When this happens we end up with an extra 0 at the end of
2662 # the number; a second rescale fixes this.
2663 if ans.adjusted() != self.adjusted():
2664 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2665 return ans
2666
2667 def to_integral_exact(self, rounding=None, context=None):
2668 """Rounds to a nearby integer.
2669
2670 If no rounding mode is specified, take the rounding mode from
2671 the context. This method raises the Rounded and Inexact flags
2672 when appropriate.
2673
2674 See also: to_integral_value, which does exactly the same as
2675 this method except that it doesn't raise Inexact or Rounded.
2676 """
2677 if self._is_special:
2678 ans = self._check_nans(context=context)
2679 if ans:
2680 return ans
2681 return Decimal(self)
2682 if self._exp >= 0:
2683 return Decimal(self)
2684 if not self:
2685 return _dec_from_triple(self._sign, '0', 0)
2686 if context is None:
2687 context = getcontext()
2688 if rounding is None:
2689 rounding = context.rounding
2690 ans = self._rescale(0, rounding)
2691 if ans != self:
2692 context._raise_error(Inexact)
2693 context._raise_error(Rounded)
2694 return ans
2695
2696 def to_integral_value(self, rounding=None, context=None):
2697 """Rounds to the nearest integer, without raising inexact, rounded."""
2698 if context is None:
2699 context = getcontext()
2700 if rounding is None:
2701 rounding = context.rounding
2702 if self._is_special:
2703 ans = self._check_nans(context=context)
2704 if ans:
2705 return ans
2706 return Decimal(self)
2707 if self._exp >= 0:
2708 return Decimal(self)
2709 else:
2710 return self._rescale(0, rounding)
2711
2712 # the method name changed, but we provide also the old one, for compatibility
2713 to_integral = to_integral_value
2714
2715 def sqrt(self, context=None):
2716 """Return the square root of self."""
2717 if context is None:
2718 context = getcontext()
2719
2720 if self._is_special:
2721 ans = self._check_nans(context=context)
2722 if ans:
2723 return ans
2724
2725 if self._isinfinity() and self._sign == 0:
2726 return Decimal(self)
2727
2728 if not self:
2729 # exponent = self._exp // 2. sqrt(-0) = -0
2730 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2731 return ans._fix(context)
2732
2733 if self._sign == 1:
2734 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2735
2736 # At this point self represents a positive number. Let p be
2737 # the desired precision and express self in the form c*100**e
2738 # with c a positive real number and e an integer, c and e
2739 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2740 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2741 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2742 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2743 # the closest integer to sqrt(c) with the even integer chosen
2744 # in the case of a tie.
2745 #
2746 # To ensure correct rounding in all cases, we use the
2747 # following trick: we compute the square root to an extra
2748 # place (precision p+1 instead of precision p), rounding down.
2749 # Then, if the result is inexact and its last digit is 0 or 5,
2750 # we increase the last digit to 1 or 6 respectively; if it's
2751 # exact we leave the last digit alone. Now the final round to
2752 # p places (or fewer in the case of underflow) will round
2753 # correctly and raise the appropriate flags.
2754
2755 # use an extra digit of precision
2756 prec = context.prec+1
2757
2758 # write argument in the form c*100**e where e = self._exp//2
2759 # is the 'ideal' exponent, to be used if the square root is
2760 # exactly representable. l is the number of 'digits' of c in
2761 # base 100, so that 100**(l-1) <= c < 100**l.
2762 op = _WorkRep(self)
2763 e = op.exp >> 1
2764 if op.exp & 1:
2765 c = op.int * 10
2766 l = (len(self._int) >> 1) + 1
2767 else:
2768 c = op.int
2769 l = len(self._int)+1 >> 1
2770
2771 # rescale so that c has exactly prec base 100 'digits'
2772 shift = prec-l
2773 if shift >= 0:
2774 c *= 100**shift
2775 exact = True
2776 else:
2777 c, remainder = divmod(c, 100**-shift)
2778 exact = not remainder
2779 e -= shift
2780
2781 # find n = floor(sqrt(c)) using Newton's method
2782 n = 10**prec
2783 while True:
2784 q = c//n
2785 if n <= q:
2786 break
2787 else:
2788 n = n + q >> 1
2789 exact = exact and n*n == c
2790
2791 if exact:
2792 # result is exact; rescale to use ideal exponent e
2793 if shift >= 0:
2794 # assert n % 10**shift == 0
2795 n //= 10**shift
2796 else:
2797 n *= 10**-shift
2798 e += shift
2799 else:
2800 # result is not exact; fix last digit as described above
2801 if n % 5 == 0:
2802 n += 1
2803
2804 ans = _dec_from_triple(0, str(n), e)
2805
2806 # round, and fit to current context
2807 context = context._shallow_copy()
2808 rounding = context._set_rounding(ROUND_HALF_EVEN)
2809 ans = ans._fix(context)
2810 context.rounding = rounding
2811
2812 return ans
2813
2814 def max(self, other, context=None):
2815 """Returns the larger value.
2816
2817 Like max(self, other) except if one is not a number, returns
2818 NaN (and signals if one is sNaN). Also rounds.
2819 """
2820 other = _convert_other(other, raiseit=True)
2821
2822 if context is None:
2823 context = getcontext()
2824
2825 if self._is_special or other._is_special:
2826 # If one operand is a quiet NaN and the other is number, then the
2827 # number is always returned
2828 sn = self._isnan()
2829 on = other._isnan()
2830 if sn or on:
2831 if on == 1 and sn == 0:
2832 return self._fix(context)
2833 if sn == 1 and on == 0:
2834 return other._fix(context)
2835 return self._check_nans(other, context)
2836
2837 c = self._cmp(other)
2838 if c == 0:
2839 # If both operands are finite and equal in numerical value
2840 # then an ordering is applied:
2841 #
2842 # If the signs differ then max returns the operand with the
2843 # positive sign and min returns the operand with the negative sign
2844 #
2845 # If the signs are the same then the exponent is used to select
2846 # the result. This is exactly the ordering used in compare_total.
2847 c = self.compare_total(other)
2848
2849 if c == -1:
2850 ans = other
2851 else:
2852 ans = self
2853
2854 return ans._fix(context)
2855
2856 def min(self, other, context=None):
2857 """Returns the smaller value.
2858
2859 Like min(self, other) except if one is not a number, returns
2860 NaN (and signals if one is sNaN). Also rounds.
2861 """
2862 other = _convert_other(other, raiseit=True)
2863
2864 if context is None:
2865 context = getcontext()
2866
2867 if self._is_special or other._is_special:
2868 # If one operand is a quiet NaN and the other is number, then the
2869 # number is always returned
2870 sn = self._isnan()
2871 on = other._isnan()
2872 if sn or on:
2873 if on == 1 and sn == 0:
2874 return self._fix(context)
2875 if sn == 1 and on == 0:
2876 return other._fix(context)
2877 return self._check_nans(other, context)
2878
2879 c = self._cmp(other)
2880 if c == 0:
2881 c = self.compare_total(other)
2882
2883 if c == -1:
2884 ans = self
2885 else:
2886 ans = other
2887
2888 return ans._fix(context)
2889
2890 def _isinteger(self):
2891 """Returns whether self is an integer"""
2892 if self._is_special:
2893 return False
2894 if self._exp >= 0:
2895 return True
2896 rest = self._int[self._exp:]
2897 return rest == '0'*len(rest)
2898
2899 def _iseven(self):
2900 """Returns True if self is even. Assumes self is an integer."""
2901 if not self or self._exp > 0:
2902 return True
2903 return self._int[-1+self._exp] in '02468'
2904
2905 def adjusted(self):
2906 """Return the adjusted exponent of self"""
2907 try:
2908 return self._exp + len(self._int) - 1
2909 # If NaN or Infinity, self._exp is string
2910 except TypeError:
2911 return 0
2912
2913 def canonical(self):
2914 """Returns the same Decimal object.
2915
2916 As we do not have different encodings for the same number, the
2917 received object already is in its canonical form.
2918 """
2919 return self
2920
2921 def compare_signal(self, other, context=None):
2922 """Compares self to the other operand numerically.
2923
2924 It's pretty much like compare(), but all NaNs signal, with signaling
2925 NaNs taking precedence over quiet NaNs.
2926 """
2927 other = _convert_other(other, raiseit = True)
2928 ans = self._compare_check_nans(other, context)
2929 if ans:
2930 return ans
2931 return self.compare(other, context=context)
2932
2933 def compare_total(self, other, context=None):
2934 """Compares self to other using the abstract representations.
2935
2936 This is not like the standard compare, which use their numerical
2937 value. Note that a total ordering is defined for all possible abstract
2938 representations.
2939 """
2940 other = _convert_other(other, raiseit=True)
2941
2942 # if one is negative and the other is positive, it's easy
2943 if self._sign and not other._sign:
2944 return _NegativeOne
2945 if not self._sign and other._sign:
2946 return _One
2947 sign = self._sign
2948
2949 # let's handle both NaN types
2950 self_nan = self._isnan()
2951 other_nan = other._isnan()
2952 if self_nan or other_nan:
2953 if self_nan == other_nan:
2954 # compare payloads as though they're integers
2955 self_key = len(self._int), self._int
2956 other_key = len(other._int), other._int
2957 if self_key < other_key:
2958 if sign:
2959 return _One
2960 else:
2961 return _NegativeOne
2962 if self_key > other_key:
2963 if sign:
2964 return _NegativeOne
2965 else:
2966 return _One
2967 return _Zero
2968
2969 if sign:
2970 if self_nan == 1:
2971 return _NegativeOne
2972 if other_nan == 1:
2973 return _One
2974 if self_nan == 2:
2975 return _NegativeOne
2976 if other_nan == 2:
2977 return _One
2978 else:
2979 if self_nan == 1:
2980 return _One
2981 if other_nan == 1:
2982 return _NegativeOne
2983 if self_nan == 2:
2984 return _One
2985 if other_nan == 2:
2986 return _NegativeOne
2987
2988 if self < other:
2989 return _NegativeOne
2990 if self > other:
2991 return _One
2992
2993 if self._exp < other._exp:
2994 if sign:
2995 return _One
2996 else:
2997 return _NegativeOne
2998 if self._exp > other._exp:
2999 if sign:
3000 return _NegativeOne
3001 else:
3002 return _One
3003 return _Zero
3004
3005
3006 def compare_total_mag(self, other, context=None):
3007 """Compares self to other using abstract repr., ignoring sign.
3008
3009 Like compare_total, but with operand's sign ignored and assumed to be 0.
3010 """
3011 other = _convert_other(other, raiseit=True)
3012
3013 s = self.copy_abs()
3014 o = other.copy_abs()
3015 return s.compare_total(o)
3016
3017 def copy_abs(self):
3018 """Returns a copy with the sign set to 0. """
3019 return _dec_from_triple(0, self._int, self._exp, self._is_special)
3020
3021 def copy_negate(self):
3022 """Returns a copy with the sign inverted."""
3023 if self._sign:
3024 return _dec_from_triple(0, self._int, self._exp, self._is_special)
3025 else:
3026 return _dec_from_triple(1, self._int, self._exp, self._is_special)
3027
3028 def copy_sign(self, other, context=None):
3029 """Returns self with the sign of other."""
3030 other = _convert_other(other, raiseit=True)
3031 return _dec_from_triple(other._sign, self._int,
3032 self._exp, self._is_special)
3033
3034 def exp(self, context=None):
3035 """Returns e ** self."""
3036
3037 if context is None:
3038 context = getcontext()
3039
3040 # exp(NaN) = NaN
3041 ans = self._check_nans(context=context)
3042 if ans:
3043 return ans
3044
3045 # exp(-Infinity) = 0
3046 if self._isinfinity() == -1:
3047 return _Zero
3048
3049 # exp(0) = 1
3050 if not self:
3051 return _One
3052
3053 # exp(Infinity) = Infinity
3054 if self._isinfinity() == 1:
3055 return Decimal(self)
3056
3057 # the result is now guaranteed to be inexact (the true
3058 # mathematical result is transcendental). There's no need to
3059 # raise Rounded and Inexact here---they'll always be raised as
3060 # a result of the call to _fix.
3061 p = context.prec
3062 adj = self.adjusted()
3063
3064 # we only need to do any computation for quite a small range
3065 # of adjusted exponents---for example, -29 <= adj <= 10 for
3066 # the default context. For smaller exponent the result is
3067 # indistinguishable from 1 at the given precision, while for
3068 # larger exponent the result either overflows or underflows.
3069 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
3070 # overflow
3071 ans = _dec_from_triple(0, '1', context.Emax+1)
3072 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
3073 # underflow to 0
3074 ans = _dec_from_triple(0, '1', context.Etiny()-1)
3075 elif self._sign == 0 and adj < -p:
3076 # p+1 digits; final round will raise correct flags
3077 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
3078 elif self._sign == 1 and adj < -p-1:
3079 # p+1 digits; final round will raise correct flags
3080 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
3081 # general case
3082 else:
3083 op = _WorkRep(self)
3084 c, e = op.int, op.exp
3085 if op.sign == 1:
3086 c = -c
3087
3088 # compute correctly rounded result: increase precision by
3089 # 3 digits at a time until we get an unambiguously
3090 # roundable result
3091 extra = 3
3092 while True:
3093 coeff, exp = _dexp(c, e, p+extra)
3094 if coeff % (5*10**(len(str(coeff))-p-1)):
3095 break
3096 extra += 3
3097
3098 ans = _dec_from_triple(0, str(coeff), exp)
3099
3100 # at this stage, ans should round correctly with *any*
3101 # rounding mode, not just with ROUND_HALF_EVEN
3102 context = context._shallow_copy()
3103 rounding = context._set_rounding(ROUND_HALF_EVEN)
3104 ans = ans._fix(context)
3105 context.rounding = rounding
3106
3107 return ans
3108
3109 def is_canonical(self):
3110 """Return True if self is canonical; otherwise return False.
3111
3112 Currently, the encoding of a Decimal instance is always
3113 canonical, so this method returns True for any Decimal.
3114 """
3115 return True
3116
3117 def is_finite(self):
3118 """Return True if self is finite; otherwise return False.
3119
3120 A Decimal instance is considered finite if it is neither
3121 infinite nor a NaN.
3122 """
3123 return not self._is_special
3124
3125 def is_infinite(self):
3126 """Return True if self is infinite; otherwise return False."""
3127 return self._exp == 'F'
3128
3129 def is_nan(self):
3130 """Return True if self is a qNaN or sNaN; otherwise return False."""
3131 return self._exp in ('n', 'N')
3132
3133 def is_normal(self, context=None):
3134 """Return True if self is a normal number; otherwise return False."""
3135 if self._is_special or not self:
3136 return False
3137 if context is None:
3138 context = getcontext()
3139 return context.Emin <= self.adjusted()
3140
3141 def is_qnan(self):
3142 """Return True if self is a quiet NaN; otherwise return False."""
3143 return self._exp == 'n'
3144
3145 def is_signed(self):
3146 """Return True if self is negative; otherwise return False."""
3147 return self._sign == 1
3148
3149 def is_snan(self):
3150 """Return True if self is a signaling NaN; otherwise return False."""
3151 return self._exp == 'N'
3152
3153 def is_subnormal(self, context=None):
3154 """Return True if self is subnormal; otherwise return False."""
3155 if self._is_special or not self:
3156 return False
3157 if context is None:
3158 context = getcontext()
3159 return self.adjusted() < context.Emin
3160
3161 def is_zero(self):
3162 """Return True if self is a zero; otherwise return False."""
3163 return not self._is_special and self._int == '0'
3164
3165 def _ln_exp_bound(self):
3166 """Compute a lower bound for the adjusted exponent of self.ln().
3167 In other words, compute r such that self.ln() >= 10**r. Assumes
3168 that self is finite and positive and that self != 1.
3169 """
3170
3171 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
3172 adj = self._exp + len(self._int) - 1
3173 if adj >= 1:
3174 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
3175 return len(str(adj*23//10)) - 1
3176 if adj <= -2:
3177 # argument <= 0.1
3178 return len(str((-1-adj)*23//10)) - 1
3179 op = _WorkRep(self)
3180 c, e = op.int, op.exp
3181 if adj == 0:
3182 # 1 < self < 10
3183 num = str(c-10**-e)
3184 den = str(c)
3185 return len(num) - len(den) - (num < den)
3186 # adj == -1, 0.1 <= self < 1
3187 return e + len(str(10**-e - c)) - 1
3188
3189
3190 def ln(self, context=None):
3191 """Returns the natural (base e) logarithm of self."""
3192
3193 if context is None:
3194 context = getcontext()
3195
3196 # ln(NaN) = NaN
3197 ans = self._check_nans(context=context)
3198 if ans:
3199 return ans
3200
3201 # ln(0.0) == -Infinity
3202 if not self:
3203 return _NegativeInfinity
3204
3205 # ln(Infinity) = Infinity
3206 if self._isinfinity() == 1:
3207 return _Infinity
3208
3209 # ln(1.0) == 0.0
3210 if self == _One:
3211 return _Zero
3212
3213 # ln(negative) raises InvalidOperation
3214 if self._sign == 1:
3215 return context._raise_error(InvalidOperation,
3216 'ln of a negative value')
3217
3218 # result is irrational, so necessarily inexact
3219 op = _WorkRep(self)
3220 c, e = op.int, op.exp
3221 p = context.prec
3222
3223 # correctly rounded result: repeatedly increase precision by 3
3224 # until we get an unambiguously roundable result
3225 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3226 while True:
3227 coeff = _dlog(c, e, places)
3228 # assert len(str(abs(coeff)))-p >= 1
3229 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3230 break
3231 places += 3
3232 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
3233
3234 context = context._shallow_copy()
3235 rounding = context._set_rounding(ROUND_HALF_EVEN)
3236 ans = ans._fix(context)
3237 context.rounding = rounding
3238 return ans
3239
3240 def _log10_exp_bound(self):
3241 """Compute a lower bound for the adjusted exponent of self.log10().
3242 In other words, find r such that self.log10() >= 10**r.
3243 Assumes that self is finite and positive and that self != 1.
3244 """
3245
3246 # For x >= 10 or x < 0.1 we only need a bound on the integer
3247 # part of log10(self), and this comes directly from the
3248 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3249 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3250 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3251
3252 adj = self._exp + len(self._int) - 1
3253 if adj >= 1:
3254 # self >= 10
3255 return len(str(adj))-1
3256 if adj <= -2:
3257 # self < 0.1
3258 return len(str(-1-adj))-1
3259 op = _WorkRep(self)
3260 c, e = op.int, op.exp
3261 if adj == 0:
3262 # 1 < self < 10
3263 num = str(c-10**-e)
3264 den = str(231*c)
3265 return len(num) - len(den) - (num < den) + 2
3266 # adj == -1, 0.1 <= self < 1
3267 num = str(10**-e-c)
3268 return len(num) + e - (num < "231") - 1
3269
3270 def log10(self, context=None):
3271 """Returns the base 10 logarithm of self."""
3272
3273 if context is None:
3274 context = getcontext()
3275
3276 # log10(NaN) = NaN
3277 ans = self._check_nans(context=context)
3278 if ans:
3279 return ans
3280
3281 # log10(0.0) == -Infinity
3282 if not self:
3283 return _NegativeInfinity
3284
3285 # log10(Infinity) = Infinity
3286 if self._isinfinity() == 1:
3287 return _Infinity
3288
3289 # log10(negative or -Infinity) raises InvalidOperation
3290 if self._sign == 1:
3291 return context._raise_error(InvalidOperation,
3292 'log10 of a negative value')
3293
3294 # log10(10**n) = n
3295 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
3296 # answer may need rounding
3297 ans = Decimal(self._exp + len(self._int) - 1)
3298 else:
3299 # result is irrational, so necessarily inexact
3300 op = _WorkRep(self)
3301 c, e = op.int, op.exp
3302 p = context.prec
3303
3304 # correctly rounded result: repeatedly increase precision
3305 # until result is unambiguously roundable
3306 places = p-self._log10_exp_bound()+2
3307 while True:
3308 coeff = _dlog10(c, e, places)
3309 # assert len(str(abs(coeff)))-p >= 1
3310 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3311 break
3312 places += 3
3313 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
3314
3315 context = context._shallow_copy()
3316 rounding = context._set_rounding(ROUND_HALF_EVEN)
3317 ans = ans._fix(context)
3318 context.rounding = rounding
3319 return ans
3320
3321 def logb(self, context=None):
3322 """ Returns the exponent of the magnitude of self's MSD.
3323
3324 The result is the integer which is the exponent of the magnitude
3325 of the most significant digit of self (as though it were truncated
3326 to a single digit while maintaining the value of that digit and
3327 without limiting the resulting exponent).
3328 """
3329 # logb(NaN) = NaN
3330 ans = self._check_nans(context=context)
3331 if ans:
3332 return ans
3333
3334 if context is None:
3335 context = getcontext()
3336
3337 # logb(+/-Inf) = +Inf
3338 if self._isinfinity():
3339 return _Infinity
3340
3341 # logb(0) = -Inf, DivisionByZero
3342 if not self:
3343 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3344
3345 # otherwise, simply return the adjusted exponent of self, as a
3346 # Decimal. Note that no attempt is made to fit the result
3347 # into the current context.
3348 ans = Decimal(self.adjusted())
3349 return ans._fix(context)
3350
3351 def _islogical(self):
3352 """Return True if self is a logical operand.
3353
3354 For being logical, it must be a finite number with a sign of 0,
3355 an exponent of 0, and a coefficient whose digits must all be
3356 either 0 or 1.
3357 """
3358 if self._sign != 0 or self._exp != 0:
3359 return False
3360 for dig in self._int:
3361 if dig not in '01':
3362 return False
3363 return True
3364
3365 def _fill_logical(self, context, opa, opb):
3366 dif = context.prec - len(opa)
3367 if dif > 0:
3368 opa = '0'*dif + opa
3369 elif dif < 0:
3370 opa = opa[-context.prec:]
3371 dif = context.prec - len(opb)
3372 if dif > 0:
3373 opb = '0'*dif + opb
3374 elif dif < 0:
3375 opb = opb[-context.prec:]
3376 return opa, opb
3377
3378 def logical_and(self, other, context=None):
3379 """Applies an 'and' operation between self and other's digits."""
3380 if context is None:
3381 context = getcontext()
3382
3383 other = _convert_other(other, raiseit=True)
3384
3385 if not self._islogical() or not other._islogical():
3386 return context._raise_error(InvalidOperation)
3387
3388 # fill to context.prec
3389 (opa, opb) = self._fill_logical(context, self._int, other._int)
3390
3391 # make the operation, and clean starting zeroes
3392 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3393 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3394
3395 def logical_invert(self, context=None):
3396 """Invert all its digits."""
3397 if context is None:
3398 context = getcontext()
3399 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3400 context)
3401
3402 def logical_or(self, other, context=None):
3403 """Applies an 'or' operation between self and other's digits."""
3404 if context is None:
3405 context = getcontext()
3406
3407 other = _convert_other(other, raiseit=True)
3408
3409 if not self._islogical() or not other._islogical():
3410 return context._raise_error(InvalidOperation)
3411
3412 # fill to context.prec
3413 (opa, opb) = self._fill_logical(context, self._int, other._int)
3414
3415 # make the operation, and clean starting zeroes
3416 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
3417 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3418
3419 def logical_xor(self, other, context=None):
3420 """Applies an 'xor' operation between self and other's digits."""
3421 if context is None:
3422 context = getcontext()
3423
3424 other = _convert_other(other, raiseit=True)
3425
3426 if not self._islogical() or not other._islogical():
3427 return context._raise_error(InvalidOperation)
3428
3429 # fill to context.prec
3430 (opa, opb) = self._fill_logical(context, self._int, other._int)
3431
3432 # make the operation, and clean starting zeroes
3433 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
3434 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3435
3436 def max_mag(self, other, context=None):
3437 """Compares the values numerically with their sign ignored."""
3438 other = _convert_other(other, raiseit=True)
3439
3440 if context is None:
3441 context = getcontext()
3442
3443 if self._is_special or other._is_special:
3444 # If one operand is a quiet NaN and the other is number, then the
3445 # number is always returned
3446 sn = self._isnan()
3447 on = other._isnan()
3448 if sn or on:
3449 if on == 1 and sn == 0:
3450 return self._fix(context)
3451 if sn == 1 and on == 0:
3452 return other._fix(context)
3453 return self._check_nans(other, context)
3454
3455 c = self.copy_abs()._cmp(other.copy_abs())
3456 if c == 0:
3457 c = self.compare_total(other)
3458
3459 if c == -1:
3460 ans = other
3461 else:
3462 ans = self
3463
3464 return ans._fix(context)
3465
3466 def min_mag(self, other, context=None):
3467 """Compares the values numerically with their sign ignored."""
3468 other = _convert_other(other, raiseit=True)
3469
3470 if context is None:
3471 context = getcontext()
3472
3473 if self._is_special or other._is_special:
3474 # If one operand is a quiet NaN and the other is number, then the
3475 # number is always returned
3476 sn = self._isnan()
3477 on = other._isnan()
3478 if sn or on:
3479 if on == 1 and sn == 0:
3480 return self._fix(context)
3481 if sn == 1 and on == 0:
3482 return other._fix(context)
3483 return self._check_nans(other, context)
3484
3485 c = self.copy_abs()._cmp(other.copy_abs())
3486 if c == 0:
3487 c = self.compare_total(other)
3488
3489 if c == -1:
3490 ans = self
3491 else:
3492 ans = other
3493
3494 return ans._fix(context)
3495
3496 def next_minus(self, context=None):
3497 """Returns the largest representable number smaller than itself."""
3498 if context is None:
3499 context = getcontext()
3500
3501 ans = self._check_nans(context=context)
3502 if ans:
3503 return ans
3504
3505 if self._isinfinity() == -1:
3506 return _NegativeInfinity
3507 if self._isinfinity() == 1:
3508 return _dec_from_triple(0, '9'*context.prec, context.Etop())
3509
3510 context = context.copy()
3511 context._set_rounding(ROUND_FLOOR)
3512 context._ignore_all_flags()
3513 new_self = self._fix(context)
3514 if new_self != self:
3515 return new_self
3516 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3517 context)
3518
3519 def next_plus(self, context=None):
3520 """Returns the smallest representable number larger than itself."""
3521 if context is None:
3522 context = getcontext()
3523
3524 ans = self._check_nans(context=context)
3525 if ans:
3526 return ans
3527
3528 if self._isinfinity() == 1:
3529 return _Infinity
3530 if self._isinfinity() == -1:
3531 return _dec_from_triple(1, '9'*context.prec, context.Etop())
3532
3533 context = context.copy()
3534 context._set_rounding(ROUND_CEILING)
3535 context._ignore_all_flags()
3536 new_self = self._fix(context)
3537 if new_self != self:
3538 return new_self
3539 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3540 context)
3541
3542 def next_toward(self, other, context=None):
3543 """Returns the number closest to self, in the direction towards other.
3544
3545 The result is the closest representable number to self
3546 (excluding self) that is in the direction towards other,
3547 unless both have the same value. If the two operands are
3548 numerically equal, then the result is a copy of self with the
3549 sign set to be the same as the sign of other.
3550 """
3551 other = _convert_other(other, raiseit=True)
3552
3553 if context is None:
3554 context = getcontext()
3555
3556 ans = self._check_nans(other, context)
3557 if ans:
3558 return ans
3559
3560 comparison = self._cmp(other)
3561 if comparison == 0:
3562 return self.copy_sign(other)
3563
3564 if comparison == -1:
3565 ans = self.next_plus(context)
3566 else: # comparison == 1
3567 ans = self.next_minus(context)
3568
3569 # decide which flags to raise using value of ans
3570 if ans._isinfinity():
3571 context._raise_error(Overflow,
3572 'Infinite result from next_toward',
3573 ans._sign)
3574 context._raise_error(Inexact)
3575 context._raise_error(Rounded)
3576 elif ans.adjusted() < context.Emin:
3577 context._raise_error(Underflow)
3578 context._raise_error(Subnormal)
3579 context._raise_error(Inexact)
3580 context._raise_error(Rounded)
3581 # if precision == 1 then we don't raise Clamped for a
3582 # result 0E-Etiny.
3583 if not ans:
3584 context._raise_error(Clamped)
3585
3586 return ans
3587
3588 def number_class(self, context=None):
3589 """Returns an indication of the class of self.
3590
3591 The class is one of the following strings:
3592 sNaN
3593 NaN
3594 -Infinity
3595 -Normal
3596 -Subnormal
3597 -Zero
3598 +Zero
3599 +Subnormal
3600 +Normal
3601 +Infinity
3602 """
3603 if self.is_snan():
3604 return "sNaN"
3605 if self.is_qnan():
3606 return "NaN"
3607 inf = self._isinfinity()
3608 if inf == 1:
3609 return "+Infinity"
3610 if inf == -1:
3611 return "-Infinity"
3612 if self.is_zero():
3613 if self._sign:
3614 return "-Zero"
3615 else:
3616 return "+Zero"
3617 if context is None:
3618 context = getcontext()
3619 if self.is_subnormal(context=context):
3620 if self._sign:
3621 return "-Subnormal"
3622 else:
3623 return "+Subnormal"
3624 # just a normal, regular, boring number, :)
3625 if self._sign:
3626 return "-Normal"
3627 else:
3628 return "+Normal"
3629
3630 def radix(self):
3631 """Just returns 10, as this is Decimal, :)"""
3632 return Decimal(10)
3633
3634 def rotate(self, other, context=None):
3635 """Returns a rotated copy of self, value-of-other times."""
3636 if context is None:
3637 context = getcontext()
3638
3639 other = _convert_other(other, raiseit=True)
3640
3641 ans = self._check_nans(other, context)
3642 if ans:
3643 return ans
3644
3645 if other._exp != 0:
3646 return context._raise_error(InvalidOperation)
3647 if not (-context.prec <= int(other) <= context.prec):
3648 return context._raise_error(InvalidOperation)
3649
3650 if self._isinfinity():
3651 return Decimal(self)
3652
3653 # get values, pad if necessary
3654 torot = int(other)
3655 rotdig = self._int
3656 topad = context.prec - len(rotdig)
3657 if topad > 0:
3658 rotdig = '0'*topad + rotdig
3659 elif topad < 0:
3660 rotdig = rotdig[-topad:]
3661
3662 # let's rotate!
3663 rotated = rotdig[torot:] + rotdig[:torot]
3664 return _dec_from_triple(self._sign,
3665 rotated.lstrip('0') or '0', self._exp)
3666
3667 def scaleb(self, other, context=None):
3668 """Returns self operand after adding the second value to its exp."""
3669 if context is None:
3670 context = getcontext()
3671
3672 other = _convert_other(other, raiseit=True)
3673
3674 ans = self._check_nans(other, context)
3675 if ans:
3676 return ans
3677
3678 if other._exp != 0:
3679 return context._raise_error(InvalidOperation)
3680 liminf = -2 * (context.Emax + context.prec)
3681 limsup = 2 * (context.Emax + context.prec)
3682 if not (liminf <= int(other) <= limsup):
3683 return context._raise_error(InvalidOperation)
3684
3685 if self._isinfinity():
3686 return Decimal(self)
3687
3688 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
3689 d = d._fix(context)
3690 return d
3691
3692 def shift(self, other, context=None):
3693 """Returns a shifted copy of self, value-of-other times."""
3694 if context is None:
3695 context = getcontext()
3696
3697 other = _convert_other(other, raiseit=True)
3698
3699 ans = self._check_nans(other, context)
3700 if ans:
3701 return ans
3702
3703 if other._exp != 0:
3704 return context._raise_error(InvalidOperation)
3705 if not (-context.prec <= int(other) <= context.prec):
3706 return context._raise_error(InvalidOperation)
3707
3708 if self._isinfinity():
3709 return Decimal(self)
3710
3711 # get values, pad if necessary
3712 torot = int(other)
3713 rotdig = self._int
3714 topad = context.prec - len(rotdig)
3715 if topad > 0:
3716 rotdig = '0'*topad + rotdig
3717 elif topad < 0:
3718 rotdig = rotdig[-topad:]
3719
3720 # let's shift!
3721 if torot < 0:
3722 shifted = rotdig[:torot]
3723 else:
3724 shifted = rotdig + '0'*torot
3725 shifted = shifted[-context.prec:]
3726
3727 return _dec_from_triple(self._sign,
3728 shifted.lstrip('0') or '0', self._exp)
3729
3730 # Support for pickling, copy, and deepcopy
3731 def __reduce__(self):
3732 return (self.__class__, (str(self),))
3733
3734 def __copy__(self):
3735 if type(self) is Decimal:
3736 return self # I'm immutable; therefore I am my own clone
3737 return self.__class__(str(self))
3738
3739 def __deepcopy__(self, memo):
3740 if type(self) is Decimal:
3741 return self # My components are also immutable
3742 return self.__class__(str(self))
3743
3744 # PEP 3101 support. the _localeconv keyword argument should be
3745 # considered private: it's provided for ease of testing only.
3746 def __format__(self, specifier, context=None, _localeconv=None):
3747 """Format a Decimal instance according to the given specifier.
3748
3749 The specifier should be a standard format specifier, with the
3750 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3751 'F', 'g', 'G', 'n' and '%' are supported. If the formatting
3752 type is omitted it defaults to 'g' or 'G', depending on the
3753 value of context.capitals.
3754 """
3755
3756 # Note: PEP 3101 says that if the type is not present then
3757 # there should be at least one digit after the decimal point.
3758 # We take the liberty of ignoring this requirement for
3759 # Decimal---it's presumably there to make sure that
3760 # format(float, '') behaves similarly to str(float).
3761 if context is None:
3762 context = getcontext()
3763
3764 spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
3765
3766 # special values don't care about the type or precision
3767 if self._is_special:
3768 sign = _format_sign(self._sign, spec)
3769 body = str(self.copy_abs())
3770 if spec['type'] == '%':
3771 body += '%'
3772 return _format_align(sign, body, spec)
3773
3774 # a type of None defaults to 'g' or 'G', depending on context
3775 if spec['type'] is None:
3776 spec['type'] = ['g', 'G'][context.capitals]
3777
3778 # if type is '%', adjust exponent of self accordingly
3779 if spec['type'] == '%':
3780 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3781
3782 # round if necessary, taking rounding mode from the context
3783 rounding = context.rounding
3784 precision = spec['precision']
3785 if precision is not None:
3786 if spec['type'] in 'eE':
3787 self = self._round(precision+1, rounding)
3788 elif spec['type'] in 'fF%':
3789 self = self._rescale(-precision, rounding)
3790 elif spec['type'] in 'gG' and len(self._int) > precision:
3791 self = self._round(precision, rounding)
3792 # special case: zeros with a positive exponent can't be
3793 # represented in fixed point; rescale them to 0e0.
3794 if not self and self._exp > 0 and spec['type'] in 'fF%':
3795 self = self._rescale(0, rounding)
3796
3797 # figure out placement of the decimal point
3798 leftdigits = self._exp + len(self._int)
3799 if spec['type'] in 'eE':
3800 if not self and precision is not None:
3801 dotplace = 1 - precision
3802 else:
3803 dotplace = 1
3804 elif spec['type'] in 'fF%':
3805 dotplace = leftdigits
3806 elif spec['type'] in 'gG':
3807 if self._exp <= 0 and leftdigits > -6:
3808 dotplace = leftdigits
3809 else:
3810 dotplace = 1
3811
3812 # find digits before and after decimal point, and get exponent
3813 if dotplace < 0:
3814 intpart = '0'
3815 fracpart = '0'*(-dotplace) + self._int
3816 elif dotplace > len(self._int):
3817 intpart = self._int + '0'*(dotplace-len(self._int))
3818 fracpart = ''
3819 else:
3820 intpart = self._int[:dotplace] or '0'
3821 fracpart = self._int[dotplace:]
3822 exp = leftdigits-dotplace
3823
3824 # done with the decimal-specific stuff; hand over the rest
3825 # of the formatting to the _format_number function
3826 return _format_number(self._sign, intpart, fracpart, exp, spec)
3827
3828def _dec_from_triple(sign, coefficient, exponent, special=False):
3829 """Create a decimal instance directly, without any validation,
3830 normalization (e.g. removal of leading zeros) or argument
3831 conversion.
3832
3833 This function is for *internal use only*.
3834 """
3835
3836 self = object.__new__(Decimal)
3837 self._sign = sign
3838 self._int = coefficient
3839 self._exp = exponent
3840 self._is_special = special
3841
3842 return self
3843
3844# Register Decimal as a kind of Number (an abstract base class).
3845# However, do not register it as Real (because Decimals are not
3846# interoperable with floats).
3847_numbers.Number.register(Decimal)
3848
3849
3850##### Context class #######################################################
3851
3852class _ContextManager(object):
3853 """Context manager class to support localcontext().
3854
3855 Sets a copy of the supplied context in __enter__() and restores
3856 the previous decimal context in __exit__()
3857 """
3858 def __init__(self, new_context):
3859 self.new_context = new_context.copy()
3860 def __enter__(self):
3861 self.saved_context = getcontext()
3862 setcontext(self.new_context)
3863 return self.new_context
3864 def __exit__(self, t, v, tb):
3865 setcontext(self.saved_context)
3866
3867class Context(object):
3868 """Contains the context for a Decimal instance.
3869
3870 Contains:
3871 prec - precision (for use in rounding, division, square roots..)
3872 rounding - rounding type (how you round)
3873 traps - If traps[exception] = 1, then the exception is
3874 raised when it is caused. Otherwise, a value is
3875 substituted in.
3876 flags - When an exception is caused, flags[exception] is set.
3877 (Whether or not the trap_enabler is set)
3878 Should be reset by user of Decimal instance.
3879 Emin - Minimum exponent
3880 Emax - Maximum exponent
3881 capitals - If 1, 1*10^1 is printed as 1E+1.
3882 If 0, printed as 1e1
3883 clamp - If 1, change exponents if too high (Default 0)
3884 """
3885
3886 def __init__(self, prec=None, rounding=None, Emin=None, Emax=None,
3887 capitals=None, clamp=None, flags=None, traps=None,
3888 _ignored_flags=None):
3889 # Set defaults; for everything except flags and _ignored_flags,
3890 # inherit from DefaultContext.
3891 try:
3892 dc = DefaultContext
3893 except NameError:
3894 pass
3895
3896 self.prec = prec if prec is not None else dc.prec
3897 self.rounding = rounding if rounding is not None else dc.rounding
3898 self.Emin = Emin if Emin is not None else dc.Emin
3899 self.Emax = Emax if Emax is not None else dc.Emax
3900 self.capitals = capitals if capitals is not None else dc.capitals
3901 self.clamp = clamp if clamp is not None else dc.clamp
3902
3903 if _ignored_flags is None:
3904 self._ignored_flags = []
3905 else:
3906 self._ignored_flags = _ignored_flags
3907
3908 if traps is None:
3909 self.traps = dc.traps.copy()
3910 elif not isinstance(traps, dict):
3911 self.traps = dict((s, int(s in traps)) for s in _signals + traps)
3912 else:
3913 self.traps = traps
3914
3915 if flags is None:
3916 self.flags = dict.fromkeys(_signals, 0)
3917 elif not isinstance(flags, dict):
3918 self.flags = dict((s, int(s in flags)) for s in _signals + flags)
3919 else:
3920 self.flags = flags
3921
3922 def _set_integer_check(self, name, value, vmin, vmax):
3923 if not isinstance(value, int):
3924 raise TypeError("%s must be an integer" % name)
3925 if vmin == '-inf':
3926 if value > vmax:
3927 raise ValueError("%s must be in [%s, %d]. got: %s" % (name, vmin, vmax, value))
3928 elif vmax == 'inf':
3929 if value < vmin:
3930 raise ValueError("%s must be in [%d, %s]. got: %s" % (name, vmin, vmax, value))
3931 else:
3932 if value < vmin or value > vmax:
3933 raise ValueError("%s must be in [%d, %d]. got %s" % (name, vmin, vmax, value))
3934 return object.__setattr__(self, name, value)
3935
3936 def _set_signal_dict(self, name, d):
3937 if not isinstance(d, dict):
3938 raise TypeError("%s must be a signal dict" % d)
3939 for key in d:
3940 if not key in _signals:
3941 raise KeyError("%s is not a valid signal dict" % d)
3942 for key in _signals:
3943 if not key in d:
3944 raise KeyError("%s is not a valid signal dict" % d)
3945 return object.__setattr__(self, name, d)
3946
3947 def __setattr__(self, name, value):
3948 if name == 'prec':
3949 return self._set_integer_check(name, value, 1, 'inf')
3950 elif name == 'Emin':
3951 return self._set_integer_check(name, value, '-inf', 0)
3952 elif name == 'Emax':
3953 return self._set_integer_check(name, value, 0, 'inf')
3954 elif name == 'capitals':
3955 return self._set_integer_check(name, value, 0, 1)
3956 elif name == 'clamp':
3957 return self._set_integer_check(name, value, 0, 1)
3958 elif name == 'rounding':
3959 if not value in _rounding_modes:
3960 # raise TypeError even for strings to have consistency
3961 # among various implementations.
3962 raise TypeError("%s: invalid rounding mode" % value)
3963 return object.__setattr__(self, name, value)
3964 elif name == 'flags' or name == 'traps':
3965 return self._set_signal_dict(name, value)
3966 elif name == '_ignored_flags':
3967 return object.__setattr__(self, name, value)
3968 else:
3969 raise AttributeError(
3970 "'decimal.Context' object has no attribute '%s'" % name)
3971
3972 def __delattr__(self, name):
3973 raise AttributeError("%s cannot be deleted" % name)
3974
3975 # Support for pickling, copy, and deepcopy
3976 def __reduce__(self):
3977 flags = [sig for sig, v in self.flags.items() if v]
3978 traps = [sig for sig, v in self.traps.items() if v]
3979 return (self.__class__,
3980 (self.prec, self.rounding, self.Emin, self.Emax,
3981 self.capitals, self.clamp, flags, traps))
3982
3983 def __repr__(self):
3984 """Show the current context."""
3985 s = []
3986 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3987 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d, '
3988 'clamp=%(clamp)d'
3989 % vars(self))
3990 names = [f.__name__ for f, v in self.flags.items() if v]
3991 s.append('flags=[' + ', '.join(names) + ']')
3992 names = [t.__name__ for t, v in self.traps.items() if v]
3993 s.append('traps=[' + ', '.join(names) + ']')
3994 return ', '.join(s) + ')'
3995
3996 def clear_flags(self):
3997 """Reset all flags to zero"""
3998 for flag in self.flags:
3999 self.flags[flag] = 0
4000
4001 def clear_traps(self):
4002 """Reset all traps to zero"""
4003 for flag in self.traps:
4004 self.traps[flag] = 0
4005
4006 def _shallow_copy(self):
4007 """Returns a shallow copy from self."""
4008 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4009 self.capitals, self.clamp, self.flags, self.traps,
4010 self._ignored_flags)
4011 return nc
4012
4013 def copy(self):
4014 """Returns a deep copy from self."""
4015 nc = Context(self.prec, self.rounding, self.Emin, self.Emax,
4016 self.capitals, self.clamp,
4017 self.flags.copy(), self.traps.copy(),
4018 self._ignored_flags)
4019 return nc
4020 __copy__ = copy
4021
4022 def _raise_error(self, condition, explanation = None, *args):
4023 """Handles an error
4024
4025 If the flag is in _ignored_flags, returns the default response.
4026 Otherwise, it sets the flag, then, if the corresponding
4027 trap_enabler is set, it reraises the exception. Otherwise, it returns
4028 the default value after setting the flag.
4029 """
4030 error = _condition_map.get(condition, condition)
4031 if error in self._ignored_flags:
4032 # Don't touch the flag
4033 return error().handle(self, *args)
4034
4035 self.flags[error] = 1
4036 if not self.traps[error]:
4037 # The errors define how to handle themselves.
4038 return condition().handle(self, *args)
4039
4040 # Errors should only be risked on copies of the context
4041 # self._ignored_flags = []
4042 raise error(explanation)
4043
4044 def _ignore_all_flags(self):
4045 """Ignore all flags, if they are raised"""
4046 return self._ignore_flags(*_signals)
4047
4048 def _ignore_flags(self, *flags):
4049 """Ignore the flags, if they are raised"""
4050 # Do not mutate-- This way, copies of a context leave the original
4051 # alone.
4052 self._ignored_flags = (self._ignored_flags + list(flags))
4053 return list(flags)
4054
4055 def _regard_flags(self, *flags):
4056 """Stop ignoring the flags, if they are raised"""
4057 if flags and isinstance(flags[0], (tuple,list)):
4058 flags = flags[0]
4059 for flag in flags:
4060 self._ignored_flags.remove(flag)
4061
4062 # We inherit object.__hash__, so we must deny this explicitly
4063 __hash__ = None
4064
4065 def Etiny(self):
4066 """Returns Etiny (= Emin - prec + 1)"""
4067 return int(self.Emin - self.prec + 1)
4068
4069 def Etop(self):
4070 """Returns maximum exponent (= Emax - prec + 1)"""
4071 return int(self.Emax - self.prec + 1)
4072
4073 def _set_rounding(self, type):
4074 """Sets the rounding type.
4075
4076 Sets the rounding type, and returns the current (previous)
4077 rounding type. Often used like:
4078
4079 context = context.copy()
4080 # so you don't change the calling context
4081 # if an error occurs in the middle.
4082 rounding = context._set_rounding(ROUND_UP)
4083 val = self.__sub__(other, context=context)
4084 context._set_rounding(rounding)
4085
4086 This will make it round up for that operation.
4087 """
4088 rounding = self.rounding
Brett Cannona721aba2016-09-09 14:57:09 -07004089 self.rounding = type
Stefan Krahb578f8a2014-09-10 17:58:15 +02004090 return rounding
4091
4092 def create_decimal(self, num='0'):
4093 """Creates a new Decimal instance but using self as context.
4094
4095 This method implements the to-number operation of the
4096 IBM Decimal specification."""
4097
Brett Cannona721aba2016-09-09 14:57:09 -07004098 if isinstance(num, str) and (num != num.strip() or '_' in num):
Stefan Krahb578f8a2014-09-10 17:58:15 +02004099 return self._raise_error(ConversionSyntax,
Brett Cannona721aba2016-09-09 14:57:09 -07004100 "trailing or leading whitespace and "
4101 "underscores are not permitted.")
Stefan Krahb578f8a2014-09-10 17:58:15 +02004102
4103 d = Decimal(num, context=self)
4104 if d._isnan() and len(d._int) > self.prec - self.clamp:
4105 return self._raise_error(ConversionSyntax,
4106 "diagnostic info too long in NaN")
4107 return d._fix(self)
4108
4109 def create_decimal_from_float(self, f):
4110 """Creates a new Decimal instance from a float but rounding using self
4111 as the context.
4112
4113 >>> context = Context(prec=5, rounding=ROUND_DOWN)
4114 >>> context.create_decimal_from_float(3.1415926535897932)
4115 Decimal('3.1415')
4116 >>> context = Context(prec=5, traps=[Inexact])
4117 >>> context.create_decimal_from_float(3.1415926535897932)
4118 Traceback (most recent call last):
4119 ...
Martin Panterbb8b1cb2016-09-22 09:37:39 +00004120 decimal.Inexact: None
Stefan Krahb578f8a2014-09-10 17:58:15 +02004121
4122 """
4123 d = Decimal.from_float(f) # An exact conversion
4124 return d._fix(self) # Apply the context rounding
4125
4126 # Methods
4127 def abs(self, a):
4128 """Returns the absolute value of the operand.
4129
4130 If the operand is negative, the result is the same as using the minus
4131 operation on the operand. Otherwise, the result is the same as using
4132 the plus operation on the operand.
4133
4134 >>> ExtendedContext.abs(Decimal('2.1'))
4135 Decimal('2.1')
4136 >>> ExtendedContext.abs(Decimal('-100'))
4137 Decimal('100')
4138 >>> ExtendedContext.abs(Decimal('101.5'))
4139 Decimal('101.5')
4140 >>> ExtendedContext.abs(Decimal('-101.5'))
4141 Decimal('101.5')
4142 >>> ExtendedContext.abs(-1)
4143 Decimal('1')
4144 """
4145 a = _convert_other(a, raiseit=True)
4146 return a.__abs__(context=self)
4147
4148 def add(self, a, b):
4149 """Return the sum of the two operands.
4150
4151 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
4152 Decimal('19.00')
4153 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
4154 Decimal('1.02E+4')
4155 >>> ExtendedContext.add(1, Decimal(2))
4156 Decimal('3')
4157 >>> ExtendedContext.add(Decimal(8), 5)
4158 Decimal('13')
4159 >>> ExtendedContext.add(5, 5)
4160 Decimal('10')
4161 """
4162 a = _convert_other(a, raiseit=True)
4163 r = a.__add__(b, context=self)
4164 if r is NotImplemented:
4165 raise TypeError("Unable to convert %s to Decimal" % b)
4166 else:
4167 return r
4168
4169 def _apply(self, a):
4170 return str(a._fix(self))
4171
4172 def canonical(self, a):
4173 """Returns the same Decimal object.
4174
4175 As we do not have different encodings for the same number, the
4176 received object already is in its canonical form.
4177
4178 >>> ExtendedContext.canonical(Decimal('2.50'))
4179 Decimal('2.50')
4180 """
4181 if not isinstance(a, Decimal):
4182 raise TypeError("canonical requires a Decimal as an argument.")
4183 return a.canonical()
4184
4185 def compare(self, a, b):
4186 """Compares values numerically.
4187
4188 If the signs of the operands differ, a value representing each operand
4189 ('-1' if the operand is less than zero, '0' if the operand is zero or
4190 negative zero, or '1' if the operand is greater than zero) is used in
4191 place of that operand for the comparison instead of the actual
4192 operand.
4193
4194 The comparison is then effected by subtracting the second operand from
4195 the first and then returning a value according to the result of the
4196 subtraction: '-1' if the result is less than zero, '0' if the result is
4197 zero or negative zero, or '1' if the result is greater than zero.
4198
4199 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
4200 Decimal('-1')
4201 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
4202 Decimal('0')
4203 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
4204 Decimal('0')
4205 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
4206 Decimal('1')
4207 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
4208 Decimal('1')
4209 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
4210 Decimal('-1')
4211 >>> ExtendedContext.compare(1, 2)
4212 Decimal('-1')
4213 >>> ExtendedContext.compare(Decimal(1), 2)
4214 Decimal('-1')
4215 >>> ExtendedContext.compare(1, Decimal(2))
4216 Decimal('-1')
4217 """
4218 a = _convert_other(a, raiseit=True)
4219 return a.compare(b, context=self)
4220
4221 def compare_signal(self, a, b):
4222 """Compares the values of the two operands numerically.
4223
4224 It's pretty much like compare(), but all NaNs signal, with signaling
4225 NaNs taking precedence over quiet NaNs.
4226
4227 >>> c = ExtendedContext
4228 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
4229 Decimal('-1')
4230 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
4231 Decimal('0')
4232 >>> c.flags[InvalidOperation] = 0
4233 >>> print(c.flags[InvalidOperation])
4234 0
4235 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
4236 Decimal('NaN')
4237 >>> print(c.flags[InvalidOperation])
4238 1
4239 >>> c.flags[InvalidOperation] = 0
4240 >>> print(c.flags[InvalidOperation])
4241 0
4242 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
4243 Decimal('NaN')
4244 >>> print(c.flags[InvalidOperation])
4245 1
4246 >>> c.compare_signal(-1, 2)
4247 Decimal('-1')
4248 >>> c.compare_signal(Decimal(-1), 2)
4249 Decimal('-1')
4250 >>> c.compare_signal(-1, Decimal(2))
4251 Decimal('-1')
4252 """
4253 a = _convert_other(a, raiseit=True)
4254 return a.compare_signal(b, context=self)
4255
4256 def compare_total(self, a, b):
4257 """Compares two operands using their abstract representation.
4258
4259 This is not like the standard compare, which use their numerical
4260 value. Note that a total ordering is defined for all possible abstract
4261 representations.
4262
4263 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
4264 Decimal('-1')
4265 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
4266 Decimal('-1')
4267 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
4268 Decimal('-1')
4269 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
4270 Decimal('0')
4271 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
4272 Decimal('1')
4273 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
4274 Decimal('-1')
4275 >>> ExtendedContext.compare_total(1, 2)
4276 Decimal('-1')
4277 >>> ExtendedContext.compare_total(Decimal(1), 2)
4278 Decimal('-1')
4279 >>> ExtendedContext.compare_total(1, Decimal(2))
4280 Decimal('-1')
4281 """
4282 a = _convert_other(a, raiseit=True)
4283 return a.compare_total(b)
4284
4285 def compare_total_mag(self, a, b):
4286 """Compares two operands using their abstract representation ignoring sign.
4287
4288 Like compare_total, but with operand's sign ignored and assumed to be 0.
4289 """
4290 a = _convert_other(a, raiseit=True)
4291 return a.compare_total_mag(b)
4292
4293 def copy_abs(self, a):
4294 """Returns a copy of the operand with the sign set to 0.
4295
4296 >>> ExtendedContext.copy_abs(Decimal('2.1'))
4297 Decimal('2.1')
4298 >>> ExtendedContext.copy_abs(Decimal('-100'))
4299 Decimal('100')
4300 >>> ExtendedContext.copy_abs(-1)
4301 Decimal('1')
4302 """
4303 a = _convert_other(a, raiseit=True)
4304 return a.copy_abs()
4305
4306 def copy_decimal(self, a):
4307 """Returns a copy of the decimal object.
4308
4309 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
4310 Decimal('2.1')
4311 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
4312 Decimal('-1.00')
4313 >>> ExtendedContext.copy_decimal(1)
4314 Decimal('1')
4315 """
4316 a = _convert_other(a, raiseit=True)
4317 return Decimal(a)
4318
4319 def copy_negate(self, a):
4320 """Returns a copy of the operand with the sign inverted.
4321
4322 >>> ExtendedContext.copy_negate(Decimal('101.5'))
4323 Decimal('-101.5')
4324 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
4325 Decimal('101.5')
4326 >>> ExtendedContext.copy_negate(1)
4327 Decimal('-1')
4328 """
4329 a = _convert_other(a, raiseit=True)
4330 return a.copy_negate()
4331
4332 def copy_sign(self, a, b):
4333 """Copies the second operand's sign to the first one.
4334
4335 In detail, it returns a copy of the first operand with the sign
4336 equal to the sign of the second operand.
4337
4338 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
4339 Decimal('1.50')
4340 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
4341 Decimal('1.50')
4342 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
4343 Decimal('-1.50')
4344 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
4345 Decimal('-1.50')
4346 >>> ExtendedContext.copy_sign(1, -2)
4347 Decimal('-1')
4348 >>> ExtendedContext.copy_sign(Decimal(1), -2)
4349 Decimal('-1')
4350 >>> ExtendedContext.copy_sign(1, Decimal(-2))
4351 Decimal('-1')
4352 """
4353 a = _convert_other(a, raiseit=True)
4354 return a.copy_sign(b)
4355
4356 def divide(self, a, b):
4357 """Decimal division in a specified context.
4358
4359 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
4360 Decimal('0.333333333')
4361 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
4362 Decimal('0.666666667')
4363 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
4364 Decimal('2.5')
4365 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
4366 Decimal('0.1')
4367 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
4368 Decimal('1')
4369 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
4370 Decimal('4.00')
4371 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
4372 Decimal('1.20')
4373 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
4374 Decimal('10')
4375 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
4376 Decimal('1000')
4377 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
4378 Decimal('1.20E+6')
4379 >>> ExtendedContext.divide(5, 5)
4380 Decimal('1')
4381 >>> ExtendedContext.divide(Decimal(5), 5)
4382 Decimal('1')
4383 >>> ExtendedContext.divide(5, Decimal(5))
4384 Decimal('1')
4385 """
4386 a = _convert_other(a, raiseit=True)
4387 r = a.__truediv__(b, context=self)
4388 if r is NotImplemented:
4389 raise TypeError("Unable to convert %s to Decimal" % b)
4390 else:
4391 return r
4392
4393 def divide_int(self, a, b):
4394 """Divides two numbers and returns the integer part of the result.
4395
4396 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
4397 Decimal('0')
4398 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
4399 Decimal('3')
4400 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
4401 Decimal('3')
4402 >>> ExtendedContext.divide_int(10, 3)
4403 Decimal('3')
4404 >>> ExtendedContext.divide_int(Decimal(10), 3)
4405 Decimal('3')
4406 >>> ExtendedContext.divide_int(10, Decimal(3))
4407 Decimal('3')
4408 """
4409 a = _convert_other(a, raiseit=True)
4410 r = a.__floordiv__(b, context=self)
4411 if r is NotImplemented:
4412 raise TypeError("Unable to convert %s to Decimal" % b)
4413 else:
4414 return r
4415
4416 def divmod(self, a, b):
4417 """Return (a // b, a % b).
4418
4419 >>> ExtendedContext.divmod(Decimal(8), Decimal(3))
4420 (Decimal('2'), Decimal('2'))
4421 >>> ExtendedContext.divmod(Decimal(8), Decimal(4))
4422 (Decimal('2'), Decimal('0'))
4423 >>> ExtendedContext.divmod(8, 4)
4424 (Decimal('2'), Decimal('0'))
4425 >>> ExtendedContext.divmod(Decimal(8), 4)
4426 (Decimal('2'), Decimal('0'))
4427 >>> ExtendedContext.divmod(8, Decimal(4))
4428 (Decimal('2'), Decimal('0'))
4429 """
4430 a = _convert_other(a, raiseit=True)
4431 r = a.__divmod__(b, context=self)
4432 if r is NotImplemented:
4433 raise TypeError("Unable to convert %s to Decimal" % b)
4434 else:
4435 return r
4436
4437 def exp(self, a):
4438 """Returns e ** a.
4439
4440 >>> c = ExtendedContext.copy()
4441 >>> c.Emin = -999
4442 >>> c.Emax = 999
4443 >>> c.exp(Decimal('-Infinity'))
4444 Decimal('0')
4445 >>> c.exp(Decimal('-1'))
4446 Decimal('0.367879441')
4447 >>> c.exp(Decimal('0'))
4448 Decimal('1')
4449 >>> c.exp(Decimal('1'))
4450 Decimal('2.71828183')
4451 >>> c.exp(Decimal('0.693147181'))
4452 Decimal('2.00000000')
4453 >>> c.exp(Decimal('+Infinity'))
4454 Decimal('Infinity')
4455 >>> c.exp(10)
4456 Decimal('22026.4658')
4457 """
4458 a =_convert_other(a, raiseit=True)
4459 return a.exp(context=self)
4460
4461 def fma(self, a, b, c):
4462 """Returns a multiplied by b, plus c.
4463
4464 The first two operands are multiplied together, using multiply,
4465 the third operand is then added to the result of that
4466 multiplication, using add, all with only one final rounding.
4467
4468 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
4469 Decimal('22')
4470 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
4471 Decimal('-8')
4472 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
4473 Decimal('1.38435736E+12')
4474 >>> ExtendedContext.fma(1, 3, 4)
4475 Decimal('7')
4476 >>> ExtendedContext.fma(1, Decimal(3), 4)
4477 Decimal('7')
4478 >>> ExtendedContext.fma(1, 3, Decimal(4))
4479 Decimal('7')
4480 """
4481 a = _convert_other(a, raiseit=True)
4482 return a.fma(b, c, context=self)
4483
4484 def is_canonical(self, a):
4485 """Return True if the operand is canonical; otherwise return False.
4486
4487 Currently, the encoding of a Decimal instance is always
4488 canonical, so this method returns True for any Decimal.
4489
4490 >>> ExtendedContext.is_canonical(Decimal('2.50'))
4491 True
4492 """
4493 if not isinstance(a, Decimal):
4494 raise TypeError("is_canonical requires a Decimal as an argument.")
4495 return a.is_canonical()
4496
4497 def is_finite(self, a):
4498 """Return True if the operand is finite; otherwise return False.
4499
4500 A Decimal instance is considered finite if it is neither
4501 infinite nor a NaN.
4502
4503 >>> ExtendedContext.is_finite(Decimal('2.50'))
4504 True
4505 >>> ExtendedContext.is_finite(Decimal('-0.3'))
4506 True
4507 >>> ExtendedContext.is_finite(Decimal('0'))
4508 True
4509 >>> ExtendedContext.is_finite(Decimal('Inf'))
4510 False
4511 >>> ExtendedContext.is_finite(Decimal('NaN'))
4512 False
4513 >>> ExtendedContext.is_finite(1)
4514 True
4515 """
4516 a = _convert_other(a, raiseit=True)
4517 return a.is_finite()
4518
4519 def is_infinite(self, a):
4520 """Return True if the operand is infinite; otherwise return False.
4521
4522 >>> ExtendedContext.is_infinite(Decimal('2.50'))
4523 False
4524 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
4525 True
4526 >>> ExtendedContext.is_infinite(Decimal('NaN'))
4527 False
4528 >>> ExtendedContext.is_infinite(1)
4529 False
4530 """
4531 a = _convert_other(a, raiseit=True)
4532 return a.is_infinite()
4533
4534 def is_nan(self, a):
4535 """Return True if the operand is a qNaN or sNaN;
4536 otherwise return False.
4537
4538 >>> ExtendedContext.is_nan(Decimal('2.50'))
4539 False
4540 >>> ExtendedContext.is_nan(Decimal('NaN'))
4541 True
4542 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
4543 True
4544 >>> ExtendedContext.is_nan(1)
4545 False
4546 """
4547 a = _convert_other(a, raiseit=True)
4548 return a.is_nan()
4549
4550 def is_normal(self, a):
4551 """Return True if the operand is a normal number;
4552 otherwise return False.
4553
4554 >>> c = ExtendedContext.copy()
4555 >>> c.Emin = -999
4556 >>> c.Emax = 999
4557 >>> c.is_normal(Decimal('2.50'))
4558 True
4559 >>> c.is_normal(Decimal('0.1E-999'))
4560 False
4561 >>> c.is_normal(Decimal('0.00'))
4562 False
4563 >>> c.is_normal(Decimal('-Inf'))
4564 False
4565 >>> c.is_normal(Decimal('NaN'))
4566 False
4567 >>> c.is_normal(1)
4568 True
4569 """
4570 a = _convert_other(a, raiseit=True)
4571 return a.is_normal(context=self)
4572
4573 def is_qnan(self, a):
4574 """Return True if the operand is a quiet NaN; otherwise return False.
4575
4576 >>> ExtendedContext.is_qnan(Decimal('2.50'))
4577 False
4578 >>> ExtendedContext.is_qnan(Decimal('NaN'))
4579 True
4580 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
4581 False
4582 >>> ExtendedContext.is_qnan(1)
4583 False
4584 """
4585 a = _convert_other(a, raiseit=True)
4586 return a.is_qnan()
4587
4588 def is_signed(self, a):
4589 """Return True if the operand is negative; otherwise return False.
4590
4591 >>> ExtendedContext.is_signed(Decimal('2.50'))
4592 False
4593 >>> ExtendedContext.is_signed(Decimal('-12'))
4594 True
4595 >>> ExtendedContext.is_signed(Decimal('-0'))
4596 True
4597 >>> ExtendedContext.is_signed(8)
4598 False
4599 >>> ExtendedContext.is_signed(-8)
4600 True
4601 """
4602 a = _convert_other(a, raiseit=True)
4603 return a.is_signed()
4604
4605 def is_snan(self, a):
4606 """Return True if the operand is a signaling NaN;
4607 otherwise return False.
4608
4609 >>> ExtendedContext.is_snan(Decimal('2.50'))
4610 False
4611 >>> ExtendedContext.is_snan(Decimal('NaN'))
4612 False
4613 >>> ExtendedContext.is_snan(Decimal('sNaN'))
4614 True
4615 >>> ExtendedContext.is_snan(1)
4616 False
4617 """
4618 a = _convert_other(a, raiseit=True)
4619 return a.is_snan()
4620
4621 def is_subnormal(self, a):
4622 """Return True if the operand is subnormal; otherwise return False.
4623
4624 >>> c = ExtendedContext.copy()
4625 >>> c.Emin = -999
4626 >>> c.Emax = 999
4627 >>> c.is_subnormal(Decimal('2.50'))
4628 False
4629 >>> c.is_subnormal(Decimal('0.1E-999'))
4630 True
4631 >>> c.is_subnormal(Decimal('0.00'))
4632 False
4633 >>> c.is_subnormal(Decimal('-Inf'))
4634 False
4635 >>> c.is_subnormal(Decimal('NaN'))
4636 False
4637 >>> c.is_subnormal(1)
4638 False
4639 """
4640 a = _convert_other(a, raiseit=True)
4641 return a.is_subnormal(context=self)
4642
4643 def is_zero(self, a):
4644 """Return True if the operand is a zero; otherwise return False.
4645
4646 >>> ExtendedContext.is_zero(Decimal('0'))
4647 True
4648 >>> ExtendedContext.is_zero(Decimal('2.50'))
4649 False
4650 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
4651 True
4652 >>> ExtendedContext.is_zero(1)
4653 False
4654 >>> ExtendedContext.is_zero(0)
4655 True
4656 """
4657 a = _convert_other(a, raiseit=True)
4658 return a.is_zero()
4659
4660 def ln(self, a):
4661 """Returns the natural (base e) logarithm of the operand.
4662
4663 >>> c = ExtendedContext.copy()
4664 >>> c.Emin = -999
4665 >>> c.Emax = 999
4666 >>> c.ln(Decimal('0'))
4667 Decimal('-Infinity')
4668 >>> c.ln(Decimal('1.000'))
4669 Decimal('0')
4670 >>> c.ln(Decimal('2.71828183'))
4671 Decimal('1.00000000')
4672 >>> c.ln(Decimal('10'))
4673 Decimal('2.30258509')
4674 >>> c.ln(Decimal('+Infinity'))
4675 Decimal('Infinity')
4676 >>> c.ln(1)
4677 Decimal('0')
4678 """
4679 a = _convert_other(a, raiseit=True)
4680 return a.ln(context=self)
4681
4682 def log10(self, a):
4683 """Returns the base 10 logarithm of the operand.
4684
4685 >>> c = ExtendedContext.copy()
4686 >>> c.Emin = -999
4687 >>> c.Emax = 999
4688 >>> c.log10(Decimal('0'))
4689 Decimal('-Infinity')
4690 >>> c.log10(Decimal('0.001'))
4691 Decimal('-3')
4692 >>> c.log10(Decimal('1.000'))
4693 Decimal('0')
4694 >>> c.log10(Decimal('2'))
4695 Decimal('0.301029996')
4696 >>> c.log10(Decimal('10'))
4697 Decimal('1')
4698 >>> c.log10(Decimal('70'))
4699 Decimal('1.84509804')
4700 >>> c.log10(Decimal('+Infinity'))
4701 Decimal('Infinity')
4702 >>> c.log10(0)
4703 Decimal('-Infinity')
4704 >>> c.log10(1)
4705 Decimal('0')
4706 """
4707 a = _convert_other(a, raiseit=True)
4708 return a.log10(context=self)
4709
4710 def logb(self, a):
4711 """ Returns the exponent of the magnitude of the operand's MSD.
4712
4713 The result is the integer which is the exponent of the magnitude
4714 of the most significant digit of the operand (as though the
4715 operand were truncated to a single digit while maintaining the
4716 value of that digit and without limiting the resulting exponent).
4717
4718 >>> ExtendedContext.logb(Decimal('250'))
4719 Decimal('2')
4720 >>> ExtendedContext.logb(Decimal('2.50'))
4721 Decimal('0')
4722 >>> ExtendedContext.logb(Decimal('0.03'))
4723 Decimal('-2')
4724 >>> ExtendedContext.logb(Decimal('0'))
4725 Decimal('-Infinity')
4726 >>> ExtendedContext.logb(1)
4727 Decimal('0')
4728 >>> ExtendedContext.logb(10)
4729 Decimal('1')
4730 >>> ExtendedContext.logb(100)
4731 Decimal('2')
4732 """
4733 a = _convert_other(a, raiseit=True)
4734 return a.logb(context=self)
4735
4736 def logical_and(self, a, b):
4737 """Applies the logical operation 'and' between each operand's digits.
4738
4739 The operands must be both logical numbers.
4740
4741 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4742 Decimal('0')
4743 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4744 Decimal('0')
4745 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4746 Decimal('0')
4747 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4748 Decimal('1')
4749 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4750 Decimal('1000')
4751 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4752 Decimal('10')
4753 >>> ExtendedContext.logical_and(110, 1101)
4754 Decimal('100')
4755 >>> ExtendedContext.logical_and(Decimal(110), 1101)
4756 Decimal('100')
4757 >>> ExtendedContext.logical_and(110, Decimal(1101))
4758 Decimal('100')
4759 """
4760 a = _convert_other(a, raiseit=True)
4761 return a.logical_and(b, context=self)
4762
4763 def logical_invert(self, a):
4764 """Invert all the digits in the operand.
4765
4766 The operand must be a logical number.
4767
4768 >>> ExtendedContext.logical_invert(Decimal('0'))
4769 Decimal('111111111')
4770 >>> ExtendedContext.logical_invert(Decimal('1'))
4771 Decimal('111111110')
4772 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4773 Decimal('0')
4774 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4775 Decimal('10101010')
4776 >>> ExtendedContext.logical_invert(1101)
4777 Decimal('111110010')
4778 """
4779 a = _convert_other(a, raiseit=True)
4780 return a.logical_invert(context=self)
4781
4782 def logical_or(self, a, b):
4783 """Applies the logical operation 'or' between each operand's digits.
4784
4785 The operands must be both logical numbers.
4786
4787 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4788 Decimal('0')
4789 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4790 Decimal('1')
4791 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4792 Decimal('1')
4793 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4794 Decimal('1')
4795 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4796 Decimal('1110')
4797 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4798 Decimal('1110')
4799 >>> ExtendedContext.logical_or(110, 1101)
4800 Decimal('1111')
4801 >>> ExtendedContext.logical_or(Decimal(110), 1101)
4802 Decimal('1111')
4803 >>> ExtendedContext.logical_or(110, Decimal(1101))
4804 Decimal('1111')
4805 """
4806 a = _convert_other(a, raiseit=True)
4807 return a.logical_or(b, context=self)
4808
4809 def logical_xor(self, a, b):
4810 """Applies the logical operation 'xor' between each operand's digits.
4811
4812 The operands must be both logical numbers.
4813
4814 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4815 Decimal('0')
4816 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4817 Decimal('1')
4818 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4819 Decimal('1')
4820 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4821 Decimal('0')
4822 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4823 Decimal('110')
4824 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4825 Decimal('1101')
4826 >>> ExtendedContext.logical_xor(110, 1101)
4827 Decimal('1011')
4828 >>> ExtendedContext.logical_xor(Decimal(110), 1101)
4829 Decimal('1011')
4830 >>> ExtendedContext.logical_xor(110, Decimal(1101))
4831 Decimal('1011')
4832 """
4833 a = _convert_other(a, raiseit=True)
4834 return a.logical_xor(b, context=self)
4835
4836 def max(self, a, b):
4837 """max compares two values numerically and returns the maximum.
4838
4839 If either operand is a NaN then the general rules apply.
4840 Otherwise, the operands are compared as though by the compare
4841 operation. If they are numerically equal then the left-hand operand
4842 is chosen as the result. Otherwise the maximum (closer to positive
4843 infinity) of the two operands is chosen as the result.
4844
4845 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
4846 Decimal('3')
4847 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
4848 Decimal('3')
4849 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4850 Decimal('1')
4851 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4852 Decimal('7')
4853 >>> ExtendedContext.max(1, 2)
4854 Decimal('2')
4855 >>> ExtendedContext.max(Decimal(1), 2)
4856 Decimal('2')
4857 >>> ExtendedContext.max(1, Decimal(2))
4858 Decimal('2')
4859 """
4860 a = _convert_other(a, raiseit=True)
4861 return a.max(b, context=self)
4862
4863 def max_mag(self, a, b):
4864 """Compares the values numerically with their sign ignored.
4865
4866 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('NaN'))
4867 Decimal('7')
4868 >>> ExtendedContext.max_mag(Decimal('7'), Decimal('-10'))
4869 Decimal('-10')
4870 >>> ExtendedContext.max_mag(1, -2)
4871 Decimal('-2')
4872 >>> ExtendedContext.max_mag(Decimal(1), -2)
4873 Decimal('-2')
4874 >>> ExtendedContext.max_mag(1, Decimal(-2))
4875 Decimal('-2')
4876 """
4877 a = _convert_other(a, raiseit=True)
4878 return a.max_mag(b, context=self)
4879
4880 def min(self, a, b):
4881 """min compares two values numerically and returns the minimum.
4882
4883 If either operand is a NaN then the general rules apply.
4884 Otherwise, the operands are compared as though by the compare
4885 operation. If they are numerically equal then the left-hand operand
4886 is chosen as the result. Otherwise the minimum (closer to negative
4887 infinity) of the two operands is chosen as the result.
4888
4889 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
4890 Decimal('2')
4891 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
4892 Decimal('-10')
4893 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
4894 Decimal('1.0')
4895 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4896 Decimal('7')
4897 >>> ExtendedContext.min(1, 2)
4898 Decimal('1')
4899 >>> ExtendedContext.min(Decimal(1), 2)
4900 Decimal('1')
4901 >>> ExtendedContext.min(1, Decimal(29))
4902 Decimal('1')
4903 """
4904 a = _convert_other(a, raiseit=True)
4905 return a.min(b, context=self)
4906
4907 def min_mag(self, a, b):
4908 """Compares the values numerically with their sign ignored.
4909
4910 >>> ExtendedContext.min_mag(Decimal('3'), Decimal('-2'))
4911 Decimal('-2')
4912 >>> ExtendedContext.min_mag(Decimal('-3'), Decimal('NaN'))
4913 Decimal('-3')
4914 >>> ExtendedContext.min_mag(1, -2)
4915 Decimal('1')
4916 >>> ExtendedContext.min_mag(Decimal(1), -2)
4917 Decimal('1')
4918 >>> ExtendedContext.min_mag(1, Decimal(-2))
4919 Decimal('1')
4920 """
4921 a = _convert_other(a, raiseit=True)
4922 return a.min_mag(b, context=self)
4923
4924 def minus(self, a):
4925 """Minus corresponds to unary prefix minus in Python.
4926
4927 The operation is evaluated using the same rules as subtract; the
4928 operation minus(a) is calculated as subtract('0', a) where the '0'
4929 has the same exponent as the operand.
4930
4931 >>> ExtendedContext.minus(Decimal('1.3'))
4932 Decimal('-1.3')
4933 >>> ExtendedContext.minus(Decimal('-1.3'))
4934 Decimal('1.3')
4935 >>> ExtendedContext.minus(1)
4936 Decimal('-1')
4937 """
4938 a = _convert_other(a, raiseit=True)
4939 return a.__neg__(context=self)
4940
4941 def multiply(self, a, b):
4942 """multiply multiplies two operands.
4943
4944 If either operand is a special value then the general rules apply.
4945 Otherwise, the operands are multiplied together
4946 ('long multiplication'), resulting in a number which may be as long as
4947 the sum of the lengths of the two operands.
4948
4949 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
4950 Decimal('3.60')
4951 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
4952 Decimal('21')
4953 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
4954 Decimal('0.72')
4955 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
4956 Decimal('-0.0')
4957 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
4958 Decimal('4.28135971E+11')
4959 >>> ExtendedContext.multiply(7, 7)
4960 Decimal('49')
4961 >>> ExtendedContext.multiply(Decimal(7), 7)
4962 Decimal('49')
4963 >>> ExtendedContext.multiply(7, Decimal(7))
4964 Decimal('49')
4965 """
4966 a = _convert_other(a, raiseit=True)
4967 r = a.__mul__(b, context=self)
4968 if r is NotImplemented:
4969 raise TypeError("Unable to convert %s to Decimal" % b)
4970 else:
4971 return r
4972
4973 def next_minus(self, a):
4974 """Returns the largest representable number smaller than a.
4975
4976 >>> c = ExtendedContext.copy()
4977 >>> c.Emin = -999
4978 >>> c.Emax = 999
4979 >>> ExtendedContext.next_minus(Decimal('1'))
4980 Decimal('0.999999999')
4981 >>> c.next_minus(Decimal('1E-1007'))
4982 Decimal('0E-1007')
4983 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4984 Decimal('-1.00000004')
4985 >>> c.next_minus(Decimal('Infinity'))
4986 Decimal('9.99999999E+999')
4987 >>> c.next_minus(1)
4988 Decimal('0.999999999')
4989 """
4990 a = _convert_other(a, raiseit=True)
4991 return a.next_minus(context=self)
4992
4993 def next_plus(self, a):
4994 """Returns the smallest representable number larger than a.
4995
4996 >>> c = ExtendedContext.copy()
4997 >>> c.Emin = -999
4998 >>> c.Emax = 999
4999 >>> ExtendedContext.next_plus(Decimal('1'))
5000 Decimal('1.00000001')
5001 >>> c.next_plus(Decimal('-1E-1007'))
5002 Decimal('-0E-1007')
5003 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
5004 Decimal('-1.00000002')
5005 >>> c.next_plus(Decimal('-Infinity'))
5006 Decimal('-9.99999999E+999')
5007 >>> c.next_plus(1)
5008 Decimal('1.00000001')
5009 """
5010 a = _convert_other(a, raiseit=True)
5011 return a.next_plus(context=self)
5012
5013 def next_toward(self, a, b):
5014 """Returns the number closest to a, in direction towards b.
5015
5016 The result is the closest representable number from the first
5017 operand (but not the first operand) that is in the direction
5018 towards the second operand, unless the operands have the same
5019 value.
5020
5021 >>> c = ExtendedContext.copy()
5022 >>> c.Emin = -999
5023 >>> c.Emax = 999
5024 >>> c.next_toward(Decimal('1'), Decimal('2'))
5025 Decimal('1.00000001')
5026 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
5027 Decimal('-0E-1007')
5028 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
5029 Decimal('-1.00000002')
5030 >>> c.next_toward(Decimal('1'), Decimal('0'))
5031 Decimal('0.999999999')
5032 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
5033 Decimal('0E-1007')
5034 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
5035 Decimal('-1.00000004')
5036 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
5037 Decimal('-0.00')
5038 >>> c.next_toward(0, 1)
5039 Decimal('1E-1007')
5040 >>> c.next_toward(Decimal(0), 1)
5041 Decimal('1E-1007')
5042 >>> c.next_toward(0, Decimal(1))
5043 Decimal('1E-1007')
5044 """
5045 a = _convert_other(a, raiseit=True)
5046 return a.next_toward(b, context=self)
5047
5048 def normalize(self, a):
5049 """normalize reduces an operand to its simplest form.
5050
5051 Essentially a plus operation with all trailing zeros removed from the
5052 result.
5053
5054 >>> ExtendedContext.normalize(Decimal('2.1'))
5055 Decimal('2.1')
5056 >>> ExtendedContext.normalize(Decimal('-2.0'))
5057 Decimal('-2')
5058 >>> ExtendedContext.normalize(Decimal('1.200'))
5059 Decimal('1.2')
5060 >>> ExtendedContext.normalize(Decimal('-120'))
5061 Decimal('-1.2E+2')
5062 >>> ExtendedContext.normalize(Decimal('120.00'))
5063 Decimal('1.2E+2')
5064 >>> ExtendedContext.normalize(Decimal('0.00'))
5065 Decimal('0')
5066 >>> ExtendedContext.normalize(6)
5067 Decimal('6')
5068 """
5069 a = _convert_other(a, raiseit=True)
5070 return a.normalize(context=self)
5071
5072 def number_class(self, a):
5073 """Returns an indication of the class of the operand.
5074
5075 The class is one of the following strings:
5076 -sNaN
5077 -NaN
5078 -Infinity
5079 -Normal
5080 -Subnormal
5081 -Zero
5082 +Zero
5083 +Subnormal
5084 +Normal
5085 +Infinity
5086
5087 >>> c = ExtendedContext.copy()
5088 >>> c.Emin = -999
5089 >>> c.Emax = 999
5090 >>> c.number_class(Decimal('Infinity'))
5091 '+Infinity'
5092 >>> c.number_class(Decimal('1E-10'))
5093 '+Normal'
5094 >>> c.number_class(Decimal('2.50'))
5095 '+Normal'
5096 >>> c.number_class(Decimal('0.1E-999'))
5097 '+Subnormal'
5098 >>> c.number_class(Decimal('0'))
5099 '+Zero'
5100 >>> c.number_class(Decimal('-0'))
5101 '-Zero'
5102 >>> c.number_class(Decimal('-0.1E-999'))
5103 '-Subnormal'
5104 >>> c.number_class(Decimal('-1E-10'))
5105 '-Normal'
5106 >>> c.number_class(Decimal('-2.50'))
5107 '-Normal'
5108 >>> c.number_class(Decimal('-Infinity'))
5109 '-Infinity'
5110 >>> c.number_class(Decimal('NaN'))
5111 'NaN'
5112 >>> c.number_class(Decimal('-NaN'))
5113 'NaN'
5114 >>> c.number_class(Decimal('sNaN'))
5115 'sNaN'
5116 >>> c.number_class(123)
5117 '+Normal'
5118 """
5119 a = _convert_other(a, raiseit=True)
5120 return a.number_class(context=self)
5121
5122 def plus(self, a):
5123 """Plus corresponds to unary prefix plus in Python.
5124
5125 The operation is evaluated using the same rules as add; the
5126 operation plus(a) is calculated as add('0', a) where the '0'
5127 has the same exponent as the operand.
5128
5129 >>> ExtendedContext.plus(Decimal('1.3'))
5130 Decimal('1.3')
5131 >>> ExtendedContext.plus(Decimal('-1.3'))
5132 Decimal('-1.3')
5133 >>> ExtendedContext.plus(-1)
5134 Decimal('-1')
5135 """
5136 a = _convert_other(a, raiseit=True)
5137 return a.__pos__(context=self)
5138
5139 def power(self, a, b, modulo=None):
5140 """Raises a to the power of b, to modulo if given.
5141
5142 With two arguments, compute a**b. If a is negative then b
5143 must be integral. The result will be inexact unless b is
5144 integral and the result is finite and can be expressed exactly
5145 in 'precision' digits.
5146
5147 With three arguments, compute (a**b) % modulo. For the
5148 three argument form, the following restrictions on the
5149 arguments hold:
5150
5151 - all three arguments must be integral
5152 - b must be nonnegative
5153 - at least one of a or b must be nonzero
5154 - modulo must be nonzero and have at most 'precision' digits
5155
5156 The result of pow(a, b, modulo) is identical to the result
5157 that would be obtained by computing (a**b) % modulo with
5158 unbounded precision, but is computed more efficiently. It is
5159 always exact.
5160
5161 >>> c = ExtendedContext.copy()
5162 >>> c.Emin = -999
5163 >>> c.Emax = 999
5164 >>> c.power(Decimal('2'), Decimal('3'))
5165 Decimal('8')
5166 >>> c.power(Decimal('-2'), Decimal('3'))
5167 Decimal('-8')
5168 >>> c.power(Decimal('2'), Decimal('-3'))
5169 Decimal('0.125')
5170 >>> c.power(Decimal('1.7'), Decimal('8'))
5171 Decimal('69.7575744')
5172 >>> c.power(Decimal('10'), Decimal('0.301029996'))
5173 Decimal('2.00000000')
5174 >>> c.power(Decimal('Infinity'), Decimal('-1'))
5175 Decimal('0')
5176 >>> c.power(Decimal('Infinity'), Decimal('0'))
5177 Decimal('1')
5178 >>> c.power(Decimal('Infinity'), Decimal('1'))
5179 Decimal('Infinity')
5180 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
5181 Decimal('-0')
5182 >>> c.power(Decimal('-Infinity'), Decimal('0'))
5183 Decimal('1')
5184 >>> c.power(Decimal('-Infinity'), Decimal('1'))
5185 Decimal('-Infinity')
5186 >>> c.power(Decimal('-Infinity'), Decimal('2'))
5187 Decimal('Infinity')
5188 >>> c.power(Decimal('0'), Decimal('0'))
5189 Decimal('NaN')
5190
5191 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
5192 Decimal('11')
5193 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
5194 Decimal('-11')
5195 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
5196 Decimal('1')
5197 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
5198 Decimal('11')
5199 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
5200 Decimal('11729830')
5201 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
5202 Decimal('-0')
5203 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
5204 Decimal('1')
5205 >>> ExtendedContext.power(7, 7)
5206 Decimal('823543')
5207 >>> ExtendedContext.power(Decimal(7), 7)
5208 Decimal('823543')
5209 >>> ExtendedContext.power(7, Decimal(7), 2)
5210 Decimal('1')
5211 """
5212 a = _convert_other(a, raiseit=True)
5213 r = a.__pow__(b, modulo, context=self)
5214 if r is NotImplemented:
5215 raise TypeError("Unable to convert %s to Decimal" % b)
5216 else:
5217 return r
5218
5219 def quantize(self, a, b):
5220 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
5221
5222 The coefficient of the result is derived from that of the left-hand
5223 operand. It may be rounded using the current rounding setting (if the
5224 exponent is being increased), multiplied by a positive power of ten (if
5225 the exponent is being decreased), or is unchanged (if the exponent is
5226 already equal to that of the right-hand operand).
5227
5228 Unlike other operations, if the length of the coefficient after the
5229 quantize operation would be greater than precision then an Invalid
5230 operation condition is raised. This guarantees that, unless there is
5231 an error condition, the exponent of the result of a quantize is always
5232 equal to that of the right-hand operand.
5233
5234 Also unlike other operations, quantize will never raise Underflow, even
5235 if the result is subnormal and inexact.
5236
5237 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
5238 Decimal('2.170')
5239 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
5240 Decimal('2.17')
5241 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
5242 Decimal('2.2')
5243 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
5244 Decimal('2')
5245 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
5246 Decimal('0E+1')
5247 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
5248 Decimal('-Infinity')
5249 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
5250 Decimal('NaN')
5251 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
5252 Decimal('-0')
5253 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
5254 Decimal('-0E+5')
5255 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
5256 Decimal('NaN')
5257 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
5258 Decimal('NaN')
5259 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
5260 Decimal('217.0')
5261 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
5262 Decimal('217')
5263 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
5264 Decimal('2.2E+2')
5265 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
5266 Decimal('2E+2')
5267 >>> ExtendedContext.quantize(1, 2)
5268 Decimal('1')
5269 >>> ExtendedContext.quantize(Decimal(1), 2)
5270 Decimal('1')
5271 >>> ExtendedContext.quantize(1, Decimal(2))
5272 Decimal('1')
5273 """
5274 a = _convert_other(a, raiseit=True)
5275 return a.quantize(b, context=self)
5276
5277 def radix(self):
5278 """Just returns 10, as this is Decimal, :)
5279
5280 >>> ExtendedContext.radix()
5281 Decimal('10')
5282 """
5283 return Decimal(10)
5284
5285 def remainder(self, a, b):
5286 """Returns the remainder from integer division.
5287
5288 The result is the residue of the dividend after the operation of
5289 calculating integer division as described for divide-integer, rounded
5290 to precision digits if necessary. The sign of the result, if
5291 non-zero, is the same as that of the original dividend.
5292
5293 This operation will fail under the same conditions as integer division
5294 (that is, if integer division on the same two operands would fail, the
5295 remainder cannot be calculated).
5296
5297 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
5298 Decimal('2.1')
5299 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
5300 Decimal('1')
5301 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
5302 Decimal('-1')
5303 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
5304 Decimal('0.2')
5305 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
5306 Decimal('0.1')
5307 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
5308 Decimal('1.0')
5309 >>> ExtendedContext.remainder(22, 6)
5310 Decimal('4')
5311 >>> ExtendedContext.remainder(Decimal(22), 6)
5312 Decimal('4')
5313 >>> ExtendedContext.remainder(22, Decimal(6))
5314 Decimal('4')
5315 """
5316 a = _convert_other(a, raiseit=True)
5317 r = a.__mod__(b, context=self)
5318 if r is NotImplemented:
5319 raise TypeError("Unable to convert %s to Decimal" % b)
5320 else:
5321 return r
5322
5323 def remainder_near(self, a, b):
5324 """Returns to be "a - b * n", where n is the integer nearest the exact
5325 value of "x / b" (if two integers are equally near then the even one
5326 is chosen). If the result is equal to 0 then its sign will be the
5327 sign of a.
5328
5329 This operation will fail under the same conditions as integer division
5330 (that is, if integer division on the same two operands would fail, the
5331 remainder cannot be calculated).
5332
5333 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
5334 Decimal('-0.9')
5335 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
5336 Decimal('-2')
5337 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
5338 Decimal('1')
5339 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
5340 Decimal('-1')
5341 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
5342 Decimal('0.2')
5343 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
5344 Decimal('0.1')
5345 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
5346 Decimal('-0.3')
5347 >>> ExtendedContext.remainder_near(3, 11)
5348 Decimal('3')
5349 >>> ExtendedContext.remainder_near(Decimal(3), 11)
5350 Decimal('3')
5351 >>> ExtendedContext.remainder_near(3, Decimal(11))
5352 Decimal('3')
5353 """
5354 a = _convert_other(a, raiseit=True)
5355 return a.remainder_near(b, context=self)
5356
5357 def rotate(self, a, b):
5358 """Returns a rotated copy of a, b times.
5359
5360 The coefficient of the result is a rotated copy of the digits in
5361 the coefficient of the first operand. The number of places of
5362 rotation is taken from the absolute value of the second operand,
5363 with the rotation being to the left if the second operand is
5364 positive or to the right otherwise.
5365
5366 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
5367 Decimal('400000003')
5368 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
5369 Decimal('12')
5370 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
5371 Decimal('891234567')
5372 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
5373 Decimal('123456789')
5374 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
5375 Decimal('345678912')
5376 >>> ExtendedContext.rotate(1333333, 1)
5377 Decimal('13333330')
5378 >>> ExtendedContext.rotate(Decimal(1333333), 1)
5379 Decimal('13333330')
5380 >>> ExtendedContext.rotate(1333333, Decimal(1))
5381 Decimal('13333330')
5382 """
5383 a = _convert_other(a, raiseit=True)
5384 return a.rotate(b, context=self)
5385
5386 def same_quantum(self, a, b):
5387 """Returns True if the two operands have the same exponent.
5388
5389 The result is never affected by either the sign or the coefficient of
5390 either operand.
5391
5392 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
5393 False
5394 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
5395 True
5396 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
5397 False
5398 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
5399 True
5400 >>> ExtendedContext.same_quantum(10000, -1)
5401 True
5402 >>> ExtendedContext.same_quantum(Decimal(10000), -1)
5403 True
5404 >>> ExtendedContext.same_quantum(10000, Decimal(-1))
5405 True
5406 """
5407 a = _convert_other(a, raiseit=True)
5408 return a.same_quantum(b)
5409
5410 def scaleb (self, a, b):
5411 """Returns the first operand after adding the second value its exp.
5412
5413 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
5414 Decimal('0.0750')
5415 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
5416 Decimal('7.50')
5417 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
5418 Decimal('7.50E+3')
5419 >>> ExtendedContext.scaleb(1, 4)
5420 Decimal('1E+4')
5421 >>> ExtendedContext.scaleb(Decimal(1), 4)
5422 Decimal('1E+4')
5423 >>> ExtendedContext.scaleb(1, Decimal(4))
5424 Decimal('1E+4')
5425 """
5426 a = _convert_other(a, raiseit=True)
5427 return a.scaleb(b, context=self)
5428
5429 def shift(self, a, b):
5430 """Returns a shifted copy of a, b times.
5431
5432 The coefficient of the result is a shifted copy of the digits
5433 in the coefficient of the first operand. The number of places
5434 to shift is taken from the absolute value of the second operand,
5435 with the shift being to the left if the second operand is
5436 positive or to the right otherwise. Digits shifted into the
5437 coefficient are zeros.
5438
5439 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
5440 Decimal('400000000')
5441 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
5442 Decimal('0')
5443 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
5444 Decimal('1234567')
5445 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
5446 Decimal('123456789')
5447 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
5448 Decimal('345678900')
5449 >>> ExtendedContext.shift(88888888, 2)
5450 Decimal('888888800')
5451 >>> ExtendedContext.shift(Decimal(88888888), 2)
5452 Decimal('888888800')
5453 >>> ExtendedContext.shift(88888888, Decimal(2))
5454 Decimal('888888800')
5455 """
5456 a = _convert_other(a, raiseit=True)
5457 return a.shift(b, context=self)
5458
5459 def sqrt(self, a):
5460 """Square root of a non-negative number to context precision.
5461
5462 If the result must be inexact, it is rounded using the round-half-even
5463 algorithm.
5464
5465 >>> ExtendedContext.sqrt(Decimal('0'))
5466 Decimal('0')
5467 >>> ExtendedContext.sqrt(Decimal('-0'))
5468 Decimal('-0')
5469 >>> ExtendedContext.sqrt(Decimal('0.39'))
5470 Decimal('0.624499800')
5471 >>> ExtendedContext.sqrt(Decimal('100'))
5472 Decimal('10')
5473 >>> ExtendedContext.sqrt(Decimal('1'))
5474 Decimal('1')
5475 >>> ExtendedContext.sqrt(Decimal('1.0'))
5476 Decimal('1.0')
5477 >>> ExtendedContext.sqrt(Decimal('1.00'))
5478 Decimal('1.0')
5479 >>> ExtendedContext.sqrt(Decimal('7'))
5480 Decimal('2.64575131')
5481 >>> ExtendedContext.sqrt(Decimal('10'))
5482 Decimal('3.16227766')
5483 >>> ExtendedContext.sqrt(2)
5484 Decimal('1.41421356')
5485 >>> ExtendedContext.prec
5486 9
5487 """
5488 a = _convert_other(a, raiseit=True)
5489 return a.sqrt(context=self)
5490
5491 def subtract(self, a, b):
5492 """Return the difference between the two operands.
5493
5494 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
5495 Decimal('0.23')
5496 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
5497 Decimal('0.00')
5498 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
5499 Decimal('-0.77')
5500 >>> ExtendedContext.subtract(8, 5)
5501 Decimal('3')
5502 >>> ExtendedContext.subtract(Decimal(8), 5)
5503 Decimal('3')
5504 >>> ExtendedContext.subtract(8, Decimal(5))
5505 Decimal('3')
5506 """
5507 a = _convert_other(a, raiseit=True)
5508 r = a.__sub__(b, context=self)
5509 if r is NotImplemented:
5510 raise TypeError("Unable to convert %s to Decimal" % b)
5511 else:
5512 return r
5513
5514 def to_eng_string(self, a):
Raymond Hettingerf6ffa982016-08-13 11:15:34 -07005515 """Convert to a string, using engineering notation if an exponent is needed.
5516
5517 Engineering notation has an exponent which is a multiple of 3. This
5518 can leave up to 3 digits to the left of the decimal place and may
5519 require the addition of either one or two trailing zeros.
Stefan Krahb578f8a2014-09-10 17:58:15 +02005520
5521 The operation is not affected by the context.
Raymond Hettingerf6ffa982016-08-13 11:15:34 -07005522
5523 >>> ExtendedContext.to_eng_string(Decimal('123E+1'))
5524 '1.23E+3'
5525 >>> ExtendedContext.to_eng_string(Decimal('123E+3'))
5526 '123E+3'
5527 >>> ExtendedContext.to_eng_string(Decimal('123E-10'))
5528 '12.3E-9'
5529 >>> ExtendedContext.to_eng_string(Decimal('-123E-12'))
5530 '-123E-12'
5531 >>> ExtendedContext.to_eng_string(Decimal('7E-7'))
5532 '700E-9'
5533 >>> ExtendedContext.to_eng_string(Decimal('7E+1'))
5534 '70'
5535 >>> ExtendedContext.to_eng_string(Decimal('0E+1'))
5536 '0.00E+3'
5537
Stefan Krahb578f8a2014-09-10 17:58:15 +02005538 """
5539 a = _convert_other(a, raiseit=True)
5540 return a.to_eng_string(context=self)
5541
5542 def to_sci_string(self, a):
5543 """Converts a number to a string, using scientific notation.
5544
5545 The operation is not affected by the context.
5546 """
5547 a = _convert_other(a, raiseit=True)
5548 return a.__str__(context=self)
5549
5550 def to_integral_exact(self, a):
5551 """Rounds to an integer.
5552
5553 When the operand has a negative exponent, the result is the same
5554 as using the quantize() operation using the given operand as the
5555 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5556 of the operand as the precision setting; Inexact and Rounded flags
5557 are allowed in this operation. The rounding mode is taken from the
5558 context.
5559
5560 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
5561 Decimal('2')
5562 >>> ExtendedContext.to_integral_exact(Decimal('100'))
5563 Decimal('100')
5564 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
5565 Decimal('100')
5566 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
5567 Decimal('102')
5568 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
5569 Decimal('-102')
5570 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
5571 Decimal('1.0E+6')
5572 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
5573 Decimal('7.89E+77')
5574 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
5575 Decimal('-Infinity')
5576 """
5577 a = _convert_other(a, raiseit=True)
5578 return a.to_integral_exact(context=self)
5579
5580 def to_integral_value(self, a):
5581 """Rounds to an integer.
5582
5583 When the operand has a negative exponent, the result is the same
5584 as using the quantize() operation using the given operand as the
5585 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
5586 of the operand as the precision setting, except that no flags will
5587 be set. The rounding mode is taken from the context.
5588
5589 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
5590 Decimal('2')
5591 >>> ExtendedContext.to_integral_value(Decimal('100'))
5592 Decimal('100')
5593 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
5594 Decimal('100')
5595 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
5596 Decimal('102')
5597 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
5598 Decimal('-102')
5599 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
5600 Decimal('1.0E+6')
5601 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
5602 Decimal('7.89E+77')
5603 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
5604 Decimal('-Infinity')
5605 """
5606 a = _convert_other(a, raiseit=True)
5607 return a.to_integral_value(context=self)
5608
5609 # the method name changed, but we provide also the old one, for compatibility
5610 to_integral = to_integral_value
5611
5612class _WorkRep(object):
5613 __slots__ = ('sign','int','exp')
5614 # sign: 0 or 1
5615 # int: int
5616 # exp: None, int, or string
5617
5618 def __init__(self, value=None):
5619 if value is None:
5620 self.sign = None
5621 self.int = 0
5622 self.exp = None
5623 elif isinstance(value, Decimal):
5624 self.sign = value._sign
5625 self.int = int(value._int)
5626 self.exp = value._exp
5627 else:
5628 # assert isinstance(value, tuple)
5629 self.sign = value[0]
5630 self.int = value[1]
5631 self.exp = value[2]
5632
5633 def __repr__(self):
5634 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
5635
5636 __str__ = __repr__
5637
5638
5639
5640def _normalize(op1, op2, prec = 0):
5641 """Normalizes op1, op2 to have the same exp and length of coefficient.
5642
5643 Done during addition.
5644 """
5645 if op1.exp < op2.exp:
5646 tmp = op2
5647 other = op1
5648 else:
5649 tmp = op1
5650 other = op2
5651
5652 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
5653 # Then adding 10**exp to tmp has the same effect (after rounding)
5654 # as adding any positive quantity smaller than 10**exp; similarly
5655 # for subtraction. So if other is smaller than 10**exp we replace
5656 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
5657 tmp_len = len(str(tmp.int))
5658 other_len = len(str(other.int))
5659 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5660 if other_len + other.exp - 1 < exp:
5661 other.int = 1
5662 other.exp = exp
5663
5664 tmp.int *= 10 ** (tmp.exp - other.exp)
5665 tmp.exp = other.exp
5666 return op1, op2
5667
5668##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
5669
5670_nbits = int.bit_length
5671
5672def _decimal_lshift_exact(n, e):
5673 """ Given integers n and e, return n * 10**e if it's an integer, else None.
5674
5675 The computation is designed to avoid computing large powers of 10
5676 unnecessarily.
5677
5678 >>> _decimal_lshift_exact(3, 4)
5679 30000
5680 >>> _decimal_lshift_exact(300, -999999999) # returns None
5681
5682 """
5683 if n == 0:
5684 return 0
5685 elif e >= 0:
5686 return n * 10**e
5687 else:
5688 # val_n = largest power of 10 dividing n.
5689 str_n = str(abs(n))
5690 val_n = len(str_n) - len(str_n.rstrip('0'))
5691 return None if val_n < -e else n // 10**-e
5692
5693def _sqrt_nearest(n, a):
5694 """Closest integer to the square root of the positive integer n. a is
5695 an initial approximation to the square root. Any positive integer
5696 will do for a, but the closer a is to the square root of n the
5697 faster convergence will be.
5698
5699 """
5700 if n <= 0 or a <= 0:
5701 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5702
5703 b=0
5704 while a != b:
5705 b, a = a, a--n//a>>1
5706 return a
5707
5708def _rshift_nearest(x, shift):
5709 """Given an integer x and a nonnegative integer shift, return closest
5710 integer to x / 2**shift; use round-to-even in case of a tie.
5711
5712 """
5713 b, q = 1 << shift, x >> shift
5714 return q + (2*(x & (b-1)) + (q&1) > b)
5715
5716def _div_nearest(a, b):
5717 """Closest integer to a/b, a and b positive integers; rounds to even
5718 in the case of a tie.
5719
5720 """
5721 q, r = divmod(a, b)
5722 return q + (2*r + (q&1) > b)
5723
5724def _ilog(x, M, L = 8):
5725 """Integer approximation to M*log(x/M), with absolute error boundable
5726 in terms only of x/M.
5727
5728 Given positive integers x and M, return an integer approximation to
5729 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5730 between the approximation and the exact result is at most 22. For
5731 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5732 both cases these are upper bounds on the error; it will usually be
5733 much smaller."""
5734
5735 # The basic algorithm is the following: let log1p be the function
5736 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5737 # the reduction
5738 #
5739 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5740 #
5741 # repeatedly until the argument to log1p is small (< 2**-L in
5742 # absolute value). For small y we can use the Taylor series
5743 # expansion
5744 #
5745 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5746 #
5747 # truncating at T such that y**T is small enough. The whole
5748 # computation is carried out in a form of fixed-point arithmetic,
5749 # with a real number z being represented by an integer
5750 # approximation to z*M. To avoid loss of precision, the y below
5751 # is actually an integer approximation to 2**R*y*M, where R is the
5752 # number of reductions performed so far.
5753
5754 y = x-M
5755 # argument reduction; R = number of reductions performed
5756 R = 0
5757 while (R <= L and abs(y) << L-R >= M or
5758 R > L and abs(y) >> R-L >= M):
5759 y = _div_nearest((M*y) << 1,
5760 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5761 R += 1
5762
5763 # Taylor series with T terms
5764 T = -int(-10*len(str(M))//(3*L))
5765 yshift = _rshift_nearest(y, R)
5766 w = _div_nearest(M, T)
5767 for k in range(T-1, 0, -1):
5768 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5769
5770 return _div_nearest(w*y, M)
5771
5772def _dlog10(c, e, p):
5773 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5774 approximation to 10**p * log10(c*10**e), with an absolute error of
5775 at most 1. Assumes that c*10**e is not exactly 1."""
5776
5777 # increase precision by 2; compensate for this by dividing
5778 # final result by 100
5779 p += 2
5780
5781 # write c*10**e as d*10**f with either:
5782 # f >= 0 and 1 <= d <= 10, or
5783 # f <= 0 and 0.1 <= d <= 1.
5784 # Thus for c*10**e close to 1, f = 0
5785 l = len(str(c))
5786 f = e+l - (e+l >= 1)
5787
5788 if p > 0:
5789 M = 10**p
5790 k = e+p-f
5791 if k >= 0:
5792 c *= 10**k
5793 else:
5794 c = _div_nearest(c, 10**-k)
5795
5796 log_d = _ilog(c, M) # error < 5 + 22 = 27
5797 log_10 = _log10_digits(p) # error < 1
5798 log_d = _div_nearest(log_d*M, log_10)
5799 log_tenpower = f*M # exact
5800 else:
5801 log_d = 0 # error < 2.31
5802 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
5803
5804 return _div_nearest(log_tenpower+log_d, 100)
5805
5806def _dlog(c, e, p):
5807 """Given integers c, e and p with c > 0, compute an integer
5808 approximation to 10**p * log(c*10**e), with an absolute error of
5809 at most 1. Assumes that c*10**e is not exactly 1."""
5810
5811 # Increase precision by 2. The precision increase is compensated
5812 # for at the end with a division by 100.
5813 p += 2
5814
5815 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5816 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5817 # as 10**p * log(d) + 10**p*f * log(10).
5818 l = len(str(c))
5819 f = e+l - (e+l >= 1)
5820
5821 # compute approximation to 10**p*log(d), with error < 27
5822 if p > 0:
5823 k = e+p-f
5824 if k >= 0:
5825 c *= 10**k
5826 else:
5827 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5828
5829 # _ilog magnifies existing error in c by a factor of at most 10
5830 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5831 else:
5832 # p <= 0: just approximate the whole thing by 0; error < 2.31
5833 log_d = 0
5834
5835 # compute approximation to f*10**p*log(10), with error < 11.
5836 if f:
5837 extra = len(str(abs(f)))-1
5838 if p + extra >= 0:
5839 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5840 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5841 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
5842 else:
5843 f_log_ten = 0
5844 else:
5845 f_log_ten = 0
5846
5847 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
5848 return _div_nearest(f_log_ten + log_d, 100)
5849
5850class _Log10Memoize(object):
5851 """Class to compute, store, and allow retrieval of, digits of the
5852 constant log(10) = 2.302585.... This constant is needed by
5853 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5854 def __init__(self):
5855 self.digits = "23025850929940456840179914546843642076011014886"
5856
5857 def getdigits(self, p):
5858 """Given an integer p >= 0, return floor(10**p)*log(10).
5859
5860 For example, self.getdigits(3) returns 2302.
5861 """
5862 # digits are stored as a string, for quick conversion to
5863 # integer in the case that we've already computed enough
5864 # digits; the stored digits should always be correct
5865 # (truncated, not rounded to nearest).
5866 if p < 0:
5867 raise ValueError("p should be nonnegative")
5868
5869 if p >= len(self.digits):
5870 # compute p+3, p+6, p+9, ... digits; continue until at
5871 # least one of the extra digits is nonzero
5872 extra = 3
5873 while True:
5874 # compute p+extra digits, correct to within 1ulp
5875 M = 10**(p+extra+2)
5876 digits = str(_div_nearest(_ilog(10*M, M), 100))
5877 if digits[-extra:] != '0'*extra:
5878 break
5879 extra += 3
5880 # keep all reliable digits so far; remove trailing zeros
5881 # and next nonzero digit
5882 self.digits = digits.rstrip('0')[:-1]
5883 return int(self.digits[:p+1])
5884
5885_log10_digits = _Log10Memoize().getdigits
5886
5887def _iexp(x, M, L=8):
5888 """Given integers x and M, M > 0, such that x/M is small in absolute
5889 value, compute an integer approximation to M*exp(x/M). For 0 <=
5890 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5891 is usually much smaller)."""
5892
5893 # Algorithm: to compute exp(z) for a real number z, first divide z
5894 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5895 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5896 # series
5897 #
5898 # expm1(x) = x + x**2/2! + x**3/3! + ...
5899 #
5900 # Now use the identity
5901 #
5902 # expm1(2x) = expm1(x)*(expm1(x)+2)
5903 #
5904 # R times to compute the sequence expm1(z/2**R),
5905 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5906
5907 # Find R such that x/2**R/M <= 2**-L
5908 R = _nbits((x<<L)//M)
5909
5910 # Taylor series. (2**L)**T > M
5911 T = -int(-10*len(str(M))//(3*L))
5912 y = _div_nearest(x, T)
5913 Mshift = M<<R
5914 for i in range(T-1, 0, -1):
5915 y = _div_nearest(x*(Mshift + y), Mshift * i)
5916
5917 # Expansion
5918 for k in range(R-1, -1, -1):
5919 Mshift = M<<(k+2)
5920 y = _div_nearest(y*(y+Mshift), Mshift)
5921
5922 return M+y
5923
5924def _dexp(c, e, p):
5925 """Compute an approximation to exp(c*10**e), with p decimal places of
5926 precision.
5927
5928 Returns integers d, f such that:
5929
5930 10**(p-1) <= d <= 10**p, and
5931 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5932
5933 In other words, d*10**f is an approximation to exp(c*10**e) with p
5934 digits of precision, and with an error in d of at most 1. This is
5935 almost, but not quite, the same as the error being < 1ulp: when d
5936 = 10**(p-1) the error could be up to 10 ulp."""
5937
5938 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5939 p += 2
5940
5941 # compute log(10) with extra precision = adjusted exponent of c*10**e
5942 extra = max(0, e + len(str(c)) - 1)
5943 q = p + extra
5944
5945 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5946 # rounding down
5947 shift = e+q
5948 if shift >= 0:
5949 cshift = c*10**shift
5950 else:
5951 cshift = c//10**-shift
5952 quot, rem = divmod(cshift, _log10_digits(q))
5953
5954 # reduce remainder back to original precision
5955 rem = _div_nearest(rem, 10**extra)
5956
5957 # error in result of _iexp < 120; error after division < 0.62
5958 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5959
5960def _dpower(xc, xe, yc, ye, p):
5961 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5962 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5963
5964 10**(p-1) <= c <= 10**p, and
5965 (c-1)*10**e < x**y < (c+1)*10**e
5966
5967 in other words, c*10**e is an approximation to x**y with p digits
5968 of precision, and with an error in c of at most 1. (This is
5969 almost, but not quite, the same as the error being < 1ulp: when c
5970 == 10**(p-1) we can only guarantee error < 10ulp.)
5971
5972 We assume that: x is positive and not equal to 1, and y is nonzero.
5973 """
5974
5975 # Find b such that 10**(b-1) <= |y| <= 10**b
5976 b = len(str(abs(yc))) + ye
5977
5978 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5979 lxc = _dlog(xc, xe, p+b+1)
5980
5981 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5982 shift = ye-b
5983 if shift >= 0:
5984 pc = lxc*yc*10**shift
5985 else:
5986 pc = _div_nearest(lxc*yc, 10**-shift)
5987
5988 if pc == 0:
5989 # we prefer a result that isn't exactly 1; this makes it
5990 # easier to compute a correctly rounded result in __pow__
5991 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5992 coeff, exp = 10**(p-1)+1, 1-p
5993 else:
5994 coeff, exp = 10**p-1, -p
5995 else:
5996 coeff, exp = _dexp(pc, -(p+1), p+1)
5997 coeff = _div_nearest(coeff, 10)
5998 exp += 1
5999
6000 return coeff, exp
6001
6002def _log10_lb(c, correction = {
6003 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
6004 '6': 23, '7': 16, '8': 10, '9': 5}):
6005 """Compute a lower bound for 100*log10(c) for a positive integer c."""
6006 if c <= 0:
6007 raise ValueError("The argument to _log10_lb should be nonnegative.")
6008 str_c = str(c)
6009 return 100*len(str_c) - correction[str_c[0]]
6010
6011##### Helper Functions ####################################################
6012
6013def _convert_other(other, raiseit=False, allow_float=False):
6014 """Convert other to Decimal.
6015
6016 Verifies that it's ok to use in an implicit construction.
6017 If allow_float is true, allow conversion from float; this
6018 is used in the comparison methods (__eq__ and friends).
6019
6020 """
6021 if isinstance(other, Decimal):
6022 return other
6023 if isinstance(other, int):
6024 return Decimal(other)
6025 if allow_float and isinstance(other, float):
6026 return Decimal.from_float(other)
6027
6028 if raiseit:
6029 raise TypeError("Unable to convert %s to Decimal" % other)
6030 return NotImplemented
6031
6032def _convert_for_comparison(self, other, equality_op=False):
6033 """Given a Decimal instance self and a Python object other, return
6034 a pair (s, o) of Decimal instances such that "s op o" is
6035 equivalent to "self op other" for any of the 6 comparison
6036 operators "op".
6037
6038 """
6039 if isinstance(other, Decimal):
6040 return self, other
6041
6042 # Comparison with a Rational instance (also includes integers):
6043 # self op n/d <=> self*d op n (for n and d integers, d positive).
6044 # A NaN or infinity can be left unchanged without affecting the
6045 # comparison result.
6046 if isinstance(other, _numbers.Rational):
6047 if not self._is_special:
6048 self = _dec_from_triple(self._sign,
6049 str(int(self._int) * other.denominator),
6050 self._exp)
6051 return self, Decimal(other.numerator)
6052
6053 # Comparisons with float and complex types. == and != comparisons
6054 # with complex numbers should succeed, returning either True or False
6055 # as appropriate. Other comparisons return NotImplemented.
6056 if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0:
6057 other = other.real
6058 if isinstance(other, float):
6059 context = getcontext()
6060 if equality_op:
6061 context.flags[FloatOperation] = 1
6062 else:
6063 context._raise_error(FloatOperation,
6064 "strict semantics for mixing floats and Decimals are enabled")
6065 return self, Decimal.from_float(other)
6066 return NotImplemented, NotImplemented
6067
6068
6069##### Setup Specific Contexts ############################################
6070
6071# The default context prototype used by Context()
6072# Is mutable, so that new contexts can have different default values
6073
6074DefaultContext = Context(
6075 prec=28, rounding=ROUND_HALF_EVEN,
6076 traps=[DivisionByZero, Overflow, InvalidOperation],
6077 flags=[],
6078 Emax=999999,
6079 Emin=-999999,
6080 capitals=1,
6081 clamp=0
6082)
6083
6084# Pre-made alternate contexts offered by the specification
6085# Don't change these; the user should be able to select these
6086# contexts and be able to reproduce results from other implementations
6087# of the spec.
6088
6089BasicContext = Context(
6090 prec=9, rounding=ROUND_HALF_UP,
6091 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
6092 flags=[],
6093)
6094
6095ExtendedContext = Context(
6096 prec=9, rounding=ROUND_HALF_EVEN,
6097 traps=[],
6098 flags=[],
6099)
6100
6101
6102##### crud for parsing strings #############################################
6103#
6104# Regular expression used for parsing numeric strings. Additional
6105# comments:
6106#
6107# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
6108# whitespace. But note that the specification disallows whitespace in
6109# a numeric string.
6110#
6111# 2. For finite numbers (not infinities and NaNs) the body of the
6112# number between the optional sign and the optional exponent must have
6113# at least one decimal digit, possibly after the decimal point. The
6114# lookahead expression '(?=\d|\.\d)' checks this.
6115
6116import re
6117_parser = re.compile(r""" # A numeric string consists of:
6118# \s*
6119 (?P<sign>[-+])? # an optional sign, followed by either...
6120 (
6121 (?=\d|\.\d) # ...a number (with at least one digit)
6122 (?P<int>\d*) # having a (possibly empty) integer part
6123 (\.(?P<frac>\d*))? # followed by an optional fractional part
6124 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
6125 |
6126 Inf(inity)? # ...an infinity, or...
6127 |
6128 (?P<signal>s)? # ...an (optionally signaling)
6129 NaN # NaN
6130 (?P<diag>\d*) # with (possibly empty) diagnostic info.
6131 )
6132# \s*
6133 \Z
6134""", re.VERBOSE | re.IGNORECASE).match
6135
6136_all_zeros = re.compile('0*$').match
6137_exact_half = re.compile('50*$').match
6138
6139##### PEP3101 support functions ##############################################
6140# The functions in this section have little to do with the Decimal
6141# class, and could potentially be reused or adapted for other pure
6142# Python numeric classes that want to implement __format__
6143#
6144# A format specifier for Decimal looks like:
6145#
6146# [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
6147
6148_parse_format_specifier_regex = re.compile(r"""\A
6149(?:
6150 (?P<fill>.)?
6151 (?P<align>[<>=^])
6152)?
6153(?P<sign>[-+ ])?
6154(?P<alt>\#)?
6155(?P<zeropad>0)?
6156(?P<minimumwidth>(?!0)\d+)?
6157(?P<thousands_sep>,)?
6158(?:\.(?P<precision>0|(?!0)\d+))?
6159(?P<type>[eEfFgGn%])?
6160\Z
6161""", re.VERBOSE|re.DOTALL)
6162
6163del re
6164
6165# The locale module is only needed for the 'n' format specifier. The
6166# rest of the PEP 3101 code functions quite happily without it, so we
6167# don't care too much if locale isn't present.
6168try:
6169 import locale as _locale
6170except ImportError:
6171 pass
6172
6173def _parse_format_specifier(format_spec, _localeconv=None):
6174 """Parse and validate a format specifier.
6175
6176 Turns a standard numeric format specifier into a dict, with the
6177 following entries:
6178
6179 fill: fill character to pad field to minimum width
6180 align: alignment type, either '<', '>', '=' or '^'
6181 sign: either '+', '-' or ' '
6182 minimumwidth: nonnegative integer giving minimum width
6183 zeropad: boolean, indicating whether to pad with zeros
6184 thousands_sep: string to use as thousands separator, or ''
6185 grouping: grouping for thousands separators, in format
6186 used by localeconv
6187 decimal_point: string to use for decimal point
6188 precision: nonnegative integer giving precision, or None
6189 type: one of the characters 'eEfFgG%', or None
6190
6191 """
6192 m = _parse_format_specifier_regex.match(format_spec)
6193 if m is None:
6194 raise ValueError("Invalid format specifier: " + format_spec)
6195
6196 # get the dictionary
6197 format_dict = m.groupdict()
6198
6199 # zeropad; defaults for fill and alignment. If zero padding
6200 # is requested, the fill and align fields should be absent.
6201 fill = format_dict['fill']
6202 align = format_dict['align']
6203 format_dict['zeropad'] = (format_dict['zeropad'] is not None)
6204 if format_dict['zeropad']:
6205 if fill is not None:
6206 raise ValueError("Fill character conflicts with '0'"
6207 " in format specifier: " + format_spec)
6208 if align is not None:
6209 raise ValueError("Alignment conflicts with '0' in "
6210 "format specifier: " + format_spec)
6211 format_dict['fill'] = fill or ' '
6212 # PEP 3101 originally specified that the default alignment should
6213 # be left; it was later agreed that right-aligned makes more sense
6214 # for numeric types. See http://bugs.python.org/issue6857.
6215 format_dict['align'] = align or '>'
6216
6217 # default sign handling: '-' for negative, '' for positive
6218 if format_dict['sign'] is None:
6219 format_dict['sign'] = '-'
6220
6221 # minimumwidth defaults to 0; precision remains None if not given
6222 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
6223 if format_dict['precision'] is not None:
6224 format_dict['precision'] = int(format_dict['precision'])
6225
6226 # if format type is 'g' or 'G' then a precision of 0 makes little
6227 # sense; convert it to 1. Same if format type is unspecified.
6228 if format_dict['precision'] == 0:
6229 if format_dict['type'] is None or format_dict['type'] in 'gGn':
6230 format_dict['precision'] = 1
6231
6232 # determine thousands separator, grouping, and decimal separator, and
6233 # add appropriate entries to format_dict
6234 if format_dict['type'] == 'n':
6235 # apart from separators, 'n' behaves just like 'g'
6236 format_dict['type'] = 'g'
6237 if _localeconv is None:
6238 _localeconv = _locale.localeconv()
6239 if format_dict['thousands_sep'] is not None:
6240 raise ValueError("Explicit thousands separator conflicts with "
6241 "'n' type in format specifier: " + format_spec)
6242 format_dict['thousands_sep'] = _localeconv['thousands_sep']
6243 format_dict['grouping'] = _localeconv['grouping']
6244 format_dict['decimal_point'] = _localeconv['decimal_point']
6245 else:
6246 if format_dict['thousands_sep'] is None:
6247 format_dict['thousands_sep'] = ''
6248 format_dict['grouping'] = [3, 0]
6249 format_dict['decimal_point'] = '.'
6250
6251 return format_dict
6252
6253def _format_align(sign, body, spec):
6254 """Given an unpadded, non-aligned numeric string 'body' and sign
6255 string 'sign', add padding and alignment conforming to the given
6256 format specifier dictionary 'spec' (as produced by
6257 parse_format_specifier).
6258
6259 """
6260 # how much extra space do we have to play with?
6261 minimumwidth = spec['minimumwidth']
6262 fill = spec['fill']
6263 padding = fill*(minimumwidth - len(sign) - len(body))
6264
6265 align = spec['align']
6266 if align == '<':
6267 result = sign + body + padding
6268 elif align == '>':
6269 result = padding + sign + body
6270 elif align == '=':
6271 result = sign + padding + body
6272 elif align == '^':
6273 half = len(padding)//2
6274 result = padding[:half] + sign + body + padding[half:]
6275 else:
6276 raise ValueError('Unrecognised alignment field')
6277
6278 return result
6279
6280def _group_lengths(grouping):
6281 """Convert a localeconv-style grouping into a (possibly infinite)
6282 iterable of integers representing group lengths.
6283
6284 """
6285 # The result from localeconv()['grouping'], and the input to this
6286 # function, should be a list of integers in one of the
6287 # following three forms:
6288 #
6289 # (1) an empty list, or
6290 # (2) nonempty list of positive integers + [0]
6291 # (3) list of positive integers + [locale.CHAR_MAX], or
6292
6293 from itertools import chain, repeat
6294 if not grouping:
6295 return []
6296 elif grouping[-1] == 0 and len(grouping) >= 2:
6297 return chain(grouping[:-1], repeat(grouping[-2]))
6298 elif grouping[-1] == _locale.CHAR_MAX:
6299 return grouping[:-1]
6300 else:
6301 raise ValueError('unrecognised format for grouping')
6302
6303def _insert_thousands_sep(digits, spec, min_width=1):
6304 """Insert thousands separators into a digit string.
6305
6306 spec is a dictionary whose keys should include 'thousands_sep' and
6307 'grouping'; typically it's the result of parsing the format
6308 specifier using _parse_format_specifier.
6309
6310 The min_width keyword argument gives the minimum length of the
6311 result, which will be padded on the left with zeros if necessary.
6312
6313 If necessary, the zero padding adds an extra '0' on the left to
6314 avoid a leading thousands separator. For example, inserting
6315 commas every three digits in '123456', with min_width=8, gives
6316 '0,123,456', even though that has length 9.
6317
6318 """
6319
6320 sep = spec['thousands_sep']
6321 grouping = spec['grouping']
6322
6323 groups = []
6324 for l in _group_lengths(grouping):
6325 if l <= 0:
6326 raise ValueError("group length should be positive")
6327 # max(..., 1) forces at least 1 digit to the left of a separator
6328 l = min(max(len(digits), min_width, 1), l)
6329 groups.append('0'*(l - len(digits)) + digits[-l:])
6330 digits = digits[:-l]
6331 min_width -= l
6332 if not digits and min_width <= 0:
6333 break
6334 min_width -= len(sep)
6335 else:
6336 l = max(len(digits), min_width, 1)
6337 groups.append('0'*(l - len(digits)) + digits[-l:])
6338 return sep.join(reversed(groups))
6339
6340def _format_sign(is_negative, spec):
6341 """Determine sign character."""
6342
6343 if is_negative:
6344 return '-'
6345 elif spec['sign'] in ' +':
6346 return spec['sign']
6347 else:
6348 return ''
6349
6350def _format_number(is_negative, intpart, fracpart, exp, spec):
6351 """Format a number, given the following data:
6352
6353 is_negative: true if the number is negative, else false
6354 intpart: string of digits that must appear before the decimal point
6355 fracpart: string of digits that must come after the point
6356 exp: exponent, as an integer
6357 spec: dictionary resulting from parsing the format specifier
6358
6359 This function uses the information in spec to:
6360 insert separators (decimal separator and thousands separators)
6361 format the sign
6362 format the exponent
6363 add trailing '%' for the '%' type
6364 zero-pad if necessary
6365 fill and align if necessary
6366 """
6367
6368 sign = _format_sign(is_negative, spec)
6369
6370 if fracpart or spec['alt']:
6371 fracpart = spec['decimal_point'] + fracpart
6372
6373 if exp != 0 or spec['type'] in 'eE':
6374 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
6375 fracpart += "{0}{1:+}".format(echar, exp)
6376 if spec['type'] == '%':
6377 fracpart += '%'
6378
6379 if spec['zeropad']:
6380 min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
6381 else:
6382 min_width = 0
6383 intpart = _insert_thousands_sep(intpart, spec, min_width)
6384
6385 return _format_align(sign, intpart+fracpart, spec)
6386
6387
6388##### Useful Constants (internal use only) ################################
6389
6390# Reusable defaults
6391_Infinity = Decimal('Inf')
6392_NegativeInfinity = Decimal('-Inf')
6393_NaN = Decimal('NaN')
6394_Zero = Decimal(0)
6395_One = Decimal(1)
6396_NegativeOne = Decimal(-1)
6397
6398# _SignedInfinity[sign] is infinity w/ that sign
6399_SignedInfinity = (_Infinity, _NegativeInfinity)
6400
6401# Constants related to the hash implementation; hash(x) is based
6402# on the reduction of x modulo _PyHASH_MODULUS
6403_PyHASH_MODULUS = sys.hash_info.modulus
6404# hash values to use for positive and negative infinities, and nans
6405_PyHASH_INF = sys.hash_info.inf
6406_PyHASH_NAN = sys.hash_info.nan
6407
6408# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
6409_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
6410del sys