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