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 (if (complexp number)
277 (complex (realpart number) (- (imagpart number)))
280 (defun signum (number)
282 "If NUMBER is zero, return NUMBER, else return (/ NUMBER (ABS NUMBER))."
285 (if (rationalp number)
286 (if (plusp number) 1 -1)
287 (/ number (abs number)))))
291 (defun numerator (number)
293 "Return the numerator of NUMBER, which must be rational."
296 (defun denominator (number)
298 "Return the denominator of NUMBER, which must be rational."
299 (denominator number))
301 ;;;; arithmetic operations
303 (macrolet ((define-arith (op init doc)
304 #!-sb-doc (declare (ignore doc))
305 `(defun ,op (&rest args)
307 (if (null args) ,init
308 (do ((args (cdr args) (cdr args))
309 (result (car args) (,op result (car args))))
311 ;; to signal TYPE-ERROR when exactly 1 arg of wrong type:
312 (declare (type number result)))))))
314 "Return the sum of its arguments. With no args, returns 0.")
316 "Return the product of its arguments. With no args, returns 1."))
318 (defun - (number &rest more-numbers)
320 "Subtract the second and all subsequent arguments from the first;
321 or with one argument, negate the first argument."
323 (do ((nlist more-numbers (cdr nlist))
325 ((atom nlist) result)
326 (declare (list nlist))
327 (setq result (- result (car nlist))))
330 (defun / (number &rest more-numbers)
332 "Divide the first argument by each of the following arguments, in turn.
333 With one argument, return reciprocal."
335 (do ((nlist more-numbers (cdr nlist))
337 ((atom nlist) result)
338 (declare (list nlist))
339 (setq result (/ result (car nlist))))
352 (eval-when (:compile-toplevel)
354 (sb!xc:defmacro two-arg-+/- (name op big-op)
356 (number-dispatch ((x number) (y number))
357 (bignum-cross-fixnum ,op ,big-op)
358 (float-contagion ,op x y)
361 (canonical-complex (,op (realpart x) (realpart y))
362 (,op (imagpart x) (imagpart y))))
363 (((foreach bignum fixnum ratio single-float double-float
364 #!+long-float long-float) complex)
365 (complex (,op x (realpart y)) (,op (imagpart y))))
366 ((complex (or rational float))
367 (complex (,op (realpart x) y) (imagpart x)))
369 (((foreach fixnum bignum) ratio)
370 (let* ((dy (denominator y))
371 (n (,op (* x dy) (numerator y))))
374 (let* ((dx (denominator x))
375 (n (,op (numerator x) (* y dx))))
378 (let* ((nx (numerator x))
384 (%make-ratio (,op (* nx dy) (* dx ny)) (* dx dy))
385 (let* ((t1 (,op (* nx (truncate dy g1)) (* (truncate dx g1) ny)))
387 (t2 (truncate dx g1)))
390 (%make-ratio t1 (* t2 dy)))
391 (T (let* ((nn (truncate t1 g2))
392 (t3 (truncate dy g2))
393 (nd (if (eql t2 1) t3 (* t2 t3))))
394 (if (eql nd 1) nn (%make-ratio nn nd))))))))))))
398 (two-arg-+/- two-arg-+ + add-bignums)
399 (two-arg-+/- two-arg-- - subtract-bignum)
401 (defun two-arg-* (x y)
402 (flet ((integer*ratio (x y)
404 (let* ((ny (numerator y))
408 (%make-ratio (* x ny) dy)
409 (let ((nn (* (truncate x gcd) ny))
410 (nd (truncate dy gcd)))
413 (%make-ratio nn nd)))))))
415 (canonical-complex (* (realpart x) y) (* (imagpart x) y))))
416 (number-dispatch ((x number) (y number))
417 (float-contagion * x y)
419 ((fixnum fixnum) (multiply-fixnums x y))
420 ((bignum fixnum) (multiply-bignum-and-fixnum x y))
421 ((fixnum bignum) (multiply-bignum-and-fixnum y x))
422 ((bignum bignum) (multiply-bignums x y))
425 (let* ((rx (realpart x))
429 (canonical-complex (- (* rx ry) (* ix iy)) (+ (* rx iy) (* ix ry)))))
430 (((foreach bignum fixnum ratio single-float double-float
431 #!+long-float long-float)
434 ((complex (or rational float))
437 (((foreach bignum fixnum) ratio) (integer*ratio x y))
438 ((ratio integer) (integer*ratio y x))
440 (let* ((nx (numerator x))
446 (build-ratio (* (maybe-truncate nx g1)
447 (maybe-truncate ny g2))
448 (* (maybe-truncate dx g2)
449 (maybe-truncate dy g1))))))))
451 ;;; Divide two integers, producing a canonical rational. If a fixnum,
452 ;;; we see whether they divide evenly before trying the GCD. In the
453 ;;; bignum case, we don't bother, since bignum division is expensive,
454 ;;; and the test is not very likely to succeed.
455 (defun integer-/-integer (x y)
456 (if (and (typep x 'fixnum) (typep y 'fixnum))
457 (multiple-value-bind (quo rem) (truncate x y)
460 (let ((gcd (gcd x y)))
461 (declare (fixnum gcd))
464 (build-ratio (truncate x gcd) (truncate y gcd))))))
465 (let ((gcd (gcd x y)))
468 (build-ratio (truncate x gcd) (truncate y gcd))))))
470 (defun two-arg-/ (x y)
471 (number-dispatch ((x number) (y number))
472 (float-contagion / x y (ratio integer))
475 (let* ((rx (realpart x))
479 (if (> (abs ry) (abs iy))
481 (dn (* ry (+ 1 (* r r)))))
482 (canonical-complex (/ (+ rx (* ix r)) dn)
483 (/ (- ix (* rx r)) dn)))
485 (dn (* iy (+ 1 (* r r)))))
486 (canonical-complex (/ (+ (* rx r) ix) dn)
487 (/ (- (* ix r) rx) dn))))))
488 (((foreach integer ratio single-float double-float) complex)
489 (let* ((ry (realpart y))
491 (if (> (abs ry) (abs iy))
493 (dn (* ry (+ 1 (* r r)))))
494 (canonical-complex (/ x dn)
497 (dn (* iy (+ 1 (* r r)))))
498 (canonical-complex (/ (* x r) dn)
500 ((complex (or rational float))
501 (canonical-complex (/ (realpart x) y)
505 (let* ((nx (numerator x))
511 (build-ratio (* (maybe-truncate nx g1) (maybe-truncate dy g2))
512 (* (maybe-truncate dx g2) (maybe-truncate ny g1)))))
515 (integer-/-integer x y))
520 (let* ((ny (numerator y))
523 (build-ratio (* (maybe-truncate x gcd) dy)
524 (maybe-truncate ny gcd)))))
527 (let* ((nx (numerator x))
529 (build-ratio (maybe-truncate nx gcd)
530 (* (maybe-truncate y gcd) (denominator x)))))))
533 (number-dispatch ((n number))
534 (((foreach fixnum single-float double-float #!+long-float long-float))
539 (%make-ratio (- (numerator n)) (denominator n)))
541 (complex (- (realpart n)) (- (imagpart n))))))
543 ;;;; TRUNCATE and friends
545 (defun truncate (number &optional (divisor 1))
547 "Return number (or number/divisor) as an integer, rounded toward 0.
548 The second returned value is the remainder."
549 (macrolet ((truncate-float (rtype)
550 `(let* ((float-div (coerce divisor ',rtype))
551 (res (%unary-truncate (/ number float-div))))
554 (* (coerce res ',rtype) float-div))))))
555 (number-dispatch ((number real) (divisor real))
556 ((fixnum fixnum) (truncate number divisor))
557 (((foreach fixnum bignum) ratio)
558 (let ((q (truncate (* number (denominator divisor))
559 (numerator divisor))))
560 (values q (- number (* q divisor)))))
562 (bignum-truncate (make-small-bignum number) divisor))
563 ((ratio (or float rational))
564 (let ((q (truncate (numerator number)
565 (* (denominator number) divisor))))
566 (values q (- number (* q divisor)))))
568 (bignum-truncate number (make-small-bignum divisor)))
570 (bignum-truncate number divisor))
572 (((foreach single-float double-float #!+long-float long-float)
573 (or rational single-float))
575 (let ((res (%unary-truncate number)))
576 (values res (- number (coerce res '(dispatch-type number)))))
577 (truncate-float (dispatch-type number))))
579 ((long-float (or single-float double-float long-float))
580 (truncate-float long-float))
582 (((foreach double-float single-float) long-float)
583 (truncate-float long-float))
584 ((double-float (or single-float double-float))
585 (truncate-float double-float))
586 ((single-float double-float)
587 (truncate-float double-float))
588 (((foreach fixnum bignum ratio)
589 (foreach single-float double-float #!+long-float long-float))
590 (truncate-float (dispatch-type divisor))))))
592 ;;; Declare these guys inline to let them get optimized a little.
593 ;;; ROUND and FROUND are not declared inline since they seem too
594 ;;; obscure and too big to inline-expand by default. Also, this gives
595 ;;; the compiler a chance to pick off the unary float case. Similarly,
596 ;;; CEILING and FLOOR are only maybe-inline for now, so that the
597 ;;; power-of-2 CEILING and FLOOR transforms get a chance.
598 #!-sb-fluid (declaim (inline rem mod fceiling ffloor ftruncate))
599 (declaim (maybe-inline ceiling floor))
601 (defun floor (number &optional (divisor 1))
603 "Return the greatest integer not greater than number, or number/divisor.
604 The second returned value is (mod number divisor)."
605 ;; If the numbers do not divide exactly and the result of
606 ;; (/ NUMBER DIVISOR) would be negative then decrement the quotient
607 ;; and augment the remainder by the divisor.
608 (multiple-value-bind (tru rem) (truncate number divisor)
609 (if (and (not (zerop rem))
613 (values (1- tru) (+ rem divisor))
616 (defun ceiling (number &optional (divisor 1))
618 "Return the smallest integer not less than number, or number/divisor.
619 The second returned value is the remainder."
620 ;; If the numbers do not divide exactly and the result of
621 ;; (/ NUMBER DIVISOR) would be positive then increment the quotient
622 ;; and decrement the remainder by the divisor.
623 (multiple-value-bind (tru rem) (truncate number divisor)
624 (if (and (not (zerop rem))
628 (values (+ tru 1) (- rem divisor))
631 (defun round (number &optional (divisor 1))
633 "Rounds number (or number/divisor) to nearest integer.
634 The second returned value is the remainder."
637 (multiple-value-bind (tru rem) (truncate number divisor)
640 (let ((thresh (/ (abs divisor) 2)))
641 (cond ((or (> rem thresh)
642 (and (= rem thresh) (oddp tru)))
644 (values (- tru 1) (+ rem divisor))
645 (values (+ tru 1) (- rem divisor))))
646 ((let ((-thresh (- thresh)))
648 (and (= rem -thresh) (oddp tru))))
650 (values (+ tru 1) (- rem divisor))
651 (values (- tru 1) (+ rem divisor))))
652 (t (values tru rem))))))))
654 (defun rem (number divisor)
656 "Return second result of TRUNCATE."
657 (multiple-value-bind (tru rem) (truncate number divisor)
658 (declare (ignore tru))
661 (defun mod (number divisor)
663 "Return second result of FLOOR."
664 (let ((rem (rem number divisor)))
665 (if (and (not (zerop rem))
672 (defmacro !define-float-rounding-function (name op doc)
673 `(defun ,name (number &optional (divisor 1))
675 (multiple-value-bind (res rem) (,op number divisor)
676 (values (float res (if (floatp rem) rem 1.0)) rem))))
678 (defun ftruncate (number &optional (divisor 1))
680 "Same as TRUNCATE, but returns first value as a float."
681 (macrolet ((ftruncate-float (rtype)
682 `(let* ((float-div (coerce divisor ',rtype))
683 (res (%unary-ftruncate (/ number float-div))))
686 (* (coerce res ',rtype) float-div))))))
687 (number-dispatch ((number real) (divisor real))
688 (((foreach fixnum bignum ratio) (or fixnum bignum ratio))
689 (multiple-value-bind (q r)
690 (truncate number divisor)
691 (values (float q) r)))
692 (((foreach single-float double-float #!+long-float long-float)
693 (or rational single-float))
695 (let ((res (%unary-ftruncate number)))
696 (values res (- number (coerce res '(dispatch-type number)))))
697 (ftruncate-float (dispatch-type number))))
699 ((long-float (or single-float double-float long-float))
700 (ftruncate-float long-float))
702 (((foreach double-float single-float) long-float)
703 (ftruncate-float long-float))
704 ((double-float (or single-float double-float))
705 (ftruncate-float double-float))
706 ((single-float double-float)
707 (ftruncate-float double-float))
708 (((foreach fixnum bignum ratio)
709 (foreach single-float double-float #!+long-float long-float))
710 (ftruncate-float (dispatch-type divisor))))))
712 (defun ffloor (number &optional (divisor 1))
713 "Same as FLOOR, but returns first value as a float."
714 (multiple-value-bind (tru rem) (ftruncate number divisor)
715 (if (and (not (zerop rem))
719 (values (1- tru) (+ rem divisor))
722 (defun fceiling (number &optional (divisor 1))
723 "Same as CEILING, but returns first value as a float."
724 (multiple-value-bind (tru rem) (ftruncate number divisor)
725 (if (and (not (zerop rem))
729 (values (+ tru 1) (- rem divisor))
732 ;;; FIXME: this probably needs treatment similar to the use of
733 ;;; %UNARY-FTRUNCATE for FTRUNCATE.
734 (defun fround (number &optional (divisor 1))
735 "Same as ROUND, but returns first value as a float."
736 (multiple-value-bind (res rem)
737 (round number divisor)
738 (values (float res (if (floatp rem) rem 1.0)) rem)))
742 (defun = (number &rest more-numbers)
744 "Return T if all of its arguments are numerically equal, NIL otherwise."
746 (do ((nlist more-numbers (cdr nlist)))
748 (declare (list nlist))
749 (if (not (= (car nlist) number)) (return nil))))
751 (defun /= (number &rest more-numbers)
753 "Return T if no two of its arguments are numerically equal, NIL otherwise."
754 (do* ((head (the number number) (car nlist))
755 (nlist more-numbers (cdr nlist)))
757 (declare (list nlist))
758 (unless (do* ((nl nlist (cdr nl)))
761 (if (= head (car nl)) (return nil)))
764 (defun < (number &rest more-numbers)
766 "Return T if its arguments are in strictly increasing order, NIL otherwise."
767 (do* ((n (the number number) (car nlist))
768 (nlist more-numbers (cdr nlist)))
770 (declare (list nlist))
771 (if (not (< n (car nlist))) (return nil))))
773 (defun > (number &rest more-numbers)
775 "Return T if its arguments are in strictly decreasing order, NIL otherwise."
776 (do* ((n (the number number) (car nlist))
777 (nlist more-numbers (cdr nlist)))
779 (declare (list nlist))
780 (if (not (> n (car nlist))) (return nil))))
782 (defun <= (number &rest more-numbers)
784 "Return T if arguments are in strictly non-decreasing order, NIL otherwise."
785 (do* ((n (the number number) (car nlist))
786 (nlist more-numbers (cdr nlist)))
788 (declare (list nlist))
789 (if (not (<= n (car nlist))) (return nil))))
791 (defun >= (number &rest more-numbers)
793 "Return T if arguments are in strictly non-increasing order, NIL otherwise."
794 (do* ((n (the number number) (car nlist))
795 (nlist more-numbers (cdr nlist)))
797 (declare (list nlist))
798 (if (not (>= n (car nlist))) (return nil))))
800 (defun max (number &rest more-numbers)
802 "Return the greatest of its arguments; among EQUALP greatest, return
804 (do ((nlist more-numbers (cdr nlist))
806 ((null nlist) (return result))
807 (declare (list nlist))
808 (declare (type real number result))
809 (if (> (car nlist) result) (setq result (car nlist)))))
811 (defun min (number &rest more-numbers)
813 "Return the least of its arguments; among EQUALP least, return
815 (do ((nlist more-numbers (cdr nlist))
817 ((null nlist) (return result))
818 (declare (list nlist))
819 (declare (type real number result))
820 (if (< (car nlist) result) (setq result (car nlist)))))
822 (eval-when (:compile-toplevel :execute)
824 ;;; The INFINITE-X-FINITE-Y and INFINITE-Y-FINITE-X args tell us how
825 ;;; to handle the case when X or Y is a floating-point infinity and
826 ;;; the other arg is a rational. (Section 12.1.4.1 of the ANSI spec
827 ;;; says that comparisons are done by converting the float to a
828 ;;; rational when comparing with a rational, but infinities can't be
829 ;;; converted to a rational, so we show some initiative and do it this
831 (defun basic-compare (op &key infinite-x-finite-y infinite-y-finite-x)
832 `(((fixnum fixnum) (,op x y))
834 ((single-float single-float) (,op x y))
836 (((foreach single-float double-float long-float) long-float)
837 (,op (coerce x 'long-float) y))
839 ((long-float (foreach single-float double-float))
840 (,op x (coerce y 'long-float)))
841 (((foreach single-float double-float) double-float)
842 (,op (coerce x 'double-float) y))
843 ((double-float single-float)
844 (,op x (coerce y 'double-float)))
845 (((foreach single-float double-float #!+long-float long-float) rational)
847 (,op x (coerce 0 '(dispatch-type x)))
848 (if (float-infinity-p x)
850 (,op (rational x) y))))
851 (((foreach bignum fixnum ratio) float)
852 (if (float-infinity-p y)
854 (,op x (rational y))))))
857 (macrolet ((def-two-arg-</> (name op ratio-arg1 ratio-arg2 &rest cases)
859 (number-dispatch ((x real) (y real))
863 (,op x (coerce 0 '(dispatch-type x)))
865 (,op (coerce 0 '(dispatch-type y)) y))
866 (((foreach fixnum bignum) ratio)
867 (,op x (,ratio-arg2 (numerator y)
870 (,op (,ratio-arg1 (numerator x)
874 (,op (* (numerator (truly-the ratio x))
875 (denominator (truly-the ratio y)))
876 (* (numerator (truly-the ratio y))
877 (denominator (truly-the ratio x)))))
879 (def-two-arg-</> two-arg-< < floor ceiling
883 (not (bignum-plus-p x)))
885 (minusp (bignum-compare x y))))
886 (def-two-arg-</> two-arg-> > ceiling floor
888 (not (bignum-plus-p y)))
892 (plusp (bignum-compare x y)))))
894 (defun two-arg-= (x y)
895 (number-dispatch ((x number) (y number))
897 ;; An infinite value is never equal to a finite value.
898 :infinite-x-finite-y nil
899 :infinite-y-finite-x nil)
900 ((fixnum (or bignum ratio)) nil)
902 ((bignum (or fixnum ratio)) nil)
904 (zerop (bignum-compare x y)))
906 ((ratio integer) nil)
908 (and (eql (numerator x) (numerator y))
909 (eql (denominator x) (denominator y))))
912 (and (= (realpart x) (realpart y))
913 (= (imagpart x) (imagpart y))))
914 (((foreach fixnum bignum ratio single-float double-float
915 #!+long-float long-float) complex)
916 (and (= x (realpart y))
917 (zerop (imagpart y))))
918 ((complex (or float rational))
919 (and (= (realpart x) y)
920 (zerop (imagpart x))))))
922 (defun eql (obj1 obj2)
924 "Return T if OBJ1 and OBJ2 represent the same object, otherwise NIL."
926 (if (or (typep obj2 'fixnum)
927 (not (typep obj2 'number)))
929 (macrolet ((foo (&rest stuff)
931 ,@(mapcar (lambda (foo)
932 (let ((type (car foo))
935 (and (typep obj1 ',type)
945 (zerop (bignum-compare x y))))
948 (and (eql (numerator x) (numerator y))
949 (eql (denominator x) (denominator y)))))
952 (and (eql (realpart x) (realpart y))
953 (eql (imagpart x) (imagpart y))))))))))
957 (defun logior (&rest integers)
959 "Return the bit-wise or of its arguments. Args must be integers."
960 (declare (list integers))
962 (do ((result (pop integers) (logior result (pop integers))))
963 ((null integers) result)
964 (declare (integer result)))
967 (defun logxor (&rest integers)
969 "Return the bit-wise exclusive or of its arguments. Args must be integers."
970 (declare (list integers))
972 (do ((result (pop integers) (logxor result (pop integers))))
973 ((null integers) result)
974 (declare (integer result)))
977 (defun logand (&rest integers)
979 "Return the bit-wise and of its arguments. Args must be integers."
980 (declare (list integers))
982 (do ((result (pop integers) (logand result (pop integers))))
983 ((null integers) result)
984 (declare (integer result)))
987 (defun logeqv (&rest integers)
989 "Return the bit-wise equivalence of its arguments. Args must be integers."
990 (declare (list integers))
992 (do ((result (pop integers) (logeqv result (pop integers))))
993 ((null integers) result)
994 (declare (integer result)))
997 (defun lognot (number)
999 "Return the bit-wise logical not of integer."
1001 (fixnum (lognot (truly-the fixnum number)))
1002 (bignum (bignum-logical-not number))))
1004 (macrolet ((def (name op big-op &optional doc)
1005 `(defun ,name (integer1 integer2)
1010 (number-dispatch ((x integer) (y integer))
1011 (bignum-cross-fixnum ,op ,big-op))))))
1012 (def two-arg-and logand bignum-logical-and)
1013 (def two-arg-ior logior bignum-logical-ior)
1014 (def two-arg-xor logxor bignum-logical-xor)
1015 ;; BIGNUM-LOGICAL-{AND,IOR,XOR} need not return a bignum, so must
1016 ;; call the generic LOGNOT...
1017 (def two-arg-eqv logeqv (lambda (x y) (lognot (bignum-logical-xor x y))))
1018 (def lognand lognand
1019 (lambda (x y) (lognot (bignum-logical-and x y)))
1020 #!+sb-doc "Complement the logical AND of INTEGER1 and INTEGER2.")
1022 (lambda (x y) (lognot (bignum-logical-ior x y)))
1023 #!+sb-doc "Complement the logical AND of INTEGER1 and INTEGER2.")
1024 ;; ... but BIGNUM-LOGICAL-NOT on a bignum will always return a bignum
1025 (def logandc1 logandc1
1026 (lambda (x y) (bignum-logical-and (bignum-logical-not x) y))
1027 #!+sb-doc "Bitwise AND (LOGNOT INTEGER1) with INTEGER2.")
1028 (def logandc2 logandc2
1029 (lambda (x y) (bignum-logical-and x (bignum-logical-not y)))
1030 #!+sb-doc "Bitwise AND INTEGER1 with (LOGNOT INTEGER2).")
1031 (def logorc1 logorc1
1032 (lambda (x y) (bignum-logical-ior (bignum-logical-not x) y))
1033 #!+sb-doc "Bitwise OR (LOGNOT INTEGER1) with INTEGER2.")
1034 (def logorc2 logorc2
1035 (lambda (x y) (bignum-logical-ior x (bignum-logical-not y)))
1036 #!+sb-doc "Bitwise OR INTEGER1 with (LOGNOT INTEGER2)."))
1038 (defun logcount (integer)
1040 "Count the number of 1 bits if INTEGER is positive, and the number of 0 bits
1041 if INTEGER is negative."
1044 (logcount (truly-the (integer 0
1045 #.(max sb!xc:most-positive-fixnum
1046 (lognot sb!xc:most-negative-fixnum)))
1047 (if (minusp (truly-the fixnum integer))
1048 (lognot (truly-the fixnum integer))
1051 (bignum-logcount integer))))
1053 (defun logtest (integer1 integer2)
1055 "Predicate which returns T if logand of integer1 and integer2 is not zero."
1056 (logtest integer1 integer2))
1058 (defun logbitp (index integer)
1060 "Predicate returns T if bit index of integer is a 1."
1061 (number-dispatch ((index integer) (integer integer))
1062 ((fixnum fixnum) (if (> index #.(- sb!vm:n-word-bits sb!vm:n-lowtag-bits))
1064 (not (zerop (logand integer (ash 1 index))))))
1065 ((fixnum bignum) (bignum-logbitp index integer))
1066 ((bignum (foreach fixnum bignum)) (minusp integer))))
1068 (defun ash (integer count)
1070 "Shifts integer left by count places preserving sign. - count shifts right."
1071 (declare (integer integer count))
1074 (cond ((zerop integer)
1077 (let ((length (integer-length (truly-the fixnum integer)))
1078 (count (truly-the fixnum count)))
1079 (declare (fixnum length count))
1080 (cond ((and (plusp count)
1082 (integer-length most-positive-fixnum)))
1083 (bignum-ashift-left (make-small-bignum integer) count))
1086 (ash (truly-the fixnum integer) count))))))
1088 (if (minusp integer) -1 0))
1090 (bignum-ashift-left (make-small-bignum integer) count))))
1093 (bignum-ashift-left integer count)
1094 (bignum-ashift-right integer (- count))))))
1096 (defun integer-length (integer)
1098 "Return the number of significant bits in the absolute value of integer."
1101 (integer-length (truly-the fixnum integer)))
1103 (bignum-integer-length integer))))
1105 ;;;; BYTE, bytespecs, and related operations
1107 (defun byte (size position)
1109 "Return a byte specifier which may be used by other byte functions
1111 (byte size position))
1113 (defun byte-size (bytespec)
1115 "Return the size part of the byte specifier bytespec."
1116 (byte-size bytespec))
1118 (defun byte-position (bytespec)
1120 "Return the position part of the byte specifier bytespec."
1121 (byte-position bytespec))
1123 (defun ldb (bytespec integer)
1125 "Extract the specified byte from integer, and right justify result."
1126 (ldb bytespec integer))
1128 (defun ldb-test (bytespec integer)
1130 "Return T if any of the specified bits in integer are 1's."
1131 (ldb-test bytespec integer))
1133 (defun mask-field (bytespec integer)
1135 "Extract the specified byte from integer, but do not right justify result."
1136 (mask-field bytespec integer))
1138 (defun dpb (newbyte bytespec integer)
1140 "Return new integer with newbyte in specified position, newbyte is right justified."
1141 (dpb newbyte bytespec integer))
1143 (defun deposit-field (newbyte bytespec integer)
1145 "Return new integer with newbyte in specified position, newbyte is not right justified."
1146 (deposit-field newbyte bytespec integer))
1148 (defun %ldb (size posn integer)
1149 (logand (ash integer (- posn))
1152 (defun %mask-field (size posn integer)
1153 (logand integer (ash (1- (ash 1 size)) posn)))
1155 (defun %dpb (newbyte size posn integer)
1156 (let ((mask (1- (ash 1 size))))
1157 (logior (logand integer (lognot (ash mask posn)))
1158 (ash (logand newbyte mask) posn))))
1160 (defun %deposit-field (newbyte size posn integer)
1161 (let ((mask (ash (ldb (byte size 0) -1) posn)))
1162 (logior (logand newbyte mask)
1163 (logand integer (lognot mask)))))
1167 ;;; The boole function dispaches to any logic operation depending on
1168 ;;; the value of a variable. Presently, legal selector values are [0..15].
1169 ;;; boole is open coded for calls with a constant selector. or with calls
1170 ;;; using any of the constants declared below.
1172 (defconstant boole-clr 0
1174 "Boole function op, makes BOOLE return 0.")
1176 (defconstant boole-set 1
1178 "Boole function op, makes BOOLE return -1.")
1180 (defconstant boole-1 2
1182 "Boole function op, makes BOOLE return integer1.")
1184 (defconstant boole-2 3
1186 "Boole function op, makes BOOLE return integer2.")
1188 (defconstant boole-c1 4
1190 "Boole function op, makes BOOLE return complement of integer1.")
1192 (defconstant boole-c2 5
1194 "Boole function op, makes BOOLE return complement of integer2.")
1196 (defconstant boole-and 6
1198 "Boole function op, makes BOOLE return logand of integer1 and integer2.")
1200 (defconstant boole-ior 7
1202 "Boole function op, makes BOOLE return logior of integer1 and integer2.")
1204 (defconstant boole-xor 8
1206 "Boole function op, makes BOOLE return logxor of integer1 and integer2.")
1208 (defconstant boole-eqv 9
1210 "Boole function op, makes BOOLE return logeqv of integer1 and integer2.")
1212 (defconstant boole-nand 10
1214 "Boole function op, makes BOOLE return log nand of integer1 and integer2.")
1216 (defconstant boole-nor 11
1218 "Boole function op, makes BOOLE return lognor of integer1 and integer2.")
1220 (defconstant boole-andc1 12
1222 "Boole function op, makes BOOLE return logandc1 of integer1 and integer2.")
1224 (defconstant boole-andc2 13
1226 "Boole function op, makes BOOLE return logandc2 of integer1 and integer2.")
1228 (defconstant boole-orc1 14
1230 "Boole function op, makes BOOLE return logorc1 of integer1 and integer2.")
1232 (defconstant boole-orc2 15
1234 "Boole function op, makes BOOLE return logorc2 of integer1 and integer2.")
1236 (defun boole (op integer1 integer2)
1238 "Bit-wise boolean function on two integers. Function chosen by OP:
1256 (0 (boole 0 integer1 integer2))
1257 (1 (boole 1 integer1 integer2))
1258 (2 (boole 2 integer1 integer2))
1259 (3 (boole 3 integer1 integer2))
1260 (4 (boole 4 integer1 integer2))
1261 (5 (boole 5 integer1 integer2))
1262 (6 (boole 6 integer1 integer2))
1263 (7 (boole 7 integer1 integer2))
1264 (8 (boole 8 integer1 integer2))
1265 (9 (boole 9 integer1 integer2))
1266 (10 (boole 10 integer1 integer2))
1267 (11 (boole 11 integer1 integer2))
1268 (12 (boole 12 integer1 integer2))
1269 (13 (boole 13 integer1 integer2))
1270 (14 (boole 14 integer1 integer2))
1271 (15 (boole 15 integer1 integer2))
1272 (t (error 'type-error :datum op :expected-type '(mod 16)))))
1276 (defun gcd (&rest numbers)
1278 "Return the greatest common divisor of the arguments, which must be
1279 integers. Gcd with no arguments is defined to be 0."
1280 (cond ((null numbers) 0)
1281 ((null (cdr numbers)) (abs (the integer (car numbers))))
1283 (do ((gcd (the integer (car numbers))
1284 (gcd gcd (the integer (car rest))))
1285 (rest (cdr numbers) (cdr rest)))
1287 (declare (integer gcd)
1290 (defun lcm (&rest numbers)
1292 "Return the least common multiple of one or more integers. LCM of no
1293 arguments is defined to be 1."
1294 (cond ((null numbers) 1)
1295 ((null (cdr numbers)) (abs (the integer (car numbers))))
1297 (do ((lcm (the integer (car numbers))
1298 (lcm lcm (the integer (car rest))))
1299 (rest (cdr numbers) (cdr rest)))
1301 (declare (integer lcm) (list rest))))))
1303 (defun two-arg-lcm (n m)
1304 (declare (integer n m))
1305 (if (or (zerop n) (zerop m))
1307 ;; KLUDGE: I'm going to assume that it was written this way
1308 ;; originally for a reason. However, this is a somewhat
1309 ;; complicated way of writing the algorithm in the CLHS page for
1310 ;; LCM, and I don't know why. To be investigated. -- CSR,
1314 (multiple-value-bind (max min)
1318 (* (truncate max (gcd n m)) min)))))
1320 ;;; Do the GCD of two integer arguments. With fixnum arguments, we use the
1321 ;;; binary GCD algorithm from Knuth's seminumerical algorithms (slightly
1322 ;;; structurified), otherwise we call BIGNUM-GCD. We pick off the special case
1323 ;;; of 0 before the dispatch so that the bignum code doesn't have to worry
1324 ;;; about "small bignum" zeros.
1325 (defun two-arg-gcd (u v)
1326 (cond ((eql u 0) (abs v))
1329 (number-dispatch ((u integer) (v integer))
1332 (declare (optimize (speed 3) (safety 0)))
1334 (u (abs u) (ash u -1))
1335 (v (abs v) (ash v -1)))
1336 ((oddp (logior u v))
1337 (do ((temp (if (oddp u) (- v) (ash u -1))
1340 (declare (fixnum temp))
1347 (let ((res (ash u k)))
1348 (declare (type (signed-byte 31) res)
1349 (optimize (inhibit-warnings 3)))
1351 (declare (type (mod 30) k)
1352 (type (signed-byte 31) u v)))))
1356 (bignum-gcd u (make-small-bignum v)))
1358 (bignum-gcd (make-small-bignum u) v))))))
1360 ;;; From discussion on comp.lang.lisp and Akira Kurihara.
1363 "Return the root of the nearest integer less than n which is a perfect
1365 (declare (type unsigned-byte n) (values unsigned-byte))
1366 ;; Theoretically (> n 7), i.e., n-len-quarter > 0.
1367 (if (and (fixnump n) (<= n 24))
1373 (let* ((n-len-quarter (ash (integer-length n) -2))
1374 (n-half (ash n (- (ash n-len-quarter 1))))
1375 (n-half-isqrt (isqrt n-half))
1376 (init-value (ash (1+ n-half-isqrt) n-len-quarter)))
1378 (let ((iterated-value
1379 (ash (+ init-value (truncate n init-value)) -1)))
1380 (unless (< iterated-value init-value)
1381 (return init-value))
1382 (setq init-value iterated-value))))))
1384 ;;;; miscellaneous number predicates
1386 (macrolet ((def (name doc)
1387 `(defun ,name (number) ,doc (,name number))))
1388 (def zerop "Is this number zero?")
1389 (def plusp "Is this real number strictly positive?")
1390 (def minusp "Is this real number strictly negative?")
1391 (def oddp "Is this integer odd?")
1392 (def evenp "Is this integer even?"))
1394 ;;;; modular functions
1397 (flet ((definition (name lambda-list width pattern)
1398 `(defun ,name ,lambda-list
1399 (flet ((prepare-argument (x)
1400 (declare (integer x))
1402 ((unsigned-byte ,width) x)
1403 (fixnum (logand x ,pattern))
1404 (bignum (logand x ,pattern)))))
1405 (,name ,@(loop for arg in lambda-list
1406 collect `(prepare-argument ,arg)))))))
1407 (loop for infos being each hash-value of sb!c::*modular-funs*
1408 ;; FIXME: We need to process only "toplevel" functions
1410 do (loop for info in infos
1411 for name = (sb!c::modular-fun-info-name info)
1412 and width = (sb!c::modular-fun-info-width info)
1413 and lambda-list = (sb!c::modular-fun-info-lambda-list info)
1414 for pattern = (1- (ash 1 width))
1415 do (forms (definition name lambda-list width pattern)))))
1418 ;;; KLUDGE: these out-of-line definitions can't use the modular
1419 ;;; arithmetic, as that is only (currently) defined for constant
1420 ;;; shifts. See also the comment in (LOGAND OPTIMIZER) for more
1421 ;;; discussion of this hack. -- CSR, 2003-10-09
1423 (defun sb!vm::ash-left-mod32 (integer amount)
1425 ((unsigned-byte 32) (ldb (byte 32 0) (ash integer amount)))
1426 (fixnum (ldb (byte 32 0) (ash (logand integer #xffffffff) amount)))
1427 (bignum (ldb (byte 32 0) (ash (logand integer #xffffffff) amount)))))
1429 (defun sb!vm::ash-left-mod64 (integer amount)
1431 ((unsigned-byte 64) (ldb (byte 64 0) (ash integer amount)))
1432 (fixnum (ldb (byte 64 0) (ash (logand integer #xffffffffffffffff) amount)))
1433 (bignum (ldb (byte 64 0)
1434 (ash (logand integer #xffffffffffffffff) amount)))))