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