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
17 (defconstant pi 3.14159265358979323846264338327950288419716939937511L0)
18 ;(defconstant e 2.71828182845904523536028747135266249775724709369996L0)
20 ;;; Make these INLINE, since the call to C is at least as compact as a
21 ;;; Lisp call, and saves number consing to boot.
22 (eval-when (:compile-toplevel :execute)
24 (sb!xc:defmacro def-math-rtn (name num-args)
25 (let ((function (symbolicate "%" (string-upcase name))))
27 (proclaim '(inline ,function))
28 (sb!alien:define-alien-routine (,name ,function) double-float
29 ,@(let ((results nil))
30 (dotimes (i num-args (nreverse results))
31 (push (list (intern (format nil "ARG-~D" i))
35 (defun handle-reals (function var)
36 `((((foreach fixnum single-float bignum ratio))
37 (coerce (,function (coerce ,var 'double-float)) 'single-float))
43 ;;;; stubs for the Unix math library
45 ;;;; Many of these are unnecessary on the X86 because they're built
49 #!-x86 (def-math-rtn "sin" 1)
50 #!-x86 (def-math-rtn "cos" 1)
51 #!-x86 (def-math-rtn "tan" 1)
52 (def-math-rtn "asin" 1)
53 (def-math-rtn "acos" 1)
54 #!-x86 (def-math-rtn "atan" 1)
55 #!-x86 (def-math-rtn "atan2" 2)
56 (def-math-rtn "sinh" 1)
57 (def-math-rtn "cosh" 1)
58 (def-math-rtn "tanh" 1)
59 (def-math-rtn "asinh" 1)
60 (def-math-rtn "acosh" 1)
61 (def-math-rtn "atanh" 1)
63 ;;; exponential and logarithmic
64 #!-x86 (def-math-rtn "exp" 1)
65 #!-x86 (def-math-rtn "log" 1)
66 #!-x86 (def-math-rtn "log10" 1)
67 (def-math-rtn "pow" 2)
68 #!-x86 (def-math-rtn "sqrt" 1)
69 (def-math-rtn "hypot" 2)
70 #!-(or hpux x86) (def-math-rtn "log1p" 1)
76 "Return e raised to the power NUMBER."
77 (number-dispatch ((number number))
78 (handle-reals %exp number)
80 (* (exp (realpart number))
81 (cis (imagpart number))))))
83 ;;; INTEXP -- Handle the rational base, integer power case.
85 ;;; FIXME: As long as the system dies on stack overflow or memory
86 ;;; exhaustion, it seems reasonable to have this, but its default
87 ;;; should be NIL, and when it's NIL, anything should be accepted.
88 (defparameter *intexp-maximum-exponent* 10000)
90 ;;; This function precisely calculates base raised to an integral
91 ;;; power. It separates the cases by the sign of power, for efficiency
92 ;;; reasons, as powers can be calculated more efficiently if power is
93 ;;; a positive integer. Values of power are calculated as positive
94 ;;; integers, and inverted if negative.
95 (defun intexp (base power)
96 (when (> (abs power) *intexp-maximum-exponent*)
97 ;; FIXME: should be ordinary error, not CERROR. (Once we set the
98 ;; default for the variable to NIL, the un-continuable error will
99 ;; be less obnoxious.)
100 (cerror "Continue with calculation."
101 "The absolute value of ~S exceeds ~S."
102 power '*intexp-maximum-exponent* base power))
103 (cond ((minusp power)
104 (/ (intexp base (- power))))
108 (do ((nextn (ash power -1) (ash power -1))
109 (total (if (oddp power) base 1)
110 (if (oddp power) (* base total) total)))
111 ((zerop nextn) total)
112 (setq base (* base base))
113 (setq power nextn)))))
115 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
116 ;;; floating point stuff. If both args are real, we try %POW right
117 ;;; off, assuming it will return 0 if the result may be complex. If
118 ;;; so, we call COMPLEX-POW which directly computes the complex
119 ;;; result. We also separate the complex-real and real-complex cases
120 ;;; from the general complex case.
121 (defun expt (base power)
123 "Return BASE raised to the POWER."
126 (labels (;; determine if the double float is an integer.
127 ;; 0 - not an integer
131 (declare (type (unsigned-byte 31) ihi)
132 (type (unsigned-byte 32) lo)
133 (optimize (speed 3) (safety 0)))
135 (declare (type fixnum isint))
136 (cond ((>= ihi #x43400000) ; exponent >= 53
139 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
140 (declare (type (mod 53) k))
142 (let* ((shift (- 52 k))
143 (j (logand (ash lo (- shift))))
145 (declare (type (mod 32) shift)
146 (type (unsigned-byte 32) j j2))
148 (setq isint (- 2 (logand j 1))))))
150 (let* ((shift (- 20 k))
151 (j (ash ihi (- shift)))
153 (declare (type (mod 32) shift)
154 (type (unsigned-byte 31) j j2))
156 (setq isint (- 2 (logand j 1))))))))))
158 (real-expt (x y rtype)
159 (let ((x (coerce x 'double-float))
160 (y (coerce y 'double-float)))
161 (declare (double-float x y))
162 (let* ((x-hi (sb!kernel:double-float-high-bits x))
163 (x-lo (sb!kernel:double-float-low-bits x))
164 (x-ihi (logand x-hi #x7fffffff))
165 (y-hi (sb!kernel:double-float-high-bits y))
166 (y-lo (sb!kernel:double-float-low-bits y))
167 (y-ihi (logand y-hi #x7fffffff)))
168 (declare (type (signed-byte 32) x-hi y-hi)
169 (type (unsigned-byte 31) x-ihi y-ihi)
170 (type (unsigned-byte 32) x-lo y-lo))
172 (when (zerop (logior y-ihi y-lo))
173 (return-from real-expt (coerce 1d0 rtype)))
175 (when (or (> x-ihi #x7ff00000)
176 (and (= x-ihi #x7ff00000) (/= x-lo 0))
178 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
179 (return-from real-expt (coerce (+ x y) rtype)))
180 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
181 (declare (type fixnum yisint))
182 ;; special value of y
183 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
185 (return-from real-expt
186 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
188 (coerce (- y y) rtype))
189 ((>= x-ihi #x3ff00000)
190 ;; (|x|>1)**+-inf = inf,0
195 ;; (|x|<1)**-,+inf = inf,0
198 (coerce 0 rtype))))))
200 (let ((abs-x (abs x)))
201 (declare (double-float abs-x))
202 ;; special value of x
203 (when (and (zerop x-lo)
204 (or (= x-ihi #x7ff00000) (zerop x-ihi)
205 (= x-ihi #x3ff00000)))
206 ;; x is +-0,+-inf,+-1
207 (let ((z (if (< y-hi 0)
208 (/ 1 abs-x) ; z = (1/|x|)
210 (declare (double-float z))
212 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
214 (let ((y*pi (* y pi)))
215 (declare (double-float y*pi))
216 (return-from real-expt
218 (coerce (%cos y*pi) rtype)
219 (coerce (%sin y*pi) rtype)))))
221 ;; (x<0)**odd = -(|x|**odd)
223 (return-from real-expt (coerce z rtype))))
227 (coerce (sb!kernel::%pow x y) rtype)
229 (let ((pow (sb!kernel::%pow abs-x y)))
230 (declare (double-float pow))
233 (coerce (* -1d0 pow) rtype))
237 (let ((y*pi (* y pi)))
238 (declare (double-float y*pi))
240 (coerce (* pow (%cos y*pi))
242 (coerce (* pow (%sin y*pi))
244 (declare (inline real-expt))
245 (number-dispatch ((base number) (power number))
246 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
248 (((foreach single-float double-float) rational)
249 (real-expt base power '(dispatch-type base)))
250 (((foreach fixnum (or bignum ratio) single-float)
251 (foreach ratio single-float))
252 (real-expt base power 'single-float))
253 (((foreach fixnum (or bignum ratio) single-float double-float)
255 (real-expt base power 'double-float))
256 ((double-float single-float)
257 (real-expt base power 'double-float))
258 (((foreach (complex rational) (complex float)) rational)
259 (* (expt (abs base) power)
260 (cis (* power (phase base)))))
261 (((foreach fixnum (or bignum ratio) single-float double-float)
263 (if (and (zerop base) (plusp (realpart power)))
265 (exp (* power (log base)))))
266 (((foreach (complex float) (complex rational))
267 (foreach complex double-float single-float))
268 (if (and (zerop base) (plusp (realpart power)))
270 (exp (* power (log base)))))))))
272 ;;; FIXME: Maybe rename this so that it's clearer that it only works
275 (declare (type integer x))
278 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
279 ;; log2(f). So we grab the top few bits of x and scale that
280 ;; appropriately, take the log of it and add it to n.
282 ;; Motivated by an attempt to get LOG to work better on bignums.
283 (let ((n (integer-length x)))
284 (if (< n sb!vm:double-float-digits)
285 (log (coerce x 'double-float) 2.0d0)
286 (let ((f (ldb (byte sb!vm:double-float-digits
287 (- n sb!vm:double-float-digits))
289 (+ n (log (scale-float (coerce f 'double-float)
290 (- sb!vm:double-float-digits))
293 (defun log (number &optional (base nil base-p))
295 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
298 ((zerop base) base) ; ANSI spec
299 ((and (typep number '(integer (0) *))
300 (typep base '(integer (0) *)))
301 (coerce (/ (log2 number) (log2 base)) 'single-float))
302 (t (/ (log number) (log base))))
303 (number-dispatch ((number number))
304 (((foreach fixnum bignum))
306 (complex (log (- number)) (coerce pi 'single-float))
307 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
310 (complex (log (- number)) (coerce pi 'single-float))
311 (let ((numerator (numerator number))
312 (denominator (denominator number)))
313 (if (= (integer-length numerator)
314 (integer-length denominator))
315 (coerce (%log1p (coerce (- number 1) 'double-float))
317 (coerce (- (log numerator) (log denominator))
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 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 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 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 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 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?
645 (declaim (inline square))
647 (declare (double-float x))
650 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
652 ;;; If you have these functions in libm, perhaps they should be used
653 ;;; instead of these Lisp versions. These versions are probably good
654 ;;; enough, especially since they are portable.
656 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
657 ;;; the underlying floating-point format.)
658 (declaim (inline scalb))
660 (declare (type double-float x)
661 (type double-float-exponent n))
664 ;;; This is like LOGB, but X is not infinity and non-zero and not a
665 ;;; NaN, so we can always return an integer.
666 (declaim (inline logb-finite))
667 (defun logb-finite (x)
668 (declare (type double-float x))
669 (multiple-value-bind (signif exponent sign)
671 (declare (ignore signif sign))
672 ;; DECODE-FLOAT is almost right, except that the exponent is off
676 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
677 ;;; For the special cases, the following values are used:
680 ;;; +/- infinity +infinity
683 (declare (type double-float x))
684 (cond ((float-nan-p x)
686 ((float-infinity-p x)
687 sb!ext:double-float-positive-infinity)
689 ;; The answer is negative infinity, but we are supposed to
690 ;; signal divide-by-zero, so do the actual division
696 ;;; This function is used to create a complex number of the
697 ;;; appropriate type:
698 ;;; Create complex number with real part X and imaginary part Y
699 ;;; such that has the same type as Z. If Z has type (complex
700 ;;; rational), the X and Y are coerced to single-float.
701 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
702 (error "needs work for long float support"))
703 (declaim (inline coerce-to-complex-type))
704 (defun coerce-to-complex-type (x y z)
705 (declare (double-float x y)
707 (if (subtypep (type-of (realpart z)) 'double-float)
709 ;; Convert anything that's not a DOUBLE-FLOAT to a SINGLE-FLOAT.
710 (complex (float x 1f0)
713 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
714 ;;; result is r + i*k, where k is an integer.
715 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
716 (error "needs work for long float support"))
718 (let ((x (float (realpart z) 1d0))
719 (y (float (imagpart z) 1d0)))
720 ;; Would this be better handled using an exception handler to
721 ;; catch the overflow or underflow signal? For now, we turn all
722 ;; traps off and look at the accrued exceptions to see if any
723 ;; signal would have been raised.
724 (with-float-traps-masked (:underflow :overflow)
725 (let ((rho (+ (square x) (square y))))
726 (declare (optimize (speed 3) (space 0)))
727 (cond ((and (or (float-nan-p rho)
728 (float-infinity-p rho))
729 (or (float-infinity-p (abs x))
730 (float-infinity-p (abs y))))
731 (values sb!ext:double-float-positive-infinity 0))
732 ((let ((threshold #.(/ least-positive-double-float
733 double-float-epsilon))
734 (traps (ldb sb!vm::float-sticky-bits
735 (sb!vm:floating-point-modes))))
736 ;; Overflow raised or (underflow raised and rho <
738 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
739 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
742 ;; If we're here, neither x nor y are infinity and at
743 ;; least one is non-zero.. Thus logb returns a nice
745 (let ((k (- (logb-finite (max (abs x) (abs y))))))
746 (values (+ (square (scalb x k))
747 (square (scalb y k)))
752 ;;; principal square root of Z
754 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
755 (defun complex-sqrt (z)
757 (multiple-value-bind (rho k)
759 (declare (type (or (member 0d0) (double-float 0d0)) rho)
761 (let ((x (float (realpart z) 1.0d0))
762 (y (float (imagpart z) 1.0d0))
765 (declare (double-float x y eta nu))
768 ;; space 0 to get maybe-inline functions inlined.
769 (declare (optimize (speed 3) (space 0)))
771 (if (not (float-nan-p x))
772 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
777 (setf k (1- (ash k -1)))
778 (setf rho (+ rho rho))))
780 (setf rho (scalb (sqrt rho) k))
786 (when (not (float-infinity-p (abs nu)))
787 (setf nu (/ (/ nu rho) 2d0)))
790 (setf nu (float-sign y rho))))
791 (coerce-to-complex-type eta nu z)))))
793 ;;; Compute log(2^j*z).
795 ;;; This is for use with J /= 0 only when |z| is huge.
796 (defun complex-log-scaled (z j)
799 ;; The constants t0, t1, t2 should be evaluated to machine
800 ;; precision. In addition, Kahan says the accuracy of log1p
801 ;; influences the choices of these constants but doesn't say how to
802 ;; choose them. We'll just assume his choices matches our
803 ;; implementation of log1p.
804 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
808 (x (float (realpart z) 1.0d0))
809 (y (float (imagpart z) 1.0d0)))
810 (multiple-value-bind (rho k)
812 (declare (optimize (speed 3)))
813 (let ((beta (max (abs x) (abs y)))
814 (theta (min (abs x) (abs y))))
815 (coerce-to-complex-type (if (and (zerop k)
819 (/ (%log1p (+ (* (- beta 1.0d0)
828 ;;; log of Z = log |Z| + i * arg Z
830 ;;; Z may be any number, but the result is always a complex.
831 (defun complex-log (z)
833 (complex-log-scaled z 0))
835 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
836 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
837 ;;; The reason for the imaginary part is caused by the fact that arg
838 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
839 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
840 (defun complex-atanh (z)
843 (theta (/ (sqrt most-positive-double-float) 4.0d0))
844 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
845 (half-pi (/ pi 2.0d0))
846 (rp (float (realpart z) 1.0d0))
847 (beta (float-sign rp 1.0d0))
849 (y (* beta (- (float (imagpart z) 1.0d0))))
852 ;; Shouldn't need this declare.
853 (declare (double-float x y))
855 (declare (optimize (speed 3)))
856 (cond ((or (> x theta)
858 ;; To avoid overflow...
859 (setf eta (float-sign y half-pi))
860 ;; nu is real part of 1/(x + iy). This is x/(x^2+y^2),
861 ;; which can cause overflow. Arrange this computation so
862 ;; that it won't overflow.
863 (setf nu (let* ((x-bigger (> x (abs y)))
864 (r (if x-bigger (/ y x) (/ x y)))
865 (d (+ 1.0d0 (* r r))))
870 ;; Should this be changed so that if y is zero, eta is set
871 ;; to +infinity instead of approx 176? In any case
872 ;; tanh(176) is 1.0d0 within working precision.
873 (let ((t1 (+ 4d0 (square y)))
874 (t2 (+ (abs y) rho)))
875 (setf eta (log (/ (sqrt (sqrt t1)))
879 (+ half-pi (atan (* 0.5d0 t2))))))))
881 (let ((t1 (+ (abs y) rho)))
882 ;; Normal case using log1p(x) = log(1 + x)
884 (%log1p (/ (* 4.0d0 x)
885 (+ (square (- 1.0d0 x))
892 (coerce-to-complex-type (* beta eta)
896 ;;; Compute tanh z = sinh z / cosh z.
897 (defun complex-tanh (z)
899 (let ((x (float (realpart z) 1.0d0))
900 (y (float (imagpart z) 1.0d0)))
902 ;; space 0 to get maybe-inline functions inlined
903 (declare (optimize (speed 3) (space 0)))
905 #-(or linux hpux) #.(/ (asinh most-positive-double-float) 4d0)
906 ;; This is more accurate under linux.
907 #+(or linux hpux) #.(/ (+ (log 2.0d0)
908 (log most-positive-double-float))
910 (coerce-to-complex-type (float-sign x)
914 (beta (+ 1.0d0 (* tv tv)))
916 (rho (sqrt (+ 1.0d0 (* s s)))))
917 (if (float-infinity-p (abs tv))
918 (coerce-to-complex-type (/ rho s)
921 (let ((den (+ 1.0d0 (* beta s s))))
922 (coerce-to-complex-type (/ (* beta rho s)
927 ;;; Compute acos z = pi/2 - asin z.
929 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
930 (defun complex-acos (z)
931 ;; Kahan says we should only compute the parts needed. Thus, the
932 ;; REALPART's below should only compute the real part, not the whole
933 ;; complex expression. Doing this can be important because we may get
934 ;; spurious signals that occur in the part that we are not using.
936 ;; However, we take a pragmatic approach and just use the whole
939 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
940 ;; it's the conjugate of the square root or the square root of the
941 ;; conjugate. This needs to be checked.
943 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
944 ;; same as (sqrt (conjugate z)) for all z. This follows because
946 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
948 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
950 ;; and these two expressions are equal if and only if arg conj z =
951 ;; -arg z, which is clearly true for all z.
953 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
954 (sqrt-1-z (complex-sqrt (- 1 z))))
955 (with-float-traps-masked (:divide-by-zero)
956 (complex (* 2 (atan (/ (realpart sqrt-1-z)
957 (realpart sqrt-1+z))))
958 (asinh (imagpart (* (conjugate sqrt-1+z)
961 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
963 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
964 (defun complex-acosh (z)
966 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
967 (sqrt-z+1 (complex-sqrt (+ z 1))))
968 (with-float-traps-masked (:divide-by-zero)
969 (complex (asinh (realpart (* (conjugate sqrt-z-1)
971 (* 2 (atan (/ (imagpart sqrt-z-1)
972 (realpart sqrt-z+1))))))))
974 ;;; Compute asin z = asinh(i*z)/i.
976 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
977 (defun complex-asin (z)
979 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
980 (sqrt-1+z (complex-sqrt (+ 1 z))))
981 (with-float-traps-masked (:divide-by-zero)
982 (complex (atan (/ (realpart z)
983 (realpart (* sqrt-1-z sqrt-1+z))))
984 (asinh (imagpart (* (conjugate sqrt-1-z)
987 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
989 ;;; Z may be any number, but the result is always a complex.
990 (defun complex-asinh (z)
992 ;; asinh z = -i * asin (i*z)
993 (let* ((iz (complex (- (imagpart z)) (realpart z)))
994 (result (complex-asin iz)))
995 (complex (imagpart result)
996 (- (realpart result)))))
998 ;;; Compute atan z = atanh (i*z) / i.
1000 ;;; Z may be any number, but the result is always a complex.
1001 (defun complex-atan (z)
1002 (declare (number z))
1003 ;; atan z = -i * atanh (i*z)
1004 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1005 (result (complex-atanh iz)))
1006 (complex (imagpart result)
1007 (- (realpart result)))))
1009 ;;; Compute tan z = -i * tanh(i * z)
1011 ;;; Z may be any number, but the result is always a complex.
1012 (defun complex-tan (z)
1013 (declare (number z))
1014 ;; tan z = -i * tanh(i*z)
1015 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1016 (result (complex-tanh iz)))
1017 (complex (imagpart result)
1018 (- (realpart result)))))