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