Debian Codegraph @

lib-python/3/_pydecimal.py

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