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 (%make-ratio num den))))
201 ;;; Truncate X and Y, but bum the case where Y is 1.
202 #!-sb-fluid (declaim (inline maybe-truncate))
203 (defun maybe-truncate (x y)
210 (defun upgraded-complex-part-type (spec)
212 "Return the element type of the most specialized COMPLEX number type that
213 can hold parts of type SPEC."
214 (cond ((unknown-type-p (specifier-type spec))
215 (error "undefined type: ~S" spec))
216 ((subtypep spec 'single-float)
218 ((subtypep spec 'double-float)
221 ((subtypep spec 'long-float)
223 ((subtypep spec 'rational)
228 (defun complex (realpart &optional (imagpart 0))
230 "Return a complex number with the specified real and imaginary components."
231 (flet ((%%make-complex (realpart imagpart)
233 ((and (typep realpart 'long-float)
234 (typep imagpart 'long-float))
235 (truly-the (complex long-float)
236 (complex realpart imagpart)))
237 ((and (typep realpart 'double-float)
238 (typep imagpart 'double-float))
239 (truly-the (complex double-float)
240 (complex realpart imagpart)))
241 ((and (typep realpart 'single-float)
242 (typep imagpart 'single-float))
243 (truly-the (complex single-float)
244 (complex realpart imagpart)))
246 (%make-complex realpart imagpart)))))
247 (number-dispatch ((realpart real) (imagpart real))
249 (canonical-complex realpart imagpart))
250 (float-contagion %%make-complex realpart imagpart (rational)))))
252 (defun realpart (number)
254 "Extract the real part of a number."
257 ((complex long-float)
258 (truly-the long-float (realpart number)))
259 ((complex double-float)
260 (truly-the double-float (realpart number)))
261 ((complex single-float)
262 (truly-the single-float (realpart number)))
264 (sb!kernel:%realpart number))
268 (defun imagpart (number)
270 "Extract the imaginary part of a number."
273 ((complex long-float)
274 (truly-the long-float (imagpart number)))
275 ((complex double-float)
276 (truly-the double-float (imagpart number)))
277 ((complex single-float)
278 (truly-the single-float (imagpart number)))
280 (sb!kernel:%imagpart number))
286 (defun conjugate (number)
288 "Return the complex conjugate of NUMBER. For non-complex numbers, this is
290 (if (complexp number)
291 (complex (realpart number) (- (imagpart number)))
294 (defun signum (number)
296 "If NUMBER is zero, return NUMBER, else return (/ NUMBER (ABS NUMBER))."
299 (if (rationalp number)
300 (if (plusp number) 1 -1)
301 (/ number (abs number)))))
305 (defun numerator (number)
307 "Return the numerator of NUMBER, which must be rational."
310 (defun denominator (number)
312 "Return the denominator of NUMBER, which must be rational."
313 (denominator number))
315 ;;;; arithmetic operations
317 (macrolet ((define-arith (op init doc)
318 #!-sb-doc (declare (ignore doc))
319 `(defun ,op (&rest args)
321 (if (null args) ,init
322 (do ((args (cdr args) (cdr args))
323 (res (car args) (,op res (car args))))
324 ((null args) res))))))
326 "Return the sum of its arguments. With no args, returns 0.")
328 "Return the product of its arguments. With no args, returns 1."))
330 (defun - (number &rest more-numbers)
332 "Subtract the second and all subsequent arguments from the first;
333 or with one argument, negate the first argument."
335 (do ((nlist more-numbers (cdr nlist))
337 ((atom nlist) result)
338 (declare (list nlist))
339 (setq result (- result (car nlist))))
342 (defun / (number &rest more-numbers)
344 "Divide the first argument by each of the following arguments, in turn.
345 With one argument, return reciprocal."
347 (do ((nlist more-numbers (cdr nlist))
349 ((atom nlist) result)
350 (declare (list nlist))
351 (setq result (/ result (car nlist))))
364 (eval-when (:compile-toplevel)
366 (sb!xc:defmacro two-arg-+/- (name op big-op)
368 (number-dispatch ((x number) (y number))
369 (bignum-cross-fixnum ,op ,big-op)
370 (float-contagion ,op x y)
373 (canonical-complex (,op (realpart x) (realpart y))
374 (,op (imagpart x) (imagpart y))))
375 (((foreach bignum fixnum ratio single-float double-float
376 #!+long-float long-float) complex)
377 (complex (,op x (realpart y)) (,op (imagpart y))))
378 ((complex (or rational float))
379 (complex (,op (realpart x) y) (imagpart x)))
381 (((foreach fixnum bignum) ratio)
382 (let* ((dy (denominator y))
383 (n (,op (* x dy) (numerator y))))
386 (let* ((dx (denominator x))
387 (n (,op (numerator x) (* y dx))))
390 (let* ((nx (numerator x))
396 (%make-ratio (,op (* nx dy) (* dx ny)) (* dx dy))
397 (let* ((t1 (,op (* nx (truncate dy g1)) (* (truncate dx g1) ny)))
399 (t2 (truncate dx g1)))
402 (%make-ratio t1 (* t2 dy)))
403 (T (let* ((nn (truncate t1 g2))
404 (t3 (truncate dy g2))
405 (nd (if (eql t2 1) t3 (* t2 t3))))
406 (if (eql nd 1) nn (%make-ratio nn nd))))))))))))
408 ); Eval-When (Compile)
410 (two-arg-+/- two-arg-+ + add-bignums)
411 (two-arg-+/- two-arg-- - subtract-bignum)
413 (defun two-arg-* (x y)
414 (flet ((integer*ratio (x y)
416 (let* ((ny (numerator y))
420 (%make-ratio (* x ny) dy)
421 (let ((nn (* (truncate x gcd) ny))
422 (nd (truncate dy gcd)))
425 (%make-ratio nn nd)))))))
427 (canonical-complex (* (realpart x) y) (* (imagpart x) y))))
428 (number-dispatch ((x number) (y number))
429 (float-contagion * x y)
431 ((fixnum fixnum) (multiply-fixnums x y))
432 ((bignum fixnum) (multiply-bignum-and-fixnum x y))
433 ((fixnum bignum) (multiply-bignum-and-fixnum y x))
434 ((bignum bignum) (multiply-bignums x y))
437 (let* ((rx (realpart x))
441 (canonical-complex (- (* rx ry) (* ix iy)) (+ (* rx iy) (* ix ry)))))
442 (((foreach bignum fixnum ratio single-float double-float
443 #!+long-float long-float)
446 ((complex (or rational float))
449 (((foreach bignum fixnum) ratio) (integer*ratio x y))
450 ((ratio integer) (integer*ratio y x))
452 (let* ((nx (numerator x))
458 (build-ratio (* (maybe-truncate nx g1)
459 (maybe-truncate ny g2))
460 (* (maybe-truncate dx g2)
461 (maybe-truncate dy g1))))))))
463 ;;; Divide two integers, producing a canonical rational. If a fixnum,
464 ;;; we see whether they divide evenly before trying the GCD. In the
465 ;;; bignum case, we don't bother, since bignum division is expensive,
466 ;;; and the test is not very likely to succeed.
467 (defun integer-/-integer (x y)
468 (if (and (typep x 'fixnum) (typep y 'fixnum))
469 (multiple-value-bind (quo rem) (truncate x y)
472 (let ((gcd (gcd x y)))
473 (declare (fixnum gcd))
476 (build-ratio (truncate x gcd) (truncate y gcd))))))
477 (let ((gcd (gcd x y)))
480 (build-ratio (truncate x gcd) (truncate y gcd))))))
482 (defun two-arg-/ (x y)
483 (number-dispatch ((x number) (y number))
484 (float-contagion / x y (ratio integer))
487 (let* ((rx (realpart x))
491 (if (> (abs ry) (abs iy))
493 (dn (* ry (+ 1 (* r r)))))
494 (canonical-complex (/ (+ rx (* ix r)) dn)
495 (/ (- ix (* rx r)) dn)))
497 (dn (* iy (+ 1 (* r r)))))
498 (canonical-complex (/ (+ (* rx r) ix) dn)
499 (/ (- (* ix r) rx) dn))))))
500 (((foreach integer ratio single-float double-float) complex)
501 (let* ((ry (realpart y))
503 (if (> (abs ry) (abs iy))
505 (dn (* ry (+ 1 (* r r)))))
506 (canonical-complex (/ x dn)
509 (dn (* iy (+ 1 (* r r)))))
510 (canonical-complex (/ (* x r) dn)
512 ((complex (or rational float))
513 (canonical-complex (/ (realpart x) y)
517 (let* ((nx (numerator x))
523 (build-ratio (* (maybe-truncate nx g1) (maybe-truncate dy g2))
524 (* (maybe-truncate dx g2) (maybe-truncate ny g1)))))
527 (integer-/-integer x y))
532 (let* ((ny (numerator y))
535 (build-ratio (* (maybe-truncate x gcd) dy)
536 (maybe-truncate ny gcd)))))
539 (let* ((nx (numerator x))
541 (build-ratio (maybe-truncate nx gcd)
542 (* (maybe-truncate y gcd) (denominator x)))))))
545 (number-dispatch ((n number))
546 (((foreach fixnum single-float double-float #!+long-float long-float))
551 (%make-ratio (- (numerator n)) (denominator n)))
553 (complex (- (realpart n)) (- (imagpart n))))))
555 ;;;; TRUNCATE and friends
557 (defun truncate (number &optional (divisor 1))
559 "Return number (or number/divisor) as an integer, rounded toward 0.
560 The second returned value is the remainder."
561 (macrolet ((truncate-float (rtype)
562 `(let* ((float-div (coerce divisor ',rtype))
563 (res (%unary-truncate (/ number float-div))))
566 (* (coerce res ',rtype) float-div))))))
567 (number-dispatch ((number real) (divisor real))
568 ((fixnum fixnum) (truncate number divisor))
569 (((foreach fixnum bignum) ratio)
570 (let ((q (truncate (* number (denominator divisor))
571 (numerator divisor))))
572 (values q (- number (* q divisor)))))
575 ((ratio (or float rational))
576 (let ((q (truncate (numerator number)
577 (* (denominator number) divisor))))
578 (values q (- number (* q divisor)))))
580 (bignum-truncate number (make-small-bignum divisor)))
582 (bignum-truncate number divisor))
584 (((foreach single-float double-float #!+long-float long-float)
585 (or rational single-float))
587 (let ((res (%unary-truncate number)))
588 (values res (- number (coerce res '(dispatch-type number)))))
589 (truncate-float (dispatch-type number))))
591 ((long-float (or single-float double-float long-float))
592 (truncate-float long-float))
594 (((foreach double-float single-float) long-float)
595 (truncate-float long-float))
596 ((double-float (or single-float double-float))
597 (truncate-float double-float))
598 ((single-float double-float)
599 (truncate-float double-float))
600 (((foreach fixnum bignum ratio)
601 (foreach single-float double-float #!+long-float long-float))
602 (truncate-float (dispatch-type divisor))))))
604 ;;; Declare these guys inline to let them get optimized a little.
605 ;;; ROUND and FROUND are not declared inline since they seem too
606 ;;; obscure and too big to inline-expand by default. Also, this gives
607 ;;; the compiler a chance to pick off the unary float case. Similarly,
608 ;;; CEILING and FLOOR are only maybe-inline for now, so that the
609 ;;; power-of-2 CEILING and FLOOR transforms get a chance.
610 #!-sb-fluid (declaim (inline rem mod fceiling ffloor ftruncate))
611 (declaim (maybe-inline ceiling floor))
613 (defun floor (number &optional (divisor 1))
615 "Return the greatest integer not greater than number, or number/divisor.
616 The second returned value is (mod number divisor)."
617 ;; If the numbers do not divide exactly and the result of
618 ;; (/ NUMBER DIVISOR) would be negative then decrement the quotient
619 ;; and augment the remainder by the divisor.
620 (multiple-value-bind (tru rem) (truncate number divisor)
621 (if (and (not (zerop rem))
625 (values (1- tru) (+ rem divisor))
628 (defun ceiling (number &optional (divisor 1))
630 "Return the smallest integer not less than number, or number/divisor.
631 The second returned value is the remainder."
632 ;; If the numbers do not divide exactly and the result of
633 ;; (/ NUMBER DIVISOR) would be positive then increment the quotient
634 ;; and decrement the remainder by the divisor.
635 (multiple-value-bind (tru rem) (truncate number divisor)
636 (if (and (not (zerop rem))
640 (values (+ tru 1) (- rem divisor))
643 (defun round (number &optional (divisor 1))
645 "Rounds number (or number/divisor) to nearest integer.
646 The second returned value is the remainder."
649 (multiple-value-bind (tru rem) (truncate number divisor)
650 (let ((thresh (/ (abs divisor) 2)))
651 (cond ((or (> rem thresh)
652 (and (= rem thresh) (oddp tru)))
654 (values (- tru 1) (+ rem divisor))
655 (values (+ tru 1) (- rem divisor))))
656 ((let ((-thresh (- thresh)))
658 (and (= rem -thresh) (oddp tru))))
660 (values (+ tru 1) (- rem divisor))
661 (values (- tru 1) (+ rem divisor))))
662 (t (values tru rem)))))))
664 (defun rem (number divisor)
666 "Return second result of TRUNCATE."
667 (multiple-value-bind (tru rem) (truncate number divisor)
668 (declare (ignore tru))
671 (defun mod (number divisor)
673 "Return second result of FLOOR."
674 (let ((rem (rem number divisor)))
675 (if (and (not (zerop rem))
682 (macrolet ((def (name op doc)
683 `(defun ,name (number &optional (divisor 1))
685 (multiple-value-bind (res rem) (,op number divisor)
686 (values (float res (if (floatp rem) rem 1.0)) rem)))))
688 "Same as FLOOR, but returns first value as a float.")
689 (def fceiling ceiling
690 "Same as CEILING, but returns first value as a float." )
691 (def ftruncate truncate
692 "Same as TRUNCATE, but returns first value as a float.")
694 "Same as ROUND, but returns first value as a float."))
698 (defun = (number &rest more-numbers)
700 "Return T if all of its arguments are numerically equal, NIL otherwise."
701 (do ((nlist more-numbers (cdr nlist)))
703 (declare (list nlist))
704 (if (not (= (car nlist) number)) (return nil))))
706 (defun /= (number &rest more-numbers)
708 "Return T if no two of its arguments are numerically equal, NIL otherwise."
709 (do* ((head number (car nlist))
710 (nlist more-numbers (cdr nlist)))
712 (declare (list nlist))
713 (unless (do* ((nl nlist (cdr nl)))
716 (if (= head (car nl)) (return nil)))
719 (defun < (number &rest more-numbers)
721 "Return T if its arguments are in strictly increasing order, NIL otherwise."
722 (do* ((n number (car nlist))
723 (nlist more-numbers (cdr nlist)))
725 (declare (list nlist))
726 (if (not (< n (car nlist))) (return nil))))
728 (defun > (number &rest more-numbers)
730 "Return T if its arguments are in strictly decreasing order, NIL otherwise."
731 (do* ((n number (car nlist))
732 (nlist more-numbers (cdr nlist)))
734 (declare (list nlist))
735 (if (not (> n (car nlist))) (return nil))))
737 (defun <= (number &rest more-numbers)
739 "Return T if arguments are in strictly non-decreasing order, NIL otherwise."
740 (do* ((n number (car nlist))
741 (nlist more-numbers (cdr nlist)))
743 (declare (list nlist))
744 (if (not (<= n (car nlist))) (return nil))))
746 (defun >= (number &rest more-numbers)
748 "Return T if arguments are in strictly non-increasing order, NIL otherwise."
749 (do* ((n number (car nlist))
750 (nlist more-numbers (cdr nlist)))
752 (declare (list nlist))
753 (if (not (>= n (car nlist))) (return nil))))
755 (defun max (number &rest more-numbers)
757 "Return the greatest of its arguments."
758 (do ((nlist more-numbers (cdr nlist))
760 ((null nlist) (return result))
761 (declare (list nlist))
762 (if (> (car nlist) result) (setq result (car nlist)))))
764 (defun min (number &rest more-numbers)
766 "Return the least of its arguments."
767 (do ((nlist more-numbers (cdr nlist))
769 ((null nlist) (return result))
770 (declare (list nlist))
771 (if (< (car nlist) result) (setq result (car nlist)))))
773 (eval-when (:compile-toplevel :execute)
775 ;;; The INFINITE-X-FINITE-Y and INFINITE-Y-FINITE-X args tell us how
776 ;;; to handle the case when X or Y is a floating-point infinity and
777 ;;; the other arg is a rational. (Section 12.1.4.1 of the ANSI spec
778 ;;; says that comparisons are done by converting the float to a
779 ;;; rational when comparing with a rational, but infinities can't be
780 ;;; converted to a rational, so we show some initiative and do it this
782 (defun basic-compare (op &key infinite-x-finite-y infinite-y-finite-x)
783 `(((fixnum fixnum) (,op x y))
785 ((single-float single-float) (,op x y))
787 (((foreach single-float double-float long-float) long-float)
788 (,op (coerce x 'long-float) y))
790 ((long-float (foreach single-float double-float))
791 (,op x (coerce y 'long-float)))
792 (((foreach single-float double-float) double-float)
793 (,op (coerce x 'double-float) y))
794 ((double-float single-float)
795 (,op x (coerce y 'double-float)))
796 (((foreach single-float double-float #!+long-float long-float) rational)
798 (,op x (coerce 0 '(dispatch-type x)))
799 (if (float-infinity-p x)
801 (,op (rational x) y))))
802 (((foreach bignum fixnum ratio) float)
803 (if (float-infinity-p y)
805 (,op x (rational y))))))
808 (macrolet ((def-two-arg-</> (name op ratio-arg1 ratio-arg2 &rest cases)
810 (number-dispatch ((x real) (y real))
814 (,op x (coerce 0 '(dispatch-type x)))
816 (,op (coerce 0 '(dispatch-type y)) y))
817 (((foreach fixnum bignum) ratio)
818 (,op x (,ratio-arg2 (numerator y)
821 (,op (,ratio-arg1 (numerator x)
825 (,op (* (numerator (truly-the ratio x))
826 (denominator (truly-the ratio y)))
827 (* (numerator (truly-the ratio y))
828 (denominator (truly-the ratio x)))))
830 (def-two-arg-</> two-arg-< < floor ceiling
834 (not (bignum-plus-p x)))
836 (minusp (bignum-compare x y))))
837 (def-two-arg-</> two-arg-> > ceiling floor
839 (not (bignum-plus-p y)))
843 (plusp (bignum-compare x y)))))
845 (defun two-arg-= (x y)
846 (number-dispatch ((x number) (y number))
848 ;; An infinite value is never equal to a finite value.
849 :infinite-x-finite-y nil
850 :infinite-y-finite-x nil)
851 ((fixnum (or bignum ratio)) nil)
853 ((bignum (or fixnum ratio)) nil)
855 (zerop (bignum-compare x y)))
857 ((ratio integer) nil)
859 (and (eql (numerator x) (numerator y))
860 (eql (denominator x) (denominator y))))
863 (and (= (realpart x) (realpart y))
864 (= (imagpart x) (imagpart y))))
865 (((foreach fixnum bignum ratio single-float double-float
866 #!+long-float long-float) complex)
867 (and (= x (realpart y))
868 (zerop (imagpart y))))
869 ((complex (or float rational))
870 (and (= (realpart x) y)
871 (zerop (imagpart x))))))
873 (defun eql (obj1 obj2)
875 "Return T if OBJ1 and OBJ2 represent the same object, otherwise NIL."
877 (if (or (typep obj2 'fixnum)
878 (not (typep obj2 'number)))
880 (macrolet ((foo (&rest stuff)
882 ,@(mapcar (lambda (foo)
883 (let ((type (car foo))
886 (and (typep obj1 ',type)
896 (zerop (bignum-compare x y))))
899 (and (eql (numerator x) (numerator y))
900 (eql (denominator x) (denominator y)))))
903 (and (eql (realpart x) (realpart y))
904 (eql (imagpart x) (imagpart y))))))))))
908 (defun logior (&rest integers)
910 "Return the bit-wise or of its arguments. Args must be integers."
911 (declare (list integers))
913 (do ((result (pop integers) (logior result (pop integers))))
914 ((null integers) result))
917 (defun logxor (&rest integers)
919 "Return the bit-wise exclusive or of its arguments. Args must be integers."
920 (declare (list integers))
922 (do ((result (pop integers) (logxor result (pop integers))))
923 ((null integers) result))
926 (defun logand (&rest integers)
928 "Return the bit-wise and of its arguments. Args must be integers."
929 (declare (list integers))
931 (do ((result (pop integers) (logand result (pop integers))))
932 ((null integers) result))
935 (defun logeqv (&rest integers)
937 "Return the bit-wise equivalence of its arguments. Args must be integers."
938 (declare (list integers))
940 (do ((result (pop integers) (logeqv result (pop integers))))
941 ((null integers) result))
944 (defun lognand (integer1 integer2)
946 "Return the complement of the logical AND of integer1 and integer2."
947 (lognand integer1 integer2))
949 (defun lognor (integer1 integer2)
951 "Return the complement of the logical OR of integer1 and integer2."
952 (lognor integer1 integer2))
954 (defun logandc1 (integer1 integer2)
956 "Return the logical AND of (LOGNOT integer1) and integer2."
957 (logandc1 integer1 integer2))
959 (defun logandc2 (integer1 integer2)
961 "Return the logical AND of integer1 and (LOGNOT integer2)."
962 (logandc2 integer1 integer2))
964 (defun logorc1 (integer1 integer2)
966 "Return the logical OR of (LOGNOT integer1) and integer2."
967 (logorc1 integer1 integer2))
969 (defun logorc2 (integer1 integer2)
971 "Return the logical OR of integer1 and (LOGNOT integer2)."
972 (logorc2 integer1 integer2))
974 (defun lognot (number)
976 "Return the bit-wise logical not of integer."
978 (fixnum (lognot (truly-the fixnum number)))
979 (bignum (bignum-logical-not number))))
981 (macrolet ((def (name op big-op)
983 (number-dispatch ((x integer) (y integer))
984 (bignum-cross-fixnum ,op ,big-op)))))
985 (def two-arg-and logand bignum-logical-and)
986 (def two-arg-ior logior bignum-logical-ior)
987 (def two-arg-xor logxor bignum-logical-xor))
989 (defun logcount (integer)
991 "Count the number of 1 bits if INTEGER is positive, and the number of 0 bits
992 if INTEGER is negative."
995 (logcount (truly-the (integer 0 #.(max most-positive-fixnum
996 (lognot most-negative-fixnum)))
997 (if (minusp (truly-the fixnum integer))
998 (lognot (truly-the fixnum integer))
1001 (bignum-logcount integer))))
1003 (defun logtest (integer1 integer2)
1005 "Predicate which returns T if logand of integer1 and integer2 is not zero."
1006 (logtest integer1 integer2))
1008 (defun logbitp (index integer)
1010 "Predicate returns T if bit index of integer is a 1."
1011 (logbitp index integer))
1013 (defun ash (integer count)
1015 "Shifts integer left by count places preserving sign. - count shifts right."
1016 (declare (integer integer count))
1019 (cond ((zerop integer)
1022 (let ((length (integer-length (truly-the fixnum integer)))
1023 (count (truly-the fixnum count)))
1024 (declare (fixnum length count))
1025 (cond ((and (plusp count)
1027 (integer-length most-positive-fixnum)))
1028 (bignum-ashift-left (make-small-bignum integer) count))
1031 (ash (truly-the fixnum integer) count))))))
1033 (if (minusp integer) -1 0))
1035 (bignum-ashift-left (make-small-bignum integer) count))))
1038 (bignum-ashift-left integer count)
1039 (bignum-ashift-right integer (- count))))))
1041 (defun integer-length (integer)
1043 "Return the number of significant bits in the absolute value of integer."
1046 (integer-length (truly-the fixnum integer)))
1048 (bignum-integer-length integer))))
1050 ;;;; BYTE, bytespecs, and related operations
1052 (defun byte (size position)
1054 "Return a byte specifier which may be used by other byte functions
1056 (byte size position))
1058 (defun byte-size (bytespec)
1060 "Return the size part of the byte specifier bytespec."
1061 (byte-size bytespec))
1063 (defun byte-position (bytespec)
1065 "Return the position part of the byte specifier bytespec."
1066 (byte-position bytespec))
1068 (defun ldb (bytespec integer)
1070 "Extract the specified byte from integer, and right justify result."
1071 (ldb bytespec integer))
1073 (defun ldb-test (bytespec integer)
1075 "Return T if any of the specified bits in integer are 1's."
1076 (ldb-test bytespec integer))
1078 (defun mask-field (bytespec integer)
1080 "Extract the specified byte from integer, but do not right justify result."
1081 (mask-field bytespec integer))
1083 (defun dpb (newbyte bytespec integer)
1085 "Return new integer with newbyte in specified position, newbyte is right justified."
1086 (dpb newbyte bytespec integer))
1088 (defun deposit-field (newbyte bytespec integer)
1090 "Return new integer with newbyte in specified position, newbyte is not right justified."
1091 (deposit-field newbyte bytespec integer))
1093 (defun %ldb (size posn integer)
1094 (logand (ash integer (- posn))
1097 (defun %mask-field (size posn integer)
1098 (logand integer (ash (1- (ash 1 size)) posn)))
1100 (defun %dpb (newbyte size posn integer)
1101 (let ((mask (1- (ash 1 size))))
1102 (logior (logand integer (lognot (ash mask posn)))
1103 (ash (logand newbyte mask) posn))))
1105 (defun %deposit-field (newbyte size posn integer)
1106 (let ((mask (ash (ldb (byte size 0) -1) posn)))
1107 (logior (logand newbyte mask)
1108 (logand integer (lognot mask)))))
1112 ;;; The boole function dispaches to any logic operation depending on
1113 ;;; the value of a variable. Presently, legal selector values are [0..15].
1114 ;;; boole is open coded for calls with a constant selector. or with calls
1115 ;;; using any of the constants declared below.
1117 (defconstant boole-clr 0
1119 "Boole function op, makes BOOLE return 0.")
1121 (defconstant boole-set 1
1123 "Boole function op, makes BOOLE return -1.")
1125 (defconstant boole-1 2
1127 "Boole function op, makes BOOLE return integer1.")
1129 (defconstant boole-2 3
1131 "Boole function op, makes BOOLE return integer2.")
1133 (defconstant boole-c1 4
1135 "Boole function op, makes BOOLE return complement of integer1.")
1137 (defconstant boole-c2 5
1139 "Boole function op, makes BOOLE return complement of integer2.")
1141 (defconstant boole-and 6
1143 "Boole function op, makes BOOLE return logand of integer1 and integer2.")
1145 (defconstant boole-ior 7
1147 "Boole function op, makes BOOLE return logior of integer1 and integer2.")
1149 (defconstant boole-xor 8
1151 "Boole function op, makes BOOLE return logxor of integer1 and integer2.")
1153 (defconstant boole-eqv 9
1155 "Boole function op, makes BOOLE return logeqv of integer1 and integer2.")
1157 (defconstant boole-nand 10
1159 "Boole function op, makes BOOLE return log nand of integer1 and integer2.")
1161 (defconstant boole-nor 11
1163 "Boole function op, makes BOOLE return lognor of integer1 and integer2.")
1165 (defconstant boole-andc1 12
1167 "Boole function op, makes BOOLE return logandc1 of integer1 and integer2.")
1169 (defconstant boole-andc2 13
1171 "Boole function op, makes BOOLE return logandc2 of integer1 and integer2.")
1173 (defconstant boole-orc1 14
1175 "Boole function op, makes BOOLE return logorc1 of integer1 and integer2.")
1177 (defconstant boole-orc2 15
1179 "Boole function op, makes BOOLE return logorc2 of integer1 and integer2.")
1181 (defun boole (op integer1 integer2)
1183 "Bit-wise boolean function on two integers. Function chosen by OP:
1201 (0 (boole 0 integer1 integer2))
1202 (1 (boole 1 integer1 integer2))
1203 (2 (boole 2 integer1 integer2))
1204 (3 (boole 3 integer1 integer2))
1205 (4 (boole 4 integer1 integer2))
1206 (5 (boole 5 integer1 integer2))
1207 (6 (boole 6 integer1 integer2))
1208 (7 (boole 7 integer1 integer2))
1209 (8 (boole 8 integer1 integer2))
1210 (9 (boole 9 integer1 integer2))
1211 (10 (boole 10 integer1 integer2))
1212 (11 (boole 11 integer1 integer2))
1213 (12 (boole 12 integer1 integer2))
1214 (13 (boole 13 integer1 integer2))
1215 (14 (boole 14 integer1 integer2))
1216 (15 (boole 15 integer1 integer2))
1217 (t (error 'type-error :datum op :expected-type '(mod 16)))))
1221 (defun gcd (&rest numbers)
1223 "Return the greatest common divisor of the arguments, which must be
1224 integers. Gcd with no arguments is defined to be 0."
1225 (cond ((null numbers) 0)
1226 ((null (cdr numbers)) (abs (the integer (car numbers))))
1228 (do ((gcd (the integer (car numbers))
1229 (gcd gcd (the integer (car rest))))
1230 (rest (cdr numbers) (cdr rest)))
1232 (declare (integer gcd)
1235 (defun lcm (&rest numbers)
1237 "Return the least common multiple of one or more integers. LCM of no
1238 arguments is defined to be 1."
1239 (cond ((null numbers) 1)
1240 ((null (cdr numbers)) (abs (the integer (car numbers))))
1242 (do ((lcm (the integer (car numbers))
1243 (lcm lcm (the integer (car rest))))
1244 (rest (cdr numbers) (cdr rest)))
1246 (declare (integer lcm) (list rest))))))
1248 (defun two-arg-lcm (n m)
1249 (declare (integer n m))
1250 (* (truncate (max n m) (gcd n m)) (min n m)))
1252 ;;; Do the GCD of two integer arguments. With fixnum arguments, we use the
1253 ;;; binary GCD algorithm from Knuth's seminumerical algorithms (slightly
1254 ;;; structurified), otherwise we call BIGNUM-GCD. We pick off the special case
1255 ;;; of 0 before the dispatch so that the bignum code doesn't have to worry
1256 ;;; about "small bignum" zeros.
1257 (defun two-arg-gcd (u v)
1261 (number-dispatch ((u integer) (v integer))
1264 (declare (optimize (speed 3) (safety 0)))
1266 (u (abs u) (ash u -1))
1267 (v (abs v) (ash v -1)))
1268 ((oddp (logior u v))
1269 (do ((temp (if (oddp u) (- v) (ash u -1))
1272 (declare (fixnum temp))
1279 (let ((res (ash u k)))
1280 (declare (type (signed-byte 31) res)
1281 (optimize (inhibit-warnings 3)))
1283 (declare (type (mod 30) k)
1284 (type (signed-byte 31) u v)))))
1288 (bignum-gcd u (make-small-bignum v)))
1290 (bignum-gcd (make-small-bignum u) v))))))
1292 ;;; From discussion on comp.lang.lisp and Akira Kurihara.
1295 "Return the root of the nearest integer less than n which is a perfect
1297 (declare (type unsigned-byte n) (values unsigned-byte))
1298 ;; Theoretically (> n 7), i.e., n-len-quarter > 0.
1299 (if (and (fixnump n) (<= n 24))
1305 (let* ((n-len-quarter (ash (integer-length n) -2))
1306 (n-half (ash n (- (ash n-len-quarter 1))))
1307 (n-half-isqrt (isqrt n-half))
1308 (init-value (ash (1+ n-half-isqrt) n-len-quarter)))
1310 (let ((iterated-value
1311 (ash (+ init-value (truncate n init-value)) -1)))
1312 (unless (< iterated-value init-value)
1313 (return init-value))
1314 (setq init-value iterated-value))))))
1316 ;;;; miscellaneous number predicates
1318 (macrolet ((def (name doc)
1319 `(defun ,name (number) ,doc (,name number))))
1320 (def zerop "Is this number zero?")
1321 (def plusp "Is this real number strictly positive?")
1322 (def minusp "Is this real number strictly negative?")
1323 (def oddp "Is this integer odd?")
1324 (def evenp "Is this integer even?"))