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