ยปCore Development>Code coverage>Lib/_pydecimal.py

Python code coverage for Lib/_pydecimal.py

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