1 (define-module (language python module decimal
)
2 #:use-module
((language python module collections
) #:select
(namedtuple))
3 #:use-module
((language python module itertools
) #:select
(chain repeat
))
4 #:use-module
((language python module sys
) #:select
(maxsize hash_info
))
5 #:use-module
(language python module
)
6 #:use-module
((language python module python
) #:select
7 (isinstance str float int tuple classmethod pow property
8 complex range reversed
(format . str-format
)))
9 #:use-module
(language python list
)
10 #:use-module
(language python number
)
11 #:use-module
(language python string
)
12 #:use-module
(language python for
)
13 #:use-module
(language python try
)
14 #:use-module
(language python hash
)
15 #:use-module
(language python dict
)
16 #:use-module
(language python def
)
17 #:use-module
(language python exceptions
)
18 #:use-module
(language python bool
)
19 #:use-module
(language python module
)
20 #:use-module
(oop pf-objects
)
21 #:use-module
(language python module re
)
22 #:use-module
(ice-9 control
)
23 #:use-module
((ice-9 match
) #:select
((match . ice
:match
)))
25 ( ;; Two major classes
28 ;; Named tuple representation
32 DefaultContext BasicContext ExtendedContext
35 DecimalException Clamped InvalidOperation DivisionByZero
36 Inexact Rounded Subnormal Overflow Underflow
39 ;; Exceptional conditions that trigger InvalidOperation
40 DivisionImpossible InvalidContext ConversionSyntax DivisionUndefined
42 ;; Constants for use in setting up contexts
43 ROUND_DOWN ROUND_HALF_UP ROUND_HALF_EVEN ROUND_CEILING
44 ROUND_FLOOR ROUND_UP ROUND_HALF_DOWN ROUND_05UP
46 ;; Functions for manipulating contexts
47 setcontext getcontext localcontext
49 ;; Limits for the C version for compatibility
50 MAX_PREC MAX_EMAX MIN_EMIN MIN_ETINY
))
53 (define-syntax-rule (aif it p . l
) (let ((it p
)) (if it . l
)))
56 This is the copyright information of the file ported over to scheme
57 # Copyright
(c) 2004 Python Software Foundation.
58 # All rights reserved.
60 # Written by Eric Price
<eprice at tjhsst.edu
>
61 # and Facundo Batista
<facundo at taniquetil.com.ar
>
62 # and Raymond Hettinger
<python at rcn.com
>
63 # and Aahz
<aahz at pobox.com
>
66 # This module should be kept in sync with the latest updates of the
67 # IBM specification as it evolves. Those updates will be treated
68 # as bug fixes
(deviation from the spec is a compatibility
, usability
69 # bug
) and will be backported. At this point the spec is stabilizing
70 # and the updates are becoming fewer
, smaller
, and less significant.
73 (define guile
:modulo
(@ (guile) modulo
))
75 (define __name__
"decimal")
76 (define __xname__ __name__
)
77 (define __version__
"1.70")
78 ;; Highest version of the spec this complies with
79 ;; See http://speleotrove.com/decimal/
82 (define DecimalTuple
(namedtuple "DecimalTuple" "sign,digits,exponent"))
85 (define ROUND_DOWN
'ROUND_DOWN
)
86 (define ROUND_HALF_UP
'ROUND_HALF_UP
)
87 (define ROUND_HALF_EVEN
'ROUND_HALF_EVEN
)
88 (define ROUND_CEILING
'ROUND_CEILING
)
89 (define ROUND_FLOOR
'ROUND_FLOOR
)
90 (define ROUND_UP
'ROUND_UP
)
91 (define ROUND_HALF_DOWN
'ROUND_HALF_DOWN
)
92 (define ROUND_05UP
'ROUND_05UP
)
94 ;; Compatibility with the C version
95 (define MAX_PREC
425000000)
96 (define MAX_EMAX
425000000)
97 (define MIN_EMIN -
425000000)
99 (if (= maxsize
(- (ash 1 63) 1))
101 (set! MAX_PREC
999999999999999999)
102 (set! MAX_EMAX
999999999999999999)
103 (set! MIN_EMIN -
999999999999999999)))
105 (define MIN_ETINY
(- MIN_EMIN
(- MAX_PREC
1)))
108 (define-inlinable (cx-prec x
) (rawref x
'prec
))
109 (define-inlinable (cx-emax x
) (rawref x
'Emax
))
110 (define-inlinable (cx-emin x
) (rawref x
'Emin
))
111 (define-inlinable (cx-etiny x
) ((ref x
'Etiny
)))
112 (define-inlinable (cx-etop x
) ((ref x
'Etop
)))
113 (define-inlinable (cx-copy x
) ((ref x
'copy
)))
114 (define-inlinable (cx-clear_flags x
) ((ref x
'clear_flags
)))
115 (define-inlinable (cx-raise x
) (ref x
'_raise_error
))
116 (define-inlinable (cx-error x
) (ref x
'_raise_error
))
117 (define-inlinable (cx-capitals x
) (rawref x
'capitals
))
118 (define-inlinable (cx-cap x
) (rawref x
'capitals
))
119 (define-inlinable (cx-rounding x
) (rawref x
'rounding
))
120 (define-inlinable (cx-clamp x
) (rawref x
'clamp
))
121 (define-inlinable (cx-traps x
) (rawref x
'traps
))
122 (define-inlinable (cx-flags x
) (rawref x
'flags
))
126 (define-python-class DecimalException
(ArithmeticError)
127 "Base exception class.
129 Used exceptions derive from this.
130 If an exception derives from another exception besides this (such as
131 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
132 called if the others are present. This isn't actually used for
135 handle -- Called when context._raise_error is called and the
136 trap_enabler is not set. First argument is self, second is the
137 context. More arguments can be given, those being after
138 the explanation in _raise_error (For example,
139 context._raise_error(NewError, '(-x)!', self._sign) would
140 call NewError().handle(context, self._sign).)
142 To define a new exception, it should be sufficient to have it derive
143 from DecimalException.
147 (lambda (self context . args
)
151 (define-python-class Clamped
(DecimalException)
152 "Exponent of a 0 changed to fit bounds.
154 This occurs and signals clamped if the exponent of a result has been
155 altered in order to fit the constraints of a specific concrete
156 representation. This may occur when the exponent of a zero result would
157 be outside the bounds of a representation, or when a large normal
158 number would have an encoded exponent that cannot be represented. In
159 this latter case, the exponent is reduced to fit and the corresponding
160 number of zero digits are appended to the coefficient ('fold-down').
163 (define-python-class InvalidOperation
(DecimalException)
164 "An invalid operation was performed.
166 Various bad things cause this:
168 Something creates a signaling NaN
174 x._rescale( non-integer )
179 An operand is invalid
181 The result of the operation after these is a quiet positive NaN,
182 except when the cause is a signaling NaN, in which case the result is
183 also a quiet NaN, but with the original sign, and an optional
184 diagnostic information.
187 (lambda (self context . args
)
189 (let ((ans (_dec_from_triple
190 (ref (car args
) '_sign
)
191 (ref (car args
) '_int
)
193 ((ref ans
'_fix_nan
) context
))
196 (define-python-class ConversionSyntax
(InvalidOperation)
197 "Trying to convert badly formed string.
199 This occurs and signals invalid-operation if a string is being
200 converted to a number and it does not conform to the numeric string
201 syntax. The result is [0,qNaN].
206 (define-python-class DivisionByZero
(DecimalException ZeroDivisionError
)
209 This occurs and signals division-by-zero if division of a finite number
210 by zero was attempted (during a divide-integer or divide operation, or a
211 power operation with negative right-hand operand), and the dividend was
214 The result of the operation is [sign,inf], where sign is the exclusive
215 or of the signs of the operands for divide, or is 1 for an odd power of
220 (lambda (self context sign . args
)
221 (pylist-ref _SignedInfinity sign
))))
223 (define-python-class DivisionImpossible
(InvalidOperation)
224 "Cannot perform the division adequately.
226 This occurs and signals invalid-operation if the integer result of a
227 divide-integer or remainder operation had too many digits (would be
228 longer than precision). The result is [0,qNaN].
234 (define-python-class DivisionUndefined
(InvalidOperation ZeroDivisionError
)
235 "Undefined result of division.
237 This occurs and signals invalid-operation if division by zero was
238 attempted (during a divide-integer, divide, or remainder operation), and
239 the dividend is also zero. The result is [0,qNaN].
245 (define-python-class Inexact
(DecimalException)
246 "Had to round, losing information.
248 This occurs and signals inexact whenever the result of an operation is
249 not exact (that is, it needed to be rounded and any discarded digits
250 were non-zero), or if an overflow or underflow condition occurs. The
251 result in all cases is unchanged.
253 The inexact signal may be tested (or trapped) to determine if a given
254 operation (or sequence of operations) was inexact.
257 (define-python-class InvalidContext
(InvalidOperation)
258 "Invalid context. Unknown rounding, for example.
260 This occurs and signals invalid-operation if an invalid context was
261 detected during an operation. This can occur if contexts are not checked
262 on creation and either the precision exceeds the capability of the
263 underlying concrete representation or an unknown or unsupported rounding
264 was specified. These aspects of the context need only be checked when
265 the values are required to be used. The result is [0,qNaN].
271 (define-python-class Rounded
(DecimalException)
272 "Number got rounded (not necessarily changed during rounding).
274 This occurs and signals rounded whenever the result of an operation is
275 rounded (that is, some zero or non-zero digits were discarded from the
276 coefficient), or if an overflow or underflow condition occurs. The
277 result in all cases is unchanged.
279 The rounded signal may be tested (or trapped) to determine if a given
280 operation (or sequence of operations) caused a loss of precision.
283 (define-python-class Subnormal
(DecimalException)
284 "Exponent < Emin before rounding.
286 This occurs and signals subnormal whenever the result of a conversion or
287 operation is subnormal (that is, its adjusted exponent is less than
288 Emin, before any rounding). The result in all cases is unchanged.
290 The subnormal signal may be tested (or trapped) to determine if a given
291 or operation (or sequence of operations) yielded a subnormal result.
294 (define-python-class Overflow
(Inexact Rounded
)
297 This occurs and signals overflow if the adjusted exponent of a result
298 (from a conversion or from an operation that is not an attempt to divide
299 by zero), after rounding, would be greater than the largest value that
300 can be handled by the implementation (the value Emax).
302 The result depends on the rounding mode:
304 For round-half-up and round-half-even (and for round-half-down and
305 round-up, if implemented), the result of the operation is [sign,inf],
306 where sign is the sign of the intermediate result. For round-down, the
307 result is the largest finite number that can be represented in the
308 current precision, with the sign of the intermediate result. For
309 round-ceiling, the result is the same as for round-down if the sign of
310 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
311 the result is the same as for round-down if the sign of the intermediate
312 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
317 (let ((l (list ROUND_HALF_UP ROUND_HALF_EVEN
318 ROUND_HALF_DOWN ROUND_UP
)))
319 (lambda (self context sign . args
)
321 (if (memq (ref context
'rounding
) l
)
322 (ret (pylist-ref _SignedInfinity sign
)))
325 (if (eq?
(ref context
'rounding
) ROUND_CEILING
)
326 (ret (pylist-ref _SignedInfinity sign
))
327 (ret (_dec_from_triple
329 (* "9" (cx-prec context
))
330 (+ (- (cx-emax context
) (cx-prec context
)) 1)))))
333 (if (eq?
(ref context
'rounding
) ROUND_FLOOR
)
334 (ret (pylist-ref _SignedInfinity sign
))
335 (ret (_dec_from_triple
337 (* "9" (cx-prec context
))
338 (+ (- (cx-emax context
) (cx-prec context
)) 1))))))))))
341 (define-python-class Underflow
(Inexact Rounded Subnormal
)
342 "Numerical underflow with result rounded to 0.
344 This occurs and signals underflow if a result is inexact and the
345 adjusted exponent of the result would be smaller (more negative) than
346 the smallest value that can be handled by the implementation (the value
347 Emin). That is, the result is both inexact and subnormal.
349 The result after an underflow will be a subnormal number rounded, if
350 necessary, so that its exponent is not less than Etiny. This may result
351 in 0 with the sign of the intermediate result and an exponent of Etiny.
353 In all cases, Inexact, Rounded, and Subnormal will also be raised.
356 (define-python-class FloatOperation
(DecimalException TypeError
)
357 "Enable stricter semantics for mixing floats and Decimals.
359 If the signal is not trapped (default), mixing floats and Decimals is
360 permitted in the Decimal() constructor, context.create_decimal() and
361 all comparison operators. Both conversion and comparisons are exact.
362 Any occurrence of a mixed operation is silently recorded by setting
363 FloatOperation in the context flags. Explicit conversions with
364 Decimal.from_float() or context.create_decimal_from_float() do not
367 Otherwise (the signal is trapped), only equality comparisons and explicit
368 conversions are silent. All other mixed operations raise FloatOperation.
371 ;; List of public traps and flags
373 (vector Clamped DivisionByZero Inexact Overflow Rounded
374 Underflow InvalidOperation Subnormal FloatOperation
))
376 ;; Map conditions (per the spec) to signals
377 (define _condition_map
378 `((,ConversionSyntax .
,InvalidOperation
)
379 (,DivisionImpossible .
,InvalidOperation
)
380 (,DivisionUndefined .
,InvalidOperation
)
381 (,InvalidContext .
,InvalidOperation
)))
383 ;; Valid rounding modes
384 (define _rounding_modes
385 (list ROUND_DOWN ROUND_HALF_UP ROUND_HALF_EVEN ROUND_CEILING
386 ROUND_FLOOR ROUND_UP ROUND_HALF_DOWN ROUND_05UP
))
388 ;; ##### Context Functions ##################################################
390 ;; The getcontext() and setcontext() function manage access to a thread-local
392 (define *context
* (make-fluid #f
))
394 (fluid-ref *context
*))
395 (define (setcontext context
)
396 (fluid-set! *context
* context
))
398 ;; ##### Decimal class #######################################################
400 ;; Do not subclass Decimal from numbers.Real and do not register it as such
401 ;; (because Decimals are not interoperable with floats). See the notes in
402 ;; numbers.py for more detail.
404 (define _dec_from_triple
405 (lam (sign coefficient exponent
(= special
#f
))
406 "Create a decimal instance directly, without any validation,
407 normalization (e.g. removal of leading zeros) or argument
410 This function is for *internal use only*.
412 (Decimal sign coefficient exponent special
)))
414 (define (get-parsed-sign m
)
415 (if (equal?
((ref m
'group
) "sign") "-")
419 (define (get-parsed-int m
)
420 ((ref m
'group
) "int"))
422 (define (get-parsed-frac m
)
423 ((ref m
'group
) "frac"))
425 (define (get-parsed-exp m
)
426 ((ref m
'group
) "exp"))
428 (define (get-parsed-diag m
)
429 ((ref m
'group
) "diag"))
431 (define (get-parsed-sig m
)
432 ((ref m
'group
) "signal"))
434 (def (_mk self __init__
(= value
"0") (= context None
))
435 "Create a decimal point instance.
437 >>> Decimal('3.14') # string input
439 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
441 >>> Decimal(314) # int
443 >>> Decimal(Decimal(314)) # another decimal instance
445 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
449 ;; Note that the coefficient, self._int, is actually stored as
450 ;; a string rather than as a tuple of digits. This speeds up
451 ;; the "digits to integer" and "integer to digits" conversions
452 ;; that are used in almost every arithmetic operation on
453 ;; Decimals. This is an internal detail: the as_tuple function
454 ;; and the Decimal constructor still deal with tuples of
458 ;; REs insist on real strings, so we can too.
460 ((isinstance value str
)
461 (let ((m (_parser (scm-str str
))))
463 (let ((context (if (eq? context None
)
468 (+ "Invalid literal for Decimal: " value
))))
470 (let ((sign (get-parsed-sign m
))
471 (intpart (get-parsed-int m
))
472 (fracpart (get-parsed-frac m
))
473 (exp (get-parsed-exp m
))
474 (diag (get-parsed-diag m
))
475 (signal (get-parsed-sig m
)))
477 (set self
'sign sign
)
479 (if (not (eq? intpart None
))
481 (set self
'_int
(str (int (+ intpart fracpart
))))
482 (set self
'_exp
(- exp
(len fracpart
)))
483 (set self
'_is_special
#f
))
485 (if (not (eq? diag None
))
489 (py-lstrip (str (int (if (bool diag
)
495 (set self
'_exp
"n")))
499 (set self
'_exp
"F")))
500 (set self
'_is_special
#t
))))))
503 ((isinstance value int
)
508 (set self
'_int
(str (abs value
)))
509 (set self
'_is_special
#f
))
511 ;; From another decimal
512 ((isinstance value Decimal
)
513 (set self
'_exp
(ref value
'_exp
))
514 (set self
'_sign
(ref value
'_sign
))
515 (set self
'_int
(ref value
'_int
))
516 (set self
'_is_special
(ref value
'_is_special
)))
518 ;; From an internal working value
519 ((isinstance value _WorkRep
)
520 (set self
'_exp
(int (ref value
'_exp
)))
521 (set self
'_sign
(ref value
'_sign
))
522 (set self
'_int
(str (ref value
'int
)))
523 (set self
'_is_special
#f
))
525 ;; tuple/list conversion (possibly from as_tuple())
526 ((isinstance value
(list list tuple
))
527 (if (not (= (len value
) 3))
529 (+ "Invalid tuple size in creation of Decimal "
530 "from list or tuple. The list or tuple "
531 "should have exactly three elements."))))
532 ;; # process sign. The isinstance test rejects floats
533 (let ((v0 (pylist-ref value
0))
534 (v1 (pylist-ref value
1))
535 (v2 (pylist-ref value
2)))
536 (if (not (and (isinstance v0 int
)
537 (or (= v0
0) (= v0
1))))
539 (+ "Invalid sign. The first value in the tuple "
540 "should be an integer; either 0 for a "
541 "positive number or 1 for a negative number."))))
547 (set self
'is_special
#t
))
548 (let ((digits (py-list)))
549 ;; process and validate the digits in value[1]
550 (for ((digit : v1
)) ()
551 (if (and (isinstance digit int
)
554 ;; skip leading zeros
555 (if (or (bool digits
) (> digit
0))
556 (pylist-append! digits digit
))
558 (+ "The second value in the tuple must "
559 "be composed of integers in the range "
563 ((or (eq? v2
'n
) (eq? v2
'N
))
565 ;; NaN: digits form the diagnostic
566 (set self
'_int
(py-join "" (map str digits
)))
568 (set self
'_is_special
#t
)))
570 ;; finite number: digits give the coefficient
571 (set self
'_int
(py-join "" (map str digits
)))
573 (set self
'_is_special
#f
))
576 (+ "The third value in the tuple must "
577 "be an integer, or one of the "
578 "strings 'F', 'n', 'N'.")))))))))
580 ((isinstance value float
)
581 (let ((context (if (eq? context None
)
586 (+ "strict semantics for mixing floats and Decimals are "
589 (__init__ self
((ref Decimal
'from_float
) value
))))
593 (format #f
"Cannot convert ~a to Decimal" value
))))))
595 (define-inlinable (divmod x y
)
596 (values (quotient x y
) (modulo x y
)))
599 (syntax-rules (when let let
* if
)
601 ((_ (let () a ...
) . l
)
602 (begin a ...
(twix . l
)))
604 ((_ (let ((a aa
) ...
) b ...
) . l
)
605 (let ((a aa
) ...
) b ...
(twix . l
)))
606 ((_ (let (a ...
)) . l
)
608 ((_ (let* (a ...
) b ...
) . l
)
609 (let* (a ...
) b ...
(twix . l
)))
611 (begin (if . u
) (twix . l
)))
613 (begin (when . u
) (twix . l
)))
614 ((_ (a it code ...
) . l
)
615 (aif it a
(begin code ...
) (twix . l
)))))
617 (define-syntax-rule (norm-op self op
)
619 (set! op
((ref self
'_convert_other
) op
))
620 (if (eq? op NotImplemented
)
624 (define-syntax-rule (get-context context code
)
625 (let ((context (if (eq? context None
)
630 (define-syntax-rule (un-special self context
)
631 (if ((ref self
'_is_special
))
632 (let ((ans ((ref self
'_check_nans
) #:context context
)))
638 (define-syntax-rule (bin-special o1 o2 context
)
639 (if (or (ref o1
'_is_special
)
640 (ref o2
'_is_special
))
641 (or (un-special o1 context
) (un-special o2 context
))))
643 (define-syntax-rule (add-special self other context
)
644 (or (bin-special self other context
)
645 (if ((ref self
'_isinfinity
))
646 ;; If both INF, same sign =>
647 ;; same as both, opposite => error.
648 (if (and (not (= (ref self
'_sign
) (ref other
'_sign
)))
649 ((ref other
'_isinfinity
)))
650 ((cx-error context
) InvalidOperation
"-INF + INF")
652 (if ((ref other
'_isinfinity
))
653 (Decimal other
) ; Can't both be infinity here
656 (define-syntax-rule (mul-special self other context resultsign
)
657 (if (or (ref self
'_is_special
) (ref other
'_is_special
))
659 ((bin-special self other context
) it it
)
661 ((if ((ref self
'_isinfinity
))
662 (if (not (bool other
))
663 ((cx-error context
) InvalidOperation
"(+-)INF * 0")
664 (pylist-ref _SignedInfinity resultsign
))
667 (if ((ref other
'_isinfinity
))
668 (if (not (bool self
))
669 ((cx-error context
) InvalidOperation
"(+-)INF * 0")
670 (pylist-ref _SignedInfinity resultsign
))
674 (define-syntax-rule (div-special self other context sign
)
675 (if (or (ref self
'_is_special
) (ref other
'_is_special
))
677 ((bin-special self other context
) it it
)
679 ((and ((ref self
'_isinfinity
)) ((ref other
'_isinfinity
))) it
680 ((cx-error context
) InvalidOperation
"(+-)INF/(+-)INF"))
682 (((ref self
'_isinfinity
)) it
683 (pylist-ref _SignedInfinity sign
))
685 (((ref other
'_isinfinity
)) it
686 ((cx-error context
) Clamped
"Division by infinity")
687 (_dec_from_triple sign
"0" (cx-etiny context
))))))
690 (define-python-class Decimal
(object)
691 "Floating point class for decimal arithmetic."
694 ;; Generally, the value of the Decimal instance is given by
695 ;; (-1)**_sign * _int * 10**_exp
696 ;; Special values are signified by _is_special == True
700 ((self sign coefficient exponent special
)
701 (set self
'_sign sign
)
702 (set self
'_int coefficient
)
703 (set self
'_exp exponent
)
704 (set self
'_is_special special
))
709 (_mk self __init__ a
))
711 (_mk self __init__ a b
))))
713 (define from_float
(pk 1
716 "Converts a float to a decimal number, exactly.
718 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
719 Since 0.1 is not exactly representable in binary floating point, the
720 value is stored as the nearest representable value which is
721 0x1.999999999999ap-4. The exact equivalent of the value in decimal
722 is 0.1000000000000000055511151231257827021181583404541015625.
724 >>> Decimal.from_float(0.1)
725 Decimal('0.1000000000000000055511151231257827021181583404541015625')
726 >>> Decimal.from_float(float('nan'))
728 >>> Decimal.from_float(float('inf'))
730 >>> Decimal.from_float(-float('inf'))
732 >>> Decimal.from_float(-0.0)
737 (if (< x
0) (set! x
(- x
)))
739 (let lp
((l (string->list
(format #f
"~e" x
))) (r1 '()))
742 (let lp
((l l
) (r2 '()))
745 (let* ((n (length r1
))
746 (m (list->string
(append (reverse r1
) (reverse r2
))))
747 (e (+ (- n
1) (string->number
(list->string l
)))))
750 (lp l
(cons x r2
))))))
753 (lp l
(cons x r1
))))))
757 ((isinstance f int
) ; handle integer inputs
759 ((not (isinstance f float
))
760 (raise (TypeError "argument must be int or float.")))
761 ((or (inf? f
) (nan? f
))
765 ((eq? f
(- (inf))) ""))))
767 (let* ((sign (if (>= f
0) 0 1))
771 (res (_dec_from_triple sign m e
)))
772 (if (eq? cls Decimal
)
778 "Returns whether the number is not actually one.
784 (if (ref self
'_is_special
)
785 (let ((exp (ref self
'_exp
)))
792 (define _isinfinity
(pk 1 1
794 "Returns whether the number is infinite
796 0 if finite or not a number
800 (if (eq?
(ref self
'_exp
) 'F
)
801 (if (eq?
(ref self
'_sign
) 1)
807 (lam (self (= other None
) (= context None
))
808 "Returns whether the number is not actually one.
810 if self, other are sNaN, signal
811 if self, other are NaN return nan
814 Done before operations.
817 (let ((self_is_nan ((ref self
'_isnan
)))
821 ((ref other
'_isnan
)))))
823 (if (or self_is_nan other_is_nan
)
824 (let ((context (if (eq? context None
)
829 ((cx-error context
) InvalidOperation
"sNaN" self
))
830 ((eq? other_is_nan
2)
831 ((cx-error context
) InvalidOperation
"sNaN" other
))
833 ((ref self
'_fix_nan
) context
))
835 ((ref other
'_fix_nan
) context
))))
839 (define _compare_check_nans
840 (lambda (self other context
)
841 "Version of _check_nans used for the signaling comparisons
842 compare_signal, __le__, __lt__, __ge__, __gt__.
844 Signal InvalidOperation if either self or other is a (quiet
845 or signaling) NaN. Signaling NaNs take precedence over quiet
848 Return 0 if neither operand is a NaN.
851 (let ((context (if (eq? context None
)
855 (if (or (ref self
'_is_special
)
856 (ref other
'_is_special
))
858 (((ref self
'is_snan
))
861 "comparison involving sNaN" self
))
863 (((ref other
'is_snan
))
866 "comparison involving sNaN" other
))
868 (((ref self
'is_qnan
))
871 "comparison involving NaN" self
))
873 (((ref other
'is_qnan
))
876 "comparison involving NaN" other
))
881 (define __bool__
(pk 1 2
883 "Return True if self is nonzero; otherwise return False.
885 NaNs and infinities are considered nonzero.
887 (or (ref self
'_is_special
) (not (equal?
(ref self
'_int
) "0"))))))
891 "Compare the two non-NaN decimal instances self and other.
893 Returns -1 if self < other, 0 if self == other and 1
894 if self > other. This routine is for internal use only."
896 (let ((self_sign (ref self
'_sign
))
897 (other_sign (ref other
'_sign
)))
899 ((or (ref self
'_is_special
) (ref other
'_is_special
))
900 (let ((self_inf ((ref self
'_isinfinity
)))
901 (other_inf ((ref other
'_isinfinity
))))
903 ((eq? self_inf other_inf
) 0)
904 ((< self_inf other_inf
) -
1)
907 ;; check for zeros; Decimal('0') == Decimal('-0')
909 (if (not (bool other
))
911 (let ((s (ref other
'_sign
)))
916 (let ((s (ref self
'_sign
)))
921 ((< other_sign self_sign
)
923 ((< self_sign other_sign
)
927 (let ((self_adjusted ((ref self
'adjusted
)))
928 (other_adjusted ((ref other
'adjusted
)))
929 (self_exp (ref self
'_exp
))
930 (other_exp (ref other
'_exp
)))
932 ((= self_adjusted other_adjusted
)
933 (let ((self_padded (+ (ref self
'_int
)
934 (* "0" (- self_exp other_exp
))))
935 (other_padded (+ (ref other
'_int
)
936 (* "0" (- other_exp self_exp
)))))
938 ((equal? self_padded other_padded
)
940 ((< self_padded other_padded
)
948 ((> self_adjusted other_adjusted
)
957 ;; Note: The Decimal standard doesn't cover rich comparisons for
958 ;; Decimals. In particular, the specification is silent on the
959 ;; subject of what should happen for a comparison involving a NaN.
960 ;; We take the following approach:
962 ;; == comparisons involving a quiet NaN always return False
963 ;; != comparisons involving a quiet NaN always return True
964 ;; == or != comparisons involving a signaling NaN signal
965 ;; InvalidOperation, and return False or True as above if the
966 ;; InvalidOperation is not trapped.
967 ;; <, >, <= and >= comparisons involving a (quiet or signaling)
968 ;; NaN signal InvalidOperation, and return False if the
969 ;; InvalidOperation is not trapped.
971 ;; This behavior is designed to conform as closely as possible to
972 ;; that specified by IEEE 754.
975 (lam (self other
(= context None
))
976 (let* ((so (_convert_for_comparison self other
#:equality_op
#t
))
981 ((eq? other NotImplemented
)
983 ((bool ((ref self
'_check_nans
) other context
))
985 (else (= ((ref self
'_cmp
) other
) 0))))))
989 (lam (self other
(= context None
))
990 (let* ((so (_convert_for_comparison self other
#:equality_op
#t
))
995 ((eq? other NotImplemented
)
997 ((bool ((ref self
'_compare_check_nans
) other context
))
999 (else (< ((ref self
'_cmp
) other
) 0))))))))
1001 (define __lt__
(lambda x
(apply (_xlt < ) x
)))
1002 (define __le__
(lambda x
(apply (_xlt <= ) x
)))
1003 (define __gt__
(lambda x
(apply (_xlt > ) x
)))
1004 (define __ge__
(lambda x
(apply (_xlt >= ) x
)))
1006 (define compare
(pk 1 4
1007 (lam (self other
(= context None
))
1008 "Compare self to other. Return a decimal value:
1010 a or b is a NaN ==> Decimal('NaN')
1011 a < b ==> Decimal('-1')
1012 a == b ==> Decimal('0')
1013 a > b ==> Decimal('1')
1015 (let ((other (_convert_other other
#:raiseit
#t
)))
1016 ;; Compare(NaN, NaN) = NaN
1017 (if (or (ref self
'_is_special
)
1019 (ref other
'_is_special
)))
1020 (aif it
((ref self
'_check_nans
) other context
)
1022 (Decimal ((ref self
'_cmp
) other
))))))))
1026 "x.__hash__() <==> hash(x)"
1028 ;; In order to make sure that the hash of a Decimal instance
1029 ;; agrees with the hash of a numerically equal integer, float
1030 ;; or Fraction, we follow the rules for numeric hashes outlined
1031 ;; in the documentation. (See library docs, 'Built-in Types').
1033 ((ref self
'_is_special
)
1035 (((ref self
'is_snan
))
1036 (raise (TypeError "Cannot hash a signaling NaN value.")))
1037 (((ref self
'is_snan
))
1038 (hash (nan) pyhash-N
))
1039 ((= 1 (ref self
'_sign
))
1040 (hash (- (inf)) pyhash-N
))
1042 (hash (inf) pyhash-N
))))
1045 (let* ((exp (ref self
'_exp
))
1048 (pow 10 exp pyhash-N
)
1049 (pow _PyHASH_10INV
(- exp
) pyhash-N
)))
1052 (modulo (* (int (ref self
'_int
)) exp_hash
)
1056 (if (>= self
0) hash_
(- hash_
))))
1057 (if (= ans -
1) -
2 ans
))))))
1061 "Represents the number as a triple tuple.
1063 To show the internals exactly as they are.
1065 (DecimalTuple (ref self
'_sign
)
1066 (tuple (map int
(ref self
'_int
)))
1069 (define as_integer_ratio
1071 "Express a finite Decimal instance in the form n / d.
1073 Returns a pair (n, d) of integers. When called on an infinity
1074 or NaN, raises OverflowError or ValueError respectively.
1076 >>> Decimal('3.14').as_integer_ratio()
1078 >>> Decimal('-123e5').as_integer_ratio()
1080 >>> Decimal('0.00').as_integer_ratio()
1083 (if (ref self
'_is_special
)
1084 (if ((ref self
'is_nan
))
1086 "cannot convert NaN to integer ratio"))
1087 (raise (OverflowError
1088 "cannot convert Infinity to integer ratio"))))
1090 (if (not (bool self
))
1092 (let* ((s (ref self
'_sign
))
1093 (n (int (ref self
'_int
)))
1094 (e (ref self
'_exp
))
1098 (/ 1 (expt 10 (- expt
)))))))
1099 (values (numerator x
)
1100 (denominator x
))))))
1102 (define __repr__
(pk 1 5
1104 "Represents the number as an instance of Decimal."
1105 ;# Invariant: eval(repr(d)) == d
1106 (format #f
"Decimal('~a')" (str self
)))))
1109 (lam (self (= eng
#f
) (= context None
))
1110 "Return string representation of the number in scientific notation.
1112 Captures all of the information in the underlying representation.
1114 (let* ((sign (if (= (ref self
'_sign
) 0) "" "-"))
1115 (exp (ref self
'_exp
))
1116 (i (ref self
'_int
))
1117 (leftdigits (+ exp
(len i
)))
1124 ((ref self
'_is_special
)
1126 ((eq?
(ref self
'_exp
) 'F
)
1127 (+ sign
"Infinity"))
1128 ((eq?
(ref self
'_exp
) 'n
)
1129 (+ sign
"NaN" (ref self
'_int
)))
1130 (else ; self._exp == 'N'
1131 (+ sign
"sNaN" (ref self
'_int
)))))
1133 ;; dotplace is number of digits of self._int to the left of the
1134 ;; decimal point in the mantissa of the output string (that is,
1135 ;; after adjusting the exponent)
1137 ((and (<= exp
0) (> leftdigits -
6))
1138 ;; no exponent required
1139 (set! dotplace leftdigits
))
1142 ;; usual scientific notation: 1 digit on left of the point
1146 ;; engineering notation, zero
1147 (set! dotplace
(- (modulo (+ leftdigits
1) 3) 1)))
1149 ;; engineering notation, nonzero
1150 (set! dotplace
(- (modulo (+ leftdigits
1) 3) 1))))
1155 (set! fracpart
(+ "." + (* "0" (- dotplace
)) + i
)))
1156 ((>= dotplace
(len i
))
1157 (set! intpart
(+ i
(* "0" (- dotplace
(len i
)))))
1160 (set! intpart
(pylist-slice i None dotplace None
))
1161 (set! fracpart
(+ '.
' (pylist-slice i dotplace None None
)))))
1165 ((= leftdigits dotplace
)
1168 (let ((context (if (eq? context None
)
1172 (+ (pylist-ref '("e" "E") (cx-capitals context
))
1173 (format #f
"~@d" (- leftdigits dotplace
)))))))
1174 (+ sign intpart fracpart exp
))))))
1176 (define to_eng_string
1177 (lam (self (= context None
))
1178 "Convert to a string, using engineering notation if an exponent is needed.
1179 Engineering notation has an exponent which is a multiple of 3. This
1180 can leave up to 3 digits to the left of the decimal place and may
1181 require the addition of either one or two trailing zeros.
1183 ((ref self
'__str__
) #:eng
#t
#:contect context
)))
1186 (lam (self (= context None
))
1187 "Returns a copy with the sign switched.
1189 Rounds, if it has reason.
1192 ((un-special self context
) it it
)
1193 (let* ((context (if (eq? context None
)
1196 (ans (if (and (not (bool self
))
1197 (not (eq?
(cx-rounding context
)
1199 ;; -Decimal('0') is Decimal('0'),
1200 ;; not Decimal('-0'), except
1201 ;; in ROUND_FLOOR rounding mode.
1202 ((ref self
'copy_abs
))
1203 ((ref self
'copy_negate
)))))
1205 ((ref ans
'_fix
) context
)))))
1207 (define __pos__
(pk 1 6
1208 (lam (self (= context None
))
1209 "Returns a copy, unless it is a sNaN.
1211 Rounds the number (if more than precision digits)
1214 ((un-special self context
) it it
)
1216 (let* ((context (if (eq? context None
)
1219 (ans (if (and (not (bool self
))
1220 (not (eq?
(cx-rounding context
)
1222 ;; -Decimal('0') is Decimal('0'),
1223 ;; not Decimal('-0'), except
1224 ;; in ROUND_FLOOR rounding mode.
1225 ((ref self
'copy_abs
))
1228 ((ref ans
'_fix
) context
))))))
1231 (lam (self (= round
#t
) (= context None
))
1232 "Returns the absolute value of self.
1234 If the keyword argument 'round' is false, do not round. The
1235 expression self.__abs__(round=False) is equivalent to
1239 ((not (bool round
)) it
1240 ((ref self
'copy_abs
)))
1242 ((un-special self context
) it it
)
1244 (if (= (ref self
'_sign
) 1)
1245 ((ref self
'__neg__
) #:context context
)
1246 ((ref self
'__pos__
) #:context context
)))))
1250 (lam (self other
(= context None
))
1251 "Returns self + other.
1253 -INF + INF (or the reverse) cause InvalidOperation errors.
1256 ((norm-op self other
) it it
)
1258 (let (get-context context
))
1260 ((add-special self other context
) it it
)
1262 (let* ((negativezero 0)
1263 (self_sign (ref self
'_sign
))
1264 (other_sign (ref other
'_sign
))
1265 (self_exp (ref self
'_sign
))
1266 (other_exp (ref other
'_sign
))
1267 (prec (cx-prec context
))
1268 (exp (min self_exp other_exp
))
1272 (if (and (eq?
(cx-rounding context
) ROUND_FLOOR
)
1273 (not (= self_sign other_sign
)))
1274 ;; If the answer is 0, the sign should be negative,
1276 (set! negativezero
1)))
1278 ((if (and (not (bool self
)) (not (bool other
)))
1280 (set! sign
(min self_sign other_sign
))
1281 (if (= negativezero
1)
1283 (set! ans
(_dec_from_triple sign
"0" exp
))
1284 (set! ans
((ref ans
'_fix
) context
))
1288 ((if (not (bool self
))
1290 (set! exp
(max exp
(- other_exp prec
1)))
1291 (set! ans
((ref other
'_rescale
) exp
1292 (cx-rounding context
)))
1293 (set! ans
((ref ans
'_fix
) context
))
1297 ((if (not (bool other
))
1299 (set! exp
(max exp
(- self_exp prec
1)))
1300 (set! ans
((ref self
'_rescale
) exp
1301 (cx-rounding context
)))
1302 (set! ans
((ref ans
'_fix
) context
))
1307 (let* ((op1 (_WorkRep self
))
1308 (op2 (_WorkRep other
))
1309 (ab (_normalize op1 op2 prec
))
1312 (result (_WorkRep))))
1315 ((not (= (ref op1
'sign
) (ref op2
'sign
)))
1316 ;; Equal and opposite
1319 (set! ans
(_dec_from_triple negativezero
"0" exp
))
1320 (set! ans
((ref ans
'_fix
) context
))
1329 (if (= (ref op1
'sign
) 1)
1330 (let ((t (ref op1
'sign
)))
1331 (set result
'sign
1)
1332 (set op1
'sign
(ref op2
'sign
))
1334 (set result
'sign
0))
1336 ((= (ref op1
'sign
) 1)
1337 (set result
'sign
1)
1341 (set result
'sign
0)
1345 (if (= (ref op2
'sign
) 0)
1346 (set result
'int
(+ (ref op1
'int
) (ref op2
'int
)))
1347 (set result
'int
(- (ref op1
'int
) (ref op2
'int
))))
1349 (set result
'exp
(ref op1
'exp
))
1350 (set! ans
(Decimal result
))
1351 ((ref ans
'_fix
) context
)))))
1353 (define __radd__ __add__
)
1356 (lam (self other
(= context None
))
1357 "Return self - other"
1359 ((norm-op self other
) it it
)
1360 ((bin-special self other context
) it it
)
1361 ((ref self
'__add__
)
1362 ((ref other
'copy_negate
)) #:context context
))))
1365 (lam (self other
(= context None
))
1366 "Return other - self"
1368 ((norm-op self other
) it it
)
1369 ((ref 'other
'__sub__
) self
#:context context
))))
1372 (lam (self other
(= context None
))
1373 "Return self * other.
1375 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1378 ((norm-op self other
) it it
)
1379 (let (get-context context
))
1381 (let ((resultsign (logxor (ref self
'_sign
)
1382 (ref other
'_sign
)))))
1384 ((mul-special self other context resultsign
) it it
)
1386 (let ((resultexp (+ (ref self
'_exp
) (ref other
'_exp
)))))
1388 ;; Special case for multiplying by zero
1389 ((or (not (bool self
)) (not (bool other
))) it
1390 (let ((ans (_dec_from_triple resultsign
"0" resultexp
)))
1391 ((ref ans
'_fix
) context
)))
1393 ;; Special case for multiplying by power of 10
1394 ((equal?
(ref self
'_int
) "1") it
1395 (let ((ans (_dec_from_triple resultsign
(ref other
'_int
) resultexp
)))
1396 ((ref ans
'_fix
) context
)))
1398 ((equal?
(ref other
'_int
) "1") it
1399 (let ((ans (_dec_from_triple resultsign
(ref self
'_int
) resultexp
)))
1400 ((ref ans
'_fix
) context
)))
1402 (let* ((op1 (_WorkRep self
))
1403 (op2 (_WorkRep other
))
1404 (ans (_dec_from_triple resultsign
1405 (str (* (ref op1
'int
) (ref op2
'int
)))
1407 ((ref ans
'_fix
) context
)))))
1409 (define __rmul__ __mul__
)
1412 (lam (self other
(= context None
))
1413 "Return self / other."
1415 ((norm-op self other
) it it
)
1416 (let (get-context context
))
1418 (let ((sign (logxor (ref self
'_sign
)
1419 (ref other
'_sign
)))))
1421 ((div-special self other context sign
) it it
)
1423 ;; Special cases for zeroes
1424 ((if (not (bool other
))
1425 (if (not (bool self
))
1426 ((cx-error context
) DivisionUndefined
"0 / 0")
1427 ((cx-error context
) DivisionByZero
"x / 0" sign
))
1432 (prec (cx-prec context
))
1433 (nself (len (ref self
'_int
)))
1434 (nother (len (ref other
'_int
))))
1435 (if (not (bool self
))
1437 (set! exp
(- (ref self
'_exp
) (ref other
'_exp
)))
1439 ;; OK, so neither = 0, INF or NaN
1440 (let ((shift (+ nother
(- nself
) prec
1))
1441 (op1 (_WorkRep self
))
1442 (op2 (_WorkRep other
)))
1443 (set! exp
(- (ref self
'_exp
) (ref other
'_exp
) shift
))
1447 (divmod (* (ref op1
'int
) (expt 10 shift
))
1449 (divmod (ref op1
'int
)
1450 (* (ref op2
'int
) (expt 10 shift
)))))
1451 (lambda (coeff- remainder
)
1453 (if (not (= remainder
0))
1454 ;; result is not exact adjust to ensure
1456 (if (= (modulo coeff-
5) 0)
1459 (let ((ideal_exp (- (ref self
'_exp
)
1460 (ref other
'_exp
))))
1461 (let lp
((coeff- coeff-
) (exp- exp
))
1462 (if (and (< exp- ideal_exp
)
1463 (= (modulo coeff
10) 0))
1464 (lp (/ coeff
10) (+ exp-
1))
1470 (let ((ans (_dec_from_triple sign
(str coeff
) exp
)))
1471 ((ref ans
'_fix
) context
))))))
1474 (lambda (self other context
)
1475 "Return (self // other, self % other), to context.prec precision.
1477 Assumes that neither self nor other is a NaN, that self is not
1478 infinite and that other is nonzero.
1483 (logxor (ref self
'_sign
)
1484 (ref other
'_sign
)))
1486 (if ((ref other
'_isinfinity
))
1488 (min (ref self
'exp
) (ref other
'_exp
))))
1490 (- ((ref self
'adjusted
)) ((ref other
'adjusted
)))))))
1492 ((or (not (bool self
))
1493 ((ref other
'_isinfinity
))
1495 (list (_dec_from_triple sign
"0" 0)
1496 ((ref self
'_rescale
) ideal_exp
(cx-rounding context
))))
1498 ((if (<= expdiff
(cx-prec context
))
1499 (let ((op1 (_WorkRep self
))
1500 (op2 (_WorkRep other
)))
1501 (if (>= (ref op1
'exp
) (ref op2
'exp
))
1502 (set op1
'int
(* (ref op1
'int
)
1503 (expt 10 (- (ref op1
'exp
)
1505 (set op2
'int
(* (ref op2
'int
)
1506 (expt 10 (- (ref op2
'exp
)
1508 (call-with-values (lambda () (divmod (ref op1
'int
)
1511 (if (< q
(expt 10 (cx-prec context
)))
1512 (list (_dec_from_triple sign
(str q
) 0)
1513 (_dec_from_triple (ref self
'_sign
)
1519 ;; Here the quotient is too large to be representable
1520 (let ((ans ((cx-raise context
) DivisionImpossible
1521 "quotient too large in //, % or divmod")))
1522 (list ans ans
)))))))
1524 (define __rtruediv__
1525 (lam (self other
(= context None
))
1526 "Swaps self/other and returns __truediv__."
1528 ((norm-op self other
) it it
)
1529 ((ref other
'__truediv__
) self
#:context context
))))
1532 (lam (self other
(= context None
))
1534 Return (self // other, self % other)
1538 ((norm-op self other
) it it
)
1540 (let (get-context context
))
1542 ((add-special self other context
) it it
)
1544 (((ref self
'_check_nans
) other context
) it
1548 (logxor (ref self
'_sign
)
1549 (ref other
'_sign
))))))
1551 (((ref self
'_isinfinity
)) it
1552 (if ((ref other
'_isinfinity
))
1553 (let ((ans ((cx-error context
) InvalidOperation
1554 "divmod(INF, INF)")))
1556 (list (list-ref _SignedInfinity sign
)
1557 ((cx-raise context
) InvalidOperation
"INF % x"))))
1559 ((not (bool other
)) it
1560 (if (not (bool self
))
1561 (let ((ans ((cx-error context
) DivisionUndefined
1564 (list ((cx-error context
) DivisionByZero
"x // 0" sign
)
1565 ((cx-error context
) InvalidOperation
"x % 0"))))
1567 (call-with-values (lambda () ((ref self
'_divide
) other context
))
1568 (lambda (quotient remainder
)
1569 (let ((remainder ((ref remainder
'_fix
) context
)))
1570 (list quotient remainder
))))))))
1573 (lam (self other
(= context None
))
1574 "Swaps self/other and returns __divmod__."
1576 ((norm-op self other
) it it
)
1577 ((ref other
'__divmod__
) self
#:context context
))))
1580 (lam (self other
(= context None
))
1585 ((norm-op self other
) it it
)
1587 (let (get-context context
))
1589 ((bin-special self other context
) it it
)
1591 (((ref self
'_isinfinity
)) it
1592 ((cx-error context
) InvalidOperation
"INF % x"))
1594 ((not (bool other
)) it
1596 ((cx-error context
) InvalidOperation
"x % 0")
1597 ((cx-error context
) DivisionUndefined
"0 % 0")))
1599 (let* ((remainder ((ref self
'_divide
) other context
)))
1600 ((ref remainder
'_fix
) context
)))))
1603 (lam (self other
(= context None
))
1604 "Swaps self/other and returns __mod__."
1606 ((norm-op self other
) it it
)
1607 ((ref other
'__mod__
) self
#:context context
))))
1609 (define remainder_near
(pk 2
1610 (lam (self other
(= context None
))
1612 Remainder nearest to 0- abs(remainder-near) <= other/2
1615 ((norm-op self other
) it it
)
1617 (let (get-context context
))
1619 ((bin-special self other context
) it it
)
1621 ;; self == +/-infinity -> InvalidOperation
1622 (((ref self
'_isinfinity
)) it
1623 ((cx-error context
) InvalidOperation
"remainder_near(infinity, x)"))
1625 ;; other == 0 -> either InvalidOperation or DivisionUndefined
1626 ((not (bool other
)) it
1627 (if (not (bool self
))
1628 ((cx-error context
) InvalidOperation
"remainder_near(x, 0)")
1629 ((cx-error context
) DivisionUndefined
"remainder_near(0, 0)")))
1631 ;; other = +/-infinity -> remainder = self
1632 (((ref other
'_isinfinity
)) it
1633 (let ((ans (Decimal self
)))
1634 ((ref ans
'_fix
) context
)))
1636 ;; self = 0 -> remainder = self, with ideal exponent
1637 (let (let ((ideal_exponent (min (ref self
'_exp
) (ref other
'_exp
))))))
1639 ((not (bool self
)) it
1640 (let ((ans (_dec_from_triple (ref self
'_sign
) "0" ideal_exponent
)))
1641 ((ref ans
'_fix
) context
)))
1643 ;; catch most cases of large or small quotient
1645 (- ((ref self
'adjusted
)) ((ref other
'adjusted
)))))))
1647 ((>= expdiff
(+ (cx-prec context
) 1)) it
1648 ;; expdiff >= prec+1 => abs(self/other) > 10**prec
1649 ((cx-error context
) DivisionImpossible
))
1652 ;; expdiff <= -2 => abs(self/other) < 0.1
1653 (let ((ans ((ref self
'_rescale
)
1654 ideal_exponent
(cx-rounding context
))))
1655 ((ref ans
'_fix
) context
)))
1657 (let ((op1 (_WorkRep self
))
1658 (op2 (_WorkRep other
)))
1660 ;; adjust both arguments to have the same exponent, then divide
1661 (if (>= (ref op1
'exp
) (ref op2
'exp
))
1662 (set op1
'int
(* (ref op1
'int
)
1663 (expt 10 (- (ref op1
'exp
) (ref op2
'exp
)))))
1664 (set op2
'int
(* (ref op2
'int
)
1665 (expt 10 (- (ref op2
'exp
) (ref op1
'exp
))))))
1667 (call-with-values (lambda () (divmod (ref op1
'int
) (ref op2
'int
)))
1670 ;; remainder is r*10**ideal_exponent; other is +/-op2.int *
1671 ;; 10**ideal_exponent. Apply correction to ensure that
1672 ;; abs(remainder) <= abs(other)/2
1673 (if (> (+ (* 2 r
) + (logand q
1)) (ref op2
'int
))
1674 (set! r
(- r
(ref op2
'int
)))
1677 (if (>= q
(expt 10 (cx-prec context
)))
1678 ((cx-error context
) DivisionImpossible
)
1679 (let ((sign (ref self
'_sign
)))
1681 (set! sign
(- 1 sign
))
1683 (let ((ans (_dec_from_triple sign
(str r
) ideal_exponent
)))
1684 ((ref ans
'_fix
) context
)))))))))))
1686 (define __floordiv__
1687 (lam (self other
(= context None
))
1690 ((norm-op self other
) it it
)
1692 (let (get-context context
))
1694 ((bin-special self other context
) it it
)
1696 (((ref self
'_isinfinity
)) it
1697 (if ((ref other
'_isinfinity
))
1698 ((cx-error context
) InvalidOperation
"INF // INF")
1699 (pylist-ref _SignedInfinity
(logxor (ref self
'_sign
)
1700 (ref other
'_sign
)))))
1702 ((not (bool other
)) it
1704 ((cx-error context
) DivisionByZero
"x // 0"
1705 (logxor (ref self
'_sign
) (ref other
'_sign
)))
1706 ((cx-error context
) DivisionUndefined
"0 // 0")))
1708 ((ref self
'_divide
) other context
))))
1710 (define __rfloordiv__
1711 (lam (self other
(= context None
))
1712 "Swaps self/other and returns __floordiv__."
1714 ((norm-op self other
) it it
)
1715 ((ref other
'__floordiv__
) self
#:context context
))))
1719 "Float representation."
1720 (if ((ref self
'_isnan
))
1721 (if ((ref self
'is_snan
))
1722 (raise (ValueError "Cannot convert signaling NaN to float"))
1723 (if (= (ref self
'_sign
))
1726 (if ((ref self
'_isspecial
))
1727 (if (= (ref self
'_sign
))
1730 (float (str self
))))))
1734 "Converts self to an int, truncating if necessary."
1735 (if ((ref self
'_isnan
))
1736 (raise (ValueError "Cannot convert NaN to integer"))
1737 (if ((ref self
'_isspecial
))
1738 (raise (OverflowError "Cannot convert infinity to integer"))
1739 (let ((s (if (= (ref self
'_sign
) 1) -
1 1)))
1740 (if (>= (ref self
'_exp
) 0)
1741 (* s
(int (ref self
'_int
)) (expt 10 (ref self
'_exp
)))
1742 (* s
(int (or (bool (pylist-slice (ref self
'_int
)
1743 None
(ref self
'_exp
) None
))
1746 (define __trunc__ __int__
)
1749 (property (lambda (self) self
)))
1757 (lambda (self) self
))
1761 (complex (float self
))))
1764 (lambda (self context
)
1765 "Decapitate the payload of a NaN to fit the context"
1766 (let ((payload (ref self
'_int
))
1768 ;; maximum length of payload is precision if clamp=0,
1769 ;; precision-1 if clamp=1.
1771 (- (ref context
'prec
)
1772 (ref context
'clamp
))))
1774 (if (> (len payload
) max_payload_len
)
1775 (let ((payload (py-lstrip
1776 (pylist-slice payload
1777 (- (len payload
) max_payload_len
)
1779 (_dec_from_triple (ref self
'_sign
) payload
(ref self
'_exp
)
1784 (lambda (self context
)
1785 "Round if it is necessary to keep self within prec precision.
1787 Rounds and fixes the exponent. Does not raise on a sNaN.
1790 self - Decimal instance
1791 context - context used.
1795 (((ref self
'_is_special
)) it
1796 (if ((ref self
'_isnan
))
1797 ;; decapitate payload if necessary
1798 ((ref self
'_fix_nan
) context
)
1800 ;; self is +/-Infinity; return unaltered
1803 ;; if self is zero then exponent should be between Etiny and
1804 ;; Emax if clamp==0, and between Etiny and Etop if clamp==1.
1805 (let ((Etiny (cx-etiny context
))
1806 (Etop (cx-etop context
))))
1808 ((not (bool self
)) it
1809 (let* ((exp_max (if (= (cx-clamp context
) 0)
1812 (new_exp (min (max (ref self
'_exp
) Etiny
) exp_max
)))
1813 (if (not (= new_exp
(ref self
'_exp
)))
1815 ((cx-error context
) Clamped
)
1816 (_dec_from_triple (ref self
'_sign
) "0" new_exp
))
1819 ;; exp_min is the smallest allowable exponent of the result,
1820 ;; equal to max(self.adjusted()-context.prec+1, Etiny)
1821 (let ((exp_min (+ (len (ref self
'_int
))
1823 (- (cx-prec context
))))))
1824 ((> exp_min Etop
) it
1825 ;; overflow: exp_min > Etop iff self.adjusted() > Emax
1826 (let ((ans ((cx-error context
) Overflow
"above Emax"
1827 (ref self
'_sign
))))
1828 ((cx-error context
) Inexact
)
1829 ((cx-error context
) Rounded
)
1832 (let* ((self_is_subnormal (< exp_min Etiny
))
1833 (exp_min (if self_is_subnormal Etiny exp_min
))))
1835 ;; round if self has too many digits
1836 ((< (ref self
'_exp
) exp_min
) it
1837 (let ((digits (+ (len (ref self
'_int
))
1841 (set! self
(_dec_from_triple (ref self
'_sign
)
1846 (rounding_method (pylist-ref
1847 (ref self
'_pick_rounding_function
)
1848 (cx-rounding context
)))
1849 (changed (rounding_method self digits
))
1850 (coeff (or (bool (pylist-slice (ref self
'_int
)
1851 None digits None
)) "0")))
1854 (set! coeff
(str (+ (int coeff
) 1)))
1855 (if (> (len coeff
) (cx-prec context
))
1857 (set! coeff
(pylist-slice coeff None -
1 None
))
1858 (set! exp_min
(+ exp_min
1))))))
1860 ;; check whether the rounding pushed the exponent out of range
1861 (if (> exp_min Etop
)
1863 ((cx-error context
) Overflow
"above Emax"
1865 (set! ans
(_dec_from_triple (ref self
'_sign
) coeff exp_min
)))
1867 ;; raise the appropriate signals, taking care to respect
1868 ;; the precedence described in the specification
1869 (if (and changed self_is_subnormal
)
1870 ((cx-error context
) Underflow
))
1871 (if self_is_subnormal
1872 ((cx-error context
) Subnormal
))
1874 ((cx-error context
) Inexact
))
1876 ((cx-error context
) Rounded
)
1878 (if (not (bool ans
))
1879 ;; raise Clamped on underflow to 0
1880 ((cx-error context
) Clamped
))
1884 (if self_is_subnormal
1885 ((cx-error context
) Subnormal
))
1888 ;; fold down if clamp == 1 and self has too few digits
1889 (if (and (= (cx-clamp context
) 1) (> (ref self
'_exp
) Etop
))
1891 ((cx-error context
) Clamped
)
1892 (let ((self_padded (+ (ref self
'_int
)
1894 (- (ref self
'_exp
) Etop
)))))
1895 (_dec_from_triple (ref self
'_sign
) self_padded Etop
)))
1897 ;; here self was representable to begin with; return unchanged
1902 ;; for each of the rounding functions below:
1903 ;; self is a finite, nonzero Decimal
1904 ;; prec is an integer satisfying 0 <= prec < len(self._int)
1906 ;; each function returns either -1, 0, or 1, as follows:
1907 ;; 1 indicates that self should be rounded up (away from zero)
1908 ;; 0 indicates that self should be truncated, and that all the
1909 ;; digits to be truncated are zeros (so the value is unchanged)
1910 ;; -1 indicates that there are nonzero digits to be truncated
1914 "Also known as round-towards-0, truncate."
1915 (if (_all_zeros (ref self
'_int
) prec
)
1921 "Rounds away from 0."
1922 (- (_round_down self prec
))))
1924 (define _round_half_up
1926 "Rounds 5 up (away from 0)"
1928 ((in (pylist-ref (ref self
'_int
) prec
) "56789")
1930 ((_all_zeros (ref self
'_int
) prec
)
1934 (define _round_half_down
1937 (if (_exact_half (ref self
'_int
) prec
)
1939 (_round_half_up self prec
))))
1941 (define _round_half_even
1943 "Round 5 to even, rest to nearest."
1944 (if (and (_exact_half (ref self
'_int
) prec
)
1946 (in (pylist-ref (ref self
'_int
) (- prec
1)) "02468")))
1948 (_round_half_up self prec
)))
1950 (define _round_ceiling
1952 "Rounds up (not away from 0 if negative.)"
1953 (if (= (ref self
'_sign
) 1)
1954 (_round_down self prec
)
1955 (- (_round_down self prec
)))))
1957 (define _round_floor
1959 "Rounds down (not towards 0 if negative)"
1960 (if (= (ref self
'_sign
) 1)
1961 (- (_round_down self prec
))
1962 (_round_down self prec
))))
1966 "Round down unless digit prec-1 is 0 or 5."
1967 (if (and prec
(not (in (pylist-ref (ref self
'_int
) (- prec
1) "05"))))
1968 (_round_down self prec
)
1969 (- (_round_down self prec
)))))
1971 (define _pick_rounding_function
1972 (dict `((,ROUND_DOWN .
,_round_down
)
1973 (,ROUND_UP .
,_round_up
)
1974 (,ROUND_HALF_UP .
,_round_half_up
)
1975 (,ROUND_HALF_DOWN .
,_round_half_down
)
1976 (,ROUND_HALF_EVEN .
,_round_half_even
)
1977 (,ROUND_CEILING .
,_round_ceiling
)
1978 (,ROUND_FLOOR .
,_round_floor
)
1979 (,ROUND_05UP .
,_round_05up
))))
1982 (lam (self (= n None
))
1983 "Round self to the nearest integer, or to a given precision.
1985 If only one argument is supplied, round a finite Decimal
1986 instance self to the nearest integer. If self is infinite or
1987 a NaN then a Python exception is raised. If self is finite
1988 and lies exactly halfway between two integers then it is
1989 rounded to the integer with even last digit.
1991 >>> round(Decimal('123.456'))
1993 >>> round(Decimal('-456.789'))
1995 >>> round(Decimal('-3.0'))
1997 >>> round(Decimal('2.5'))
1999 >>> round(Decimal('3.5'))
2001 >>> round(Decimal('Inf'))
2002 Traceback (most recent call last):
2004 OverflowError: cannot round an infinity
2005 >>> round(Decimal('NaN'))
2006 Traceback (most recent call last):
2008 ValueError: cannot round a NaN
2010 If a second argument n is supplied, self is rounded to n
2011 decimal places using the rounding mode for the current
2014 For an integer n, round(self, -n) is exactly equivalent to
2015 self.quantize(Decimal('1En')).
2017 >>> round(Decimal('123.456'), 0)
2019 >>> round(Decimal('123.456'), 2)
2021 >>> round(Decimal('123.456'), -2)
2023 >>> round(Decimal('-Infinity'), 37)
2025 >>> round(Decimal('sNaN123'), 0)
2029 (if (not (eq? n None
))
2030 ;; two-argument form: use the equivalent quantize call
2031 (if (not (isinstance n int
))
2033 "Second argument to round should be integral"))
2034 (let ((exp (_dec_from_triple 0 "1" (- n
))))
2035 ((ref self
'quantize
) exp
)))
2037 ;; one-argument form§x
2038 (if (ref self
'_is_special
)
2039 (if ((ref self
'is_nan
))
2040 (raise (ValueError "cannot round a NaN"))
2041 (raise (OverflowError "cannot round an infinity")))
2042 (int ((ref self
'_rescale
) 0 ROUND_HALF_EVEN
))))))
2046 "Return the floor of self, as an integer.
2048 For a finite Decimal instance self, return the greatest
2049 integer n such that n <= self. If self is infinite or a NaN
2050 then a Python exception is raised.
2053 (if (ref self
'_is_special
)
2054 (if ((ref self
'is_nan
))
2055 (raise (ValueError "cannot round a NaN"))
2056 (raise (OverflowError "cannot round an infinity")))
2057 (int ((ref self
'_rescale
) 0 ROUND_FLOOR
)))))
2061 """Return the ceiling of self, as an integer.
2063 For a finite Decimal instance self, return the least integer n
2064 such that n >= self. If self is infinite or a NaN then a
2065 Python exception is raised.
2068 (if (ref self
'_is_special
)
2069 (if ((ref self
'is_nan
))
2070 (raise (ValueError "cannot round a NaN"))
2071 (raise (OverflowError "cannot round an infinity")))
2072 (int ((ref self
'_rescale
) 0 ROUND_CEILING
)))))
2075 (lam (self other third
(= context None
))
2076 "Fused multiply-add.
2078 Returns self*other+third with no rounding of the intermediate
2081 self and other are multiplied together, with no rounding of
2082 the result. The third operand is then added to the result,
2083 and a single final rounding is performed.
2086 (let ((other (_convert_other other
#:raiseit
#t
))
2087 (third (_convert_other third
#:raiseit
#t
))
2088 (fin (lambda (product)
2089 ((ref product
'__add__
) third context
)))))
2090 ;; compute product; raise InvalidOperation if either operand is
2091 ;; a signaling NaN or if the product is zero times infinity.
2092 ((if (or (ref self
'_is_special
) (ref other
'_is_special
))
2094 (let (get-context context
))
2095 ((equal?
(ref self
'_exp
) "N") it
2096 ((cx-error context
) InvalidOperation
"sNaN" self
))
2097 ((equal?
(ref other
'_exp
) "N") it
2098 ((cx-error context
) InvalidOperation
"sNaN" other
))
2099 ((equal?
(ref self
'_exp
) "n") it
2101 ((equal?
(ref other
'_exp
) "n") it
2103 ((equal?
(ref self
'_exp
) "F") it
2104 (if (not (bool other
))
2105 ((cx-error context
) InvalidOperation
"INF * 0 in fma")
2106 (pylist-ref _SignedInfinity
2107 (logxor (ref self
'_sign
)
2108 (ref other
'_sign
)))))
2109 ((equal?
(ref other
'_exp
) "F") it
2110 (if (not (bool self
))
2111 ((cx-error context
) InvalidOperation
"0 * INF in fma")
2112 (pylist-ref _SignedInfinity
2113 (logxor (ref self
'_sign
)
2114 (ref other
'_sign
)))))
2118 (_dec_from_triple (logxor (ref self
'_sign
) (ref other
'_sign
))
2119 (str (* (int (ref self
'_int
))
2120 (int (ref other
'_int
))))
2121 (+ (ref self
'_exp
) (ref other
'_exp
)))))))
2123 (define _power_modulo
2124 (lam (self other modulo
(= context None
))
2125 "Three argument version of __pow__"
2127 ((norm-op self other
) it it
)
2128 ((norm-op self modulo
) it it
)
2129 (let (get-context context
))
2131 ;; deal with NaNs: if there are any sNaNs then first one wins,
2132 ;; (i.e. behaviour for NaNs is identical to that of fma)
2133 (let ((self_is_nan (ref self
'_isnan
))
2134 (other_is_nan (ref other
'_isnan
))
2135 (modulo_is_nan (ref modulo
'_isnan
))))
2137 ((or (bool self_is_nan
) (bool other_is_nan
) (bool modulo_is_nan
)) it
2140 ((cx-error context
) InvalidOperation
"sNaN" self
))
2142 ((cx-error context
) InvalidOperation
"sNaN" other
))
2144 ((cx-error context
) InvalidOperation
"sNaN" modulo
))
2146 (_fix_nan self context
))
2147 ((bool other_is_nan
)
2148 (_fix_nan other context
))
2150 (_fix_nan modulo context
))))
2152 ;;check inputs: we apply same restrictions as Python's pow()
2153 ((not (and ((ref self
'_isinteger
))
2154 ((ref other
'_isinteger
))
2155 ((ref modulo
'_isinteger
)))) it
2156 ((cx-error context
) InvalidOperation
2157 (+ "pow() 3rd argument not allowed "
2158 "unless all arguments are integers")))
2161 ((cx-error context
) InvalidOperation
2162 (+ "pow() 2nd argument cannot be "
2163 "negative when 3rd argument specified")))
2165 ((not (bool modulo
)) it
2166 ((cx-error context
) InvalidOperation
2167 "pow() 3rd argument cannot be 0"))
2169 ;; additional restriction for decimal: the modulus must be less
2170 ;; than 10**prec in absolute value
2171 ((>= ((ref modulo
'adjusted
)) (cx-prec context
)) it
2172 ((cx-error context
) InvalidOperation
2173 (+ "insufficient precision: pow() 3rd "
2174 "argument must not have more than "
2175 "precision digits")))
2177 ;; define 0**0 == NaN, for consistency with two-argument pow
2178 ;; (even though it hurts!)
2179 ((and (not (bool other
)) (not (bool self
))) it
2180 ((cx-error context
) InvalidOperation
2181 (+ "at least one of pow() 1st argument "
2182 "and 2nd argument must be nonzero ;"
2183 "0**0 is not defined")))
2185 ;; compute sign of result
2186 (let ((sign (if ((ref other
'_iseven
))
2189 (base (_WorkRep ((ref self
'to_integral_value
))))
2190 (exponent (_WorkRep ((ref other
'to_integral_value
)))))
2193 ;; convert modulo to a Python integer, and self and other to
2194 ;; Decimal integers (i.e. force their exponents to be >= 0)
2195 (set! modulo
(abs (int modulo
)))
2197 ;; compute result using integer pow()
2198 (set! base
(guile:modulo
2199 (* (guile:modulo
(ref base
'int
) modulo
)
2200 (modulo-expt 10 (ref base
'exp
) modulo
))
2203 (let lp
((i (ref exponent
'exp
)))
2206 (set! base
(modulo-expt base
10 modulo
))
2209 (set! base
(modulo-expt base
(ref exponent
'int
) modulo
))
2211 (_dec_from_triple sign
(str base
) 0)))))
2213 (define _power_exact
(pk 3
2214 (lambda (self other p
)
2215 "Attempt to compute self**other exactly.
2217 Given Decimals self and other and an integer p, attempt to
2218 compute an exact result for the power self**other, with p
2219 digits of precision. Return None if self**other is not
2220 exactly representable in p digits.
2222 Assumes that elimination of special cases has already been
2223 performed: self and other must both be nonspecial; self must
2224 be positive and not numerically equal to 1; other must be
2225 nonzero. For efficiency, other._exp should not be too large,
2226 so that 10**abs(other._exp) is a feasible calculation."
2228 ;; In the comments below, we write x for the value of self and y for the
2229 ;; value of other. Write x = xc*10**xe and abs(y) = yc*10**ye, with xc
2230 ;; and yc positive integers not divisible by 10.
2232 ;; The main purpose of this method is to identify the *failure*
2233 ;; of x**y to be exactly representable with as little effort as
2234 ;; possible. So we look for cheap and easy tests that
2235 ;; eliminate the possibility of x**y being exact. Only if all
2236 ;; these tests are passed do we go on to actually compute x**y.
2238 ;; Here's the main idea. Express y as a rational number m/n, with m and
2239 ;; n relatively prime and n>0. Then for x**y to be exactly
2240 ;; representable (at *any* precision), xc must be the nth power of a
2241 ;; positive integer and xe must be divisible by n. If y is negative
2242 ;; then additionally xc must be a power of either 2 or 5, hence a power
2245 ;; There's a limit to how small |y| can be: if y=m/n as above
2248 ;; (1) if xc != 1 then for the result to be representable we
2249 ;; need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
2250 ;; if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
2251 ;; 2**(1/|y|), hence xc**|y| < 2 and the result is not
2254 ;; (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
2255 ;; |y| < 1/|xe| then the result is not representable.
2257 ;; Note that since x is not equal to 1, at least one of (1) and
2258 ;; (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
2259 ;; 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
2261 ;; There's also a limit to how large y can be, at least if it's
2262 ;; positive: the normalized result will have coefficient xc**y,
2263 ;; so if it's representable then xc**y < 10**p, and y <
2264 ;; p/log10(xc). Hence if y*log10(xc) >= p then the result is
2265 ;; not exactly representable.
2267 ;; if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
2268 ;; so |y| < 1/xe and the result is not representable.
2269 ;; Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
2274 (define-syntax-rule (clean xc xe n
+)
2276 (if (= (modulo xc n
) 0)
2282 (let* ((x (_WorkRep self
))
2287 (let* ((y (_WorkRep other
))
2292 ;; case where xc == 1: result is 10**(xe*y), with xe*y
2293 ;; required to be an integer
2297 ;; result is now 10**(xe * 10**ye); xe * 10**ye must be integral
2302 (let ((exponent (* xe
(expt 10 ye
)))
2304 (if (= (ref y
'sign
) 1)
2305 (set! exponent
(- exponent
)))
2307 ;;if other is a nonnegative integer, use ideal exponent
2308 (if (and ((ref other
'_isinteger
)) (= (ref other
'_sign
) 0))
2310 (let ((ideal_exponent (* (ref self
'_exp
) (int other
))))
2311 (set! zeros
(min (- exponent ideal_exponent
) (- p
1)))))
2314 (_dec_from_triple 0 (+ "1" (* "0" zeros
)) (- exponent zeros
)))))
2316 ;; case where y is negative: xc must be either a power
2317 ;; of 2 or a power of 5.
2318 ((= (ref y
'sign
) 1) it
2319 (let ((last_digit (modulo xc
10)))
2323 ((= (modulo last_digit
2) 0)
2324 ;; quick test for power of 2
2326 ((not (= (logand xc
(- xc
)) xc
)) it
2328 ;; now xc is a power of 2; e is its exponent
2329 (let () (set! e
(- (_nbits xc
) 1)))
2333 ;; x = 2**e * 10**xe, e > 0, and y < 0.
2335 ;; The exact result is:
2337 ;; x**y = 5**(-e*y) * 10**(e*y + xe*y)
2339 ;; provided that both e*y and xe*y are integers.
2341 ;; 5**(-e*y) >= 10**p, then the result can't be expressed
2342 ;; exactly with p digits of precision.
2344 ;; Using the above, we can guard against large values of ye.
2345 ;; 93/65 is an upper bound for log(10)/log(5), so if
2347 ;; ye >= len(str(93*p//65))
2351 ;; -e*y >= -y >= 10**ye > 93*p/65 > p*log(10)/log(5),
2353 ;; so 5**(-e*y) >= 10**p, and the coefficient of the result
2354 ;; can't be expressed in p digits.
2356 ;; emax >= largest e such that 5**e < 10**p.
2357 (let ((emax (quotient (* p
93) 65))))
2359 ((>= ye
(len (str emax
))) it
2362 ;; Find -e*y and -xe*y; both must be integers
2364 (set! e
(_decimal_lshift_exact (* e yc
) ye
))
2365 (set! xe
(_decimal_lshift_exact (* xe yc
) ye
)))
2367 ((or (eq? e None
) (eq? xe None
)) it
2374 (set! xc
(expt 5 e
))
2379 ;; e >= log_5(xc) if xc is a power of 5; we have
2380 ;; equality all the way up to xc=5**2658
2381 (let* ((e (quotient (* (_nbits xc
) 28) 65))
2384 (xc (quotient q xz
))
2385 (remainder (modulo q xz
))))
2387 ((not (= remainder
0)) it
2390 (let () (clean xc e
5 -
))
2392 ;; Guard against large values of ye, using the same logic as in
2393 ;; the 'xc is a power of 2' branch. 10/3 is an upper bound for
2395 (let ((emax (quotient (* p
10) 3))))
2397 ((>= ye
(len (str emax
))) it
2401 (set! e
(_decimal_lshift_exact (* e yc
) ye
))
2402 (set! xe
(_decimal_lshift_exact (* xe yc
) ye
)))
2404 ((or (eq? e None
) (eq? xe None
)) it
2411 (set! xc
(expt 2 e
))
2417 ((>= xc
(expt 10 p
)) it it
)
2420 (set! xe
(+ (- e
) (- xe
)))
2421 (_dec_from_triple 0 (str xc
) xe
)))))
2423 ;; now y is positive; find m and n such that y = m/n
2424 (let ((m #f
) (n #f
) (xc_bits (_nbits xc
))))
2427 (set! m
(* yc
(expt 10 ye
)))
2431 ((and (not (= xe
0)) (<= (len (str (abs (* yc xe
)))) (- ye
))) it
2434 ((and (not (= xc
1))
2435 (<= (len (str (* (abs yc
) xc_bits
))) (- ye
))) it
2440 (set! n
(expt 10 (- ye
)))
2443 (if (and (= (modulo m
2) 0) (= (modulo n
2) 0))
2445 (set! m
(quotient m
2))
2446 (set! n
(quotient n
2)))))
2448 (if (and (= (modulo m
5) 0) (= (modulo n
5) 0))
2450 (set! m
(quotient m
5))
2451 (set! n
(quotient n
5)))))
2454 ;; compute nth root of xc*10**xe
2458 ;; if 1 < xc < 2**n then xc isn't an nth power
2459 ((and (not (= xc
1)) (<= xc_bits n
)) it
2462 ((not (= (modulo xe n
) 0)) it
2466 (let ((a (ash 1 (- (quotient (- xc_bits
) n
)))))
2467 (set! xe
(quotient xe n
))
2469 ;; compute nth root of xc using Newton's method
2471 (let* ((x (expt a
(- n
1)))
2475 (if (not (and (= a q
) (= r
0)))
2481 (set! a
(quotient (+ (* a
(- n
1)) q
) n
))
2485 ;; now xc*10**xe is the nth root of the original xc*10**xe
2486 ;; compute mth power of xc*10**xe
2488 ;; if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2489 ;; 10**p and the result is not representable.
2490 ((and (> xc
1) (> m
(quotient (* p
100) (_log10_lb xc
)))) it
2494 (set! xc
(expt xc m
))
2497 ((> xc
(expt 10 p
)) it
2501 ;; by this point the result *is* exactly representable
2502 ;; adjust the exponent to get as close as possible to the ideal
2503 ;; exponent, if necessary
2504 (let* ((str_xc (str xc
))
2505 (zeros (if (and ((ref other
'_isinteger
))
2506 (= (ref other
'_sign
) 0))
2507 (let ((ideal_exponent
2508 (* (ref self
'_exp
) (int other
))))
2509 (min (- xe ideal_exponent
)
2510 (- p
(len str_xc
))))
2512 (_dec_from_triple 0 (+ str_xc
(* '0' zeros
)) (- xe zeros
))))))))
2515 (lam (self other
(= modulo None
) (= context None
))
2516 "Return self ** other [ % modulo].
2518 With two arguments, compute self**other.
2520 With three arguments, compute (self**other) % modulo. For the
2521 three argument form, the following restrictions on the
2524 - all three arguments must be integral
2525 - other must be nonnegative
2526 - either self or other (or both) must be nonzero
2527 - modulo must be nonzero and must have at most p digits,
2528 where p is the context precision.
2530 If any of these restrictions is violated the InvalidOperation
2533 The result of pow(self, other, modulo) is identical to the
2534 result that would be obtained by computing (self**other) %
2535 modulo with unbounded precision but is computed more
2536 efficiently. It is always exact.
2540 ((not (eq? modulo None
)) it
2541 ((ref self
'_power_modulo
) other modulo context
))
2543 ((norm-op self other
) it it
)
2544 (let (get-context context
))
2546 ;; either argument is a NaN => result is NaN
2547 ((bin-special self other context
) it it
)
2549 ;; 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2550 ((not (bool other
)) it
2551 (if (not (bool self
))
2552 ((cx-error context
) InvalidOperation
"0 ** 0")
2555 ;; result has sign 1 iff self._sign is 1 and other is an odd integer
2556 (let ((result_sign 0)))
2558 ((if (= (ref self
'_sign
) 1)
2560 ((if ((ref other
'_isinteger
))
2561 (if (not ((ref other
'_iseven
)))
2563 (set! result_sign
1)
2566 ;; -ve**noninteger = NaN
2567 ;; (-0)**noninteger = 0**noninteger
2569 ((cx-error context
) InvalidOperation
2570 "x ** y with x negative and y not an integer")
2573 ;; negate self, without doing any unwanted rounding
2574 (set! self
((ref self
'copy_negate
)))
2578 ;; 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2579 ((not (bool self
)) it
2580 (if (= (ref other
'_sign
) 0)
2581 (_dec_from_triple result_sign
"0" 0)
2582 (pylist-ref _SignedInfinity result_sign
)))
2584 ;; Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2585 (((self '_isinfinity
)) it
2586 (if (= (ref other
'_sign
) 0)
2587 (pylist-ref _SignedInfinity result_sign
)
2588 (_dec_from_triple result_sign
"0" 0)))
2590 ;; 1**other = 1, but the choice of exponent and the flags
2591 ;; depend on the exponent of self, and on whether other is a
2592 ;; positive integer, a negative integer, or neither
2593 (let ((prec (cx-prec context
))))
2595 ((equal? self _One
) it
2597 (if ((ref other
'_isinteger
))
2598 ;; exp = max(self._exp*max(int(other), 0),
2599 ;; 1-context.prec) but evaluating int(other) directly
2600 ;; is dangerous until we know other is small (other
2601 ;; could be 1e999999999)
2604 ((= (ref other
'_sign
) 1)
2611 (set! exp
(* (ref self
'_exp
) multiplier
))
2612 (if (< exp
(- 1 prec
))
2614 (set! exp
(- 1 prec
))
2615 ((cx-error context
) Rounded
))))
2617 ((cx-error context
) Inexact
)
2618 ((cx-error context
) Rounded
)
2619 (set! exp
(- 1 prec
))))
2621 (_dec_from_triple result_sign
(+ "1" (* "0" (- exp
)) exp
))))
2623 ;; compute adjusted exponent of self
2624 (let ((self_adj ((ref self
'adjusted
)))))
2626 ;; self ** infinity is infinity if self > 1, 0 if self < 1
2627 ;; self ** -infinity is infinity if self < 1, 0 if self > 1
2628 (((ref other
'_isinfinity
)) it
2629 (if (eq?
(= (ref other
'_sign
) 0)
2631 (_dec_from_triple result_sign
"0" 0)
2632 (pylist-ref _SignedInfinity result_sign
)))
2634 ;; from here on, the result always goes through the call
2635 ;; to _fix at the end of this function.
2638 (bound (+ ((ref self
'_log10_exp_bound
))
2639 ((ref other
'adjusted
)))))
2641 ;; crude test to catch cases of extreme overflow/underflow. If
2642 ;; log10(self)*other >= 10**bound and bound >= len(str(Emax))
2643 ;; then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2644 ;; self**other >= 10**(Emax+1), so overflow occurs. The test
2645 ;; for underflow is similar.
2647 (if (eq?
(>= self_adj
0) (= (ref other
'_sign
) 0))
2648 ;; self > 1 and other +ve, or self < 1 and other -ve
2649 ;; possibility of overflow
2650 (if (>= bound
(len (str (cx-emax context
))))
2652 (_dec_from_triple result_sign
"1"
2653 (+ (cx-emax context
) 1))))
2655 ;; self > 1 and other -ve, or self < 1 and other +ve
2656 ;; possibility of underflow to 0
2657 (let ((Etiny (cx-etiny context
)))
2658 (if (>= bound
(len (str (- Etiny
))))
2659 (set! ans
(_dec_from_triple result_sign
"1" (- Etiny
1))))))
2661 ;; try for an exact result with precision +1
2662 (when (eq? ans None
)
2663 (set! ans
((ref self
'_power_exact
) other
(+ prec
1)))
2664 (when (not (eq? ans None
))
2665 (if (= result_sign
1)
2666 (set! ans
(_dec_from_triple 1 (ref ans
'_int
)
2670 ;; usual case: inexact result, x**y computed directly as exp(y*log(x))
2671 (when (eq? ans None
)
2678 (y (_WorkRep other
))
2682 (if (= (ref y
'sign
) 1)
2685 ;; compute correctly rounded result: start with precision +3,
2686 ;; then increase precision until result is unambiguously roundable
2691 (lambda () (_dpower xc xe yc ye
(+ p extra
)))
2694 (* 5 (expt 10 (- (len (str coeff
)) p
1))))
2696 (lp (+ extra
3)))))))
2698 (set! ans
(_dec_from_triple result_sign
(str coeff
) exp
))))))
2700 ;; unlike exp, ln and log10, the power function respects the
2701 ;; rounding mode; no need to switch to ROUND_HALF_EVEN here
2703 ;; There's a difficulty here when 'other' is not an integer and
2704 ;; the result is exact. In this case, the specification
2705 ;; requires that the Inexact flag be raised (in spite of
2706 ;; exactness), but since the result is exact _fix won't do this
2707 ;; for us. (Correspondingly, the Underflow signal should also
2708 ;; be raised for subnormal results.) We can't directly raise
2709 ;; these signals either before or after calling _fix, since
2710 ;; that would violate the precedence for signals. So we wrap
2711 ;; the ._fix call in a temporary context, and reraise
2713 (if (and exact
(not ((ref other
'_isinteger
))))
2715 ;; pad with zeros up to length context.prec+1 if necessary; this
2716 ;; ensures that the Rounded signal will be raised.
2717 (if (<= (len (ref ans
'_int
)) prec
)
2718 (let ((expdiff (+ prec
1 (- (len (ref ans
'_int
))))))
2719 (set! ans
(_dec_from_triple (ref ans
'_sign
)
2722 (- (ref ans
'_exp
) expdiff
)))))
2724 ;; create a copy of the current context, with cleared flags/traps
2725 (let ((newcontext (cx-copy context
)))
2726 (cx-clear_flags newcontext
)
2728 (for ((exception : _signals
)) ()
2729 (pylist-set! (cx-traps newcontext
) exception
0)
2732 ;; round in the new context
2733 (set! ans
((ref ans
'_fix
) newcontext
))
2735 ;; raise Inexact, and if necessary, Underflow
2736 ((cx-error newcontext
) Inexact
)
2737 (if (bool (pylist-ref (cx-flags newcontext
) Subnormal
))
2738 ((cx-error newcontext
) Underflow
))
2740 ;; propagate signals to the original context; _fix could
2741 ;; have raised any of Overflow, Underflow, Subnormal,
2742 ;; Inexact, Rounded, Clamped. Overflow needs the correct
2743 ;; arguments. Note that the order of the exceptions is
2745 (if (bool (pylist-ref (cx-flags newcontext
) Overflow
))
2746 ((cx-error newcontext
)
2747 Overflow
"above Emax" (ref ans
'_sign
)))
2749 (for ((exception : (list Underflow Subnormal
2750 Inexact Rounded Clamped
))) ()
2751 (if (bool (pylist-ref (cx-flags newcontext
) exception
))
2752 ((cx-error newcontext
) exception
)
2755 (set! ans
((ref ans
'_fix
) context
)))
2760 (lam (self other
(= context None
))
2761 "Swaps self/other and returns __pow__."
2763 ((norm-op self other
) it it
)
2764 ((ref 'other
'__pow__
) self
#:context context
))))
2767 (lam (self (= context None
))
2768 "Normalize- strip trailing 0s, change anything equal to 0 to 0e0"
2771 (let (get-context context
))
2772 ((un-special self context
) it it
)
2773 (let ((dup ((ref self _fix
) context
))))
2774 (((dup '_isinfinity
)) it dup
)
2775 ((not (bool dup
)) it
2776 (_dec_from_triple (ref dup
'_sign
) "0" 0))
2778 (let* ((_int (ref dup
'_int
))
2779 (exp_max (let ((i (cx-clamp context
)))
2782 (cx-etop context
)))))
2783 (let lp
((end (len _int
)) (exp (ref dup
'_exp
)))
2784 (if (and (equal?
(pylist-ref _int
(- end
1))
2787 (lp (- end
1) (+ exp
1))
2790 (pylist-slice _int None end None
)
2794 (lam (self exp
(= rounding None
) (= context None
))
2795 "Quantize self so its exponent is the same as that of exp.
2797 Similar to self._rescale(exp._exp) but with error checking.
2800 (let* ((exp (_convert_other exp
#:raiseit
#t
))
2801 (context (if (eq? context None
) (getcontext) context
))
2802 (rounding (if (eq? rounding None
)
2803 (cx-rounding context
)
2806 ((if (or ((self '_is_special
)) ((exp '_is_special
)))
2807 (let ((ans ((ref self
'_check_nans
) exp context
)))
2811 ((or ((ref exp
'_isinfinity
)) ((ref self
'_isinfinity
)))
2812 (if (and ((ref exp
'_isinfinity
))
2813 ((ref self
'_isinfinity
)))
2814 (Decimal self
)) ; if both are inf, it is OK
2815 ((cx-error context
) InvalidOperation
"quantize with one INF"))
2820 ;; exp._exp should be between Etiny and Emax
2821 (let ((_eexp (ref exp
'_exp
))
2822 (Emax (cx-emax context
))))
2824 ((not (and (<= (cx-etiny context
) _eexp
) (<= _eexp Emax
))) it
2825 ((cx-error context
) InvalidOperation
2826 "target exponent out of bounds in quantize"))
2828 ((not (bool self
)) it
2829 (let ((ans (_dec_from_triple (ref self
'_sign
) "0" _eexp
)))
2830 ((ref ans
'_fix
) context
)))
2832 (let ((self_adjusted ((ref self
'adjusted
)))
2833 (prec (cx-prec context
))))
2835 ((> self_adjusted
(cx-emax context
)) it
2836 ((cx-error context
) InvalidOperation
2837 "exponent of quantize result too large for current context"))
2839 ((> (+ self_adjusted
(- _eexp
) 1) prec
) it
2840 ((cx-error context
) InvalidOperation
2841 "quantize result has too many digits for current context"))
2843 (let ((ans ((ref self
'_rescale
) _eexp rounding
))))
2845 (if (> ((ref ans
'adjusted
)) Emax
)
2846 ((cx-error context
) InvalidOperation
2847 "exponent of quantize result too large for current context"))
2849 (if (> (len (ref ans
'_int
)) prec
)
2850 ((cx-error context
) InvalidOperation
2851 "quantize result has too many digits for current context"))
2855 ;; raise appropriate flags
2856 (if (and (bool ans
) (< ((ref ans
'adjusted
)) (cx-emin context
)))
2857 ((cx-error context
) Subnormal
))
2859 (when (> (ref ans
'_exp
) (ref self
'_exp
))
2860 (if (not (equal? ans self
))
2861 ((cx-error context
) Inexact
))
2862 ((cx-error context
) Rounded
))
2864 ;; call to fix takes care of any necessary folddown, and
2865 ;; signals Clamped if necessary
2866 ((ref ans
'_fix
) context
)))))
2868 (define same_quantum
2869 (lam (self other
(= context None
))
2870 "Return True if self and other have the same exponent; otherwise
2873 If either operand is a special value, the following rules are used:
2874 * return True if both operands are infinities
2875 * return True if both operands are NaNs
2876 * otherwise, return False.
2878 (let ((other (_convert_other other
#:raiseit
#t
)))
2879 (if (or (ref self
'_is_special
) (ref other
'_is_special
))
2880 (or (and ((ref self
'is_nan
)) ((ref other
'is_nan
)))
2881 (and ((ref self
'is_infinite
)) ((ref other
'is_infinite
))))))
2883 (= (ref self
'_exp
) (ref other
'_exp
))))
2886 (lam (self exp rounding
)
2887 "Rescale self so that the exponent is exp, either by padding with zeros
2888 or by truncating digits, using the given rounding mode.
2890 Specials are returned without change. This operation is
2891 quiet: it raises no flags, and uses no information from the
2894 exp = exp to scale to (an integer)
2895 rounding = rounding mode
2899 ((ref self
'_is_special
) it
2902 ((not (bool self
)) it
2903 (_dec_from_triple (ref self
'_sign
) "0" exp
))
2905 (let ((_exp (ref self
'_exp
))
2906 (_sign (ref self
'_sign
))
2907 (_int (ref self
'_int
))))
2910 ;; pad answer with zeros if necessary
2911 (_dec_from_triple _sign
(+ _int
(* "0" (- _exp exp
))) exp
))
2914 ;; too many digits; round and lose data. If self.adjusted() <
2915 ;; exp-1, replace self by 10**(exp-1) before rounding
2916 (let ((digits (+ (len _int
) _exp
(- exp
))))
2918 (set! self
(_dec_from_triple _sign
"1" (- exp
1)))
2921 (let* ((this_function (pylist-ref (ref self
'_pick_rounding_function
)
2923 (changed (this_function self digits
))
2925 (pylist-slice _int None digits None
))
2928 (set! coeff
(str (+ (int coeff
) 1))))
2930 (_dec_from_triple _sign coeff exp
))))))
2933 (lam (self places rounding
)
2934 "Round a nonzero, nonspecial Decimal to a fixed number of
2935 significant figures, using the given rounding mode.
2937 Infinities, NaNs and zeros are returned unaltered.
2939 This operation is quiet: it raises no flags, and uses no
2940 information from the context.
2945 (raise (ValueError "argument should be at least 1 in _round")))
2946 ((or (ref self
'_is_special
) (not (bool self
)))
2949 (let ((ans ((ref self
'_rescale
) (+ ((self 'adjusted
)) 1 (- places
))
2951 ;; it can happen that the rescale alters the adjusted exponent;
2952 ;; for example when rounding 99.97 to 3 significant figures.
2953 ;; When this happens we end up with an extra 0 at the end of
2954 ;; the number; a second rescale fixes this.
2955 (if (not (= ((ref ans
'adjusted
)) ((ref self
'adjusted
))))
2956 (set! ans
((ref ans
'_rescale
) (+ ((ans 'adjusted
)) 1
2961 (define to_integral_exact
(pk 4
2962 (lam (self (= rounding None
) (= context None
))
2963 "Rounds to a nearby integer.
2965 If no rounding mode is specified, take the rounding mode from
2966 the context. This method raises the Rounded and Inexact flags
2969 See also: to_integral_value, which does exactly the same as
2970 this method except that it doesn't raise Inexact or Rounded.
2973 ((ref self
'_is_special
)
2974 (let ((ans ((ref self
'_check_nans
) #:context context
)))
2979 ((>= (ref self
'_exp
) 0)
2982 (_dec_from_triple (ref self
'_sign
) "0" 0))
2984 (let* ((context (if (eq? context None
) (getcontext) context
))
2985 (rounding (if (eq? rounding None
)
2986 (cx-rounding context
)
2988 (ans ((ref self
'_rescale
) 0 rounding
)))
2990 (if (not (equal? ans self
))
2991 ((cx-error context
) Inexact
))
2993 ((cx-error context
) Rounded
)
2997 (define to_integral_value
2998 (lam (self (= rounding None
) (= context None
))
2999 "Rounds to the nearest integer, without raising inexact, rounded."
3000 (let* ((context (if (eq? context None
) (getcontext) context
))
3001 (rounding (if (eq? rounding None
)
3002 (cx-rounding context
)
3006 ((ref self
'_is_special
)
3007 (let ((ans ((ref self
'_check_nans
) #:context context
)))
3012 ((>= (ref self
'_exp
) 0)
3016 ((ref self
'_rescale
) 0 rounding
))))))
3018 ;; the method name changed, but we provide also the old one,
3019 ;; for compatibility
3020 (define to_integral to_integral_value
)
3023 (lam (self (= context None
))
3024 "Return the square root of self."
3026 (let (get-context context
))
3028 ((if (ref self
'_is_special
)
3029 (let ((ans ((ref self
'_check_nans
) #:context context
)))
3032 (if (and ((self '_isinfinity
)) (= (ref self
'_sign
) 0))
3038 ((not (bool self
)) it
3039 ;; exponent = self._exp // 2. sqrt(-0) = -0
3040 (let ((ans (_dec_from_triple (ref self
'_sign
) "0"
3041 (quotient (ref self
'_exp
) 2))))
3042 ((ref ans
'_fix
) context
)))
3044 ((= (ref self
'_sign
) 1) it
3045 ((cx-error context
) InvalidOperation
"sqrt(-x), x > 0"))
3047 ;; At this point self represents a positive number. Let p be
3048 ;; the desired precision and express self in the form c*100**e
3049 ;; with c a positive real number and e an integer, c and e
3050 ;; being chosen so that 100**(p-1) <= c < 100**p. Then the
3051 ;; (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
3052 ;; <= sqrt(c) < 10**p, so the closest representable Decimal at
3053 ;; precision p is n*10**e where n = round_half_even(sqrt(c)),
3054 ;; the closest integer to sqrt(c) with the even integer chosen
3055 ;; in the case of a tie.
3057 ;; To ensure correct rounding in all cases, we use the
3058 ;; following trick: we compute the square root to an extra
3059 ;; place (precision p+1 instead of precision p), rounding down.
3060 ;; Then, if the result is inexact and its last digit is 0 or 5,
3061 ;; we increase the last digit to 1 or 6 respectively; if it's
3062 ;; exact we leave the last digit alone. Now the final round to
3063 ;; p places (or fewer in the case of underflow) will round
3064 ;; correctly and raise the appropriate flags.
3066 ;; use an extra digit of precision
3067 (let* ((prec (+ (cx-prec context
) 1))
3068 (op (_WorkRep self
))
3069 (e (ash (ref op
'exp
) -
1))
3075 ;; write argument in the form c*100**e where e = self._exp//2
3076 ;; is the 'ideal' exponent, to be used if the square root is
3077 ;; exactly representable. l is the number of 'digits' of c in
3078 ;; base 100, so that 100**(l-1) <= c < 100**l.
3079 (if (= (logand (ref op
'exp
) 1) 1)
3081 (set! c
(* (ref op
'int
) 10))
3082 (set! l
(+ (ash (len (ref self
'_int
)) -
1) 1)))
3084 (set! c
(ref op
'int
))
3085 (set! l
(ash (+ (len (ref self
'_int
)) 1) -
1))))
3087 ;; rescale so that c has exactly prec base 100 'digits'
3088 (set! shift
(- prec l
))
3091 (set! c
(* c
(expt 100 shift
)))
3093 (let ((x (expt 100 (- shift
))))
3094 (set! c
(quotient c x
))
3095 (let ((remainder (modulo c x
)))
3096 (set! exact
(= remainder
0)))))
3098 (set! e
(- e shift
))
3100 ;; find n = floor(sqrt(c)) using Newton's method
3101 (let ((n (let lp
((n (expt 10 prec
)))
3102 (let ((q (quotient c n
)))
3105 (lp (ash (+ n q
) -
1)))))))
3107 (set! exact
(and exact
(= (* n n
) c
)))
3110 ;; result is exact; rescale to use ideal exponent e
3113 ;; assert n % 10**shift == 0
3114 (set! n
(quotient n
(expt 10 shift
)))
3115 (set! n
(* n
(expt 10 (- shift
)))))
3116 (set! e
(+ e shift
)))
3117 ;; result is not exact; fix last digit as described above
3118 (if (= (modulo n
5) 0)
3121 (let* ((ans (_dec_from_triple 0 (str n
) e
))
3122 ;; round, and fit to current context
3123 (context ((ref context
'_shallow_copy
)))
3124 (rounding ((ref context
'_set_rounding
) ROUND_HALF_EVEN
))
3125 (ans ((ref ans
'_fix
) context
)))
3126 (set context
'rounding rounding
)
3130 (lam (self other
(= context None
))
3131 "Returns the larger value.
3133 Like max(self, other) except if one is not a number, returns
3134 NaN (and signals if one is sNaN). Also rounds.
3137 (let ((other (_convert_other other
#:raiseit