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