1 (define-module (language python module decimal
)
2 #:use-module
((language python module collections
) #:select
(namedtuple))
5 (define guile
:modulo
(@ (guile) moduolo
))
7 (define __name__
"decimal")
8 (define __xname__ __name__
)
9 (define __version__
"1.70")
10 ;; Highest version of the spec this complies with
11 ;; See http://speleotrove.com/decimal/
14 (define DecimalTuple
(namedtuple "DecimalTuple" "sign digits exponent"))
17 (define ROUND_DOWN
'ROUND_DOWN
)
18 (define ROUND_HALF_UP
'ROUND_HALF_UP
)
19 (define ROUND_HALF_EVEN
'ROUND_HALF_EVEN
)
20 (define ROUND_CEILING
'ROUND_CEILING
)
21 (define ROUND_FLOOR
'ROUND_FLOOR
)
22 (define ROUND_UP
'ROUND_UP
)
23 (define ROUND_HALF_DOWN
'ROUND_HALF_DOWN
)
24 (define ROUND_05UP
'ROUND_05UP
)
26 ;; Compatibility with the C version
27 (define MAX_PREC
425000000)
28 (define MAX_EMAX
425000000)
29 (define MIN_EMIN -
425000000)
31 (if (= sys
:maxsize
(- (ash 1 63) 1))
33 (set! MAX_PREC
999999999999999999)
34 (set! MAX_EMAX
999999999999999999)
35 (set! MIN_EMIN -
999999999999999999)))
37 (define MIN_ETINY
(- MIN_EMIN
(- MAX_PREC
1)))
40 (define (cx-prec x
) (vector-ref x
0))
41 (define (cx-emax x
) (vector-ref x
1))
42 (define (cx-raise x
) (vector-ref x
2))
43 (define (cx-error x
) (vector-ref x
3))
44 (define (cx-capitals x
) (vector-ref x
4))
45 (define (cx-rounding x
) (vector-ref x
5))
48 (define-python-class DecimalException
(ArithmeticError)
49 "Base exception class.
51 Used exceptions derive from this.
52 If an exception derives from another exception besides this (such as
53 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
54 called if the others are present. This isn't actually used for
57 handle -- Called when context._raise_error is called and the
58 trap_enabler is not set. First argument is self, second is the
59 context. More arguments can be given, those being after
60 the explanation in _raise_error (For example,
61 context._raise_error(NewError, '(-x)!', self._sign) would
62 call NewError().handle(context, self._sign).)
64 To define a new exception, it should be sufficient to have it derive
65 from DecimalException.
69 (lambda (self context . args
)
73 (define-python-class Clamped
(DecimalException)
74 """Exponent of a 0 changed to fit bounds.
76 This occurs and signals clamped if the exponent of a result has been
77 altered in order to fit the constraints of a specific concrete
78 representation. This may occur when the exponent of a zero result would
79 be outside the bounds of a representation, or when a large normal
80 number would have an encoded exponent that cannot be represented. In
81 this latter case, the exponent is reduced to fit and the corresponding
82 number of zero digits are appended to the coefficient ("fold-down
").
85 (define-python-class InvalidOperation
(DecimalException)
86 "An invalid operation was performed.
88 Various bad things cause this:
90 Something creates a signaling NaN
96 x._rescale( non-integer )
101 An operand is invalid
103 The result of the operation after these is a quiet positive NaN,
104 except when the cause is a signaling NaN, in which case the result is
105 also a quiet NaN, but with the original sign, and an optional
106 diagnostic information.
109 (lambda (self context . args
)
111 (let ((ans (_dec_from_triple
112 (ref (car args
) '_sign
)
113 (ref (car args
) '_int
)
115 ((ref ans
'_fix_nan
) context
))
118 (define-python-class ConversionSyntax
(InvalidOperation)
119 "Trying to convert badly formed string.
121 This occurs and signals invalid-operation if a string is being
122 converted to a number and it does not conform to the numeric string
123 syntax. The result is [0,qNaN].
128 (define-python-class DivisionByZero
(DecimalException ZeroDivisionError
)
131 This occurs and signals division-by-zero if division of a finite number
132 by zero was attempted (during a divide-integer or divide operation, or a
133 power operation with negative right-hand operand), and the dividend was
136 The result of the operation is [sign,inf], where sign is the exclusive
137 or of the signs of the operands for divide, or is 1 for an odd power of
142 (lambda (self context sign . args
)
143 (pylist-ref _SignedInfinity sign
))))
145 (define-python-class DivisionImpossible
(InvalidOperation)
146 "Cannot perform the division adequately.
148 This occurs and signals invalid-operation if the integer result of a
149 divide-integer or remainder operation had too many digits (would be
150 longer than precision). The result is [0,qNaN].
156 (define-python-class DivisionUndefined
(InvalidOperation ZeroDivisionError
)
157 "Undefined result of division.
159 This occurs and signals invalid-operation if division by zero was
160 attempted (during a divide-integer, divide, or remainder operation), and
161 the dividend is also zero. The result is [0,qNaN].
167 (define-python-class Inexact
(DecimalException)
168 "Had to round, losing information.
170 This occurs and signals inexact whenever the result of an operation is
171 not exact (that is, it needed to be rounded and any discarded digits
172 were non-zero), or if an overflow or underflow condition occurs. The
173 result in all cases is unchanged.
175 The inexact signal may be tested (or trapped) to determine if a given
176 operation (or sequence of operations) was inexact.
179 (define-python-class InvalidContext
(InvalidOperation)
180 "Invalid context. Unknown rounding, for example.
182 This occurs and signals invalid-operation if an invalid context was
183 detected during an operation. This can occur if contexts are not checked
184 on creation and either the precision exceeds the capability of the
185 underlying concrete representation or an unknown or unsupported rounding
186 was specified. These aspects of the context need only be checked when
187 the values are required to be used. The result is [0,qNaN].
193 (define-python-class Rounded
(DecimalException)
194 "Number got rounded (not necessarily changed during rounding).
196 This occurs and signals rounded whenever the result of an operation is
197 rounded (that is, some zero or non-zero digits were discarded from the
198 coefficient), or if an overflow or underflow condition occurs. The
199 result in all cases is unchanged.
201 The rounded signal may be tested (or trapped) to determine if a given
202 operation (or sequence of operations) caused a loss of precision.
205 (define-python-class Subnormal
(DecimalException)
206 "Exponent < Emin before rounding.
208 This occurs and signals subnormal whenever the result of a conversion or
209 operation is subnormal (that is, its adjusted exponent is less than
210 Emin, before any rounding). The result in all cases is unchanged.
212 The subnormal signal may be tested (or trapped) to determine if a given
213 or operation (or sequence of operations) yielded a subnormal result.
216 (define-python-class Overflow
(Inexact Rounded
)
219 This occurs and signals overflow if the adjusted exponent of a result
220 (from a conversion or from an operation that is not an attempt to divide
221 by zero), after rounding, would be greater than the largest value that
222 can be handled by the implementation (the value Emax).
224 The result depends on the rounding mode:
226 For round-half-up and round-half-even (and for round-half-down and
227 round-up, if implemented), the result of the operation is [sign,inf],
228 where sign is the sign of the intermediate result. For round-down, the
229 result is the largest finite number that can be represented in the
230 current precision, with the sign of the intermediate result. For
231 round-ceiling, the result is the same as for round-down if the sign of
232 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
233 the result is the same as for round-down if the sign of the intermediate
234 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
239 (let ((l (list ROUND_HALF_UP ROUND_HALF_EVEN
240 ROUND_HALF_DOWN ROUND_U
)))
241 (lambda (self context sign . args
)
243 (if (memq (ref context
'rounding
) l
)
244 (ret (pylist-ref _SignedInfinity sign
)))
247 (if (eq?
(ref context
'rounding
) ROUND_CEILING
)
248 (ret (pylist-ref _SignedInfinity sign
))
249 (ret (_dec_from_triple
251 (* "9" (cx-prec context
))
252 (+ (- (cx-emax context
) (cx-prec context
)) 1)))))
255 (if (eq?
(ref context
'rounding
) ROUND_FLOOR
)
256 (ret (pylist-ref _SignedInfinity sign
))
257 (ret (_dec_from_triple
259 (* "9" (cx-prec context
))
260 (+ (- (cx-emax context
) (cx-prec context
)) 1))))))))))
263 (define-python-class Underflow
(Inexact Rounded Subnormal
)
264 "Numerical underflow with result rounded to 0.
266 This occurs and signals underflow if a result is inexact and the
267 adjusted exponent of the result would be smaller (more negative) than
268 the smallest value that can be handled by the implementation (the value
269 Emin). That is, the result is both inexact and subnormal.
271 The result after an underflow will be a subnormal number rounded, if
272 necessary, so that its exponent is not less than Etiny. This may result
273 in 0 with the sign of the intermediate result and an exponent of Etiny.
275 In all cases, Inexact, Rounded, and Subnormal will also be raised.
278 (define-python-class FloatOperation
(DecimalException TypeError
)
279 """Enable stricter semantics for mixing floats and Decimals.
281 If the signal is not trapped (default), mixing floats and Decimals is
282 permitted in the Decimal() constructor, context.create_decimal() and
283 all comparison operators. Both conversion and comparisons are exact.
284 Any occurrence of a mixed operation is silently recorded by setting
285 FloatOperation in the context flags. Explicit conversions with
286 Decimal.from_float() or context.create_decimal_from_float() do not
289 Otherwise (the signal is trapped), only equality comparisons and explicit
290 conversions are silent. All other mixed operations raise FloatOperation.
293 ;; List of public traps and flags
295 (vector Clamped DivisionByZero Inexact Overflow Rounded
,
296 Underflow InvalidOperation Subnormal FloatOperation
))
298 ;; Map conditions (per the spec) to signals
299 (define _condition_map
300 `((,ConversionSyntax .
,InvalidOperation
)
301 (,DivisionImpossible .
,InvalidOperation
)
302 (,DivisionUndefined .
,InvalidOperation
)
303 (,InvalidContext .
,InvalidOperation
)))
305 ;; Valid rounding modes
306 (define _rounding_modes
307 (list ROUND_DOWN ROUND_HALF_UP ROUND_HALF_EVEN ROUND_CEILING
,
308 ROUND_FLOOR ROUND_UP ROUND_HALF_DOWN ROUND_05UP
))
310 ;; ##### Context Functions ##################################################
312 ;; The getcontext() and setcontext() function manage access to a thread-local
314 (define *context
* (make-fluid #f
))
316 (fluid-ref *context
*))
317 (define (setcontext context
)
318 (fluid-set! *context
* context
))
320 ;; ##### Decimal class #######################################################
322 ;; Do not subclass Decimal from numbers.Real and do not register it as such
323 ;; (because Decimals are not interoperable with floats). See the notes in
324 ;; numbers.py for more detail.
326 (define _dec_from_triple
327 (lam (sign coefficient exponent
(= special
#f
))
328 "Create a decimal instance directly, without any validation,
329 normalization (e.g. removal of leading zeros) or argument
332 This function is for *internal use only*.
334 (Decimal sign coeficient exponent special
)))
336 (def _mk
(self (= value
"0") (= context None
))
337 "Create a decimal point instance.
339 >>> Decimal('3.14') # string input
341 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
343 >>> Decimal(314) # int
345 >>> Decimal(Decimal(314)) # another decimal instance
347 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
351 ;; Note that the coefficient, self._int, is actually stored as
352 ;; a string rather than as a tuple of digits. This speeds up
353 ;; the "digits to integer" and "integer to digits" conversions
354 ;; that are used in almost every arithmetic operation on
355 ;; Decimals. This is an internal detail: the as_tuple function
356 ;; and the Decimal constructor still deal with tuples of
360 ;; REs insist on real strings, so we can too.
362 ((isinstance value str
)
363 (let ((m (parser (scm-str str
))))
365 (let ((context (if (eq? context None
)
370 (+ "Invalid literal for Decimal: " value
))))
372 (let ((sign (get-parsed-sign m
))
373 (intpart (get-parsed-int m
))
374 (fracpart (get-parsed-frac m
))
375 (exp (get-parsed-exp m
))
376 (diag (get-parsed-diag m
))
377 (signal (get-parsed-sig m
)))
379 (set self
'sign sign
)
381 (if (not (eq? intpart None
))
383 (set self
'_int
(str (int (+ intpart fracpart
))))
384 (set self
'_exp
(- exp
(len fracpart
)))
385 (set self
'_is_special False
))
387 (if (not (eq? diag None
))
391 (py-lstrip (str (int (if (bool diag
)
397 (set self
'_exp
"n")))
401 (set self
'_exp
"F")))
402 (set self
'_is_special
#t
))))))
405 ((isinstance value int
)
410 (set self
'_int
(str (abs value
)))
411 (set self
'_is_special
#f
))
413 ;; From another decimal
414 ((isinstance value Decimal
)
415 (set self
'_exp
(ref value
'_exp
))
416 (set self
'_sign
(ref value
'_sign
))
417 (set self
'_int
(ref value
'_int
))
418 (set self
'_is_special
(ref value
'_is_special
)))
420 ;; From an internal working value
421 ((isinstance value _WorkRep
)
422 (set self
'_exp
(int (ref value
'_exp
)))
423 (set self
'_sign
(ref value
'_sign
))
424 (set self
'_int
(str (ref value
'int
)))
425 (set self
'_is_special
#f
))
427 ;; tuple/list conversion (possibly from as_tuple())
428 ((isinstance value
(list list tuple
))
429 (if (not (= (len value
) 3))
431 (+ "Invalid tuple size in creation of Decimal "
432 "from list or tuple. The list or tuple "
433 "should have exactly three elements."))))
434 ;; # process sign. The isinstance test rejects floats
435 (let ((v0 (pylist-ref value
0))
436 (v1 (pylist-ref value
1))
437 (v2 (pylist-ref value
2)))
438 (if (not (and (isinstance v0 int
)
439 (or (= v0
0) (= v0
1))))
441 (+ "Invalid sign. The first value in the tuple "
442 "should be an integer; either 0 for a "
443 "positive number or 1 for a negative number."))))
449 (set self
'is_special
#t
))
450 (let ((digits (py-list)))
451 ;; process and validate the digits in value[1]
452 (for ((digit : v1
)) ()
453 (if (and (isinstance digit int
)
456 ;; skip leading zeros
457 (if (or (bool digits
) (> digit
0))
458 (pylist-append digits digit
))
460 (+ "The second value in the tuple must "
461 "be composed of integers in the range "
465 ((or (eq? v2
'n
) (eq? v2
'N
))
467 ;; NaN: digits form the diagnostic
468 (set self
'_int
(py-join "" (map str digits
)))
470 (set self
'_is_special
#t
)))
472 ;; finite number: digits give the coefficient
473 (set self
'_int
(py-join "" (map str digits
)))
475 (set self
'_is_special
#f
))
478 (+ "The third value in the tuple must "
479 "be an integer, or one of the "
480 "strings 'F', 'n', 'N'.")))))))))
482 ((isinstance value float
)
483 (let ((context (if (eq? context None
)
488 (+ "strict semantics for mixing floats and Decimals are "
491 (__init__ self
((ref Decimal
'from_float
) value
))))
495 (format #f
"Cannot convert %r to Decimal" value
))))))
497 (define-inlinable (divmod x y
)
498 (values (quotient x y
) (modulo x y
)))
503 ((_ (let (a ...
)) . l
)
505 ((_ (a it code ...
) . l
)
506 (aif it a
(begin code ...
) (twix - l
)))))
508 (define-syntax-rule (norm-op op
)
510 (set! op
((ref self
'_convert_other
) op
))
511 (if (eq? op NotImplemented
)
515 (define-syntax-rule (get-context context code
)
516 (let ((context (if (eq? context None
)
521 (define-syntax-rule (un-special self context
)
522 (if ((ref self
'_is_special
))
523 (let ((ans ((ref self
'_check_nans
) #:context context
)))
529 (define-syntax-rule (bin-special o1 o2 context
)
530 (if (or (ref o1
'_is_special
)
531 (ref o2
'_is_special
))
532 (or (un-special o1 context
) (un-special o2 context
))))
534 (define-syntax-rule (add-special self other context
)
535 (or (bin-special self other context
)
536 (if ((ref self
'_isinfinity
))
537 ;; If both INF, same sign =>
538 ;; same as both, opposite => error.
539 (if (and (not (= (ref self
'_sign
) (ref other
'_sign
)))
540 ((ref other
'_isinfinity
)))
541 ((cx-error context
) InvalidOperation
"-INF + INF")
543 (if ((ref other
'_isinfinity
))
544 (ret (Decimal other
)) ; Can't both be infinity here
547 (define-syntax-rule (mul-special self other context
)
548 (if (or (ref self
'_is_special
) (ref other
'_is_special
))
550 ((bin-special self other context
) it it
)
552 ((if ((ref self
'_isinfinity
))
553 (if (not (bool other
))
554 ((cx-error context
) InvalidOperation
"(+-)INF * 0")
555 (pylist-ref _SignedInfinity resultsign
))
558 (if ((ref other
'_isinfinity
))
559 (if (not (bool self
))
560 ((cx-error context
) InvalidOperation
"(+-)INF * 0")
561 (pylist-ref _SignedInfinity resultsign
))
565 (define-syntax-rule (div-special self other context
)
566 (if (or (ref self
'_is_special
) (ref other
'_is_special
))
568 ((bin-special self other context
) it it
)
570 ((and ((ref self
'_isinfinity
)) ((ref other
'_isinfinity
))) it
571 ((cx-error context
) InvalidOperation
"(+-)INF/(+-)INF"))
573 (((ref self
'_isinfinity
)) it
574 (pylist-ref _SignedInfinity sign
))
576 (((ref other
'_isinfinity
)) it
577 ((cx-error context
) Clamped
"Division by infinity")
578 (_dec_from_triple sign
"0", (cx-etiny context
))))))
581 (define-python-class Decimal
(object)
582 "Floating point class for decimal arithmetic."
585 ;; Generally, the value of the Decimal instance is given by
586 ;; (-1)**_sign * _int * 10**_exp
587 ;; Special values are signified by _is_special == True
591 ((self sign coefficient exponent special
)
592 (set self
'_sign sign
)
593 (set self
'_int coefficient
)
594 (set self
'_exp exponent
)
595 (set self
'_is_special special
))
607 "Converts a float to a decimal number, exactly.
609 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
610 Since 0.1 is not exactly representable in binary floating point, the
611 value is stored as the nearest representable value which is
612 0x1.999999999999ap-4. The exact equivalent of the value in decimal
613 is 0.1000000000000000055511151231257827021181583404541015625.
615 >>> Decimal.from_float(0.1)
616 Decimal('0.1000000000000000055511151231257827021181583404541015625')
617 >>> Decimal.from_float(float('nan'))
619 >>> Decimal.from_float(float('inf'))
621 >>> Decimal.from_float(-float('inf'))
623 >>> Decimal.from_float(-0.0)
628 ((isinstance f int
) ; handle integer inputs
630 ((not (isinstance f float
))
631 (raise (TypeError "argument must be int or float.")))
632 ((or (inf? f
) (nan? f
))
636 (eq? f
(- (inf))) "")))
638 (let* ((sign (if (>= f
0) 0 1))
642 (res (_dec_from_triple sign
, str
(m) e
)))
643 (if (eq? cls Decimal
)
649 "Returns whether the number is not actually one.
655 (if (ref self
'_is_special
)
656 (let ((exp (ref self
'_exp
)))
665 "Returns whether the number is infinite
667 0 if finite or not a number
671 (if (eq?
(ref self
'_exp
) 'F
)
672 (if (eq?
(ref self
'_sign
) 1)
678 (lam (self (= other None
) (= context None
))
679 "Returns whether the number is not actually one.
681 if self, other are sNaN, signal
682 if self, other are NaN return nan
685 Done before operations.
688 (let ((self_is_nan ((ref self
'_isnan
)))
692 ((ref other
'_isnan
)))))
694 (if (or self_is_nan other_is_nan
)
695 (let ((context (if (eq? context None
)
700 ((cx-error context
) InvalidOperation
"sNaN" self
))
701 ((eq? other_is_nan
2)
702 ((cx-error context
) InvalidOperation
"sNaN" other
))
704 ((ref self
'_fix_nan
) context
))
706 ((ref other
'_fix_nan
) context
))))
710 (define _compare_check_nans
711 (lambda (self other context
)
712 "Version of _check_nans used for the signaling comparisons
713 compare_signal, __le__, __lt__, __ge__, __gt__.
715 Signal InvalidOperation if either self or other is a (quiet
716 or signaling) NaN. Signaling NaNs take precedence over quiet
719 Return 0 if neither operand is a NaN.
722 (let ((context (if (eq? context None
)
726 (if (or (ref self
'_is_special
)
727 (ref other
'_is_special
))
729 (((ref self
'is_snan
))
732 "comparison involving sNaN" self
))
734 (((ref other
'is_snan
))
737 "comparison involving sNaN" other
))
739 (((ref self
'is_qnan
))
742 "comparison involving NaN" self
))
744 (((ref other
'is_qnan
))
747 "comparison involving NaN" other
))
754 "Return True if self is nonzero; otherwise return False.
756 NaNs and infinities are considered nonzero.
758 (or (ref self
'_is_special
) (not (equal (ref self
'_int
) "0")))))
762 "Compare the two non-NaN decimal instances self and other.
764 Returns -1 if self < other, 0 if self == other and 1
765 if self > other. This routine is for internal use only."
767 (let ((self_sign (ref self
'_sign
))
768 (other_sign (ref other
'_sign
)))
770 ((or (ref self
'_is_special
) (ref other
'_is_special
))
771 (let ((self_inf ((ref self
'_isinfinity
)))
772 (other_inf ((ref other
'_isinfinity
))))
774 ((eq? self_inf other_inf
) 0)
775 ((< self_inf other_inf
) -
1)
778 ;; check for zeros; Decimal('0') == Decimal('-0')
780 (if (not (bool other
))
782 (let ((s (ref other
'_sign
)))
787 (let ((s (ref self
'_sign
)))
792 ((< other_sign self_sign
)
794 ((< self_sign other_sign
)
798 (let ((self_adjusted ((ref self
'adjusted
)))
799 (other_adjusted ((ref other
'adjusted
)))
800 (self_exp (ref self
'_exp
))
801 (other_exp (ref other
'_exp
)))
803 ((= self_adjusted other_adjusted
)
804 (let ((self_padded (+ (ref self
'_int
)
805 (* "0" (- self_exp other_exp
))))
806 (other_padded (+ (ref other
'_int
)
807 (* "0" (- other_exp self_exp
)))))
809 ((equal? self_padded other_padded
)
811 ((< self_padded other_padded
)
819 ((> self_adjusted other_adjusted
)
828 ;; Note: The Decimal standard doesn't cover rich comparisons for
829 ;; Decimals. In particular, the specification is silent on the
830 ;; subject of what should happen for a comparison involving a NaN.
831 ;; We take the following approach:
833 ;; == comparisons involving a quiet NaN always return False
834 ;; != comparisons involving a quiet NaN always return True
835 ;; == or != comparisons involving a signaling NaN signal
836 ;; InvalidOperation, and return False or True as above if the
837 ;; InvalidOperation is not trapped.
838 ;; <, >, <= and >= comparisons involving a (quiet or signaling)
839 ;; NaN signal InvalidOperation, and return False if the
840 ;; InvalidOperation is not trapped.
842 ;; This behavior is designed to conform as closely as possible to
843 ;; that specified by IEEE 754.
846 (lam (self other
(= context None
))
847 (let ((so (_convert_for_comparisonc self other
#:equality_op
#t
))
852 ((eq? other NotImplemented
)
854 ((bool ((ref self
'_check_nans
) other context
))
856 (else (= ((ref self
'_cmp
) other
) 0))))))
860 (lam (self other
(= context None
))
861 (let ((so (_convert_for_comparisonc self other
#:equality_op
#t
))
866 ((eq? other NotImplemented
)
868 ((bool ((ref self
'_compare_check_nans
) other context
))
870 (else (< ((ref self
'_cmp
) other
) 0)))))))
872 (define __lt__
(_xlt < ))
873 (define __le__
(_xlt <=))
874 (define __gt__
(_xlt > ))
875 (define __ge__
(_xlt >=))
878 (lam (self other
(= context None
))
879 "Compare self to other. Return a decimal value:
881 a or b is a NaN ==> Decimal('NaN')
882 a < b ==> Decimal('-1')
883 a == b ==> Decimal('0')
884 a > b ==> Decimal('1')
886 (let ((other (_convert_other other
#:raiseit
#t
)))
887 ;; Compare(NaN, NaN) = NaN
888 (if (or (ref self
'_is_special
)
890 (ref other
'_is_special
)))
891 (aif it
((ref self
'_check_nans
) other context
)
893 (Decimal ((ref self
'_cmp
) other
)))))))
897 "x.__hash__() <==> hash(x)"
899 ;; In order to make sure that the hash of a Decimal instance
900 ;; agrees with the hash of a numerically equal integer, float
901 ;; or Fraction, we follow the rules for numeric hashes outlined
902 ;; in the documentation. (See library docs, 'Built-in Types').
904 ((ref self
'_is_special
)
906 (((ref self
'is_snan
))
907 (raise (TypeError "Cannot hash a signaling NaN value.")))
908 (((ref self
'is_snan
))
910 ((= 1 (ref self
'_sign
))
916 (let* ((exp (ref self
'_exp
))
919 (expt 10 exp _ pyhash-N
)
920 (expt _PyHASH_10INV
(- exp
) pyhash-N
)))
923 (modulus (* (int (ref self
'_int
)) exp_hash
)
927 (if (>= self
0) hash_
(- hash_
))))
928 (if (= ans -
1) -
2 ans
))))))
932 "Represents the number as a triple tuple.
934 To show the internals exactly as they are.
936 (DecimalTuple self._sign
937 (tuple (map int
(ref self
'_int
)))
940 (define as_integer_ratio
942 "Express a finite Decimal instance in the form n / d.
944 Returns a pair (n, d) of integers. When called on an infinity
945 or NaN, raises OverflowError or ValueError respectively.
947 >>> Decimal('3.14').as_integer_ratio()
949 >>> Decimal('-123e5').as_integer_ratio()
951 >>> Decimal('0.00').as_integer_ratio()
954 (if (ref self
'_is_special
)
955 (if ((ref self
'is_nan
))
957 "cannot convert NaN to integer ratio"))
958 (raise (OverflowError
959 "cannot convert Infinity to integer ratio"))))
961 (if (not (bool self
))
963 (let ((s (ref self
'_sign
))
964 (n (int (ref self
'_int
)))
969 (/ 1 (expt 10 (- expt
)))))))
970 (values (numerator x
)
975 "Represents the number as an instance of Decimal."
976 ;# Invariant: eval(repr(d)) == d
977 (format #f
"Decimal('~a')" (str self
))))
980 (lam (self (= eng
#f
) (= context None
))
981 "Return string representation of the number in scientific notation.
983 Captures all of the information in the underlying representation.
985 (let* ((sign (if (= (reg self
'_sign
) 0) "" "-"))
986 (exp (ref self
'_exp
))
988 (leftdigits (+ exp
(len i
)))
995 ((ref self
'_is_special
)
997 ((eq?
(ref self
'_exp
) 'F
)
999 ((eq?
(ref self
'_exp
) 'n
)
1000 (+ sign
"NaN" (ref self
'_int
)))
1001 (else ; self._exp == 'N'
1002 (+ sign
"sNaN" (ref self
'_int
)))))
1004 ;; dotplace is number of digits of self._int to the left of the
1005 ;; decimal point in the mantissa of the output string (that is,
1006 ;; after adjusting the exponent)
1008 ((and (<= exp
0) (> leftdigits -
6))
1009 ;; no exponent required
1010 (set! dotplace leftdigits
))
1013 ;; usual scientific notation: 1 digit on left of the point
1017 ;; engineering notation, zero
1018 (set! dotplace
(- (modulo (+ leftdigits
1) 3) 1)))
1020 ;; engineering notation, nonzero
1021 (set! dotplace
(- (modulo (+ leftdigits
1) 3) 1))))
1026 (set! fracpart
(+ "." + (* "0" (- dotplace
)) + i
)))
1027 ((>= dotplace
(len i
))
1028 (set! intpart
(+ i
(* "0" (- dotplace
(len i
)))))
1031 (set! intpart
(pylist-slice i None dotplace None
))
1032 (set! fracpart
(+ '.
' (pylist-slice i dotplace None None
)))))
1036 ((= leftdigits dotplace
)
1039 (let ((context (if (eq? context None
)
1043 (+ (pylist-ref (lise "e" "E") (cx-capitals context
))
1044 (format #f
"%@d" (- leftdigits dotplace
)))))))
1045 (+ sign intpart fracpart exp
))))))
1047 (define to_eng_string
1048 (lam (self (= context None
))
1049 "Convert to a string, using engineering notation if an exponent is needed.
1050 Engineering notation has an exponent which is a multiple of 3. This
1051 can leave up to 3 digits to the left of the decimal place and may
1052 require the addition of either one or two trailing zeros.
1054 ((ref self
'__str__
) #:eng
#t
#:contect context
)))
1057 (lam (self (= contextNone
))
1058 "Returns a copy with the sign switched.
1060 Rounds, if it has reason.
1063 ((un-special self context
) it it
)
1064 (let* ((context (if (eq? context None
)
1067 (ans (if (and (not (bool self
))
1068 (not (eq?
(cx-rounding context
)
1070 ;; -Decimal('0') is Decimal('0'),
1071 ;; not Decimal('-0'), except
1072 ;; in ROUND_FLOOR rounding mode.
1073 ((ref self
'copy_abs
))
1074 ((ref self
'copy_negate
)))))
1076 ((ref ans
'_fix
) context
)))))
1079 (lam (self (= context None
))
1080 "Returns a copy, unless it is a sNaN.
1082 Rounds the number (if more than precision digits)
1085 ((un-special self context
) it it
)
1087 (let* ((context (if (eq? context None
)
1090 (ans (if (and (not (bool self
))
1091 (not (eq?
(cx-rounding context
)
1093 ;; -Decimal('0') is Decimal('0'),
1094 ;; not Decimal('-0'), except
1095 ;; in ROUND_FLOOR rounding mode.
1096 ((ref self
'copy_abs
))
1099 ((ref ans
'_fix
) context
)))))
1102 (lam (self (= round
#t
) (= context None
))
1103 "Returns the absolute value of self.
1105 If the keyword argument 'round' is false, do not round. The
1106 expression self.__abs__(round=False) is equivalent to
1111 ((ref self
'copy_abs
)))
1113 ((un-special self context
) it it
)
1115 (if (= (ref self
'_sign
) 1)
1116 ((ref self
'__neg__
) #:context context
)
1117 ((ref self
'__pos__
) #:context context
)))))
1120 (lam (self other
(= context None
))
1121 "Returns self + other.
1123 -INF + INF (or the reverse) cause InvalidOperation errors.
1126 ((norm-op other
) it it
)
1128 (let (get-context context
))
1130 ((add-special o1 o2 context
) it it
)
1132 (let (let* ((negativezero 0)
1133 (self_sign (ref self
'_sign
))
1134 (other_sign (ref other
'_sign
))
1135 (self_exp (ref self
'_sign
))
1136 (other_exp (ref other
'_sign
))
1137 (prec (cx-prec context
))
1138 (exp (min self_exp other_exp
))
1142 (if (and (eq?
(cx-rounding context
) ROUND_FLOOR
)
1143 (not (= self_sign other_sign
)))
1144 ;; If the answer is 0, the sign should be negative,
1146 (set! negativezero
1))))
1148 ((if (and (not (bool self
)) (not (bool other
)))
1150 (set! sign
(min self_sign other_sign
))
1151 (if (= negativezero
1)
1153 (set! ans
(_dec_from_triple sign
"0" exp
))
1154 (set! ans
((ref ans
'_fix
) context
))
1158 ((if (not (bool self
))
1160 (set! exp
(max exp
(- other_exp prec
1)))
1161 (set! ans
((ref other
'_rescale
) exp
1162 (cx-rounding rounding
)))
1163 (set! ans
((ref ans
'_fix
) context
))
1167 ((if (not (bool other
))
1169 (set! exp
(max exp
(- self_exp prec
1)))
1170 (set! ans
((ref self
'_rescale
) exp
1171 (cx-rounding rounding
)))
1172 (set! ans
((ref ans
'_fix
) context
))
1177 (let (let* ((op1 (_WorkRep self
))
1178 (op2 (_WorkRep other
))
1179 (ab (_normalize op1 op2 prec
))
1182 (result (_WorkRep)))))
1185 ((not (= (ref op1
'sign
) (ref op2
'sign
)))
1186 ;; Equal and opposite
1189 (set! ans
(_dec_from_triple negativezero
"0" exp
))
1190 (set! ans
((ref ans
'_fix
) context
))
1199 (if (= (ref op1
'sign
) 1)
1200 (let ((t (ref op1
'sign
)))
1201 (set result
'sign
1)
1202 (set op1
'sign
(ref op2
'sign
))
1204 (set result
'sign
0))
1206 ((= (ref op1
'sign
) 1)
1207 (set result
'sign
1)
1211 (set result
'sign
0)
1215 (if (= (ref op2
'sign
) 0)
1216 (set result
'int
(+ (ref op1
'int
) (ref op2
'int
)))
1217 (set result
'int
(- (ref op1
'int
) (ref op2
'int
))))
1219 (set result
'exp
(ref op1
'exp
))
1220 (set! ans
(Decimal result
))
1221 ((ref ans
'_fix
) context
)))))
1223 (define __radd__ __add__
)
1226 (lam (self other
(= context None
))
1227 "Return self - other"
1229 ((norm-op other
) it it
)
1230 ((bin-special o1 o2 context
) it it
)
1231 ((ref self
'__add__
)
1232 ((ref other
'copy_negate
)) #:context context
))))
1235 (lam (self other
(= context None
))
1236 "Return other - self"
1238 ((norm-op other
) it it
)
1239 ((ref 'other
'__sub__
) self
#:context context
))))
1242 (lam (self other
(= context None
))
1243 "Return self * other.
1245 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1248 ((norm-op other
) it it
)
1249 (let (get-context context
))
1251 (let (let ((resultsign (logxor (ref self
'_sign
)
1252 (ref other
'_sign
))))))
1254 ((mul-special o1 o2 context
) it it
)
1256 (let (let ((resultexp (+ (ref self
'_exp
) (ref other
'_exp
))))))
1258 ;; Special case for multiplying by zero
1259 ((or (not (bool self
)) (not (bool other
)))
1260 (let ((ans (_dec_from_triple resultsign
"0" resultexp
)))
1261 ((ref and
'_fix
) context
)))
1263 ;; Special case for multiplying by power of 10
1264 ((equal?
(ref self
'_int
) "1")
1265 (let ((ans (_dec_from_triple resultsign
(ref other
'_int
) resultexp
)))
1266 ((ref and
'_fix
) context
)))
1268 ((equal?
(ref other
'_int
) "1")
1269 (let ((ans (_dec_from_triple resultsign
(ref self
'_int
) resultexp
)))
1270 ((ref and
'_fix
) context
)))
1272 (let* ((op1 (_WorkRep self
))
1273 (op2 (_WorkRep other
))
1274 (ans (_dec_from_triple resultsign
1275 (str (* (ref op1
') (ref op2
'int
)))
1277 ((ref and
'_fix
) context
)))))
1279 (define __rmul__ __mul__
)
1282 (lam (self other
(= context None
))
1283 "Return self / other."
1285 ((norm-op other
) it it
)
1286 (let (get-context context
))
1288 (let (let ((sign (logxor (ref self
'_sign
)
1289 (ref other
'_sign
))))))
1291 ((div-special o1 o2 context
) it it
)
1293 ;; Special cases for zeroes
1294 ((if (not (bool other
))
1295 (if (not (bool self
))
1296 ((cx-error context
) DivisionUndefined
"0 / 0")
1297 ((cx-error context
) DivisionByZero
"x / 0" sign
))
1302 (nself (len (ref self
'_int
)))
1303 (nother (len (ref other
'_int
))))
1304 (if (not (bool self
))
1306 (set! exp
(- (ref self
'_exp
) (ref other
'_exp
)))
1308 ;; OK, so neither = 0, INF or NaN
1309 (let ((shift (+ nother
(- nself
) prec
1))
1310 (op1 (_WorkRep self
))
1311 (op2 (_WorkRep other
)))
1312 (set! exp
(- (ref self
'_exp
) (ref other
'_exp
) shift
))
1316 (divmod (* (ref op1
'int
) (expt 10 shift
))
1318 (divmod (ref op1
'int
)
1319 (* (ref op2
'int
) (expt 10 shift
)))))
1320 (lambda (coeff- remainder
)
1322 (if (not (= remainder
0))
1323 ;; result is not exact adjust to ensure
1325 (if (= (modulus coeff-
5) 0)
1328 (let (ideal_exp (- (ref self
'_exp
)
1330 (let lp
((coeff- coeff-
) (exp- exp
))
1331 (if (and (< exp- indeal_exp
)
1332 (= (modulo coeff
10) 0))
1333 (lp (/ coeff
10) (+ exp-
1))
1339 (let ((ans (_dec_from_triple sign
, (str coeff
) exp
)))
1340 ((ref ans
'_fix
) context
))))))
1343 (lambda (self other context
)
1344 "Return (self // other, self % other), to context.prec precision.
1346 Assumes that neither self nor other is a NaN, that self is not
1347 infinite and that other is nonzero.
1352 (logxor (ref self
'_sign
)
1353 (ref other
'_sign
)))
1355 (if ((ref other
'_isinfinity
))
1357 (min (ref self
'exp
) (ref other
'_exp
))))
1359 (- ((ref self
'adjusted
)) ((ref other
'adjusted
)))))))
1361 ((or (not (bool self
))
1362 ((ref other
'_isinfinity
))
1364 (list (_dec_from_tripple sign
"0" 0)
1365 ((ref self
'_rescale
) ideal_exp
(cx-rounding context
))))
1367 ((if (<= expdiff
(cx-prec context
))
1368 (let ((op1 (_WorkRep self
))
1369 (op2 (_WorkRep other
)))
1370 (if (>= (ref op1
'exp
) (ref op2
'exp
))
1371 (set op1
'int
(* (ref op1
'int
)
1372 (expt 10 (- (ref op1
'exp
)
1374 (set op2
'int
(* (ref op2
'int
)
1375 (expt 10 (- (ref op2
'exp
)
1377 (call-with-values (lambda () (divmod (ref op1
'int
)
1380 (if (< q
(expt 10 (cx-prec context
)))
1381 (list (_dec_from_triple sign
(str q
) 0)
1382 (_dec_from_triple (ref self
'_sign
)
1388 ;; Here the quotient is too large to be representable
1389 (let ((ans ((cx-raise context
) DivisionImpossible
1390 "quotient too large in //, % or divmod")))
1391 (list ans ans
)))))))
1393 (define __rtruediv__
1394 (lam (self other
(= context None
))
1395 ""Swaps self
/other and returns __truediv__.
""
1397 ((norm-op other
) it it
)
1398 ((ref other
'__truediv__
) self
#:context context
))))
1401 (lam (self other
(= context None
))
1403 Return (self // other, self % other)
1407 ((norm-op other
) it it
)
1409 (let (get-context context
))
1411 ((add-special o1 o2 context
) it it
)
1413 (((ref self
'_check_nans
) other context
) it
1417 (logxor (ref self
'_sign
)
1418 (ref other
'_sign
))))))
1420 (((ref self
'_isinfinity
)) it
1421 (if ((ref other
'_isinfinity
))
1422 (let ((ans ((cx-error context
) InvalidOperation
1423 "divmod(INF, INF)")))
1425 (list (list-ref _SignedInfinity sign
)
1426 ((cx-raise context
) InvalidOperation
, "INF % x"))))
1428 ((not (bool other
)) it
1429 (if (not (bool self
))
1430 (let ((ans ((cx-error context
) DivisionUndefined
1433 (list ((cx-error context
) DivisionByZero
"x // 0" sign
)
1434 ((cx-error context
) InvalidOperation
"x % 0"))))
1436 (call-with-values (lambda () ((ref self
'_divide
) other context
))
1437 (lambda (quotient remainder
)
1438 (let ((remainder ((ref remainder
'_fix
) context
)))
1439 (list quotient remainder
))))))))
1442 (lam (self other
(= context None
))
1443 "Swaps self/other and returns __divmod__."
1445 ((norm-op other
) it it
)
1446 ((ref other
'__divmod__
) self
#:context context
))))
1449 (lam (self other
(= context None
))
1454 ((norm-op other
) it it
)
1456 (let (get-context context
))
1458 ((bin-special o1 o2 context
) it it
)
1460 (((ref self
'_isinfinity
)) it
1461 ((cx-error context
) InvalidOperation
"INF % x"))
1465 ((cx-error context
) InvalidOperation
"x % 0")
1466 ((cx-error context
) DivisionUndefined
"0 % 0")))
1468 (let* ((remainder ((ref self
'_divide
) other context
)))
1469 ((ref remainder
'_fix
) context
)))))
1472 (lam (self other
(= context None
))
1473 "Swaps self/other and returns __mod__."
1475 ((norm-op other
) it it
)
1476 ((ref other
'__mod__
) self
#:context context
))))
1478 (define remainder_near
1479 (lambda (self other
(= context None
))
1481 Remainder nearest to 0- abs(remainder-near) <= other/2
1484 ((norm-op other
) it it
)
1486 (let (get-context context
))
1488 ((bin-special self other context
) it it
)
1490 ;; self == +/-infinity -> InvalidOperation
1491 (((ref self
'_isinfinity
)) it
1492 ((cx-error context
) InvalidOperation
"remainder_near(infinity, x)"))
1494 ;; other == 0 -> either InvalidOperation or DivisionUndefined
1495 ((not (bool other
)) it
1496 (if (not (bool self
))
1497 ((cx-error context
) InvalidOperation
"remainder_near(x, 0)")
1498 ((cx-error context
) DivisionUndefined
"remainder_near(0, 0)")))
1500 ;; other = +/-infinity -> remainder = self
1501 (((ref other
'_isinfinity
())) it
1502 (let ((ans (Decimal self
)))
1503 ((ref ans
'_fix
) context
)))
1505 ;; self = 0 -> remainder = self, with ideal exponent
1506 (let (let ((ideal_exponent (min (ref self
'_exp
) (ref other
'_exp
))))))
1508 ((not (bool self
)) it
1509 (let ((ans (_dec_from_triple (ref self
'_sign
) "0" ideal_exponent
)))
1510 ((ref ans
'_fix
) context
)))
1512 ;; catch most cases of large or small quotient
1514 (- ((ref self
'adjusted
)) ((red other
'adjusted
)))))))
1516 ((>= expdiff
(+ (cx-prec context
) 1)) it
1517 ;; expdiff >= prec+1 => abs(self/other) > 10**prec
1518 ((cx-error context
) DivisionImpossible
))
1521 ;; expdiff <= -2 => abs(self/other) < 0.1
1522 (let ((ans ((ref self
'_rescale
)
1523 ideal_exponent
(cx-rounding context
))))
1524 ((ref ans
'_fix
) context
)))
1526 (let ((op1 (_WorkRep self
))
1527 (op2 (_WorkRep other
)))
1529 ;; adjust both arguments to have the same exponent, then divide
1530 (if (>= (ref op1
'exp
) (ref op2
'exp
))
1531 (set op1
'int
(* (ref op1
'int
)
1532 (expt 10 (- (ref op1
'exp
) (ref op2
'exp
)))))
1533 (set op2
'int
(* (ref op2
'int
)
1534 (expt 10 (- (ref op2
'exp
) (ref op1
'exp
))))))
1536 (call-with-values (lambda () (divmod (ref op1
'int
) (ref op2
'int
)))
1539 ;; remainder is r*10**ideal_exponent; other is +/-op2.int *
1540 ;; 10**ideal_exponent. Apply correction to ensure that
1541 ;; abs(remainder) <= abs(other)/2
1542 (if (> (+ (* 2 r
) + (logand q
1)) (ref op2
'int
))
1543 (set! r
(- r
(ref op2
'int
)))
1546 (if (>= q
(expt 10 (cx-prec context
)))
1547 ((cx-error context
) DivisionImpossible
)
1548 (let ((sign (ref self
'_sign
)))
1550 (set! sign
(- 1 sign
))
1552 (let ((ans (_dec_from_triple sign
(str r
) ideal_exponent
)))
1553 ((ref ans
'_fix
) context
))))))))))
1555 (define __floordiv__
1556 (lambda (self other
(= context None
))
1559 ((norm-op other
) it it
)
1561 (let (get-context context
))
1563 ((bin-special self other context
) it it
)
1565 (((ref self
'_isinfinity
)) it
1566 (if ((ref other
'_isinfinity
))
1567 ((cx-error context
) InvalidOperation
"INF // INF")
1568 (pylist-ref _SignedInfinity
(logxor (ref self
'_sign
)
1569 (ref other
'_sign
)))))
1571 ((not (bool other
)) it
1573 ((cx-error context
) DivisionByZero
"x // 0"
1574 (logxor (ref self
'_sign
) (ref other
'_sign
)))
1575 ((cx-error context
) DivisionUndefined
"0 // 0")))
1577 ((ref self
'_divide
) other context
))))
1579 (define __rfloordiv__
1580 (lam (self other
(= context None
))
1581 "Swaps self/other and returns __floordiv__."
1583 ((norm-op other
) it it
)
1584 ((ref other
'__floordiv__
) self
#:context context
))))
1588 "Float representation."
1589 (if ((ref self
'_isnan
))
1590 (if ((ref self
'is_snan
))
1591 (raise (ValueError "Cannot convert signaling NaN to float"))
1592 (if (= (ref self
'_sign
))
1595 (if ((ref self
'_isspecial
))
1596 (if (= (ref self
'_sign
))
1599 (float (str self
)))))
1603 "Converts self to an int, truncating if necessary."
1604 (if ((ref self
'_isnan
))
1605 (raise (ValueError "Cannot convert NaN to integer"))
1606 (if ((ref self
'_isspecial
))
1607 (raise (OverflowError "Cannot convert infinity to integer"))
1608 (let ((s (if (= (ref self
'_sign
) 1) -
1 1)))
1609 (if (>= (ref self
'_exp
) 0)
1610 (* s
(int (ref self
'_int
)) (expt 10 (ref self
'_exp
)))
1611 (* s
(int (or (bool (py-slice (ref self
'_int
)
1612 None
(ref self
'_exp
) None
))
1615 (define __trunc__ __int__
)
1618 (property (lambda (self) self
)))
1626 (lambda (self) self
))
1630 (complex (float self
))))
1633 (lambda (self context
)
1634 "Decapitate the payload of a NaN to fit the context"
1635 (let ((payload (ref self
'_int
))
1637 ;; maximum length of payload is precision if clamp=0,
1638 ;; precision-1 if clamp=1.
1640 (- (ref context
'prec
)
1641 (ref context
'clamp
))))
1643 (if (> (len payload
) max_payload_len
)
1644 (let ((payload (py-lstrip
1645 (pylist-slice payload
1646 (- (len payload
) max_payload_len
)
1648 (_dec_from_triple (ref self
'_sign
) payload
(ref self
'_exp
)
1653 (lambda (self context
)
1654 "Round if it is necessary to keep self within prec precision.
1656 Rounds and fixes the exponent. Does not raise on a sNaN.
1659 self - Decimal instance
1660 context - context used.
1664 (((ref self
'_is_special
)) it
1665 (if ((ref self
'_isnan
))
1666 ;; decapitate payload if necessary
1667 ((ref self
'_fix_nan
) context
)
1669 ;; self is +/-Infinity; return unaltered
1672 ;; if self is zero then exponent should be between Etiny and
1673 ;; Emax if clamp==0, and between Etiny and Etop if clamp==1.
1674 (let ((Etiny (cx-etiny context
))
1675 (Etop (cx-etop context
))))
1677 ((not (bool self
)) it
1678 (let ((exp_max (if (= (cx-clamp context
) 0)
1681 (new_exp (min (max (ref self
'_exp
) Etiny
) exp_max
)))
1682 (if (not (= new_exp
(ref self
'_exp
)))
1684 ((cx-error context
) Clamped
)
1685 (_dec_from_triple (ref self
'_sign
) "0" new_exp
))
1688 ;; exp_min is the smallest allowable exponent of the result,
1689 ;; equal to max(self.adjusted()-context.prec+1, Etiny)
1690 (let ((exp_min (+ (len (ref self
'_int
))
1692 (- (cx-prec context
)))))))
1693 ((> exp_min Etop
) it
1694 ;; overflow: exp_min > Etop iff self.adjusted() > Emax
1695 (let ((ans ((cx-error context
) Overflow
"above Emax"
1696 (ref self
'_sign
))))
1697 ((cx-error context
) Inexact
)
1698 ((cx-error context
) Rounded
)
1701 (let* ((self_is_subnormal (< exp_min Etiny
))
1702 (exp_min (if self_is_subnormal Eriny exp_min
)))))
1704 ;; round if self has too many digits
1705 ((< self._exp exp_min
) it
1706 (let ((digits (+ (len (ref self
'_int
))
1710 (set! self
(_dec_from_triple (ref self
'_sign
)
1715 (rounding_method (pylist-ref
1716 (ref self
'_pick_rounding_function
)
1717 (cx-rounding context
)))
1718 (changed (rounding_method self digits
))
1719 (coeff (or (bool (pylist-slice (ref self
'_int
)
1720 None digits None
)) "0")))
1723 (set! coeff
(str (+ (int coeff
) 1)))
1724 (if (> (len coeff
) (cx-prec context
))
1726 (set! coeff
(pylist-clice coeff None -
1 None
))
1727 (set! exp_min
(+ exp_min
1))))))
1729 ;; check whether the rounding pushed the exponent out of range
1730 (if (> exp_min Etop
)
1732 ((cx-error context
) Overflow
"above Emax"
1734 (set! ans
(_dec_from_triple (ref self
'_sign
) coeff exp_min
)))
1736 ;; raise the appropriate signals, taking care to respect
1737 ;; the precedence described in the specification
1738 (if (and changed self_is_subnormal
)
1739 ((cx-error context
) Underflow
))
1740 (if self_is_subnormal
1741 ((cx-error context
) Subnormal
))
1743 ((cx-error context
) Inexact
))
1745 ((cx-error context
) Rounded
)
1747 (if (not (bool ans
))
1748 ;; raise Clamped on underflow to 0
1749 ((cx-error context
) Clamped
))
1753 (if self_is_subnormal
1754 ((cx-error context
) Subnormal
))
1757 ;; fold down if clamp == 1 and self has too few digits
1758 (if (and (= (cx-clamp context
) 1) (> (ref self
'_exp
) Etop
))
1760 ((cx-error context
) Clamped
)
1761 (let ((self_padded (+ (ref self
'_int
)
1763 (- (ref self
'_exp
) Etop
)))))
1764 (_dec_from_triple (ref self
'_sign
) self_padded Etop
)))
1766 ;; here self was representable to begin with; return unchanged
1770 ;; for each of the rounding functions below:
1771 ;; self is a finite, nonzero Decimal
1772 ;; prec is an integer satisfying 0 <= prec < len(self._int)
1774 ;; each function returns either -1, 0, or 1, as follows:
1775 ;; 1 indicates that self should be rounded up (away from zero)
1776 ;; 0 indicates that self should be truncated, and that all the
1777 ;; digits to be truncated are zeros (so the value is unchanged)
1778 ;; -1 indicates that there are nonzero digits to be truncated
1782 "Also known as round-towards-0, truncate."
1783 (if (_all_zeros (ref self
'_int
) prec
)
1789 "Rounds away from 0."
1790 (- (_round_down self prec
))))
1792 (define _round_half_up
1794 "Rounds 5 up (away from 0)"
1796 ((in (pylist-ref (ref self
'_int
) prec
) "56789")
1798 ((_all_zeros (ref self
'_int
) prec
)
1802 (define _round_half_down
1805 (if (_exact_half (ref self
'_int
) prec
)
1807 (_round_half_up self prec
))))
1809 (define _round_half_even
1811 "Round 5 to even, rest to nearest."
1812 (if (and (_exact_half (ref self
'_int
) prec
)
1814 (in (pylist-ref (ref self
'_int
) (- prec
1)) "02468")))
1816 (_round_half_up self prec
)))
1818 (define _round_ceiling
1820 "Rounds up (not away from 0 if negative.)"
1821 (if (= (ref self
'_sign
) 1)
1822 (_round_down self prec
)
1823 (- (_round_down self prec
)))))
1825 (define _round_floor
1827 "Rounds down (not towards 0 if negative)"
1828 (if (= (ref self
'_sign
) 1)
1829 (- (_round_down self prec
))
1830 (_round_down self prec
))))
1834 "Round down unless digit prec-1 is 0 or 5."
1835 (if (and prec
(not (in (pylist-ref (ref self
'_int
) (- prec
1) "05"))))
1836 (_round_down self prec
)
1837 (- (_round_down self prec
)))))
1839 (define _pick_rounding_function
1840 (dict `((,ROUND_DOWN .
,_round_down
)
1841 (,ROUND_UP .
,_round_up
)
1842 (,ROUND_HALF_UP .
,_round_half_up
)
1843 (,ROUND_HALF_DOWN .
,_round_half_down
)
1844 (,ROUND_HALF_EVEN .
,_round_half_even
)
1845 (,ROUND_CEILING .
,_round_ceiling
)
1846 (,ROUND_FLOOR .
,_round_floor
)
1847 (,ROUND_05UP .
,_round_05up
))))
1850 (lam (self (= n None
))
1851 "Round self to the nearest integer, or to a given precision.
1853 If only one argument is supplied, round a finite Decimal
1854 instance self to the nearest integer. If self is infinite or
1855 a NaN then a Python exception is raised. If self is finite
1856 and lies exactly halfway between two integers then it is
1857 rounded to the integer with even last digit.
1859 >>> round(Decimal('123.456'))
1861 >>> round(Decimal('-456.789'))
1863 >>> round(Decimal('-3.0'))
1865 >>> round(Decimal('2.5'))
1867 >>> round(Decimal('3.5'))
1869 >>> round(Decimal('Inf'))
1870 Traceback (most recent call last):
1872 OverflowError: cannot round an infinity
1873 >>> round(Decimal('NaN'))
1874 Traceback (most recent call last):
1876 ValueError: cannot round a NaN
1878 If a second argument n is supplied, self is rounded to n
1879 decimal places using the rounding mode for the current
1882 For an integer n, round(self, -n) is exactly equivalent to
1883 self.quantize(Decimal('1En')).
1885 >>> round(Decimal('123.456'), 0)
1887 >>> round(Decimal('123.456'), 2)
1889 >>> round(Decimal('123.456'), -2)
1891 >>> round(Decimal('-Infinity'), 37)
1893 >>> round(Decimal('sNaN123'), 0)
1897 (if (not (eq? n None
))
1898 ;; two-argument form: use the equivalent quantize call
1899 (if (not (isinstance n int
))
1901 "Second argument to round should be integral"))
1902 (let ((exp (_dec_from_triple 0, "1", (- n
))))
1903 ((ref self
'quantize
) exp
)))
1905 ;; one-argument form
1906 (if (ref self
'_is_special
)
1907 (if ((ref self
'is_nan
))
1908 (raise (ValueError "cannot round a NaN"))
1909 (raise (OverflowError "cannot round an infinity")))
1910 (int ((ref self
'_rescale
) 0 ROUND_HALF_EVEN
))))))
1914 "Return the floor of self, as an integer.
1916 For a finite Decimal instance self, return the greatest
1917 integer n such that n <= self. If self is infinite or a NaN
1918 then a Python exception is raised.
1921 (if (ref self
'_is_special
)
1922 (if ((ref self
'is_nan
))
1923 (raise (ValueError "cannot round a NaN"))
1924 (raise (OverflowError "cannot round an infinity")))
1925 (int ((ref self
'_rescale
) 0 ROUND_FLOOR
)))))
1929 """Return the ceiling of self, as an integer.
1931 For a finite Decimal instance self, return the least integer n
1932 such that n >= self. If self is infinite or a NaN then a
1933 Python exception is raised.
1936 (if (ref self
'_is_special
)
1937 (if ((ref self
'is_nan
))
1938 (raise (ValueError "cannot round a NaN"))
1939 (raise (OverflowError "cannot round an infinity")))
1940 (int ((ref self
'_rescale
) 0 ROUND_CEILING
)))))
1943 (lam (self other third
(= context None
))
1944 "Fused multiply-add.
1946 Returns self*other+third with no rounding of the intermediate
1949 self and other are multiplied together, with no rounding of
1950 the result. The third operand is then added to the result,
1951 and a single final rounding is performed.
1954 (let ((other (_convert_other other
#:raiseit
#t
))
1955 (third (_convert_other third
#:raiseit
#t
))
1956 (fin (lambda (product)
1957 ((ref product
'__add__
) third context
)))))
1958 ;; compute product; raise InvalidOperation if either operand is
1959 ;; a signaling NaN or if the product is zero times infinity.
1960 ((if (or (ref self
'_is_special
) (ref other
'_is_special
))
1962 (let (get-context context
))
1963 ((equals?
(ref self
'_exp
) "N") it
1964 ((cx-error context
) InvalidOperation
"sNaN" self
))
1965 ((equals?
(ref other
'_exp
) "N") it
1966 ((cx-error context
) InvalidOperation
"sNaN" other
))
1967 ((equals?
(ref self
'_exp
) "n") it
1969 ((equals?
(ref other
'_exp
) "n") it
1971 ((equals?
(ref self
'_exp
) "F") it
1972 (if (not (bool other
))
1973 ((cx-error context
) InvalidOperation
"INF * 0 in fma")
1974 (pylist-ref _SignedInfinity
1975 (logxor (ref self
'_sign
)
1976 (ref other
'_sign
)))))
1977 ((equals?
(ref other
'_exp
) "F") it
1978 (if (not (bool self
))
1979 ((cx-error context
) InvalidOperation
"0 * INF in fma")
1980 (pylist-ref _SignedInfinity
1981 (logxor (ref self
'_sign
)
1982 (ref other
'_sign
)))))
1986 (_dec_from_triple (logxor (ref self
'_sign
) (ref other
'_sign
))
1987 (str (* (int (ref self
'_int
))
1988 (int (ref other
'_int
))))
1989 (+ (ref self
'_exp
) (ref other
'_exp
)))))))
1991 (define _power_modulo
1992 (lam (self other modulo
(= context None
))
1993 "Three argument version of __pow__"
1995 ((norm-op other
) it it
)
1996 ((norm-op modulo
) it it
)
1997 (let (get-context context
))
1999 ;; deal with NaNs: if there are any sNaNs then first one wins,
2000 ;; (i.e. behaviour for NaNs is identical to that of fma)
2001 (let ((self_is_nan (ref self
'_isnan
))
2002 (other_is_nan (ref other
'_isnan
))
2003 (modulo_is_nan (ref modulo
'_isnan
))))
2005 ((or (bool self_is_nan
) (bool other_is_nan
) (bool modulo_is_nan
)) it
2008 ((cx-error context
) InvalidOperation
, "sNaN" self
))
2010 ((cx-error context
) InvalidOperation
, "sNaN" other
))
2012 ((cx-error context
) InvalidOperation
, "sNaN" modulo
))
2014 (_fix_nan self context
))
2015 ((bool other_is_nan
)
2016 (_fix_nan other context
))
2018 (_fix_nan modulo context
))))
2020 ;;check inputs: we apply same restrictions as Python's pow()
2021 ((not (and ((ref self
'_isinteger
))
2022 ((ref other
'_isinteger
))
2023 ((ref modulo
'_isinteger
)))) it
2024 ((cx-error context
) InvalidOperation
2025 (+ "pow() 3rd argument not allowed "
2026 "unless all arguments are integers")))
2029 ((cx-error context
) InvalidOperation
2030 (+ "pow() 2nd argument cannot be "
2031 "negative when 3rd argument specified")))
2033 ((not (bool modulo
)) it
2034 ((cx-error context
) InvalidOperation
2035 "pow() 3rd argument cannot be 0"))
2037 ;; additional restriction for decimal: the modulus must be less
2038 ;; than 10**prec in absolute value
2039 ((>= ((ref modulo
'adjusted
)) (cx-prec context
)) it
2040 ((cx-error context
) InvalidOperation
2041 (+ "insufficient precision: pow() 3rd "
2042 "argument must not have more than "
2043 "precision digits")))
2045 ;; define 0**0 == NaN, for consistency with two-argument pow
2046 ;; (even though it hurts!)
2047 ((and (not (bool other
)) (not (bool self
)))
2048 ((cx-error context
) InvalidOperation
2049 (+ "at least one of pow() 1st argument "
2050 "and 2nd argument must be nonzero ;"
2051 "0**0 is not defined")))
2053 ;; compute sign of result
2054 (let ((sign (if ((ref other
'_iseven
))
2057 (base (_WorkRep ((ref self
'to_integral_value
))))
2058 (exponent (_WorkRep ((ref other
'to_integral_value
)))))
2061 ;; convert modulo to a Python integer, and self and other to
2062 ;; Decimal integers (i.e. force their exponents to be >= 0)
2063 (set! modulo
(abs (int modulo
)))
2065 ;; compute result using integer pow()
2066 (set! base
(guile:modulo
2067 (* (guile:modulo
(ref base
'int
) modulo
)
2068 (modulo-expt 10 (ref base
'exp
) modulo
))
2071 (let lp
((i (ref exponent
'exp
)))
2074 (set! base
(modulo-expt base
10 modulo
))
2077 (set! base
(modulo-expt base
(ref exponent
'int
) modulo
))
2079 (_dec_from_triple sign
(str base
) 0)))))
2081 (define _power_exact
2082 (lambda (self other p
)
2083 "Attempt to compute self**other exactly.
2085 Given Decimals self and other and an integer p, attempt to
2086 compute an exact result for the power self**other, with p
2087 digits of precision. Return None if self**other is not
2088 exactly representable in p digits.
2090 Assumes that elimination of special cases has already been
2091 performed: self and other must both be nonspecial; self must
2092 be positive and not numerically equal to 1; other must be
2093 nonzero. For efficiency, other._exp should not be too large,
2094 so that 10**abs(other._exp) is a feasible calculation."
2096 ;; In the comments below, we write x for the value of self and y for the
2097 ;; value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
2098 ;; and yc positive integers not divisible by 10.
2100 ;; The main purpose of this method is to identify the *failure*
2101 ;; of x**y to be exactly representable with as little effort as
2102 ;; possible. So we look for cheap and easy tests that
2103 ;; eliminate the possibility of x**y being exact. Only if all
2104 ;; these tests are passed do we go on to actually compute x**y.
2106 ;; Here's the main idea. Express y as a rational number m/n, with m and
2107 ;; n relatively prime and n>0. Then for x**y to be exactly
2108 ;; representable (at *any* precision), xc must be the nth power of a
2109 ;; positive integer and xe must be divisible by n. If y is negative
2110 ;; then additionally xc must be a power of either 2 or 5, hence a power
2113 ;; There's a limit to how small |y| can be: if y=m/n as above
2116 ;; (1) if xc != 1 then for the result to be representable we
2117 ;; need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2118 ;; if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2119 ;; 2**(1/|y|), hence xc**|y| < 2 and the result is not
2122 ;; (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2123 ;; |y| < 1/|xe| then the result is not representable.
2125 ;; Note that since x is not equal to 1, at least one of (1) and
2126 ;; (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2127 ;; 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2129 ;; There's also a limit to how large y can be, at least if it's
2130 ;; positive: the normalized result will have coefficient xc**y,
2131 ;; so if it's representable then xc**y < 10**p, and y <
2132 ;; p/log10(xc). Hence if y*log10(xc) >= p then the result is
2133 ;; not exactly representable.
2135 ;; if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2136 ;; so |y| < 1/xe and the result is not representable.
2137 ;; Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2142 (define-syntax-rule (clean xc xe n
+)
2144 (if (= (modulo xc n
) 0)
2150 (let* ((x (_WorkRep self
))
2155 (let* ((y (_WorkRep other
))
2160 ;; case where xc == 1: result is 10**(xe*y), with xe*y
2161 ;; required to be an integer
2165 ;; result is now 10**(xe * 10**ye); xe * 10**ye must be integral
2170 (let ((exponent (* xe
(expt 10 ye
)))
2172 (if (= (ref y
'sign
) 1)
2173 (set! exponent
(- exponent
)))
2175 ;;if other is a nonnegative integer, use ideal exponent
2176 (if (and ((ref other
'_isinteger
)) (= (ref other
'_sign
) 0))
2178 (let ((ideal_exponent (* (ref self
'_exp
) (int other
))))
2179 (set! zeros
(min (- exponent ideal_exponent
) (- p
1)))))
2182 (_dec_from_triple 0 (+ "1" (* "0" zeros
)) exponent-zeros
))))
2184 ;; case where y is negative: xc must be either a power
2185 ;; of 2 or a power of 5.
2186 ((= (ref y
'sign
) 1) it
2187 (let ((last_digit (modulo xc
10)))
2190 ((= (modulo last_digit
2) 0)
2191 ;; quick test for power of 2
2193 ((not (= (logand xc
(- xc
)) xc
))
2195 ;; now xc is a power of 2; e is its exponent
2196 (let ((e (- (_nbits xc
) 1))))
2200 ;; x = 2**e * 10**xe, e > 0, and y < 0.
2202 ;; The exact result is:
2204 ;; x**y = 5**(-e*y) * 10**(e*y + xe*y)
2206 ;; provided that both e*y and xe*y are integers.
2208 ;; 5**(-e*y) >= 10**p, then the result can't be expressed
2209 ;; exactly with p digits of precision.
2211 ;; Using the above, we can guard against large values of ye.
2212 ;; 93/65 is an upper bound for log(10)/log(5), so if
2214 ;; ye >= len(str(93*p//65))
2218 ;; -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
2220 ;; so 5**(-e*y) >= 10**p, and the coefficient of the result
2221 ;; can't be expressed in p digits.
2223 ;; emax >= largest e such that 5**e < 10**p.
2224 (let ((emax (quotient (* p
93) 65))))
2226 ((>= ye
(len (str emax
))) it
2229 ;; Find -e*y and -xe*y; both must be integers
2231 (set! e
(_decimal_lshift_exact (* e yc
) ye
))
2232 (set! xe
(_decimal_lshift_exact (* xe yc
) ye
)))
2234 ((or (eq? e None
) (eq? xe None
)) it
2241 (set! xc
(expt 5 e
))
2246 ;; e >= log_5(xc) if xc is a power of 5; we have
2247 ;; equality all the way up to xc=5**2658
2248 (let* ((e (quotient (* (_nbits xc
) 28) 65))
2250 (xc (quotient q xz
))
2251 (remainder (modulo q xc
))))
2253 ((not (= remainder
0)) it
2256 (let () (clean xc e
5 -
))
2258 ;; Guard against large values of ye, using the same logic as in
2259 ;; the 'xc is a power of 2' branch. 10/3 is an upper bound for
2261 (let ((emax (quotient (* p
10) 3))))
2263 ((>= ye
(len (str emax
)))
2267 (set! e
(_decimal_lshift_exact (* e yc
) ye
))
2268 (set! xe
(_decimal_lshift_exact (* xe yc
) ye
)))
2270 ((or (eq? e None
= (eq? xe None
))) it
2277 (set! xc
(expt 2 e
))
2283 ((>= xc
(expt 10 p
)) it it
)
2286 (set! xe
(+ (- e
) (- xe
)))
2287 return _dec_from_triple
(0, str
(xc), xe
)
2289 # now y is positive
; find m and n such that y = m/n
2293 if xe
!= 0 and len
(str(abs(yc*xe
))) <= -ye
:
2295 xc_bits
= _nbits
(xc)
2296 if xc
!= 1 and len
(str(abs(yc)*xc_bits
)) <= -ye
:
2298 m
, n
= yc
, 10**(-ye)
2299 while m %
2 == n %
2 == 0:
2302 while m %
5 == n %
5 == 0:
2306 # compute nth root of xc
*10**xe
2308 # if
1 < xc
< 2**n then xc isn
't an nth power
2309 if xc
!= 1 and xc_bits
<= n
:
2312 xe
, rem
= divmod
(xe, n
)
2316 # compute nth root of xc using Newton
's method
2317 a
= 1 << -
(-_nbits(xc)//n
) # initial estimate
2319 q
, r
= divmod
(xc, a
**(n-1))
2323 a
= (a*(n-1) + q
)//n
2324 if not
(a == q and r
== 0):
2328 # now xc
*10**xe is the nth root of the original xc
*10**xe
2329 # compute mth power of xc
*10**xe
2331 # if m
> p
*100//_log10_lb
(xc) then m
> p
/log10
(xc), hence xc
**m
>
2332 # 10**p and the result is not representable.
2333 if xc
> 1 and m
> p
*100//_log10_lb
(xc):
2340 # by this point the result
*is
* exactly representable
2341 # adjust the exponent to get as close as possible to the ideal
2342 # exponent
, if necessary
2344 if other._isinteger
() and other._sign
== 0:
2345 ideal_exponent
= self._exp
*int
(other)
2346 zeros
= min
(xe-ideal_exponent, p-len
(str_xc))
2349 return _dec_from_triple
(0, str_xc
+'0'*zeros
, xe-zeros
)
2351 def __pow__
(self, other
, modulo
=None
, context
=None
):
2352 """Return self ** other [ % modulo].
2354 With two arguments, compute self**other.
2356 With three arguments, compute (self**other) % modulo. For the
2357 three argument form, the following restrictions on the
2360 - all three arguments must be integral
2361 - other must be nonnegative
2362 - either self or other (or both) must be nonzero
2363 - modulo must be nonzero and must have at most p digits,
2364 where p is the context precision.
2366 If any of these restrictions is violated the InvalidOperation
2369 The result of pow(self, other, modulo) is identical to the
2370 result that would be obtained by computing (self**other) %
2371 modulo with unbounded precision, but is computed more
2372 efficiently. It is always exact.
2375 if modulo is not None
:
2376 return self._power_modulo
(other, modulo
, context
)
2378 other
= _convert_other
(other)
2379 if other is NotImplemented
:
2383 context
= getcontext
()
2385 # either argument is a NaN
=> result is NaN
2386 ans
= self._check_nans
(other, context
)
2390 # 0**0 = NaN
(!), x
**0 = 1 for nonzero x
(including +/-Infinity
)
2393 return context._raise_error
(InvalidOperation, '0 ** 0')
2397 # result has sign
1 iff self._sign is
1 and other is an odd integer
2400 if other._isinteger
():
2401 if not other._iseven
():
2404 # -ve
**noninteger
= NaN
2405 # (-0)**noninteger
= 0**noninteger
2407 return context._raise_error
(InvalidOperation,
2408 'x
** y with x negative and y not an integer
')
2409 # negate self
, without doing any unwanted rounding
2410 self
= self.copy_negate
()
2412 # 0**(+ve or Inf
)= 0; 0**(-ve or -Inf) = Infinity
2414 if other._sign
== 0:
2415 return _dec_from_triple
(result_sign, '0', 0)
2417 return _SignedInfinity
[result_sign]
2419 # Inf
**(+ve or Inf
) = Inf
; Inf**(-ve or -Inf) = 0
2420 if self._isinfinity
():
2421 if other._sign
== 0:
2422 return _SignedInfinity
[result_sign]
2424 return _dec_from_triple
(result_sign, '0', 0)
2426 # 1**other
= 1, but the choice of exponent and the flags
2427 # depend on the exponent of self
, and on whether other is a
2428 # positive integer
, a negative integer
, or neither
2430 if other._isinteger
():
2431 # exp
= max
(self._exp
*max
(int(other), 0),
2432 # 1-context.prec
) but evaluating int
(other) directly
2433 # is dangerous until we know other is small
(other
2434 # could be
1e999999999
)
2435 if other._sign
== 1:
2437 elif other
> context.prec
:
2438 multiplier
= context.prec
2440 multiplier
= int
(other)
2442 exp
= self._exp
* multiplier
2443 if exp
< 1-context.prec
:
2444 exp
= 1-context.prec
2445 context._raise_error
(Rounded)
2447 context._raise_error
(Inexact)
2448 context._raise_error
(Rounded)
2449 exp
= 1-context.prec
2451 return _dec_from_triple
(result_sign, '1'+'0'*-exp
, exp
)
2453 # compute adjusted exponent of self
2454 self_adj
= self.adjusted
()
2456 # self
** infinity is infinity if self
> 1, 0 if self
< 1
2457 # self
** -infinity is infinity if self
< 1, 0 if self
> 1
2458 if other._isinfinity
():
2459 if
(other._sign
== 0) == (self_adj < 0):
2460 return _dec_from_triple
(result_sign, '0', 0)
2462 return _SignedInfinity
[result_sign]
2464 # from here on
, the result always goes through the call
2465 # to _fix at the end of this function.
2469 # crude test to catch cases of extreme overflow
/underflow. If
2470 # log10
(self)*other
>= 10**bound and bound
>= len
(str(Emax))
2471 # then
10**bound
>= 10**len
(str(Emax)) >= Emax
+1 and hence
2472 # self
**other
>= 10**(Emax+1), so overflow occurs. The test
2473 # for underflow is similar.
2474 bound
= self._log10_exp_bound
() + other.adjusted
()
2475 if
(self_adj >= 0) == (other._sign
== 0):
2476 # self
> 1 and other
+ve
, or self
< 1 and other -ve
2477 # possibility of overflow
2478 if bound
>= len
(str(context.Emax
)):
2479 ans
= _dec_from_triple
(result_sign, '1', context.Emax
+1)
2481 # self
> 1 and other -ve
, or self
< 1 and other
+ve
2482 # possibility of underflow to
0
2483 Etiny
= context.Etiny
()
2484 if bound
>= len
(str(-Etiny)):
2485 ans
= _dec_from_triple
(result_sign, '1', Etiny-1
)
2487 # try for an exact result with precision
+1
2489 ans
= self._power_exact
(other, context.prec
+ 1)
2491 if result_sign
== 1:
2492 ans
= _dec_from_triple
(1, ans._int
, ans._exp
)
2495 # usual case
: inexact result
, x
**y computed directly as exp
(y*log
(x))
2499 xc
, xe
= x.int
, x.exp
2501 yc
, ye
= y.int
, y.exp
2505 # compute correctly rounded result
: start with precision
+3,
2506 # then increase precision until result is unambiguously roundable
2509 coeff
, exp
= _dpower
(xc, xe
, yc
, ye
, p
+extra
)
2510 if coeff %
(5*10**(len(str(coeff))-p-1
)):
2514 ans
= _dec_from_triple
(result_sign, str
(coeff), exp
)
2516 # unlike exp
, ln and log10
, the power function respects the
2517 # rounding mode
; no need to switch to ROUND_HALF_EVEN here
2519 # There
's a difficulty here when
'other
' is not an integer and
2520 # the result is exact. In this case
, the specification
2521 # requires that the Inexact flag be raised
(in spite of
2522 # exactness
), but since the result is exact _fix won
't do this
2523 # for us.
(Correspondingly, the Underflow signal should also
2524 # be raised for subnormal results.
) We can
't directly raise
2525 # these signals either before or after calling _fix
, since
2526 # that would violate the precedence for signals. So we wrap
2527 # the ._fix call in a temporary context
, and reraise
2529 if exact and not other._isinteger
():
2530 # pad with zeros up to length context.prec
+1 if necessary
; this
2531 # ensures that the Rounded signal will be raised.
2532 if len
(ans._int
) <= context.prec
:
2533 expdiff
= context.prec
+ 1 - len
(ans._int
)
2534 ans
= _dec_from_triple
(ans._sign
, ans._int
+'0'*expdiff
,
2537 # create a copy of the current context
, with cleared flags
/traps
2538 newcontext
= context.copy
()
2539 newcontext.clear_flags
()
2540 for exception in _signals
:
2541 newcontext.traps
[exception] = 0
2543 # round in the new context
2544 ans
= ans._fix
(newcontext)
2546 # raise Inexact
, and if necessary
, Underflow
2547 newcontext._raise_error
(Inexact)
2548 if newcontext.flags
[Subnormal]:
2549 newcontext._raise_error
(Underflow)
2551 # propagate signals to the original context
; _fix could
2552 # have raised any of Overflow
, Underflow
, Subnormal
,
2553 # Inexact
, Rounded
, Clamped. Overflow needs the correct
2554 # arguments. Note that the order of the exceptions is
2556 if newcontext.flags
[Overflow]:
2557 context._raise_error
(Overflow, 'above Emax
', ans._sign
)
2558 for exception in Underflow
, Subnormal
, Inexact
, Rounded
, Clamped
:
2559 if newcontext.flags
[exception]:
2560 context._raise_error
(exception)
2563 ans
= ans._fix
(context)
2567 def __rpow__
(self, other
, context
=None
):
2568 """Swaps self/other and returns __pow__."""
2569 other
= _convert_other
(other)
2570 if other is NotImplemented
:
2572 return other.__pow__
(self, context
=context
)
2574 def normalize
(self, context
=None
):
2575 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2578 context
= getcontext
()
2580 if self._is_special
:
2581 ans
= self._check_nans
(context=context
)
2585 dup
= self._fix
(context)
2586 if dup._isinfinity
():
2590 return _dec_from_triple
(dup._sign
, '0', 0)
2591 exp_max
= [context.Emax, context.Etop()][context.clamp]
2594 while dup._int
[end-1] == '0' and exp
< exp_max
:
2597 return _dec_from_triple
(dup._sign
, dup._int
[:end], exp
)
2599 def quantize
(self, exp
, rounding
=None
, context
=None
):
2600 """Quantize self so its exponent is the same as that of exp.
2602 Similar to self._rescale(exp._exp) but with error checking.
2604 exp
= _convert_other
(exp, raiseit
=True
)
2607 context
= getcontext
()
2608 if rounding is None
:
2609 rounding
= context.rounding
2611 if self._is_special or exp._is_special
:
2612 ans
= self._check_nans
(exp, context
)
2616 if exp._isinfinity
() or self._isinfinity
():
2617 if exp._isinfinity
() and self._isinfinity
():
2618 return Decimal
(self) # if both are inf
, it is OK
2619 return context._raise_error
(InvalidOperation,
2620 'quantize with one INF
')
2622 # exp._exp should be between Etiny and Emax
2623 if not
(context.Etiny
() <= exp._exp
<= context.Emax
):
2624 return context._raise_error
(InvalidOperation,
2625 'target exponent out of bounds in quantize
')
2628 ans
= _dec_from_triple
(self._sign
, '0', exp._exp
)
2629 return ans._fix
(context)
2631 self_adjusted
= self.adjusted
()
2632 if self_adjusted
> context.Emax
:
2633 return context._raise_error
(InvalidOperation,
2634 'exponent of quantize result too large for current context
')
2635 if self_adjusted - exp._exp
+ 1 > context.prec
:
2636 return context._raise_error
(InvalidOperation,
2637 'quantize result has too many digits for current context
')
2639 ans
= self._rescale
(exp._exp
, rounding
)
2640 if ans.adjusted
() > context.Emax
:
2641 return context._raise_error
(InvalidOperation,
2642 'exponent of quantize result too large for current context
')
2643 if len
(ans._int
) > context.prec
:
2644 return context._raise_error
(InvalidOperation,
2645 'quantize result has too many digits for current context
')
2647 # raise appropriate flags
2648 if ans and ans.adjusted
() < context.Emin
:
2649 context._raise_error
(Subnormal)
2650 if ans._exp
> self._exp
:
2652 context._raise_error
(Inexact)
2653 context._raise_error
(Rounded)
2655 # call to fix takes care of any necessary folddown
, and
2656 # signals Clamped if necessary
2657 ans
= ans._fix
(context)
2660 def same_quantum
(self, other
, context
=None
):
2661 """Return True if self and other have the same exponent; otherwise
2664 If either operand is a special value, the following rules are used:
2665 * return True if both operands are infinities
2666 * return True if both operands are NaNs
2667 * otherwise, return False.
2669 other
= _convert_other
(other, raiseit
=True
)
2670 if self._is_special or other._is_special
:
2671 return
(self.is_nan
() and other.is_nan
() or
2672 self.is_infinite
() and other.is_infinite
())
2673 return self._exp
== other._exp
2675 def _rescale
(self, exp
, rounding
):
2676 """Rescale self so that the exponent is exp, either by padding with zeros
2677 or by truncating digits, using the given rounding mode.
2679 Specials are returned without change. This operation is
2680 quiet: it raises no flags, and uses no information from the
2683 exp = exp to scale to (an integer)
2684 rounding = rounding mode
2686 if self._is_special
:
2687 return Decimal
(self)
2689 return _dec_from_triple
(self._sign
, '0', exp
)
2691 if self._exp
>= exp
:
2692 # pad answer with zeros if necessary
2693 return _dec_from_triple
(self._sign
,
2694 self._int
+ '0'*(self._exp - exp
), exp
)
2696 # too many digits
; round and lose data. If self.adjusted() <
2697 # exp-1
, replace self by
10**(exp-1) before rounding
2698 digits
= len
(self._int
) + self._exp - exp
2700 self
= _dec_from_triple
(self._sign
, '1', exp-1
)
2702 this_function
= self._pick_rounding_function
[rounding]
2703 changed
= this_function
(self, digits
)
2704 coeff
= self._int
[:digits] or
'0'
2706 coeff
= str
(int(coeff)+1)
2707 return _dec_from_triple
(self._sign
, coeff
, exp
)
2709 def _round
(self, places
, rounding
):
2710 """Round a nonzero, nonspecial Decimal to a fixed number of
2711 significant figures, using the given rounding mode.
2713 Infinities, NaNs and zeros are returned unaltered.
2715 This operation is quiet: it raises no flags, and uses no
2716 information from the context.
2720 raise ValueError
("argument should be at least 1 in _round")
2721 if self._is_special or not self
:
2722 return Decimal
(self)
2723 ans
= self._rescale
(self.adjusted
()+1-places
, rounding
)
2724 # it can happen that the rescale alters the adjusted exponent
;
2725 # for example when rounding
99.97 to
3 significant figures.
2726 # When this happens we end up with an extra
0 at the end of
2727 # the number
; a second rescale fixes this.
2728 if ans.adjusted
() != self.adjusted
():
2729 ans
= ans._rescale
(ans.adjusted
()+1-places
, rounding
)
2732 def to_integral_exact
(self, rounding
=None
, context
=None
):
2733 """Rounds to a nearby integer.
2735 If no rounding mode is specified, take the rounding mode from
2736 the context. This method raises the Rounded and Inexact flags
2739 See also: to_integral_value, which does exactly the same as
2740 this method except that it doesn't raise Inexact or Rounded.
2742 if self._is_special
:
2743 ans
= self._check_nans
(context=context
)
2746 return Decimal
(self)
2748 return Decimal
(self)
2750 return _dec_from_triple
(self._sign
, '0', 0)
2752 context
= getcontext
()
2753 if rounding is None
:
2754 rounding
= context.rounding
2755 ans
= self._rescale
(0, rounding
)
2757 context._raise_error
(Inexact)
2758 context._raise_error
(Rounded)
2761 def to_integral_value
(self, rounding
=None
, context
=None
):
2762 """Rounds to the nearest integer, without raising inexact, rounded."""
2764 context
= getcontext
()
2765 if rounding is None
:
2766 rounding
= context.rounding
2767 if self._is_special
:
2768 ans
= self._check_nans
(context=context
)
2771 return Decimal
(self)
2773 return Decimal
(self)
2775 return self._rescale
(0, rounding
)
2777 # the method name changed
, but we provide also the old one
, for compatibility
2778 to_integral
= to_integral_value
2780 def sqrt
(self, context
=None
):
2781 """Return the square root of self."""
2783 context
= getcontext
()
2785 if self._is_special
:
2786 ans
= self._check_nans
(context=context
)
2790 if self._isinfinity
() and self._sign
== 0:
2791 return Decimal
(self)
2794 # exponent
= self._exp
// 2. sqrt
(-0) = -
0
2795 ans
= _dec_from_triple
(self._sign
, '0', self._exp
// 2)
2796 return ans._fix
(context)
2799 return context._raise_error
(InvalidOperation, 'sqrt
(-x), x
> 0')
2801 # At this point self represents a positive number. Let p be
2802 # the desired precision and express self in the form c
*100**e
2803 # with c a positive real number and e an integer
, c and e
2804 # being chosen so that
100**(p-1) <= c
< 100**p. Then the
2805 # (exact) square root of self is sqrt
(c)*10**e
, and
10**(p-1)
2806 # <= sqrt
(c) < 10**p
, so the closest representable Decimal at
2807 # precision p is n
*10**e where n
= round_half_even
(sqrt(c)),
2808 # the closest integer to sqrt
(c) with the even integer chosen
2809 # in the case of a tie.
2811 # To ensure correct rounding in all cases
, we use the
2812 # following trick
: we compute the square root to an extra
2813 # place
(precision p
+1 instead of precision p
), rounding down.
2814 # Then
, if the result is inexact and its last digit is
0 or
5,
2815 # we increase the last digit to
1 or
6 respectively
; if it's
2816 # exact we leave the last digit alone. Now the final round to
2817 # p places
(or fewer in the case of underflow
) will round
2818 # correctly and raise the appropriate flags.
2820 # use an extra digit of precision
2821 prec
= context.prec
+1
2823 # write argument in the form c
*100**e where e
= self._exp
//2
2824 # is the
'ideal
' exponent
, to be used if the square root is
2825 # exactly representable. l is the number of
'digits
' of c in
2826 # base
100, so that
100**(l-1) <= c
< 100**l.
2831 l
= (len(self._int
) >> 1) + 1
2834 l
= len
(self._int
)+1 >> 1
2836 # rescale so that c has exactly prec base
100 'digits
'
2842 c
, remainder
= divmod
(c, 100**-shift
)
2843 exact
= not remainder
2846 # find n
= floor
(sqrt(c)) using Newton
's method
2854 exact
= exact and n
*n
== c
2857 # result is exact
; rescale to use ideal exponent e
2859 # assert n %
10**shift
== 0
2865 # result is not exact
; fix last digit as described above
2869 ans
= _dec_from_triple
(0, str
(n), e
)
2871 # round
, and fit to current context
2872 context
= context._shallow_copy
()
2873 rounding
= context._set_rounding
(ROUND_HALF_EVEN)
2874 ans
= ans._fix
(context)
2875 context.rounding
= rounding
2879 def max
(self, other
, context
=None
):
2880 """Returns the larger value.
2882 Like max(self, other) except if one is not a number, returns
2883 NaN (and signals if one is sNaN). Also rounds.
2885 other
= _convert_other
(other, raiseit
=True
)
2888 context
= getcontext
()
2890 if self._is_special or other._is_special
:
2891 # If one operand is a quiet NaN and the other is number
, then the
2892 # number is always returned
2896 if on
== 1 and sn
== 0:
2897 return self._fix
(context)
2898 if sn
== 1 and on
== 0:
2899 return other._fix
(context)
2900 return self._check_nans
(other, context
)
2902 c
= self._cmp
(other)
2904 # If both operands are finite and equal in numerical value
2905 # then an ordering is applied
:
2907 # If the signs differ then max returns the operand with the
2908 # positive sign and min returns the operand with the negative sign
2910 # If the signs are the same then the exponent is used to select
2911 # the result. This is exactly the ordering used in compare_total.
2912 c
= self.compare_total
(other)
2919 return ans._fix
(context)
2921 def min
(self, other
, context
=None
):
2922 """Returns the smaller value.
2924 Like min(self, other) except if one is not a number, returns
2925 NaN (and signals if one is sNaN). Also rounds.
2927 other
= _convert_other
(other, raiseit
=True
)
2930 context
= getcontext
()
2932 if self._is_special or other._is_special
:
2933 # If one operand is a quiet NaN and the other is number
, then the
2934 # number is always returned
2938 if on
== 1 and sn
== 0:
2939 return self._fix
(context)
2940 if sn
== 1 and on
== 0:
2941 return other._fix
(context)
2942 return self._check_nans
(other, context
)
2944 c
= self._cmp
(other)
2946 c
= self.compare_total
(other)
2953 return ans._fix
(context)
2955 def _isinteger
(self):
2956 """Returns whether self is an integer"""
2957 if self._is_special
:
2961 rest
= self._int
[self._exp:]
2962 return rest
== '0'*len
(rest)
2965 """Returns True if self is even. Assumes self is an integer."""
2966 if not self or self._exp
> 0:
2968 return self._int
[-1+self._exp] in
'02468'
2971 """Return the adjusted exponent of self"""
2973 return self._exp
+ len
(self._int
) -
1
2974 # If NaN or Infinity
, self._exp is string
2978 def canonical
(self):
2979 """Returns the same Decimal object.
2981 As we do not have different encodings for the same number, the
2982 received object already is in its canonical form.
2986 def compare_signal
(self, other
, context
=None
):
2987 """Compares self to the other operand numerically.
2989 It's pretty much like compare(), but all NaNs signal, with signaling
2990 NaNs taking precedence over quiet NaNs.
2992 other
= _convert_other
(other, raiseit
= True
)
2993 ans
= self._compare_check_nans
(other, context
)
2996 return self.compare
(other, context
=context
)
2998 def compare_total
(self, other
, context
=None
):
2999 """Compares self to other using the abstract representations.
3001 This is not like the standard compare, which use their numerical
3002 value. Note that a total ordering is defined for all possible abstract
3005 other
= _convert_other
(other, raiseit
=True
)
3007 # if one is negative and the other is positive
, it
's easy
3008 if self._sign and not other._sign
:
3010 if not self._sign and other._sign
:
3014 # let
's handle both NaN types
3015 self_nan
= self._isnan
()
3016 other_nan
= other._isnan
()
3017 if self_nan or other_nan
:
3018 if self_nan
== other_nan
:
3019 # compare payloads as though they
're integers
3020 self_key
= len
(self._int
), self._int
3021 other_key
= len
(other._int
), other._int
3022 if self_key
< other_key
:
3027 if self_key
> other_key
:
3058 if self._exp
< other._exp
:
3063 if self._exp
> other._exp
:
3071 def compare_total_mag
(self, other
, context
=None
):
3072 """Compares self to other using abstract repr., ignoring sign.
3074 Like compare_total, but with operand's sign ignored and assumed to be 0.
3076 other
= _convert_other
(other, raiseit
=True
)
3079 o
= other.copy_abs
()
3080 return s.compare_total
(o)
3083 """Returns a copy with the sign set to 0. """
3084 return _dec_from_triple
(0, self._int
, self._exp
, self._is_special
)
3086 def copy_negate
(self):
3087 """Returns a copy with the sign inverted."""
3089 return _dec_from_triple
(0, self._int
, self._exp
, self._is_special
)
3091 return _dec_from_triple
(1, self._int
, self._exp
, self._is_special
)
3093 def copy_sign
(self, other
, context
=None
):
3094 """Returns self with the sign of other."""
3095 other
= _convert_other
(other, raiseit
=True
)
3096 return _dec_from_triple
(other._sign
, self._int
,
3097 self._exp
, self._is_special
)
3099 def exp
(self, context
=None
):
3100 """Returns e ** self."""
3103 context
= getcontext
()
3106 ans
= self._check_nans
(context=context
)
3110 # exp
(-Infinity) = 0
3111 if self._isinfinity
() == -
1:
3118 # exp
(Infinity) = Infinity
3119 if self._isinfinity
() == 1:
3120 return Decimal
(self)
3122 # the result is now guaranteed to be inexact
(the true
3123 # mathematical result is transcendental
). There
's no need to
3124 # raise Rounded and Inexact here---they
'll always be raised as
3125 # a result of the call to _fix.
3127 adj
= self.adjusted
()
3129 # we only need to do any computation for quite a small range
3130 # of adjusted exponents---for example
, -
29 <= adj
<= 10 for
3131 # the default context. For smaller exponent the result is
3132 # indistinguishable from
1 at the given precision
, while for
3133 # larger exponent the result either overflows or underflows.
3134 if self._sign
== 0 and adj
> len
(str((context.Emax
+1)*3)):
3136 ans
= _dec_from_triple
(0, '1', context.Emax
+1)
3137 elif self._sign
== 1 and adj
> len
(str((-context.Etiny
()+1)*3)):
3139 ans
= _dec_from_triple
(0, '1', context.Etiny
()-
1)
3140 elif self._sign
== 0 and adj
< -p
:
3141 # p
+1 digits
; final round will raise correct flags
3142 ans
= _dec_from_triple
(0, '1' + '0'*(p-1) + '1', -p
)
3143 elif self._sign
== 1 and adj
< -p-1
:
3144 # p
+1 digits
; final round will raise correct flags
3145 ans
= _dec_from_triple
(0, '9'*(p+1), -p-1
)
3149 c
, e
= op.int
, op.exp
3153 # compute correctly rounded result
: increase precision by
3154 # 3 digits at a time until we get an unambiguously
3158 coeff
, exp
= _dexp
(c, e
, p
+extra
)
3159 if coeff %
(5*10**(len(str(coeff))-p-1
)):
3163 ans
= _dec_from_triple
(0, str
(coeff), exp
)
3165 # at this stage
, ans should round correctly with
*any
*
3166 # rounding mode
, not just with ROUND_HALF_EVEN
3167 context
= context._shallow_copy
()
3168 rounding
= context._set_rounding
(ROUND_HALF_EVEN)
3169 ans
= ans._fix
(context)
3170 context.rounding
= rounding
3174 def is_canonical
(self):
3175 """Return True if self is canonical; otherwise return False.
3177 Currently, the encoding of a Decimal instance is always
3178 canonical, so this method returns True for any Decimal.
3182 def is_finite
(self):
3183 """Return True if self is finite; otherwise return False.
3185 A Decimal instance is considered finite if it is neither
3188 return not self._is_special
3190 def is_infinite
(self):
3191 """Return True if self is infinite; otherwise return False."""
3192 return self._exp
== 'F
'
3195 """Return True if self is a qNaN or sNaN; otherwise return False."""
3196 return self._exp in
('n
', 'N
')
3198 def is_normal
(self, context
=None
):
3199 """Return True if self is a normal number; otherwise return False."""
3200 if self._is_special or not self
:
3203 context
= getcontext
()
3204 return context.Emin
<= self.adjusted
()
3207 """Return True if self is a quiet NaN; otherwise return False."""
3208 return self._exp
== 'n
'
3210 def is_signed
(self):
3211 """Return True if self is negative; otherwise return False."""
3212 return self._sign
== 1
3215 """Return True if self is a signaling NaN; otherwise return False."""
3216 return self._exp
== 'N
'
3218 def is_subnormal
(self, context
=None
):
3219 """Return True if self is subnormal; otherwise return False."""
3220 if self._is_special or not self
:
3223 context
= getcontext
()
3224 return self.adjusted
() < context.Emin
3227 """Return True if self is a zero; otherwise return False."""
3228 return not self._is_special and self._int
== '0'
3230 def _ln_exp_bound
(self):
3231 """Compute a lower bound for the adjusted exponent of self.ln().
3232 In other words, compute r such that self.ln() >= 10**r. Assumes
3233 that self is finite and positive and that self != 1.
3236 # for
0.1 <= x
<= 10 we use the inequalities
1-
1/x
<= ln
(x) <= x-1