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