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