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))))
28 (declaim (inline ,function))
29 (sb!alien:define-alien-routine (,name ,function) double-float
30 ,@(let ((results nil))
31 (dotimes (i num-args (nreverse results))
32 (push (list (intern (format nil "ARG-~D" i))
36 (defun handle-reals (function var)
37 `((((foreach fixnum single-float bignum ratio))
38 (coerce (,function (coerce ,var 'double-float)) 'single-float))
44 ;;;; stubs for the Unix math library
46 ;;;; Many of these are unnecessary on the X86 because they're built
50 #!-x86 (def-math-rtn "sin" 1)
51 #!-x86 (def-math-rtn "cos" 1)
52 #!-x86 (def-math-rtn "tan" 1)
53 (def-math-rtn "asin" 1)
54 (def-math-rtn "acos" 1)
55 #!-x86 (def-math-rtn "atan" 1)
56 #!-x86 (def-math-rtn "atan2" 2)
57 (def-math-rtn "sinh" 1)
58 (def-math-rtn "cosh" 1)
59 (def-math-rtn "tanh" 1)
60 (def-math-rtn "asinh" 1)
61 (def-math-rtn "acosh" 1)
62 (def-math-rtn "atanh" 1)
64 ;;; exponential and logarithmic
65 #!-x86 (def-math-rtn "exp" 1)
66 #!-x86 (def-math-rtn "log" 1)
67 #!-x86 (def-math-rtn "log10" 1)
68 (def-math-rtn "pow" 2)
69 #!-x86 (def-math-rtn "sqrt" 1)
70 (def-math-rtn "hypot" 2)
71 #!-(or hpux x86) (def-math-rtn "log1p" 1)
77 "Return e raised to the power NUMBER."
78 (number-dispatch ((number number))
79 (handle-reals %exp number)
81 (* (exp (realpart number))
82 (cis (imagpart number))))))
84 ;;; INTEXP -- Handle the rational base, integer power case.
86 (declaim (type (or integer null) *intexp-maximum-exponent*))
87 (defparameter *intexp-maximum-exponent* nil)
89 ;;; This function precisely calculates base raised to an integral
90 ;;; power. It separates the cases by the sign of power, for efficiency
91 ;;; reasons, as powers can be calculated more efficiently if power is
92 ;;; a positive integer. Values of power are calculated as positive
93 ;;; integers, and inverted if negative.
94 (defun intexp (base power)
95 (when (and *intexp-maximum-exponent*
96 (> (abs power) *intexp-maximum-exponent*))
97 (error "The absolute value of ~S exceeds ~S."
98 power '*intexp-maximum-exponent*))
100 (/ (intexp base (- power))))
104 (do ((nextn (ash power -1) (ash power -1))
105 (total (if (oddp power) base 1)
106 (if (oddp power) (* base total) total)))
107 ((zerop nextn) total)
108 (setq base (* base base))
109 (setq power nextn)))))
111 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
112 ;;; floating point stuff. If both args are real, we try %POW right
113 ;;; off, assuming it will return 0 if the result may be complex. If
114 ;;; so, we call COMPLEX-POW which directly computes the complex
115 ;;; result. We also separate the complex-real and real-complex cases
116 ;;; from the general complex case.
117 (defun expt (base power)
119 "Return BASE raised to the POWER."
121 (let ((result (1+ (* base power))))
122 (if (and (floatp result) (float-nan-p result))
125 (labels (;; determine if the double float is an integer.
126 ;; 0 - not an integer
130 (declare (type (unsigned-byte 31) ihi)
131 (type (unsigned-byte 32) lo)
132 (optimize (speed 3) (safety 0)))
134 (declare (type fixnum isint))
135 (cond ((>= ihi #x43400000) ; exponent >= 53
138 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
139 (declare (type (mod 53) k))
141 (let* ((shift (- 52 k))
142 (j (logand (ash lo (- shift))))
144 (declare (type (mod 32) shift)
145 (type (unsigned-byte 32) j j2))
147 (setq isint (- 2 (logand j 1))))))
149 (let* ((shift (- 20 k))
150 (j (ash ihi (- shift)))
152 (declare (type (mod 32) shift)
153 (type (unsigned-byte 31) j j2))
155 (setq isint (- 2 (logand j 1))))))))))
157 (real-expt (x y rtype)
158 (let ((x (coerce x 'double-float))
159 (y (coerce y 'double-float)))
160 (declare (double-float x y))
161 (let* ((x-hi (sb!kernel:double-float-high-bits x))
162 (x-lo (sb!kernel:double-float-low-bits x))
163 (x-ihi (logand x-hi #x7fffffff))
164 (y-hi (sb!kernel:double-float-high-bits y))
165 (y-lo (sb!kernel:double-float-low-bits y))
166 (y-ihi (logand y-hi #x7fffffff)))
167 (declare (type (signed-byte 32) x-hi y-hi)
168 (type (unsigned-byte 31) x-ihi y-ihi)
169 (type (unsigned-byte 32) x-lo y-lo))
171 (when (zerop (logior y-ihi y-lo))
172 (return-from real-expt (coerce 1d0 rtype)))
174 (when (or (> x-ihi #x7ff00000)
175 (and (= x-ihi #x7ff00000) (/= x-lo 0))
177 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
178 (return-from real-expt (coerce (+ x y) rtype)))
179 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
180 (declare (type fixnum yisint))
181 ;; special value of y
182 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
184 (return-from real-expt
185 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
187 (coerce (- y y) rtype))
188 ((>= x-ihi #x3ff00000)
189 ;; (|x|>1)**+-inf = inf,0
194 ;; (|x|<1)**-,+inf = inf,0
197 (coerce 0 rtype))))))
199 (let ((abs-x (abs x)))
200 (declare (double-float abs-x))
201 ;; special value of x
202 (when (and (zerop x-lo)
203 (or (= x-ihi #x7ff00000) (zerop x-ihi)
204 (= x-ihi #x3ff00000)))
205 ;; x is +-0,+-inf,+-1
206 (let ((z (if (< y-hi 0)
207 (/ 1 abs-x) ; z = (1/|x|)
209 (declare (double-float z))
211 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
213 (let ((y*pi (* y pi)))
214 (declare (double-float y*pi))
215 (return-from real-expt
217 (coerce (%cos y*pi) rtype)
218 (coerce (%sin y*pi) rtype)))))
220 ;; (x<0)**odd = -(|x|**odd)
222 (return-from real-expt (coerce z rtype))))
226 (coerce (sb!kernel::%pow x y) rtype)
228 (let ((pow (sb!kernel::%pow abs-x y)))
229 (declare (double-float pow))
232 (coerce (* -1d0 pow) rtype))
236 (let ((y*pi (* y pi)))
237 (declare (double-float y*pi))
239 (coerce (* pow (%cos y*pi))
241 (coerce (* pow (%sin y*pi))
243 (declare (inline real-expt))
244 (number-dispatch ((base number) (power number))
245 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
247 (((foreach single-float double-float) rational)
248 (real-expt base power '(dispatch-type base)))
249 (((foreach fixnum (or bignum ratio) single-float)
250 (foreach ratio single-float))
251 (real-expt base power 'single-float))
252 (((foreach fixnum (or bignum ratio) single-float double-float)
254 (real-expt base power 'double-float))
255 ((double-float single-float)
256 (real-expt base power 'double-float))
257 (((foreach (complex rational) (complex float)) rational)
258 (* (expt (abs base) power)
259 (cis (* power (phase base)))))
260 (((foreach fixnum (or bignum ratio) single-float double-float)
262 (if (and (zerop base) (plusp (realpart power)))
264 (exp (* power (log base)))))
265 (((foreach (complex float) (complex rational))
266 (foreach complex double-float single-float))
267 (if (and (zerop base) (plusp (realpart power)))
269 (exp (* power (log base)))))))))
271 ;;; FIXME: Maybe rename this so that it's clearer that it only works
274 (declare (type integer x))
277 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
278 ;; log2(f). So we grab the top few bits of x and scale that
279 ;; appropriately, take the log of it and add it to n.
281 ;; Motivated by an attempt to get LOG to work better on bignums.
282 (let ((n (integer-length x)))
283 (if (< n sb!vm:double-float-digits)
284 (log (coerce x 'double-float) 2.0d0)
285 (let ((f (ldb (byte sb!vm:double-float-digits
286 (- n sb!vm:double-float-digits))
288 (+ n (log (scale-float (coerce f 'double-float)
289 (- sb!vm:double-float-digits))
292 (defun log (number &optional (base nil base-p))
294 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
297 ((zerop base) 0f0) ; FIXME: type
298 ((and (typep number '(integer (0) *))
299 (typep base '(integer (0) *)))
300 (coerce (/ (log2 number) (log2 base)) 'single-float))
301 (t (/ (log number) (log base))))
302 (number-dispatch ((number number))
303 (((foreach fixnum bignum))
305 (complex (log (- number)) (coerce pi 'single-float))
306 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
309 (complex (log (- number)) (coerce pi 'single-float))
310 (let ((numerator (numerator number))
311 (denominator (denominator number)))
312 (if (= (integer-length numerator)
313 (integer-length denominator))
314 (coerce (%log1p (coerce (- number 1) 'double-float))
316 (coerce (/ (- (log2 numerator) (log2 denominator))
317 (log (exp 1.0d0) 2.0d0))
319 (((foreach single-float double-float))
320 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
321 ;; Since this doesn't seem to be an implementation issue
322 ;; I (pw) take the Kahan result.
323 (if (< (float-sign number)
324 (coerce 0 '(dispatch-type number)))
325 (complex (log (- number)) (coerce pi '(dispatch-type number)))
326 (coerce (%log (coerce number 'double-float))
327 '(dispatch-type number))))
329 (complex-log number)))))
333 "Return the square root of NUMBER."
334 (number-dispatch ((number number))
335 (((foreach fixnum bignum ratio))
337 (complex-sqrt number)
338 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
339 (((foreach single-float double-float))
341 (complex-sqrt (complex number))
342 (coerce (%sqrt (coerce number 'double-float))
343 '(dispatch-type number))))
345 (complex-sqrt number))))
347 ;;;; trigonometic and related functions
351 "Return the absolute value of the number."
352 (number-dispatch ((number number))
353 (((foreach single-float double-float fixnum rational))
356 (let ((rx (realpart number))
357 (ix (imagpart number)))
360 (sqrt (+ (* rx rx) (* ix ix))))
362 (coerce (%hypot (coerce rx 'double-float)
363 (coerce ix 'double-float))
368 (defun phase (number)
370 "Return the angle part of the polar representation of a complex number.
371 For complex numbers, this is (atan (imagpart number) (realpart number)).
372 For non-complex positive numbers, this is 0. For non-complex negative
377 (coerce pi 'single-float)
380 (if (minusp (float-sign number))
381 (coerce pi 'single-float)
384 (if (minusp (float-sign number))
385 (coerce pi 'double-float)
388 (atan (imagpart number) (realpart number)))))
392 "Return the sine of NUMBER."
393 (number-dispatch ((number number))
394 (handle-reals %sin number)
396 (let ((x (realpart number))
397 (y (imagpart number)))
398 (complex (* (sin x) (cosh y))
399 (* (cos x) (sinh y)))))))
403 "Return the cosine of NUMBER."
404 (number-dispatch ((number number))
405 (handle-reals %cos number)
407 (let ((x (realpart number))
408 (y (imagpart number)))
409 (complex (* (cos x) (cosh y))
410 (- (* (sin x) (sinh y))))))))
414 "Return the tangent of NUMBER."
415 (number-dispatch ((number number))
416 (handle-reals %tan number)
418 (complex-tan number))))
422 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
423 (declare (type real theta))
424 (complex (cos theta) (sin theta)))
428 "Return the arc sine of NUMBER."
429 (number-dispatch ((number number))
431 (if (or (> number 1) (< number -1))
432 (complex-asin number)
433 (coerce (%asin (coerce number 'double-float)) 'single-float)))
434 (((foreach single-float double-float))
435 (if (or (> number (coerce 1 '(dispatch-type number)))
436 (< number (coerce -1 '(dispatch-type number))))
437 (complex-asin (complex number))
438 (coerce (%asin (coerce number 'double-float))
439 '(dispatch-type number))))
441 (complex-asin number))))
445 "Return the arc cosine of NUMBER."
446 (number-dispatch ((number number))
448 (if (or (> number 1) (< number -1))
449 (complex-acos number)
450 (coerce (%acos (coerce number 'double-float)) 'single-float)))
451 (((foreach single-float double-float))
452 (if (or (> number (coerce 1 '(dispatch-type number)))
453 (< number (coerce -1 '(dispatch-type number))))
454 (complex-acos (complex number))
455 (coerce (%acos (coerce number 'double-float))
456 '(dispatch-type number))))
458 (complex-acos number))))
460 (defun atan (y &optional (x nil xp))
462 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
465 (declare (type double-float y x)
466 (values double-float))
469 (if (plusp (float-sign x))
472 (float-sign y (/ pi 2)))
474 (number-dispatch ((y real) (x real))
476 (foreach double-float single-float fixnum bignum ratio))
477 (atan2 y (coerce x 'double-float)))
478 (((foreach single-float fixnum bignum ratio)
480 (atan2 (coerce y 'double-float) x))
481 (((foreach single-float fixnum bignum ratio)
482 (foreach single-float fixnum bignum ratio))
483 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
485 (number-dispatch ((y number))
486 (handle-reals %atan y)
490 ;;; It seems that every target system has a C version of sinh, cosh,
491 ;;; and tanh. Let's use these for reals because the original
492 ;;; implementations based on the definitions lose big in round-off
493 ;;; error. These bad definitions also mean that sin and cos for
494 ;;; complex numbers can also lose big.
498 "Return the hyperbolic sine of NUMBER."
499 (number-dispatch ((number number))
500 (handle-reals %sinh number)
502 (let ((x (realpart number))
503 (y (imagpart number)))
504 (complex (* (sinh x) (cos y))
505 (* (cosh x) (sin y)))))))
509 "Return the hyperbolic cosine of NUMBER."
510 (number-dispatch ((number number))
511 (handle-reals %cosh number)
513 (let ((x (realpart number))
514 (y (imagpart number)))
515 (complex (* (cosh x) (cos y))
516 (* (sinh x) (sin y)))))))
520 "Return the hyperbolic tangent of NUMBER."
521 (number-dispatch ((number number))
522 (handle-reals %tanh number)
524 (complex-tanh number))))
526 (defun asinh (number)
528 "Return the hyperbolic arc sine of NUMBER."
529 (number-dispatch ((number number))
530 (handle-reals %asinh number)
532 (complex-asinh number))))
534 (defun acosh (number)
536 "Return the hyperbolic arc cosine of NUMBER."
537 (number-dispatch ((number number))
539 ;; acosh is complex if number < 1
541 (complex-acosh number)
542 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
543 (((foreach single-float double-float))
544 (if (< number (coerce 1 '(dispatch-type number)))
545 (complex-acosh (complex number))
546 (coerce (%acosh (coerce number 'double-float))
547 '(dispatch-type number))))
549 (complex-acosh number))))
551 (defun atanh (number)
553 "Return the hyperbolic arc tangent of NUMBER."
554 (number-dispatch ((number number))
556 ;; atanh is complex if |number| > 1
557 (if (or (> number 1) (< number -1))
558 (complex-atanh number)
559 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
560 (((foreach single-float double-float))
561 (if (or (> number (coerce 1 '(dispatch-type number)))
562 (< number (coerce -1 '(dispatch-type number))))
563 (complex-atanh (complex number))
564 (coerce (%atanh (coerce number 'double-float))
565 '(dispatch-type number))))
567 (complex-atanh number))))
569 ;;; HP-UX does not supply a C version of log1p, so use the definition.
571 ;;; FIXME: This is really not a good definition. As per Raymond Toy
572 ;;; working on CMU CL, "The definition really loses big-time in
573 ;;; roundoff as x gets small."
575 #!-sb-fluid (declaim (inline %log1p))
577 (defun %log1p (number)
578 (declare (double-float number)
579 (optimize (speed 3) (safety 0)))
580 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
582 ;;;; not-OLD-SPECFUN stuff
584 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
585 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
586 ;;;; the standard special function system.)
588 ;;;; This is a set of routines that implement many elementary
589 ;;;; transcendental functions as specified by ANSI Common Lisp. The
590 ;;;; implementation is based on Kahan's paper.
592 ;;;; I believe I have accurately implemented the routines and are
593 ;;;; correct, but you may want to check for your self.
595 ;;;; These functions are written for CMU Lisp and take advantage of
596 ;;;; some of the features available there. It may be possible,
597 ;;;; however, to port this to other Lisps.
599 ;;;; Some functions are significantly more accurate than the original
600 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
601 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
602 ;;;; answer is pi + i*log(2-sqrt(3)).
604 ;;;; All of the implemented functions will take any number for an
605 ;;;; input, but the result will always be a either a complex
606 ;;;; single-float or a complex double-float.
608 ;;;; general functions:
620 ;;;; utility functions:
623 ;;;; internal functions:
624 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
627 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
628 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
629 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
632 ;;;; The original CMU CL code requested:
633 ;;;; Please send any bug reports, comments, or improvements to
634 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
636 ;;; FIXME: In SBCL, the floating point infinity constants like
637 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
638 ;;; constants at cross-compile time, because the cross-compilation
639 ;;; host might not have support for floating point infinities. Thus,
640 ;;; they're effectively implemented as special variable references,
641 ;;; and the code below which uses them might be unnecessarily
642 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
643 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
644 ;;; special variable references with (probably equally slow)
647 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
648 ;;; differ in their interpretations of the real line, IMAGPART was
649 ;;; patch, which without a certain amount of effort would have altered
650 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
651 ;;; were patched to use explicit COMPLEX, rather than implicitly
652 ;;; passing in real numbers for treatment with IMAGPART, and these
653 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
654 ;;; however, someone needs to go back to Kahan for the definitive
655 ;;; answer for treatment of negative real floating point numbers and
656 ;;; branch cuts. If adjustment is needed, it is probably the removal
657 ;;; of explicit calls to COMPLEX in the clients of irrational
658 ;;; functions. -- a slightly bitter CSR, 2004-05-16
660 (declaim (inline square))
662 (declare (double-float x))
665 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
667 ;;; If you have these functions in libm, perhaps they should be used
668 ;;; instead of these Lisp versions. These versions are probably good
669 ;;; enough, especially since they are portable.
671 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
672 ;;; the underlying floating-point format.)
673 (declaim (inline scalb))
675 (declare (type double-float x)
676 (type double-float-exponent n))
679 ;;; This is like LOGB, but X is not infinity and non-zero and not a
680 ;;; NaN, so we can always return an integer.
681 (declaim (inline logb-finite))
682 (defun logb-finite (x)
683 (declare (type double-float x))
684 (multiple-value-bind (signif exponent sign)
686 (declare (ignore signif sign))
687 ;; DECODE-FLOAT is almost right, except that the exponent is off
691 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
692 ;;; For the special cases, the following values are used:
695 ;;; +/- infinity +infinity
698 (declare (type double-float x))
699 (cond ((float-nan-p x)
701 ((float-infinity-p x)
702 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
703 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
705 ;; The answer is negative infinity, but we are supposed to
706 ;; signal divide-by-zero, so do the actual division
712 ;;; This function is used to create a complex number of the
713 ;;; appropriate type:
714 ;;; Create complex number with real part X and imaginary part Y
715 ;;; such that has the same type as Z. If Z has type (complex
716 ;;; rational), the X and Y are coerced to single-float.
717 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
718 (error "needs work for long float support"))
719 (declaim (inline coerce-to-complex-type))
720 (defun coerce-to-complex-type (x y z)
721 (declare (double-float x y)
723 (if (typep (realpart z) 'double-float)
725 ;; Convert anything that's not already a DOUBLE-FLOAT (because
726 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
727 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
728 (complex (float x 1f0)
731 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
732 ;;; result is r + i*k, where k is an integer.
733 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
734 (error "needs work for long float support"))
736 (let ((x (float (realpart z) 1d0))
737 (y (float (imagpart z) 1d0)))
738 ;; Would this be better handled using an exception handler to
739 ;; catch the overflow or underflow signal? For now, we turn all
740 ;; traps off and look at the accrued exceptions to see if any
741 ;; signal would have been raised.
742 (with-float-traps-masked (:underflow :overflow)
743 (let ((rho (+ (square x) (square y))))
744 (declare (optimize (speed 3) (space 0)))
745 (cond ((and (or (float-nan-p rho)
746 (float-infinity-p rho))
747 (or (float-infinity-p (abs x))
748 (float-infinity-p (abs y))))
749 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
751 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
753 ((let ((threshold #.(/ least-positive-double-float
754 double-float-epsilon))
755 (traps (ldb sb!vm::float-sticky-bits
756 (sb!vm:floating-point-modes))))
757 ;; Overflow raised or (underflow raised and rho <
759 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
760 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
763 ;; If we're here, neither x nor y are infinity and at
764 ;; least one is non-zero.. Thus logb returns a nice
766 (let ((k (- (logb-finite (max (abs x) (abs y))))))
767 (values (+ (square (scalb x k))
768 (square (scalb y k)))
773 ;;; principal square root of Z
775 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
776 (defun complex-sqrt (z)
777 ;; KLUDGE: Here and below, we can't just declare Z to be of type
778 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
779 ;; Since there isn't a rational negative zero, this is OK from the
780 ;; point of view of getting the right answer in the face of branch
781 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
782 ;; still ugly. -- CSR, 2004-05-16
783 (declare (type (or complex rational) z))
784 (multiple-value-bind (rho k)
786 (declare (type (or (member 0d0) (double-float 0d0)) rho)
788 (let ((x (float (realpart z) 1.0d0))
789 (y (float (imagpart z) 1.0d0))
792 (declare (double-float x y eta nu))
795 ;; space 0 to get maybe-inline functions inlined.
796 (declare (optimize (speed 3) (space 0)))
798 (if (not (float-nan-p x))
799 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
804 (setf k (1- (ash k -1)))
805 (setf rho (+ rho rho))))
807 (setf rho (scalb (sqrt rho) k))
813 (when (not (float-infinity-p (abs nu)))
814 (setf nu (/ (/ nu rho) 2d0)))
817 (setf nu (float-sign y rho))))
818 (coerce-to-complex-type eta nu z)))))
820 ;;; Compute log(2^j*z).
822 ;;; This is for use with J /= 0 only when |z| is huge.
823 (defun complex-log-scaled (z j)
824 (declare (type (or rational complex) z)
826 ;; The constants t0, t1, t2 should be evaluated to machine
827 ;; precision. In addition, Kahan says the accuracy of log1p
828 ;; influences the choices of these constants but doesn't say how to
829 ;; choose them. We'll just assume his choices matches our
830 ;; implementation of log1p.
831 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
835 (x (float (realpart z) 1.0d0))
836 (y (float (imagpart z) 1.0d0)))
837 (multiple-value-bind (rho k)
839 (declare (optimize (speed 3)))
840 (let ((beta (max (abs x) (abs y)))
841 (theta (min (abs x) (abs y))))
842 (coerce-to-complex-type (if (and (zerop k)
846 (/ (%log1p (+ (* (- beta 1.0d0)
855 ;;; log of Z = log |Z| + i * arg Z
857 ;;; Z may be any number, but the result is always a complex.
858 (defun complex-log (z)
859 (declare (type (or rational complex) z))
860 (complex-log-scaled z 0))
862 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
863 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
864 ;;; The reason for the imaginary part is caused by the fact that arg
865 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
866 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
867 (defun complex-atanh (z)
868 (declare (type (or rational complex) z))
870 (theta (/ (sqrt most-positive-double-float) 4.0d0))
871 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
872 (half-pi (/ pi 2.0d0))
873 (rp (float (realpart z) 1.0d0))
874 (beta (float-sign rp 1.0d0))
876 (y (* beta (- (float (imagpart z) 1.0d0))))
879 ;; Shouldn't need this declare.
880 (declare (double-float x y))
882 (declare (optimize (speed 3)))
883 (cond ((or (> x theta)
885 ;; To avoid overflow...
886 (setf nu (float-sign y half-pi))
887 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
888 ;; which can cause overflow. Arrange this computation so
889 ;; that it won't overflow.
890 (setf eta (let* ((x-bigger (> x (abs y)))
891 (r (if x-bigger (/ y x) (/ x y)))
892 (d (+ 1.0d0 (* r r))))
897 ;; Should this be changed so that if y is zero, eta is set
898 ;; to +infinity instead of approx 176? In any case
899 ;; tanh(176) is 1.0d0 within working precision.
900 (let ((t1 (+ 4d0 (square y)))
901 (t2 (+ (abs y) rho)))
902 (setf eta (log (/ (sqrt (sqrt t1))
906 (+ half-pi (atan (* 0.5d0 t2))))))))
908 (let ((t1 (+ (abs y) rho)))
909 ;; Normal case using log1p(x) = log(1 + x)
911 (%log1p (/ (* 4.0d0 x)
912 (+ (square (- 1.0d0 x))
919 (coerce-to-complex-type (* beta eta)
923 ;;; Compute tanh z = sinh z / cosh z.
924 (defun complex-tanh (z)
925 (declare (type (or rational complex) z))
926 (let ((x (float (realpart z) 1.0d0))
927 (y (float (imagpart z) 1.0d0)))
929 ;; space 0 to get maybe-inline functions inlined
930 (declare (optimize (speed 3) (space 0)))
932 ;; FIXME: this form is hideously broken wrt
933 ;; cross-compilation portability. Much else in this
934 ;; file is too, of course, sometimes hidden by
935 ;; constant-folding, but this one in particular clearly
936 ;; depends on host and target
937 ;; MOST-POSITIVE-DOUBLE-FLOATs being equal. -- CSR,
940 (log most-positive-double-float))
942 (coerce-to-complex-type (float-sign x)
946 (beta (+ 1.0d0 (* tv tv)))
948 (rho (sqrt (+ 1.0d0 (* s s)))))
949 (if (float-infinity-p (abs tv))
950 (coerce-to-complex-type (/ rho s)
953 (let ((den (+ 1.0d0 (* beta s s))))
954 (coerce-to-complex-type (/ (* beta rho s)
959 ;;; Compute acos z = pi/2 - asin z.
961 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
962 (defun complex-acos (z)
963 ;; Kahan says we should only compute the parts needed. Thus, the
964 ;; REALPART's below should only compute the real part, not the whole
965 ;; complex expression. Doing this can be important because we may get
966 ;; spurious signals that occur in the part that we are not using.
968 ;; However, we take a pragmatic approach and just use the whole
971 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
972 ;; it's the conjugate of the square root or the square root of the
973 ;; conjugate. This needs to be checked.
975 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
976 ;; same as (sqrt (conjugate z)) for all z. This follows because
978 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
980 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
982 ;; and these two expressions are equal if and only if arg conj z =
983 ;; -arg z, which is clearly true for all z.
984 (declare (type (or rational complex) z))
985 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
986 (sqrt-1-z (complex-sqrt (- 1 z))))
987 (with-float-traps-masked (:divide-by-zero)
988 (complex (* 2 (atan (/ (realpart sqrt-1-z)
989 (realpart sqrt-1+z))))
990 (asinh (imagpart (* (conjugate sqrt-1+z)
993 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
995 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
996 (defun complex-acosh (z)
997 (declare (type (or rational complex) z))
998 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
999 (sqrt-z+1 (complex-sqrt (+ z 1))))
1000 (with-float-traps-masked (:divide-by-zero)
1001 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1003 (* 2 (atan (/ (imagpart sqrt-z-1)
1004 (realpart sqrt-z+1))))))))
1006 ;;; Compute asin z = asinh(i*z)/i.
1008 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1009 (defun complex-asin (z)
1010 (declare (type (or rational complex) z))
1011 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1012 (sqrt-1+z (complex-sqrt (+ 1 z))))
1013 (with-float-traps-masked (:divide-by-zero)
1014 (complex (atan (/ (realpart z)
1015 (realpart (* sqrt-1-z sqrt-1+z))))
1016 (asinh (imagpart (* (conjugate sqrt-1-z)
1019 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1021 ;;; Z may be any number, but the result is always a complex.
1022 (defun complex-asinh (z)
1023 (declare (type (or rational complex) z))
1024 ;; asinh z = -i * asin (i*z)
1025 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1026 (result (complex-asin iz)))
1027 (complex (imagpart result)
1028 (- (realpart result)))))
1030 ;;; Compute atan z = atanh (i*z) / i.
1032 ;;; Z may be any number, but the result is always a complex.
1033 (defun complex-atan (z)
1034 (declare (type (or rational complex) z))
1035 ;; atan z = -i * atanh (i*z)
1036 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1037 (result (complex-atanh iz)))
1038 (complex (imagpart result)
1039 (- (realpart result)))))
1041 ;;; Compute tan z = -i * tanh(i * z)
1043 ;;; Z may be any number, but the result is always a complex.
1044 (defun complex-tan (z)
1045 (declare (type (or rational complex) z))
1046 ;; tan z = -i * tanh(i*z)
1047 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1048 (result (complex-tanh iz)))
1049 (complex (imagpart result)
1050 (- (realpart result)))))