1 ;;;; This file contains the definitions of most number functions.
3 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
12 (in-package "SB!KERNEL")
14 ;;;; the NUMBER-DISPATCH macro
16 (eval-when (:compile-toplevel :load-toplevel :execute)
18 ;;; Grovel an individual case to NUMBER-DISPATCH, augmenting RESULT
19 ;;; with the type dispatches and bodies. Result is a tree built of
20 ;;; alists representing the dispatching off each arg (in order). The
21 ;;; leaf is the body to be executed in that case.
22 (defun parse-number-dispatch (vars result types var-types body)
24 (unless (null types) (error "More types than vars."))
26 (error "Duplicate case: ~S." body))
28 (sublis var-types body :test #'equal)))
30 (error "More vars than types."))
32 (flet ((frob (var type)
33 (parse-number-dispatch
35 (or (assoc type (cdr result) :test #'equal)
36 (car (setf (cdr result)
37 (acons type nil (cdr result)))))
39 (acons `(dispatch-type ,var) type var-types)
41 (let ((type (first types))
43 (if (and (consp type) (eq (first type) 'foreach))
44 (dolist (type (rest type))
48 ;;; our guess for the preferred order in which to do type tests
49 ;;; (cheaper and/or more probable first.)
50 (defparameter *type-test-ordering*
51 '(fixnum single-float double-float integer #!+long-float long-float bignum
54 ;;; Should TYPE1 be tested before TYPE2?
55 (defun type-test-order (type1 type2)
56 (let ((o1 (position type1 *type-test-ordering*))
57 (o2 (position type2 *type-test-ordering*)))
63 ;;; Return an ETYPECASE form that does the type dispatch, ordering the
64 ;;; cases for efficiency.
65 (defun generate-number-dispatch (vars error-tags cases)
67 (let ((var (first vars))
68 (cases (sort cases #'type-test-order :key #'car)))
70 ,@(mapcar (lambda (case)
72 ,@(generate-number-dispatch (rest vars)
76 (t (go ,(first error-tags))))))
81 ;;; This is a vaguely case-like macro that does number cross-product
82 ;;; dispatches. The Vars are the variables we are dispatching off of.
83 ;;; The Type paired with each Var is used in the error message when no
84 ;;; case matches. Each case specifies a Type for each var, and is
85 ;;; executed when that signature holds. A type may be a list
86 ;;; (FOREACH Each-Type*), causing that case to be repeatedly
87 ;;; instantiated for every Each-Type. In the body of each case, any
88 ;;; list of the form (DISPATCH-TYPE Var-Name) is substituted with the
89 ;;; type of that var in that instance of the case.
91 ;;; As an alternate to a case spec, there may be a form whose CAR is a
92 ;;; symbol. In this case, we apply the CAR of the form to the CDR and
93 ;;; treat the result of the call as a list of cases. This process is
94 ;;; not applied recursively.
95 (defmacro number-dispatch (var-specs &body cases)
96 (let ((res (list nil))
97 (vars (mapcar #'car var-specs))
100 (if (symbolp (first case))
101 (let ((cases (apply (symbol-function (first case)) (rest case))))
103 (parse-number-dispatch vars res (first case) nil (rest case))))
104 (parse-number-dispatch vars res (first case) nil (rest case))))
108 (dolist (spec var-specs)
109 (let ((var (first spec))
114 (errors `(return-from
116 (error 'simple-type-error :datum ,var
117 :expected-type ',type
119 "~@<Argument ~A is not a ~S: ~2I~_~S~:>"
121 (list ',var ',type ,var))))))
126 ,@(generate-number-dispatch vars (error-tags)
130 ;;;; binary operation dispatching utilities
132 (eval-when (:compile-toplevel :execute)
134 ;;; Return NUMBER-DISPATCH forms for rational X float.
135 (defun float-contagion (op x y &optional (rat-types '(fixnum bignum ratio)))
136 `(((single-float single-float) (,op ,x ,y))
137 (((foreach ,@rat-types)
138 (foreach single-float double-float #!+long-float long-float))
139 (,op (coerce ,x '(dispatch-type ,y)) ,y))
140 (((foreach single-float double-float #!+long-float long-float)
141 (foreach ,@rat-types))
142 (,op ,x (coerce ,y '(dispatch-type ,x))))
144 (((foreach single-float double-float long-float) long-float)
145 (,op (coerce ,x 'long-float) ,y))
147 ((long-float (foreach single-float double-float))
148 (,op ,x (coerce ,y 'long-float)))
149 (((foreach single-float double-float) double-float)
150 (,op (coerce ,x 'double-float) ,y))
151 ((double-float single-float)
152 (,op ,x (coerce ,y 'double-float)))))
154 ;;; Return NUMBER-DISPATCH forms for bignum X fixnum.
155 (defun bignum-cross-fixnum (fix-op big-op)
156 `(((fixnum fixnum) (,fix-op x y))
158 (,big-op (make-small-bignum x) y))
160 (,big-op x (make-small-bignum y)))
166 ;;;; canonicalization utilities
168 ;;; If IMAGPART is 0, return REALPART, otherwise make a complex. This is
169 ;;; used when we know that REALPART and IMAGPART are the same type, but
170 ;;; rational canonicalization might still need to be done.
171 #!-sb-fluid (declaim (inline canonical-complex))
172 (defun canonical-complex (realpart imagpart)
176 ((and (typep realpart 'long-float)
177 (typep imagpart 'long-float))
178 (truly-the (complex long-float) (complex realpart imagpart)))
179 ((and (typep realpart 'double-float)
180 (typep imagpart 'double-float))
181 (truly-the (complex double-float) (complex realpart imagpart)))
182 ((and (typep realpart 'single-float)
183 (typep imagpart 'single-float))
184 (truly-the (complex single-float) (complex realpart imagpart)))
186 (%make-complex realpart imagpart)))))
188 ;;; Given a numerator and denominator with the GCD already divided
189 ;;; out, make a canonical rational. We make the denominator positive,
190 ;;; and check whether it is 1.
191 #!-sb-fluid (declaim (inline build-ratio))
192 (defun build-ratio (num den)
193 (multiple-value-bind (num den)
195 (values (- num) (- den))
199 (error 'division-by-zero
200 :operands (list num den)
201 :operation 'build-ratio))
203 (t (%make-ratio num den)))))
205 ;;; Truncate X and Y, but bum the case where Y is 1.
206 #!-sb-fluid (declaim (inline maybe-truncate))
207 (defun maybe-truncate (x y)
214 (defun complex (realpart &optional (imagpart 0))
216 "Return a complex number with the specified real and imaginary components."
217 (flet ((%%make-complex (realpart imagpart)
219 ((and (typep realpart 'long-float)
220 (typep imagpart 'long-float))
221 (truly-the (complex long-float)
222 (complex realpart imagpart)))
223 ((and (typep realpart 'double-float)
224 (typep imagpart 'double-float))
225 (truly-the (complex double-float)
226 (complex realpart imagpart)))
227 ((and (typep realpart 'single-float)
228 (typep imagpart 'single-float))
229 (truly-the (complex single-float)
230 (complex realpart imagpart)))
232 (%make-complex realpart imagpart)))))
233 (number-dispatch ((realpart real) (imagpart real))
235 (canonical-complex realpart imagpart))
236 (float-contagion %%make-complex realpart imagpart (rational)))))
238 (defun realpart (number)
240 "Extract the real part of a number."
243 ((complex long-float)
244 (truly-the long-float (realpart number)))
245 ((complex double-float)
246 (truly-the double-float (realpart number)))
247 ((complex single-float)
248 (truly-the single-float (realpart number)))
250 (sb!kernel:%realpart number))
254 (defun imagpart (number)
256 "Extract the imaginary part of a number."
259 ((complex long-float)
260 (truly-the long-float (imagpart number)))
261 ((complex double-float)
262 (truly-the double-float (imagpart number)))
263 ((complex single-float)
264 (truly-the single-float (imagpart number)))
266 (sb!kernel:%imagpart number))
272 (defun conjugate (number)
274 "Return the complex conjugate of NUMBER. For non-complex numbers, this is
276 (declare (type number number))
277 (if (complexp number)
278 (complex (realpart number) (- (imagpart number)))
281 (defun signum (number)
283 "If NUMBER is zero, return NUMBER, else return (/ NUMBER (ABS NUMBER))."
286 (if (rationalp number)
287 (if (plusp number) 1 -1)
288 (/ number (abs number)))))
292 (defun numerator (number)
294 "Return the numerator of NUMBER, which must be rational."
297 (defun denominator (number)
299 "Return the denominator of NUMBER, which must be rational."
300 (denominator number))
302 ;;;; arithmetic operations
304 (macrolet ((define-arith (op init doc)
305 #!-sb-doc (declare (ignore doc))
306 `(defun ,op (&rest args)
308 (if (null args) ,init
309 (do ((args (cdr args) (cdr args))
310 (result (car args) (,op result (car args))))
312 ;; to signal TYPE-ERROR when exactly 1 arg of wrong type:
313 (declare (type number result)))))))
315 "Return the sum of its arguments. With no args, returns 0.")
317 "Return the product of its arguments. With no args, returns 1."))
319 (defun - (number &rest more-numbers)
321 "Subtract the second and all subsequent arguments from the first;
322 or with one argument, negate the first argument."
324 (do ((nlist more-numbers (cdr nlist))
326 ((atom nlist) result)
327 (declare (list nlist))
328 (setq result (- result (car nlist))))
331 (defun / (number &rest more-numbers)
333 "Divide the first argument by each of the following arguments, in turn.
334 With one argument, return reciprocal."
336 (do ((nlist more-numbers (cdr nlist))
338 ((atom nlist) result)
339 (declare (list nlist))
340 (setq result (/ result (car nlist))))
353 (eval-when (:compile-toplevel)
355 (sb!xc:defmacro two-arg-+/- (name op big-op)
357 (number-dispatch ((x number) (y number))
358 (bignum-cross-fixnum ,op ,big-op)
359 (float-contagion ,op x y)
362 (canonical-complex (,op (realpart x) (realpart y))
363 (,op (imagpart x) (imagpart y))))
364 (((foreach bignum fixnum ratio single-float double-float
365 #!+long-float long-float) complex)
366 (complex (,op x (realpart y)) (,op (imagpart y))))
367 ((complex (or rational float))
368 (complex (,op (realpart x) y) (imagpart x)))
370 (((foreach fixnum bignum) ratio)
371 (let* ((dy (denominator y))
372 (n (,op (* x dy) (numerator y))))
375 (let* ((dx (denominator x))
376 (n (,op (numerator x) (* y dx))))
379 (let* ((nx (numerator x))
385 (%make-ratio (,op (* nx dy) (* dx ny)) (* dx dy))
386 (let* ((t1 (,op (* nx (truncate dy g1)) (* (truncate dx g1) ny)))
388 (t2 (truncate dx g1)))
391 (%make-ratio t1 (* t2 dy)))
392 (t (let* ((nn (truncate t1 g2))
393 (t3 (truncate dy g2))
394 (nd (if (eql t2 1) t3 (* t2 t3))))
395 (if (eql nd 1) nn (%make-ratio nn nd))))))))))))
399 (two-arg-+/- two-arg-+ + add-bignums)
400 (two-arg-+/- two-arg-- - subtract-bignum)
402 (defun two-arg-* (x y)
403 (flet ((integer*ratio (x y)
405 (let* ((ny (numerator y))
409 (%make-ratio (* x ny) dy)
410 (let ((nn (* (truncate x gcd) ny))
411 (nd (truncate dy gcd)))
414 (%make-ratio nn nd)))))))
416 (canonical-complex (* (realpart x) y) (* (imagpart x) y))))
417 (number-dispatch ((x number) (y number))
418 (float-contagion * x y)
420 ((fixnum fixnum) (multiply-fixnums x y))
421 ((bignum fixnum) (multiply-bignum-and-fixnum x y))
422 ((fixnum bignum) (multiply-bignum-and-fixnum y x))
423 ((bignum bignum) (multiply-bignums x y))
426 (let* ((rx (realpart x))
430 (canonical-complex (- (* rx ry) (* ix iy)) (+ (* rx iy) (* ix ry)))))
431 (((foreach bignum fixnum ratio single-float double-float
432 #!+long-float long-float)
435 ((complex (or rational float))
438 (((foreach bignum fixnum) ratio) (integer*ratio x y))
439 ((ratio integer) (integer*ratio y x))
441 (let* ((nx (numerator x))
447 (build-ratio (* (maybe-truncate nx g1)
448 (maybe-truncate ny g2))
449 (* (maybe-truncate dx g2)
450 (maybe-truncate dy g1))))))))
452 ;;; Divide two integers, producing a canonical rational. If a fixnum,
453 ;;; we see whether they divide evenly before trying the GCD. In the
454 ;;; bignum case, we don't bother, since bignum division is expensive,
455 ;;; and the test is not very likely to succeed.
456 (defun integer-/-integer (x y)
457 (if (and (typep x 'fixnum) (typep y 'fixnum))
458 (multiple-value-bind (quo rem) (truncate x y)
461 (let ((gcd (gcd x y)))
462 (declare (fixnum gcd))
465 (build-ratio (truncate x gcd) (truncate y gcd))))))
466 (let ((gcd (gcd x y)))
469 (build-ratio (truncate x gcd) (truncate y gcd))))))
471 (defun two-arg-/ (x y)
472 (number-dispatch ((x number) (y number))
473 (float-contagion / x y (ratio integer))
476 (let* ((rx (realpart x))
480 (if (> (abs ry) (abs iy))
482 (dn (* ry (+ 1 (* r r)))))
483 (canonical-complex (/ (+ rx (* ix r)) dn)
484 (/ (- ix (* rx r)) dn)))
486 (dn (* iy (+ 1 (* r r)))))
487 (canonical-complex (/ (+ (* rx r) ix) dn)
488 (/ (- (* ix r) rx) dn))))))
489 (((foreach integer ratio single-float double-float) complex)
490 (let* ((ry (realpart y))
492 (if (> (abs ry) (abs iy))
494 (dn (* ry (+ 1 (* r r)))))
495 (canonical-complex (/ x dn)
498 (dn (* iy (+ 1 (* r r)))))
499 (canonical-complex (/ (* x r) dn)
501 ((complex (or rational float))
502 (canonical-complex (/ (realpart x) y)
506 (let* ((nx (numerator x))
512 (build-ratio (* (maybe-truncate nx g1) (maybe-truncate dy g2))
513 (* (maybe-truncate dx g2) (maybe-truncate ny g1)))))
516 (integer-/-integer x y))
521 (let* ((ny (numerator y))
524 (build-ratio (* (maybe-truncate x gcd) dy)
525 (maybe-truncate ny gcd)))))
528 (let* ((nx (numerator x))
530 (build-ratio (maybe-truncate nx gcd)
531 (* (maybe-truncate y gcd) (denominator x)))))))
534 (number-dispatch ((n number))
535 (((foreach fixnum single-float double-float #!+long-float long-float))
540 (%make-ratio (- (numerator n)) (denominator n)))
542 (complex (- (realpart n)) (- (imagpart n))))))
544 ;;;; TRUNCATE and friends
546 (defun truncate (number &optional (divisor 1))
548 "Return number (or number/divisor) as an integer, rounded toward 0.
549 The second returned value is the remainder."
550 (macrolet ((truncate-float (rtype)
551 `(let* ((float-div (coerce divisor ',rtype))
552 (res (%unary-truncate (/ number float-div))))
555 (* (coerce res ',rtype) float-div))))))
556 (number-dispatch ((number real) (divisor real))
557 ((fixnum fixnum) (truncate number divisor))
558 (((foreach fixnum bignum) ratio)
559 (let ((q (truncate (* number (denominator divisor))
560 (numerator divisor))))
561 (values q (- number (* q divisor)))))
563 (bignum-truncate (make-small-bignum number) divisor))
564 ((ratio (or float rational))
565 (let ((q (truncate (numerator number)
566 (* (denominator number) divisor))))
567 (values q (- number (* q divisor)))))
569 (bignum-truncate number (make-small-bignum divisor)))
571 (bignum-truncate number divisor))
573 (((foreach single-float double-float #!+long-float long-float)
574 (or rational single-float))
576 (let ((res (%unary-truncate number)))
577 (values res (- number (coerce res '(dispatch-type number)))))
578 (truncate-float (dispatch-type number))))
580 ((long-float (or single-float double-float long-float))
581 (truncate-float long-float))
583 (((foreach double-float single-float) long-float)
584 (truncate-float long-float))
585 ((double-float (or single-float double-float))
586 (truncate-float double-float))
587 ((single-float double-float)
588 (truncate-float double-float))
589 (((foreach fixnum bignum ratio)
590 (foreach single-float double-float #!+long-float long-float))
591 (truncate-float (dispatch-type divisor))))))
593 ;;; Declare these guys inline to let them get optimized a little.
594 ;;; ROUND and FROUND are not declared inline since they seem too
595 ;;; obscure and too big to inline-expand by default. Also, this gives
596 ;;; the compiler a chance to pick off the unary float case. Similarly,
597 ;;; CEILING and FLOOR are only maybe-inline for now, so that the
598 ;;; power-of-2 CEILING and FLOOR transforms get a chance.
599 #!-sb-fluid (declaim (inline rem mod fceiling ffloor ftruncate))
600 (declaim (maybe-inline ceiling floor))
602 (defun floor (number &optional (divisor 1))
604 "Return the greatest integer not greater than number, or number/divisor.
605 The second returned value is (mod number divisor)."
606 ;; If the numbers do not divide exactly and the result of
607 ;; (/ NUMBER DIVISOR) would be negative then decrement the quotient
608 ;; and augment the remainder by the divisor.
609 (multiple-value-bind (tru rem) (truncate number divisor)
610 (if (and (not (zerop rem))
614 (values (1- tru) (+ rem divisor))
617 (defun ceiling (number &optional (divisor 1))
619 "Return the smallest integer not less than number, or number/divisor.
620 The second returned value is the remainder."
621 ;; If the numbers do not divide exactly and the result of
622 ;; (/ NUMBER DIVISOR) would be positive then increment the quotient
623 ;; and decrement the remainder by the divisor.
624 (multiple-value-bind (tru rem) (truncate number divisor)
625 (if (and (not (zerop rem))
629 (values (+ tru 1) (- rem divisor))
632 (defun round (number &optional (divisor 1))
634 "Rounds number (or number/divisor) to nearest integer.
635 The second returned value is the remainder."
638 (multiple-value-bind (tru rem) (truncate number divisor)
641 (let ((thresh (/ (abs divisor) 2)))
642 (cond ((or (> rem thresh)
643 (and (= rem thresh) (oddp tru)))
645 (values (- tru 1) (+ rem divisor))
646 (values (+ tru 1) (- rem divisor))))
647 ((let ((-thresh (- thresh)))
649 (and (= rem -thresh) (oddp tru))))
651 (values (+ tru 1) (- rem divisor))
652 (values (- tru 1) (+ rem divisor))))
653 (t (values tru rem))))))))
655 (defun rem (number divisor)
657 "Return second result of TRUNCATE."
658 (multiple-value-bind (tru rem) (truncate number divisor)
659 (declare (ignore tru))
662 (defun mod (number divisor)
664 "Return second result of FLOOR."
665 (let ((rem (rem number divisor)))
666 (if (and (not (zerop rem))
673 (defmacro !define-float-rounding-function (name op doc)
674 `(defun ,name (number &optional (divisor 1))
676 (multiple-value-bind (res rem) (,op number divisor)
677 (values (float res (if (floatp rem) rem 1.0)) rem))))
679 (defun ftruncate (number &optional (divisor 1))
681 "Same as TRUNCATE, but returns first value as a float."
682 (macrolet ((ftruncate-float (rtype)
683 `(let* ((float-div (coerce divisor ',rtype))
684 (res (%unary-ftruncate (/ number float-div))))
687 (* (coerce res ',rtype) float-div))))))
688 (number-dispatch ((number real) (divisor real))
689 (((foreach fixnum bignum ratio) (or fixnum bignum ratio))
690 (multiple-value-bind (q r)
691 (truncate number divisor)
692 (values (float q) r)))
693 (((foreach single-float double-float #!+long-float long-float)
694 (or rational single-float))
696 (let ((res (%unary-ftruncate number)))
697 (values res (- number (coerce res '(dispatch-type number)))))
698 (ftruncate-float (dispatch-type number))))
700 ((long-float (or single-float double-float long-float))
701 (ftruncate-float long-float))
703 (((foreach double-float single-float) long-float)
704 (ftruncate-float long-float))
705 ((double-float (or single-float double-float))
706 (ftruncate-float double-float))
707 ((single-float double-float)
708 (ftruncate-float double-float))
709 (((foreach fixnum bignum ratio)
710 (foreach single-float double-float #!+long-float long-float))
711 (ftruncate-float (dispatch-type divisor))))))
713 (defun ffloor (number &optional (divisor 1))
714 "Same as FLOOR, but returns first value as a float."
715 (multiple-value-bind (tru rem) (ftruncate number divisor)
716 (if (and (not (zerop rem))
720 (values (1- tru) (+ rem divisor))
723 (defun fceiling (number &optional (divisor 1))
724 "Same as CEILING, but returns first value as a float."
725 (multiple-value-bind (tru rem) (ftruncate number divisor)
726 (if (and (not (zerop rem))
730 (values (+ tru 1) (- rem divisor))
733 ;;; FIXME: this probably needs treatment similar to the use of
734 ;;; %UNARY-FTRUNCATE for FTRUNCATE.
735 (defun fround (number &optional (divisor 1))
736 "Same as ROUND, but returns first value as a float."
737 (multiple-value-bind (res rem)
738 (round number divisor)
739 (values (float res (if (floatp rem) rem 1.0)) rem)))
743 (defun = (number &rest more-numbers)
745 "Return T if all of its arguments are numerically equal, NIL otherwise."
746 (declare (truly-dynamic-extent more-numbers))
748 (do ((nlist more-numbers (cdr nlist)))
750 (declare (list nlist))
751 (if (not (= (car nlist) number)) (return nil))))
753 (defun /= (number &rest more-numbers)
755 "Return T if no two of its arguments are numerically equal, NIL otherwise."
756 (declare (truly-dynamic-extent more-numbers))
757 (do* ((head (the number number) (car nlist))
758 (nlist more-numbers (cdr nlist)))
760 (declare (list nlist))
761 (unless (do* ((nl nlist (cdr nl)))
764 (if (= head (car nl)) (return nil)))
767 (defun < (number &rest more-numbers)
769 "Return T if its arguments are in strictly increasing order, NIL otherwise."
770 (declare (truly-dynamic-extent more-numbers))
771 (do* ((n (the number number) (car nlist))
772 (nlist more-numbers (cdr nlist)))
774 (declare (list nlist))
775 (if (not (< n (car nlist))) (return nil))))
777 (defun > (number &rest more-numbers)
779 "Return T if its arguments are in strictly decreasing order, NIL otherwise."
780 (declare (truly-dynamic-extent more-numbers))
781 (do* ((n (the number number) (car nlist))
782 (nlist more-numbers (cdr nlist)))
784 (declare (list nlist))
785 (if (not (> n (car nlist))) (return nil))))
787 (defun <= (number &rest more-numbers)
789 "Return T if arguments are in strictly non-decreasing order, NIL otherwise."
790 (declare (truly-dynamic-extent more-numbers))
791 (do* ((n (the number number) (car nlist))
792 (nlist more-numbers (cdr nlist)))
794 (declare (list nlist))
795 (if (not (<= n (car nlist))) (return nil))))
797 (defun >= (number &rest more-numbers)
799 "Return T if arguments are in strictly non-increasing order, NIL otherwise."
800 (declare (truly-dynamic-extent more-numbers))
801 (do* ((n (the number number) (car nlist))
802 (nlist more-numbers (cdr nlist)))
804 (declare (list nlist))
805 (if (not (>= n (car nlist))) (return nil))))
807 (defun max (number &rest more-numbers)
809 "Return the greatest of its arguments; among EQUALP greatest, return
811 (declare (truly-dynamic-extent more-numbers))
812 (do ((nlist more-numbers (cdr nlist))
814 ((null nlist) (return result))
815 (declare (list nlist))
816 (declare (type real number result))
817 (if (> (car nlist) result) (setq result (car nlist)))))
819 (defun min (number &rest more-numbers)
821 "Return the least of its arguments; among EQUALP least, return
823 (declare (truly-dynamic-extent more-numbers))
824 (do ((nlist more-numbers (cdr nlist))
826 ((null nlist) (return result))
827 (declare (list nlist))
828 (declare (type real number result))
829 (if (< (car nlist) result) (setq result (car nlist)))))
831 (eval-when (:compile-toplevel :execute)
833 ;;; The INFINITE-X-FINITE-Y and INFINITE-Y-FINITE-X args tell us how
834 ;;; to handle the case when X or Y is a floating-point infinity and
835 ;;; the other arg is a rational. (Section 12.1.4.1 of the ANSI spec
836 ;;; says that comparisons are done by converting the float to a
837 ;;; rational when comparing with a rational, but infinities can't be
838 ;;; converted to a rational, so we show some initiative and do it this
840 (defun basic-compare (op &key infinite-x-finite-y infinite-y-finite-x)
841 `(((fixnum fixnum) (,op x y))
843 ((single-float single-float) (,op x y))
845 (((foreach single-float double-float long-float) long-float)
846 (,op (coerce x 'long-float) y))
848 ((long-float (foreach single-float double-float))
849 (,op x (coerce y 'long-float)))
850 ((fixnum (foreach single-float double-float))
851 (if (float-infinity-p y)
853 ;; If the fixnum has an exact float representation, do a
854 ;; float comparison. Otherwise do the slow float -> ratio
856 (multiple-value-bind (lo hi)
857 (case '(dispatch-type y)
859 (values most-negative-exactly-single-float-fixnum
860 most-positive-exactly-single-float-fixnum))
862 (values most-negative-exactly-double-float-fixnum
863 most-positive-exactly-double-float-fixnum)))
865 (,op (coerce x '(dispatch-type y)) y)
866 (,op x (rational y))))))
867 (((foreach single-float double-float) fixnum)
869 (,op x (coerce 0 '(dispatch-type x)))
870 (if (float-infinity-p x)
873 (multiple-value-bind (lo hi)
874 (case '(dispatch-type x)
876 (values most-negative-exactly-single-float-fixnum
877 most-positive-exactly-single-float-fixnum))
879 (values most-negative-exactly-double-float-fixnum
880 most-positive-exactly-double-float-fixnum)))
882 (,op x (coerce y '(dispatch-type x)))
883 (,op (rational x) y))))))
884 (((foreach single-float double-float) double-float)
885 (,op (coerce x 'double-float) y))
886 ((double-float single-float)
887 (,op x (coerce y 'double-float)))
888 (((foreach single-float double-float #!+long-float long-float) rational)
890 (,op x (coerce 0 '(dispatch-type x)))
891 (if (float-infinity-p x)
893 (,op (rational x) y))))
894 (((foreach bignum fixnum ratio) float)
895 (if (float-infinity-p y)
897 (,op x (rational y))))))
900 (macrolet ((def-two-arg-</> (name op ratio-arg1 ratio-arg2 &rest cases)
902 (number-dispatch ((x real) (y real))
906 (,op x (coerce 0 '(dispatch-type x)))
908 (,op (coerce 0 '(dispatch-type y)) y))
909 (((foreach fixnum bignum) ratio)
910 (,op x (,ratio-arg2 (numerator y)
913 (,op (,ratio-arg1 (numerator x)
917 (,op (* (numerator (truly-the ratio x))
918 (denominator (truly-the ratio y)))
919 (* (numerator (truly-the ratio y))
920 (denominator (truly-the ratio x)))))
922 (def-two-arg-</> two-arg-< < floor ceiling
926 (not (bignum-plus-p x)))
928 (minusp (bignum-compare x y))))
929 (def-two-arg-</> two-arg-> > ceiling floor
931 (not (bignum-plus-p y)))
935 (plusp (bignum-compare x y)))))
937 (defun two-arg-= (x y)
938 (number-dispatch ((x number) (y number))
940 ;; An infinite value is never equal to a finite value.
941 :infinite-x-finite-y nil
942 :infinite-y-finite-x nil)
943 ((fixnum (or bignum ratio)) nil)
945 ((bignum (or fixnum ratio)) nil)
947 (zerop (bignum-compare x y)))
949 ((ratio integer) nil)
951 (and (eql (numerator x) (numerator y))
952 (eql (denominator x) (denominator y))))
955 (and (= (realpart x) (realpart y))
956 (= (imagpart x) (imagpart y))))
957 (((foreach fixnum bignum ratio single-float double-float
958 #!+long-float long-float) complex)
959 (and (= x (realpart y))
960 (zerop (imagpart y))))
961 ((complex (or float rational))
962 (and (= (realpart x) y)
963 (zerop (imagpart x))))))
967 (defun logior (&rest integers)
969 "Return the bit-wise or of its arguments. Args must be integers."
970 (declare (list integers))
972 (do ((result (pop integers) (logior result (pop integers))))
973 ((null integers) result)
974 (declare (integer result)))
977 (defun logxor (&rest integers)
979 "Return the bit-wise exclusive or of its arguments. Args must be integers."
980 (declare (list integers))
982 (do ((result (pop integers) (logxor result (pop integers))))
983 ((null integers) result)
984 (declare (integer result)))
987 (defun logand (&rest integers)
989 "Return the bit-wise and of its arguments. Args must be integers."
990 (declare (list integers))
992 (do ((result (pop integers) (logand result (pop integers))))
993 ((null integers) result)
994 (declare (integer result)))
997 (defun logeqv (&rest integers)
999 "Return the bit-wise equivalence of its arguments. Args must be integers."
1000 (declare (list integers))
1002 (do ((result (pop integers) (logeqv result (pop integers))))
1003 ((null integers) result)
1004 (declare (integer result)))
1007 (defun lognot (number)
1009 "Return the bit-wise logical not of integer."
1011 (fixnum (lognot (truly-the fixnum number)))
1012 (bignum (bignum-logical-not number))))
1014 (macrolet ((def (name op big-op &optional doc)
1015 `(defun ,name (integer1 integer2)
1020 (number-dispatch ((x integer) (y integer))
1021 (bignum-cross-fixnum ,op ,big-op))))))
1022 (def two-arg-and logand bignum-logical-and)
1023 (def two-arg-ior logior bignum-logical-ior)
1024 (def two-arg-xor logxor bignum-logical-xor)
1025 ;; BIGNUM-LOGICAL-{AND,IOR,XOR} need not return a bignum, so must
1026 ;; call the generic LOGNOT...
1027 (def two-arg-eqv logeqv (lambda (x y) (lognot (bignum-logical-xor x y))))
1028 (def lognand lognand
1029 (lambda (x y) (lognot (bignum-logical-and x y)))
1030 #!+sb-doc "Complement the logical AND of INTEGER1 and INTEGER2.")
1032 (lambda (x y) (lognot (bignum-logical-ior x y)))
1033 #!+sb-doc "Complement the logical AND of INTEGER1 and INTEGER2.")
1034 ;; ... but BIGNUM-LOGICAL-NOT on a bignum will always return a bignum
1035 (def logandc1 logandc1
1036 (lambda (x y) (bignum-logical-and (bignum-logical-not x) y))
1037 #!+sb-doc "Bitwise AND (LOGNOT INTEGER1) with INTEGER2.")
1038 (def logandc2 logandc2
1039 (lambda (x y) (bignum-logical-and x (bignum-logical-not y)))
1040 #!+sb-doc "Bitwise AND INTEGER1 with (LOGNOT INTEGER2).")
1041 (def logorc1 logorc1
1042 (lambda (x y) (bignum-logical-ior (bignum-logical-not x) y))
1043 #!+sb-doc "Bitwise OR (LOGNOT INTEGER1) with INTEGER2.")
1044 (def logorc2 logorc2
1045 (lambda (x y) (bignum-logical-ior x (bignum-logical-not y)))
1046 #!+sb-doc "Bitwise OR INTEGER1 with (LOGNOT INTEGER2)."))
1048 (defun logcount (integer)
1050 "Count the number of 1 bits if INTEGER is positive, and the number of 0 bits
1051 if INTEGER is negative."
1054 (logcount (truly-the (integer 0
1055 #.(max sb!xc:most-positive-fixnum
1056 (lognot sb!xc:most-negative-fixnum)))
1057 (if (minusp (truly-the fixnum integer))
1058 (lognot (truly-the fixnum integer))
1061 (bignum-logcount integer))))
1063 (defun logtest (integer1 integer2)
1065 "Predicate which returns T if logand of integer1 and integer2 is not zero."
1066 (logtest integer1 integer2))
1068 (defun logbitp (index integer)
1070 "Predicate returns T if bit index of integer is a 1."
1071 (number-dispatch ((index integer) (integer integer))
1072 ((fixnum fixnum) (if (> index #.(- sb!vm:n-word-bits sb!vm:n-lowtag-bits))
1074 (not (zerop (logand integer (ash 1 index))))))
1075 ((fixnum bignum) (bignum-logbitp index integer))
1076 ((bignum (foreach fixnum bignum)) (minusp integer))))
1078 (defun ash (integer count)
1080 "Shifts integer left by count places preserving sign. - count shifts right."
1081 (declare (integer integer count))
1084 (cond ((zerop integer)
1087 (let ((length (integer-length (truly-the fixnum integer)))
1088 (count (truly-the fixnum count)))
1089 (declare (fixnum length count))
1090 (cond ((and (plusp count)
1092 (integer-length most-positive-fixnum)))
1093 (bignum-ashift-left (make-small-bignum integer) count))
1096 (ash (truly-the fixnum integer) count))))))
1098 (if (minusp integer) -1 0))
1100 (bignum-ashift-left (make-small-bignum integer) count))))
1103 (bignum-ashift-left integer count)
1104 (bignum-ashift-right integer (- count))))))
1106 (defun integer-length (integer)
1108 "Return the number of non-sign bits in the twos-complement representation
1112 (integer-length (truly-the fixnum integer)))
1114 (bignum-integer-length integer))))
1116 ;;;; BYTE, bytespecs, and related operations
1118 (defun byte (size position)
1120 "Return a byte specifier which may be used by other byte functions
1122 (byte size position))
1124 (defun byte-size (bytespec)
1126 "Return the size part of the byte specifier bytespec."
1127 (byte-size bytespec))
1129 (defun byte-position (bytespec)
1131 "Return the position part of the byte specifier bytespec."
1132 (byte-position bytespec))
1134 (defun ldb (bytespec integer)
1136 "Extract the specified byte from integer, and right justify result."
1137 (ldb bytespec integer))
1139 (defun ldb-test (bytespec integer)
1141 "Return T if any of the specified bits in integer are 1's."
1142 (ldb-test bytespec integer))
1144 (defun mask-field (bytespec integer)
1146 "Extract the specified byte from integer, but do not right justify result."
1147 (mask-field bytespec integer))
1149 (defun dpb (newbyte bytespec integer)
1151 "Return new integer with newbyte in specified position, newbyte is right justified."
1152 (dpb newbyte bytespec integer))
1154 (defun deposit-field (newbyte bytespec integer)
1156 "Return new integer with newbyte in specified position, newbyte is not right justified."
1157 (deposit-field newbyte bytespec integer))
1159 (defun %ldb (size posn integer)
1160 (logand (ash integer (- posn))
1163 (defun %mask-field (size posn integer)
1164 (logand integer (ash (1- (ash 1 size)) posn)))
1166 (defun %dpb (newbyte size posn integer)
1167 (let ((mask (1- (ash 1 size))))
1168 (logior (logand integer (lognot (ash mask posn)))
1169 (ash (logand newbyte mask) posn))))
1171 (defun %deposit-field (newbyte size posn integer)
1172 (let ((mask (ash (ldb (byte size 0) -1) posn)))
1173 (logior (logand newbyte mask)
1174 (logand integer (lognot mask)))))
1176 (defun sb!c::mask-signed-field (size integer)
1178 "Extract SIZE lower bits from INTEGER, considering them as a
1179 2-complement SIZE-bits representation of a signed integer."
1182 ((logbitp (1- size) integer)
1183 (dpb integer (byte size 0) -1))
1185 (ldb (byte size 0) integer))))
1190 ;;; The boole function dispaches to any logic operation depending on
1191 ;;; the value of a variable. Presently, legal selector values are [0..15].
1192 ;;; boole is open coded for calls with a constant selector. or with calls
1193 ;;; using any of the constants declared below.
1195 (defconstant boole-clr 0
1197 "Boole function op, makes BOOLE return 0.")
1199 (defconstant boole-set 1
1201 "Boole function op, makes BOOLE return -1.")
1203 (defconstant boole-1 2
1205 "Boole function op, makes BOOLE return integer1.")
1207 (defconstant boole-2 3
1209 "Boole function op, makes BOOLE return integer2.")
1211 (defconstant boole-c1 4
1213 "Boole function op, makes BOOLE return complement of integer1.")
1215 (defconstant boole-c2 5
1217 "Boole function op, makes BOOLE return complement of integer2.")
1219 (defconstant boole-and 6
1221 "Boole function op, makes BOOLE return logand of integer1 and integer2.")
1223 (defconstant boole-ior 7
1225 "Boole function op, makes BOOLE return logior of integer1 and integer2.")
1227 (defconstant boole-xor 8
1229 "Boole function op, makes BOOLE return logxor of integer1 and integer2.")
1231 (defconstant boole-eqv 9
1233 "Boole function op, makes BOOLE return logeqv of integer1 and integer2.")
1235 (defconstant boole-nand 10
1237 "Boole function op, makes BOOLE return log nand of integer1 and integer2.")
1239 (defconstant boole-nor 11
1241 "Boole function op, makes BOOLE return lognor of integer1 and integer2.")
1243 (defconstant boole-andc1 12
1245 "Boole function op, makes BOOLE return logandc1 of integer1 and integer2.")
1247 (defconstant boole-andc2 13
1249 "Boole function op, makes BOOLE return logandc2 of integer1 and integer2.")
1251 (defconstant boole-orc1 14
1253 "Boole function op, makes BOOLE return logorc1 of integer1 and integer2.")
1255 (defconstant boole-orc2 15
1257 "Boole function op, makes BOOLE return logorc2 of integer1 and integer2.")
1259 (defun boole (op integer1 integer2)
1261 "Bit-wise boolean function on two integers. Function chosen by OP:
1279 (0 (boole 0 integer1 integer2))
1280 (1 (boole 1 integer1 integer2))
1281 (2 (boole 2 integer1 integer2))
1282 (3 (boole 3 integer1 integer2))
1283 (4 (boole 4 integer1 integer2))
1284 (5 (boole 5 integer1 integer2))
1285 (6 (boole 6 integer1 integer2))
1286 (7 (boole 7 integer1 integer2))
1287 (8 (boole 8 integer1 integer2))
1288 (9 (boole 9 integer1 integer2))
1289 (10 (boole 10 integer1 integer2))
1290 (11 (boole 11 integer1 integer2))
1291 (12 (boole 12 integer1 integer2))
1292 (13 (boole 13 integer1 integer2))
1293 (14 (boole 14 integer1 integer2))
1294 (15 (boole 15 integer1 integer2))
1295 (t (error 'type-error :datum op :expected-type '(mod 16)))))
1299 (defun gcd (&rest integers)
1301 "Return the greatest common divisor of the arguments, which must be
1302 integers. Gcd with no arguments is defined to be 0."
1303 (cond ((null integers) 0)
1304 ((null (cdr integers)) (abs (the integer (car integers))))
1306 (do ((gcd (the integer (car integers))
1307 (gcd gcd (the integer (car rest))))
1308 (rest (cdr integers) (cdr rest)))
1310 (declare (integer gcd)
1313 (defun lcm (&rest integers)
1315 "Return the least common multiple of one or more integers. LCM of no
1316 arguments is defined to be 1."
1317 (cond ((null integers) 1)
1318 ((null (cdr integers)) (abs (the integer (car integers))))
1320 (do ((lcm (the integer (car integers))
1321 (lcm lcm (the integer (car rest))))
1322 (rest (cdr integers) (cdr rest)))
1324 (declare (integer lcm) (list rest))))))
1326 (defun two-arg-lcm (n m)
1327 (declare (integer n m))
1328 (if (or (zerop n) (zerop m))
1330 ;; KLUDGE: I'm going to assume that it was written this way
1331 ;; originally for a reason. However, this is a somewhat
1332 ;; complicated way of writing the algorithm in the CLHS page for
1333 ;; LCM, and I don't know why. To be investigated. -- CSR,
1336 ;; It seems to me that this is written this way to avoid
1337 ;; unnecessary bignumification of intermediate results.
1338 ;; -- TCR, 2008-03-05
1341 (multiple-value-bind (max min)
1345 (* (truncate max (gcd n m)) min)))))
1347 ;;; Do the GCD of two integer arguments. With fixnum arguments, we use the
1348 ;;; binary GCD algorithm from Knuth's seminumerical algorithms (slightly
1349 ;;; structurified), otherwise we call BIGNUM-GCD. We pick off the special case
1350 ;;; of 0 before the dispatch so that the bignum code doesn't have to worry
1351 ;;; about "small bignum" zeros.
1352 (defun two-arg-gcd (u v)
1353 (cond ((eql u 0) (abs v))
1356 (number-dispatch ((u integer) (v integer))
1359 (declare (optimize (speed 3) (safety 0)))
1361 (u (abs u) (ash u -1))
1362 (v (abs v) (ash v -1)))
1363 ((oddp (logior u v))
1364 (do ((temp (if (oddp u) (- v) (ash u -1))
1367 (declare (fixnum temp))
1374 (let ((res (ash u k)))
1375 (declare (type sb!vm:signed-word res)
1376 (optimize (inhibit-warnings 3)))
1378 (declare (type (mod #.sb!vm:n-word-bits) k)
1379 (type sb!vm:signed-word u v)))))
1383 (bignum-gcd u (make-small-bignum v)))
1385 (bignum-gcd (make-small-bignum u) v))))))
1387 ;;; From discussion on comp.lang.lisp and Akira Kurihara.
1390 "Return the root of the nearest integer less than n which is a perfect
1392 (declare (type unsigned-byte n) (values unsigned-byte))
1393 ;; Theoretically (> n 7), i.e., n-len-quarter > 0.
1394 (if (and (fixnump n) (<= n 24))
1400 (let* ((n-len-quarter (ash (integer-length n) -2))
1401 (n-half (ash n (- (ash n-len-quarter 1))))
1402 (n-half-isqrt (isqrt n-half))
1403 (init-value (ash (1+ n-half-isqrt) n-len-quarter)))
1405 (let ((iterated-value
1406 (ash (+ init-value (truncate n init-value)) -1)))
1407 (unless (< iterated-value init-value)
1408 (return init-value))
1409 (setq init-value iterated-value))))))
1411 ;;;; miscellaneous number predicates
1413 (macrolet ((def (name doc)
1414 `(defun ,name (number) ,doc (,name number))))
1415 (def zerop "Is this number zero?")
1416 (def plusp "Is this real number strictly positive?")
1417 (def minusp "Is this real number strictly negative?")
1418 (def oddp "Is this integer odd?")
1419 (def evenp "Is this integer even?"))
1421 ;;;; modular functions
1424 (flet ((unsigned-definition (name lambda-list width)
1425 (let ((pattern (1- (ash 1 width))))
1426 `(defun ,name ,lambda-list
1427 (flet ((prepare-argument (x)
1428 (declare (integer x))
1430 ((unsigned-byte ,width) x)
1431 (fixnum (logand x ,pattern))
1432 (bignum (logand x ,pattern)))))
1433 (,name ,@(loop for arg in lambda-list
1434 collect `(prepare-argument ,arg)))))))
1435 (signed-definition (name lambda-list width)
1436 `(defun ,name ,lambda-list
1437 (flet ((prepare-argument (x)
1438 (declare (integer x))
1440 ((signed-byte ,width) x)
1441 (fixnum (sb!c::mask-signed-field ,width x))
1442 (bignum (sb!c::mask-signed-field ,width x)))))
1443 (,name ,@(loop for arg in lambda-list
1444 collect `(prepare-argument ,arg)))))))
1445 (flet ((do-mfuns (class)
1446 (loop for infos being each hash-value of (sb!c::modular-class-funs class)
1447 ;; FIXME: We need to process only "toplevel" functions
1449 do (loop for info in infos
1450 for name = (sb!c::modular-fun-info-name info)
1451 and width = (sb!c::modular-fun-info-width info)
1452 and signedp = (sb!c::modular-fun-info-signedp info)
1453 and lambda-list = (sb!c::modular-fun-info-lambda-list info)
1455 do (forms (signed-definition name lambda-list width))
1457 do (forms (unsigned-definition name lambda-list width))))))
1458 (do-mfuns sb!c::*untagged-unsigned-modular-class*)
1459 (do-mfuns sb!c::*untagged-signed-modular-class*)
1460 (do-mfuns sb!c::*tagged-modular-class*)))
1463 ;;; KLUDGE: these out-of-line definitions can't use the modular
1464 ;;; arithmetic, as that is only (currently) defined for constant
1465 ;;; shifts. See also the comment in (LOGAND OPTIMIZER) for more
1466 ;;; discussion of this hack. -- CSR, 2003-10-09
1467 #!+#.(cl:if (cl:= sb!vm:n-machine-word-bits 32) '(and) '(or))
1468 (defun sb!vm::ash-left-mod32 (integer amount)
1470 ((unsigned-byte 32) (ldb (byte 32 0) (ash integer amount)))
1471 (fixnum (ldb (byte 32 0) (ash (logand integer #xffffffff) amount)))
1472 (bignum (ldb (byte 32 0) (ash (logand integer #xffffffff) amount)))))
1473 #!+#.(cl:if (cl:= sb!vm:n-machine-word-bits 64) '(and) '(or))
1474 (defun sb!vm::ash-left-mod64 (integer amount)
1476 ((unsigned-byte 64) (ldb (byte 64 0) (ash integer amount)))
1477 (fixnum (ldb (byte 64 0) (ash (logand integer #xffffffffffffffff) amount)))
1478 (bignum (ldb (byte 64 0)
1479 (ash (logand integer #xffffffffffffffff) amount)))))
1482 (defun sb!vm::ash-left-smod30 (integer amount)
1484 ((signed-byte 30) (sb!c::mask-signed-field 30 (ash integer amount)))
1485 (integer (sb!c::mask-signed-field 30 (ash (sb!c::mask-signed-field 30 integer) amount)))))
1488 (defun sb!vm::ash-left-smod61 (integer amount)
1490 ((signed-byte 61) (sb!c::mask-signed-field 61 (ash integer amount)))
1491 (integer (sb!c::mask-signed-field 61 (ash (sb!c::mask-signed-field 61 integer) amount)))))