1 ;;;; This file contains all the irrational functions. (Actually, most
2 ;;;; of the work is done by calling out to C.)
4 ;;;; This software is part of the SBCL system. See the README file for
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
13 (in-package "SB!KERNEL")
15 ;;;; miscellaneous constants, utility functions, and macros
18 #!+long-float 3.14159265358979323846264338327950288419716939937511l0
19 #!-long-float 3.14159265358979323846264338327950288419716939937511d0)
21 ;;; Make these INLINE, since the call to C is at least as compact as a
22 ;;; Lisp call, and saves number consing to boot.
23 (eval-when (:compile-toplevel :execute)
25 (sb!xc:defmacro def-math-rtn (name num-args)
26 (let ((function (symbolicate "%" (string-upcase name)))
27 (args (loop for i below num-args
28 collect (intern (format nil "ARG~D" i)))))
30 (declaim (inline ,function))
31 (defun ,function ,args
34 (function double-float
35 ,@(loop repeat num-args
36 collect 'double-float)))
39 (defun handle-reals (function var)
40 `((((foreach fixnum single-float bignum ratio))
41 (coerce (,function (coerce ,var 'double-float)) 'single-float))
47 #!+x86 ;; for constant folding
48 (macrolet ((def (name ll)
49 `(defun ,name ,ll (,name ,@ll))))
62 #!+x86-64 ;; for constant folding
63 (macrolet ((def (name ll)
64 `(defun ,name ,ll (,name ,@ll))))
67 ;;;; stubs for the Unix math library
69 ;;;; Many of these are unnecessary on the X86 because they're built
73 #!-x86 (def-math-rtn "sin" 1)
74 #!-x86 (def-math-rtn "cos" 1)
75 #!-x86 (def-math-rtn "tan" 1)
76 #!-x86 (def-math-rtn "atan" 1)
77 #!-x86 (def-math-rtn "atan2" 2)
80 (def-math-rtn "acos" 1)
81 (def-math-rtn "asin" 1)
82 (def-math-rtn "cosh" 1)
83 (def-math-rtn "sinh" 1)
84 (def-math-rtn "tanh" 1)
85 (def-math-rtn "asinh" 1)
86 (def-math-rtn "acosh" 1)
87 (def-math-rtn "atanh" 1))
90 (declaim (inline %asin))
92 (%atan (/ number (sqrt (- 1 (* number number))))))
93 (declaim (inline %acos))
95 (- (/ pi 2) (%asin number)))
96 (declaim (inline %cosh))
98 (/ (+ (exp number) (exp (- number))) 2))
99 (declaim (inline %sinh))
100 (defun %sinh (number)
101 (/ (- (exp number) (exp (- number))) 2))
102 (declaim (inline %tanh))
103 (defun %tanh (number)
104 (/ (%sinh number) (%cosh number)))
105 (declaim (inline %asinh))
106 (defun %asinh (number)
107 (log (+ number (sqrt (+ (* number number) 1.0d0))) #.(exp 1.0d0)))
108 (declaim (inline %acosh))
109 (defun %acosh (number)
110 (log (+ number (sqrt (- (* number number) 1.0d0))) #.(exp 1.0d0)))
111 (declaim (inline %atanh))
112 (defun %atanh (number)
113 (let ((ratio (/ (+ 1 number) (- 1 number))))
114 ;; Were we effectively zero?
117 (/ (log ratio #.(exp 1.0d0)) 2.0d0)))))
119 ;;; exponential and logarithmic
120 #!-x86 (def-math-rtn "exp" 1)
121 #!-x86 (def-math-rtn "log" 1)
122 #!-x86 (def-math-rtn "log10" 1)
123 #!-win32(def-math-rtn "pow" 2)
124 #!-(or x86 x86-64) (def-math-rtn "sqrt" 1)
125 #!-win32 (def-math-rtn "hypot" 2)
126 #!-x86 (def-math-rtn "log1p" 1)
130 ;; This is written in a peculiar way to avoid overflow. Note that in
131 ;; sqrt(x^2 + y^2), either square or the sum can overflow.
133 ;; Factoring x^2 out of sqrt(x^2 + y^2) gives us the expression
134 ;; |x|sqrt(1 + (y/x)^2), which, assuming |x| >= |y|, can only overflow
135 ;; if |x| is sufficiently large.
137 ;; The ZEROP test suffices (y is non-negative) to guard against
138 ;; divisions by zero: x >= y > 0.
139 (declaim (inline %hypot))
141 (declare (type double-float x y))
149 (* x (sqrt (1+ (* y/x y/x)))))))))
155 "Return e raised to the power NUMBER."
156 (number-dispatch ((number number))
157 (handle-reals %exp number)
159 (* (exp (realpart number))
160 (cis (imagpart number))))))
162 ;;; INTEXP -- Handle the rational base, integer power case.
164 (declaim (type (or integer null) *intexp-maximum-exponent*))
165 (defparameter *intexp-maximum-exponent* nil)
167 ;;; This function precisely calculates base raised to an integral
168 ;;; power. It separates the cases by the sign of power, for efficiency
169 ;;; reasons, as powers can be calculated more efficiently if power is
170 ;;; a positive integer. Values of power are calculated as positive
171 ;;; integers, and inverted if negative.
172 (defun intexp (base power)
173 (when (and *intexp-maximum-exponent*
174 (> (abs power) *intexp-maximum-exponent*))
175 (error "The absolute value of ~S exceeds ~S."
176 power '*intexp-maximum-exponent*))
177 (cond ((minusp power)
178 (/ (intexp base (- power))))
182 (do ((nextn (ash power -1) (ash power -1))
183 (total (if (oddp power) base 1)
184 (if (oddp power) (* base total) total)))
185 ((zerop nextn) total)
186 (setq base (* base base))
187 (setq power nextn)))))
189 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
190 ;;; floating point stuff. If both args are real, we try %POW right
191 ;;; off, assuming it will return 0 if the result may be complex. If
192 ;;; so, we call COMPLEX-POW which directly computes the complex
193 ;;; result. We also separate the complex-real and real-complex cases
194 ;;; from the general complex case.
195 (defun expt (base power)
197 "Return BASE raised to the POWER."
199 (if (and (zerop base) (floatp power))
200 (error 'arguments-out-of-domain-error
201 :operands (list base power)
203 :references (list '(:ansi-cl :function expt)))
204 (let ((result (1+ (* base power))))
205 (if (and (floatp result) (float-nan-p result))
208 (labels (;; determine if the double float is an integer.
209 ;; 0 - not an integer
213 (declare (type (unsigned-byte 31) ihi)
214 (type (unsigned-byte 32) lo)
215 (optimize (speed 3) (safety 0)))
217 (declare (type fixnum isint))
218 (cond ((>= ihi #x43400000) ; exponent >= 53
221 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
222 (declare (type (mod 53) k))
224 (let* ((shift (- 52 k))
225 (j (logand (ash lo (- shift))))
227 (declare (type (mod 32) shift)
228 (type (unsigned-byte 32) j j2))
230 (setq isint (- 2 (logand j 1))))))
232 (let* ((shift (- 20 k))
233 (j (ash ihi (- shift)))
235 (declare (type (mod 32) shift)
236 (type (unsigned-byte 31) j j2))
238 (setq isint (- 2 (logand j 1))))))))))
240 (real-expt (x y rtype)
241 (let ((x (coerce x 'double-float))
242 (y (coerce y 'double-float)))
243 (declare (double-float x y))
244 (let* ((x-hi (sb!kernel:double-float-high-bits x))
245 (x-lo (sb!kernel:double-float-low-bits x))
246 (x-ihi (logand x-hi #x7fffffff))
247 (y-hi (sb!kernel:double-float-high-bits y))
248 (y-lo (sb!kernel:double-float-low-bits y))
249 (y-ihi (logand y-hi #x7fffffff)))
250 (declare (type (signed-byte 32) x-hi y-hi)
251 (type (unsigned-byte 31) x-ihi y-ihi)
252 (type (unsigned-byte 32) x-lo y-lo))
254 (when (zerop (logior y-ihi y-lo))
255 (return-from real-expt (coerce 1d0 rtype)))
257 ;; FIXME: Hardcoded qNaN/sNaN values are not portable.
258 (when (or (> x-ihi #x7ff00000)
259 (and (= x-ihi #x7ff00000) (/= x-lo 0))
261 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
262 (return-from real-expt (coerce (+ x y) rtype)))
263 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
264 (declare (type fixnum yisint))
265 ;; special value of y
266 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
268 (return-from real-expt
269 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
271 (coerce (- y y) rtype))
272 ((>= x-ihi #x3ff00000)
273 ;; (|x|>1)**+-inf = inf,0
278 ;; (|x|<1)**-,+inf = inf,0
281 (coerce 0 rtype))))))
283 (let ((abs-x (abs x)))
284 (declare (double-float abs-x))
285 ;; special value of x
286 (when (and (zerop x-lo)
287 (or (= x-ihi #x7ff00000) (zerop x-ihi)
288 (= x-ihi #x3ff00000)))
289 ;; x is +-0,+-inf,+-1
290 (let ((z (if (< y-hi 0)
291 (/ 1 abs-x) ; z = (1/|x|)
293 (declare (double-float z))
295 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
297 (let ((y*pi (* y pi)))
298 (declare (double-float y*pi))
299 (return-from real-expt
301 (coerce (%cos y*pi) rtype)
302 (coerce (%sin y*pi) rtype)))))
304 ;; (x<0)**odd = -(|x|**odd)
306 (return-from real-expt (coerce z rtype))))
310 (coerce (sb!kernel::%pow x y) rtype)
312 (let ((pow (sb!kernel::%pow abs-x y)))
313 (declare (double-float pow))
316 (coerce (* -1d0 pow) rtype))
320 (let ((y*pi (* y pi)))
321 (declare (double-float y*pi))
323 (coerce (* pow (%cos y*pi))
325 (coerce (* pow (%sin y*pi))
327 (declare (inline real-expt))
328 (number-dispatch ((base number) (power number))
329 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
331 (((foreach single-float double-float) rational)
332 (real-expt base power '(dispatch-type base)))
333 (((foreach fixnum (or bignum ratio) single-float)
334 (foreach ratio single-float))
335 (real-expt base power 'single-float))
336 (((foreach fixnum (or bignum ratio) single-float double-float)
338 (real-expt base power 'double-float))
339 ((double-float single-float)
340 (real-expt base power 'double-float))
341 (((foreach (complex rational) (complex float)) rational)
342 (* (expt (abs base) power)
343 (cis (* power (phase base)))))
344 (((foreach fixnum (or bignum ratio) single-float double-float)
346 (if (and (zerop base) (plusp (realpart power)))
348 (exp (* power (log base)))))
349 (((foreach (complex float) (complex rational))
350 (foreach complex double-float single-float))
351 (if (and (zerop base) (plusp (realpart power)))
353 (exp (* power (log base)))))))))
355 ;;; FIXME: Maybe rename this so that it's clearer that it only works
358 (declare (type integer x))
361 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
362 ;; log2(f). So we grab the top few bits of x and scale that
363 ;; appropriately, take the log of it and add it to n.
365 ;; Motivated by an attempt to get LOG to work better on bignums.
366 (let ((n (integer-length x)))
367 (if (< n sb!vm:double-float-digits)
368 (log (coerce x 'double-float) 2.0d0)
369 (let ((f (ldb (byte sb!vm:double-float-digits
370 (- n sb!vm:double-float-digits))
372 (+ n (log (scale-float (coerce f 'double-float)
373 (- sb!vm:double-float-digits))
376 (defun log (number &optional (base nil base-p))
378 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
382 (if (or (typep number 'double-float) (typep base 'double-float))
385 ((and (typep number '(integer (0) *))
386 (typep base '(integer (0) *)))
387 (coerce (/ (log2 number) (log2 base)) 'single-float))
388 ((and (typep number 'integer) (typep base 'double-float))
389 ;; No single float intermediate result
390 (/ (log2 number) (log base 2.0d0)))
391 ((and (typep number 'double-float) (typep base 'integer))
392 (/ (log number 2.0d0) (log2 base)))
394 (/ (log number) (log base))))
395 (number-dispatch ((number number))
396 (((foreach fixnum bignum))
398 (complex (log (- number)) (coerce pi 'single-float))
399 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
402 (complex (log (- number)) (coerce pi 'single-float))
403 (let ((numerator (numerator number))
404 (denominator (denominator number)))
405 (if (= (integer-length numerator)
406 (integer-length denominator))
407 (coerce (%log1p (coerce (- number 1) 'double-float))
409 (coerce (/ (- (log2 numerator) (log2 denominator))
410 (log (exp 1.0d0) 2.0d0))
412 (((foreach single-float double-float))
413 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
414 ;; Since this doesn't seem to be an implementation issue
415 ;; I (pw) take the Kahan result.
416 (if (< (float-sign number)
417 (coerce 0 '(dispatch-type number)))
418 (complex (log (- number)) (coerce pi '(dispatch-type number)))
419 (coerce (%log (coerce number 'double-float))
420 '(dispatch-type number))))
422 (complex-log number)))))
426 "Return the square root of NUMBER."
427 (number-dispatch ((number number))
428 (((foreach fixnum bignum ratio))
430 (complex-sqrt number)
431 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
432 (((foreach single-float double-float))
434 (complex-sqrt (complex number))
435 (coerce (%sqrt (coerce number 'double-float))
436 '(dispatch-type number))))
438 (complex-sqrt number))))
440 ;;;; trigonometic and related functions
444 "Return the absolute value of the number."
445 (number-dispatch ((number number))
446 (((foreach single-float double-float fixnum rational))
449 (let ((rx (realpart number))
450 (ix (imagpart number)))
453 (sqrt (+ (* rx rx) (* ix ix))))
455 (coerce (%hypot (coerce rx 'double-float)
456 (coerce ix 'double-float))
461 (defun phase (number)
463 "Return the angle part of the polar representation of a complex number.
464 For complex numbers, this is (atan (imagpart number) (realpart number)).
465 For non-complex positive numbers, this is 0. For non-complex negative
470 (coerce pi 'single-float)
473 (if (minusp (float-sign number))
474 (coerce pi 'single-float)
477 (if (minusp (float-sign number))
478 (coerce pi 'double-float)
481 (atan (imagpart number) (realpart number)))))
485 "Return the sine of NUMBER."
486 (number-dispatch ((number number))
487 (handle-reals %sin number)
489 (let ((x (realpart number))
490 (y (imagpart number)))
491 (complex (* (sin x) (cosh y))
492 (* (cos x) (sinh y)))))))
496 "Return the cosine of NUMBER."
497 (number-dispatch ((number number))
498 (handle-reals %cos number)
500 (let ((x (realpart number))
501 (y (imagpart number)))
502 (complex (* (cos x) (cosh y))
503 (- (* (sin x) (sinh y))))))))
507 "Return the tangent of NUMBER."
508 (number-dispatch ((number number))
509 (handle-reals %tan number)
511 (complex-tan number))))
515 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
516 (declare (type real theta))
517 (complex (cos theta) (sin theta)))
521 "Return the arc sine of NUMBER."
522 (number-dispatch ((number number))
524 (if (or (> number 1) (< number -1))
525 (complex-asin number)
526 (coerce (%asin (coerce number 'double-float)) 'single-float)))
527 (((foreach single-float double-float))
528 (if (or (> number (coerce 1 '(dispatch-type number)))
529 (< number (coerce -1 '(dispatch-type number))))
530 (complex-asin (complex number))
531 (coerce (%asin (coerce number 'double-float))
532 '(dispatch-type number))))
534 (complex-asin number))))
538 "Return the arc cosine of NUMBER."
539 (number-dispatch ((number number))
541 (if (or (> number 1) (< number -1))
542 (complex-acos number)
543 (coerce (%acos (coerce number 'double-float)) 'single-float)))
544 (((foreach single-float double-float))
545 (if (or (> number (coerce 1 '(dispatch-type number)))
546 (< number (coerce -1 '(dispatch-type number))))
547 (complex-acos (complex number))
548 (coerce (%acos (coerce number 'double-float))
549 '(dispatch-type number))))
551 (complex-acos number))))
553 (defun atan (y &optional (x nil xp))
555 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
558 (declare (type double-float y x)
559 (values double-float))
562 (if (plusp (float-sign x))
565 (float-sign y (/ pi 2)))
567 (number-dispatch ((y real) (x real))
569 (foreach double-float single-float fixnum bignum ratio))
570 (atan2 y (coerce x 'double-float)))
571 (((foreach single-float fixnum bignum ratio)
573 (atan2 (coerce y 'double-float) x))
574 (((foreach single-float fixnum bignum ratio)
575 (foreach single-float fixnum bignum ratio))
576 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
578 (number-dispatch ((y number))
579 (handle-reals %atan y)
583 ;;; It seems that every target system has a C version of sinh, cosh,
584 ;;; and tanh. Let's use these for reals because the original
585 ;;; implementations based on the definitions lose big in round-off
586 ;;; error. These bad definitions also mean that sin and cos for
587 ;;; complex numbers can also lose big.
591 "Return the hyperbolic sine of NUMBER."
592 (number-dispatch ((number number))
593 (handle-reals %sinh number)
595 (let ((x (realpart number))
596 (y (imagpart number)))
597 (complex (* (sinh x) (cos y))
598 (* (cosh x) (sin y)))))))
602 "Return the hyperbolic cosine of NUMBER."
603 (number-dispatch ((number number))
604 (handle-reals %cosh number)
606 (let ((x (realpart number))
607 (y (imagpart number)))
608 (complex (* (cosh x) (cos y))
609 (* (sinh x) (sin y)))))))
613 "Return the hyperbolic tangent of NUMBER."
614 (number-dispatch ((number number))
615 (handle-reals %tanh number)
617 (complex-tanh number))))
619 (defun asinh (number)
621 "Return the hyperbolic arc sine of NUMBER."
622 (number-dispatch ((number number))
623 (handle-reals %asinh number)
625 (complex-asinh number))))
627 (defun acosh (number)
629 "Return the hyperbolic arc cosine of NUMBER."
630 (number-dispatch ((number number))
632 ;; acosh is complex if number < 1
634 (complex-acosh number)
635 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
636 (((foreach single-float double-float))
637 (if (< number (coerce 1 '(dispatch-type number)))
638 (complex-acosh (complex number))
639 (coerce (%acosh (coerce number 'double-float))
640 '(dispatch-type number))))
642 (complex-acosh number))))
644 (defun atanh (number)
646 "Return the hyperbolic arc tangent of NUMBER."
647 (number-dispatch ((number number))
649 ;; atanh is complex if |number| > 1
650 (if (or (> number 1) (< number -1))
651 (complex-atanh number)
652 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
653 (((foreach single-float double-float))
654 (if (or (> number (coerce 1 '(dispatch-type number)))
655 (< number (coerce -1 '(dispatch-type number))))
656 (complex-atanh (complex number))
657 (coerce (%atanh (coerce number 'double-float))
658 '(dispatch-type number))))
660 (complex-atanh number))))
663 ;;;; not-OLD-SPECFUN stuff
665 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
666 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
667 ;;;; the standard special function system.)
669 ;;;; This is a set of routines that implement many elementary
670 ;;;; transcendental functions as specified by ANSI Common Lisp. The
671 ;;;; implementation is based on Kahan's paper.
673 ;;;; I believe I have accurately implemented the routines and are
674 ;;;; correct, but you may want to check for your self.
676 ;;;; These functions are written for CMU Lisp and take advantage of
677 ;;;; some of the features available there. It may be possible,
678 ;;;; however, to port this to other Lisps.
680 ;;;; Some functions are significantly more accurate than the original
681 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
682 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
683 ;;;; answer is pi + i*log(2-sqrt(3)).
685 ;;;; All of the implemented functions will take any number for an
686 ;;;; input, but the result will always be a either a complex
687 ;;;; single-float or a complex double-float.
689 ;;;; general functions:
701 ;;;; utility functions:
704 ;;;; internal functions:
705 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
708 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
709 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
710 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
713 ;;;; The original CMU CL code requested:
714 ;;;; Please send any bug reports, comments, or improvements to
715 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
717 ;;; FIXME: In SBCL, the floating point infinity constants like
718 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
719 ;;; constants at cross-compile time, because the cross-compilation
720 ;;; host might not have support for floating point infinities. Thus,
721 ;;; they're effectively implemented as special variable references,
722 ;;; and the code below which uses them might be unnecessarily
723 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
724 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
725 ;;; special variable references with (probably equally slow)
728 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
729 ;;; differ in their interpretations of the real line, IMAGPART was
730 ;;; patch, which without a certain amount of effort would have altered
731 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
732 ;;; were patched to use explicit COMPLEX, rather than implicitly
733 ;;; passing in real numbers for treatment with IMAGPART, and these
734 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
735 ;;; however, someone needs to go back to Kahan for the definitive
736 ;;; answer for treatment of negative real floating point numbers and
737 ;;; branch cuts. If adjustment is needed, it is probably the removal
738 ;;; of explicit calls to COMPLEX in the clients of irrational
739 ;;; functions. -- a slightly bitter CSR, 2004-05-16
741 (declaim (inline square))
743 (declare (double-float x))
746 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
748 ;;; If you have these functions in libm, perhaps they should be used
749 ;;; instead of these Lisp versions. These versions are probably good
750 ;;; enough, especially since they are portable.
752 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
753 ;;; the underlying floating-point format.)
754 (declaim (inline scalb))
756 (declare (type double-float x)
757 (type double-float-exponent n))
760 ;;; This is like LOGB, but X is not infinity and non-zero and not a
761 ;;; NaN, so we can always return an integer.
762 (declaim (inline logb-finite))
763 (defun logb-finite (x)
764 (declare (type double-float x))
765 (multiple-value-bind (signif exponent sign)
767 (declare (ignore signif sign))
768 ;; DECODE-FLOAT is almost right, except that the exponent is off
772 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
773 ;;; For the special cases, the following values are used:
776 ;;; +/- infinity +infinity
779 (declare (type double-float x))
780 (cond ((float-nan-p x)
782 ((float-infinity-p x)
783 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
784 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
786 ;; The answer is negative infinity, but we are supposed to
787 ;; signal divide-by-zero, so do the actual division
793 ;;; This function is used to create a complex number of the
794 ;;; appropriate type:
795 ;;; Create complex number with real part X and imaginary part Y
796 ;;; such that has the same type as Z. If Z has type (complex
797 ;;; rational), the X and Y are coerced to single-float.
798 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
799 (error "needs work for long float support"))
800 (declaim (inline coerce-to-complex-type))
801 (defun coerce-to-complex-type (x y z)
802 (declare (double-float x y)
804 (if (typep (realpart z) 'double-float)
806 ;; Convert anything that's not already a DOUBLE-FLOAT (because
807 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
808 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
809 (complex (float x 1f0)
812 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
813 ;;; result is r + i*k, where k is an integer.
814 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
815 (error "needs work for long float support"))
817 (let ((x (float (realpart z) 1d0))
818 (y (float (imagpart z) 1d0)))
819 ;; Would this be better handled using an exception handler to
820 ;; catch the overflow or underflow signal? For now, we turn all
821 ;; traps off and look at the accrued exceptions to see if any
822 ;; signal would have been raised.
823 (with-float-traps-masked (:underflow :overflow)
824 (let ((rho (+ (square x) (square y))))
825 (declare (optimize (speed 3) (space 0)))
826 (cond ((and (or (float-nan-p rho)
827 (float-infinity-p rho))
828 (or (float-infinity-p (abs x))
829 (float-infinity-p (abs y))))
830 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
832 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
835 ;; (/ least-positive-double-float double-float-epsilon)
838 (sb!kernel:make-double-float #x1fffff #xfffffffe)
840 (error "(/ least-positive-long-float long-float-epsilon)")))
841 (traps (ldb sb!vm::float-sticky-bits
842 (sb!vm:floating-point-modes))))
843 ;; Overflow raised or (underflow raised and rho <
845 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
846 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
849 ;; If we're here, neither x nor y are infinity and at
850 ;; least one is non-zero.. Thus logb returns a nice
852 (let ((k (- (logb-finite (max (abs x) (abs y))))))
853 (values (+ (square (scalb x k))
854 (square (scalb y k)))
859 ;;; principal square root of Z
861 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
862 (defun complex-sqrt (z)
863 ;; KLUDGE: Here and below, we can't just declare Z to be of type
864 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
865 ;; Since there isn't a rational negative zero, this is OK from the
866 ;; point of view of getting the right answer in the face of branch
867 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
868 ;; still ugly. -- CSR, 2004-05-16
869 (declare (type (or complex rational) z))
870 (multiple-value-bind (rho k)
872 (declare (type (or (member 0d0) (double-float 0d0)) rho)
874 (let ((x (float (realpart z) 1.0d0))
875 (y (float (imagpart z) 1.0d0))
878 (declare (double-float x y eta nu))
881 ;; space 0 to get maybe-inline functions inlined.
882 (declare (optimize (speed 3) (space 0)))
884 (if (not (float-nan-p x))
885 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
890 (setf k (1- (ash k -1)))
891 (setf rho (+ rho rho))))
893 (setf rho (scalb (sqrt rho) k))
899 (when (not (float-infinity-p (abs nu)))
900 (setf nu (/ (/ nu rho) 2d0)))
903 (setf nu (float-sign y rho))))
904 (coerce-to-complex-type eta nu z)))))
906 ;;; Compute log(2^j*z).
908 ;;; This is for use with J /= 0 only when |z| is huge.
909 (defun complex-log-scaled (z j)
910 (declare (type (or rational complex) z)
912 ;; The constants t0, t1, t2 should be evaluated to machine
913 ;; precision. In addition, Kahan says the accuracy of log1p
914 ;; influences the choices of these constants but doesn't say how to
915 ;; choose them. We'll just assume his choices matches our
916 ;; implementation of log1p.
917 (let ((t0 (load-time-value
919 (sb!kernel:make-double-float #x3fe6a09e #x667f3bcd)
921 (error "(/ (sqrt 2l0))")))
922 ;; KLUDGE: if repeatable fasls start failing under some weird
923 ;; xc host, this 1.2d0 might be a good place to examine: while
924 ;; it _should_ be the same in all vaguely-IEEE754 hosts, 1.2
925 ;; is not exactly representable, so something could go wrong.
928 (ln2 (load-time-value
930 (sb!kernel:make-double-float #x3fe62e42 #xfefa39ef)
932 (error "(log 2l0)")))
933 (x (float (realpart z) 1.0d0))
934 (y (float (imagpart z) 1.0d0)))
935 (multiple-value-bind (rho k)
937 (declare (optimize (speed 3)))
938 (let ((beta (max (abs x) (abs y)))
939 (theta (min (abs x) (abs y))))
940 (coerce-to-complex-type (if (and (zerop k)
944 (/ (%log1p (+ (* (- beta 1.0d0)
953 ;;; log of Z = log |Z| + i * arg Z
955 ;;; Z may be any number, but the result is always a complex.
956 (defun complex-log (z)
957 (declare (type (or rational complex) z))
958 (complex-log-scaled z 0))
960 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
961 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
962 ;;; The reason for the imaginary part is caused by the fact that arg
963 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
964 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
965 (defun complex-atanh (z)
966 (declare (type (or rational complex) z))
968 (theta (/ (sqrt most-positive-double-float) 4.0d0))
969 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
970 (half-pi (/ pi 2.0d0))
971 (rp (float (realpart z) 1.0d0))
972 (beta (float-sign rp 1.0d0))
974 (y (* beta (- (float (imagpart z) 1.0d0))))
977 ;; Shouldn't need this declare.
978 (declare (double-float x y))
980 (declare (optimize (speed 3)))
981 (cond ((or (> x theta)
983 ;; To avoid overflow...
984 (setf nu (float-sign y half-pi))
985 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
986 ;; which can cause overflow. Arrange this computation so
987 ;; that it won't overflow.
988 (setf eta (let* ((x-bigger (> x (abs y)))
989 (r (if x-bigger (/ y x) (/ x y)))
990 (d (+ 1.0d0 (* r r))))
995 ;; Should this be changed so that if y is zero, eta is set
996 ;; to +infinity instead of approx 176? In any case
997 ;; tanh(176) is 1.0d0 within working precision.
998 (let ((t1 (+ 4d0 (square y)))
999 (t2 (+ (abs y) rho)))
1000 (setf eta (log (/ (sqrt (sqrt t1))
1004 (+ half-pi (atan (* 0.5d0 t2))))))))
1006 (let ((t1 (+ (abs y) rho)))
1007 ;; Normal case using log1p(x) = log(1 + x)
1009 (%log1p (/ (* 4.0d0 x)
1010 (+ (square (- 1.0d0 x))
1017 (coerce-to-complex-type (* beta eta)
1021 ;;; Compute tanh z = sinh z / cosh z.
1022 (defun complex-tanh (z)
1023 (declare (type (or rational complex) z))
1024 (let ((x (float (realpart z) 1.0d0))
1025 (y (float (imagpart z) 1.0d0)))
1027 ;; space 0 to get maybe-inline functions inlined
1028 (declare (optimize (speed 3) (space 0)))
1032 (sb!kernel:make-double-float #x406633ce #x8fb9f87e)
1034 (error "(/ (+ (log 2l0) (log most-positive-long-float)) 4l0)")))
1035 (coerce-to-complex-type (float-sign x)
1038 (let* ((tv (%tan y))
1039 (beta (+ 1.0d0 (* tv tv)))
1041 (rho (sqrt (+ 1.0d0 (* s s)))))
1042 (if (float-infinity-p (abs tv))
1043 (coerce-to-complex-type (/ rho s)
1046 (let ((den (+ 1.0d0 (* beta s s))))
1047 (coerce-to-complex-type (/ (* beta rho s)
1052 ;;; Compute acos z = pi/2 - asin z.
1054 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1055 (defun complex-acos (z)
1056 ;; Kahan says we should only compute the parts needed. Thus, the
1057 ;; REALPART's below should only compute the real part, not the whole
1058 ;; complex expression. Doing this can be important because we may get
1059 ;; spurious signals that occur in the part that we are not using.
1061 ;; However, we take a pragmatic approach and just use the whole
1064 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1065 ;; it's the conjugate of the square root or the square root of the
1066 ;; conjugate. This needs to be checked.
1068 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1069 ;; same as (sqrt (conjugate z)) for all z. This follows because
1071 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1073 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1075 ;; and these two expressions are equal if and only if arg conj z =
1076 ;; -arg z, which is clearly true for all z.
1077 (declare (type (or rational complex) z))
1078 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
1079 (sqrt-1-z (complex-sqrt (- 1 z))))
1080 (with-float-traps-masked (:divide-by-zero)
1081 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1082 (realpart sqrt-1+z))))
1083 (asinh (imagpart (* (conjugate sqrt-1+z)
1086 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1088 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1089 (defun complex-acosh (z)
1090 (declare (type (or rational complex) z))
1091 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1092 (sqrt-z+1 (complex-sqrt (+ z 1))))
1093 (with-float-traps-masked (:divide-by-zero)
1094 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1096 (* 2 (atan (/ (imagpart sqrt-z-1)
1097 (realpart sqrt-z+1))))))))
1099 ;;; Compute asin z = asinh(i*z)/i.
1101 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1102 (defun complex-asin (z)
1103 (declare (type (or rational complex) z))
1104 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1105 (sqrt-1+z (complex-sqrt (+ 1 z))))
1106 (with-float-traps-masked (:divide-by-zero)
1107 (complex (atan (/ (realpart z)
1108 (realpart (* sqrt-1-z sqrt-1+z))))
1109 (asinh (imagpart (* (conjugate sqrt-1-z)
1112 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1114 ;;; Z may be any number, but the result is always a complex.
1115 (defun complex-asinh (z)
1116 (declare (type (or rational complex) z))
1117 ;; asinh z = -i * asin (i*z)
1118 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1119 (result (complex-asin iz)))
1120 (complex (imagpart result)
1121 (- (realpart result)))))
1123 ;;; Compute atan z = atanh (i*z) / i.
1125 ;;; Z may be any number, but the result is always a complex.
1126 (defun complex-atan (z)
1127 (declare (type (or rational complex) z))
1128 ;; atan z = -i * atanh (i*z)
1129 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1130 (result (complex-atanh iz)))
1131 (complex (imagpart result)
1132 (- (realpart result)))))
1134 ;;; Compute tan z = -i * tanh(i * z)
1136 ;;; Z may be any number, but the result is always a complex.
1137 (defun complex-tan (z)
1138 (declare (type (or rational complex) z))
1139 ;; tan z = -i * tanh(i*z)
1140 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1141 (result (complex-tanh iz)))
1142 (complex (imagpart result)
1143 (- (realpart result)))))