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