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 ;;; Please refer to the Unix man pages for details about these routines.
48 #!-x86 (def-math-rtn "sin" 1)
49 #!-x86 (def-math-rtn "cos" 1)
50 #!-x86 (def-math-rtn "tan" 1)
51 (def-math-rtn "asin" 1)
52 (def-math-rtn "acos" 1)
53 #!-x86 (def-math-rtn "atan" 1)
54 #!-x86 (def-math-rtn "atan2" 2)
55 (def-math-rtn "sinh" 1)
56 (def-math-rtn "cosh" 1)
57 (def-math-rtn "tanh" 1)
58 (def-math-rtn "asinh" 1)
59 (def-math-rtn "acosh" 1)
60 (def-math-rtn "atanh" 1)
62 ;;; exponential and logarithmic
63 #!-x86 (def-math-rtn "exp" 1)
64 #!-x86 (def-math-rtn "log" 1)
65 #!-x86 (def-math-rtn "log10" 1)
66 (def-math-rtn "pow" 2)
67 #!-x86 (def-math-rtn "sqrt" 1)
68 (def-math-rtn "hypot" 2)
69 #!-(or hpux x86) (def-math-rtn "log1p" 1)
75 "Return e raised to the power NUMBER."
76 (number-dispatch ((number number))
77 (handle-reals %exp number)
79 (* (exp (realpart number))
80 (cis (imagpart number))))))
82 ;;; INTEXP -- Handle the rational base, integer power case.
84 ;;; FIXME: As long as the system dies on stack overflow or memory
85 ;;; exhaustion, it seems reasonable to have this, but its default
86 ;;; should be NIL, and when it's NIL, anything should be accepted.
87 (defparameter *intexp-maximum-exponent* 10000)
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 (> (abs power) *intexp-maximum-exponent*)
96 ;; FIXME: should be ordinary error, not CERROR. (Once we set the
97 ;; default for the variable to NIL, the un-continuable error will
98 ;; be less obnoxious.)
99 (cerror "Continue with calculation."
100 "The absolute value of ~S exceeds ~S."
101 power '*intexp-maximum-exponent* base power))
102 (cond ((minusp power)
103 (/ (intexp base (- power))))
107 (do ((nextn (ash power -1) (ash power -1))
108 (total (if (oddp power) base 1)
109 (if (oddp power) (* base total) total)))
110 ((zerop nextn) total)
111 (setq base (* base base))
112 (setq power nextn)))))
114 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
115 ;;; floating point stuff. If both args are real, we try %POW right
116 ;;; off, assuming it will return 0 if the result may be complex. If
117 ;;; so, we call COMPLEX-POW which directly computes the complex
118 ;;; result. We also separate the complex-real and real-complex cases
119 ;;; from the general complex case.
120 (defun expt (base power)
122 "Return BASE raised to the POWER."
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 (defun log (number &optional (base nil base-p))
273 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
277 (/ (log number) (log base)))
278 (number-dispatch ((number number))
279 (((foreach fixnum bignum ratio))
281 (complex (log (- number)) (coerce pi 'single-float))
282 (coerce (%log (coerce number 'double-float)) 'single-float)))
283 (((foreach single-float double-float))
284 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
285 ;; Since this doesn't seem to be an implementation issue
286 ;; I (pw) take the Kahan result.
287 (if (< (float-sign number)
288 (coerce 0 '(dispatch-type number)))
289 (complex (log (- number)) (coerce pi '(dispatch-type number)))
290 (coerce (%log (coerce number 'double-float))
291 '(dispatch-type number))))
293 (complex-log number)))))
297 "Return the square root of NUMBER."
298 (number-dispatch ((number number))
299 (((foreach fixnum bignum ratio))
301 (complex-sqrt number)
302 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
303 (((foreach single-float double-float))
305 (complex-sqrt number)
306 (coerce (%sqrt (coerce number 'double-float))
307 '(dispatch-type number))))
309 (complex-sqrt number))))
311 ;;;; trigonometic and related functions
315 "Return the absolute value of the number."
316 (number-dispatch ((number number))
317 (((foreach single-float double-float fixnum rational))
320 (let ((rx (realpart number))
321 (ix (imagpart number)))
324 (sqrt (+ (* rx rx) (* ix ix))))
326 (coerce (%hypot (coerce rx 'double-float)
327 (coerce ix 'double-float))
332 (defun phase (number)
334 "Return the angle part of the polar representation of a complex number.
335 For complex numbers, this is (atan (imagpart number) (realpart number)).
336 For non-complex positive numbers, this is 0. For non-complex negative
341 (coerce pi 'single-float)
344 (if (minusp (float-sign number))
345 (coerce pi 'single-float)
348 (if (minusp (float-sign number))
349 (coerce pi 'double-float)
352 (atan (imagpart number) (realpart number)))))
356 "Return the sine of NUMBER."
357 (number-dispatch ((number number))
358 (handle-reals %sin number)
360 (let ((x (realpart number))
361 (y (imagpart number)))
362 (complex (* (sin x) (cosh y))
363 (* (cos x) (sinh y)))))))
367 "Return the cosine of NUMBER."
368 (number-dispatch ((number number))
369 (handle-reals %cos number)
371 (let ((x (realpart number))
372 (y (imagpart number)))
373 (complex (* (cos x) (cosh y))
374 (- (* (sin x) (sinh y))))))))
378 "Return the tangent of NUMBER."
379 (number-dispatch ((number number))
380 (handle-reals %tan number)
382 (complex-tan number))))
386 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
387 (declare (type real theta))
388 (complex (cos theta) (sin theta)))
392 "Return the arc sine of NUMBER."
393 (number-dispatch ((number number))
395 (if (or (> number 1) (< number -1))
396 (complex-asin number)
397 (coerce (%asin (coerce number 'double-float)) 'single-float)))
398 (((foreach single-float double-float))
399 (if (or (> number (coerce 1 '(dispatch-type number)))
400 (< number (coerce -1 '(dispatch-type number))))
401 (complex-asin number)
402 (coerce (%asin (coerce number 'double-float))
403 '(dispatch-type number))))
405 (complex-asin number))))
409 "Return the arc cosine of NUMBER."
410 (number-dispatch ((number number))
412 (if (or (> number 1) (< number -1))
413 (complex-acos number)
414 (coerce (%acos (coerce number 'double-float)) 'single-float)))
415 (((foreach single-float double-float))
416 (if (or (> number (coerce 1 '(dispatch-type number)))
417 (< number (coerce -1 '(dispatch-type number))))
418 (complex-acos number)
419 (coerce (%acos (coerce number 'double-float))
420 '(dispatch-type number))))
422 (complex-acos number))))
424 (defun atan (y &optional (x nil xp))
426 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
429 (declare (type double-float y x)
430 (values double-float))
433 (if (plusp (float-sign x))
436 (float-sign y (/ pi 2)))
438 (number-dispatch ((y number) (x number))
440 (foreach double-float single-float fixnum bignum ratio))
441 (atan2 y (coerce x 'double-float)))
442 (((foreach single-float fixnum bignum ratio)
444 (atan2 (coerce y 'double-float) x))
445 (((foreach single-float fixnum bignum ratio)
446 (foreach single-float fixnum bignum ratio))
447 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
449 (number-dispatch ((y number))
450 (handle-reals %atan y)
454 ;; It seems that everyone has a C version of sinh, cosh, and
455 ;; tanh. Let's use these for reals because the original
456 ;; implementations based on the definitions lose big in round-off
457 ;; error. These bad definitions also mean that sin and cos for
458 ;; complex numbers can also lose big.
462 "Return the hyperbolic sine of NUMBER."
463 (number-dispatch ((number number))
464 (handle-reals %sinh number)
466 (let ((x (realpart number))
467 (y (imagpart number)))
468 (complex (* (sinh x) (cos y))
469 (* (cosh x) (sin y)))))))
473 "Return the hyperbolic cosine of NUMBER."
474 (number-dispatch ((number number))
475 (handle-reals %cosh number)
477 (let ((x (realpart number))
478 (y (imagpart number)))
479 (complex (* (cosh x) (cos y))
480 (* (sinh x) (sin y)))))))
484 "Return the hyperbolic tangent of NUMBER."
485 (number-dispatch ((number number))
486 (handle-reals %tanh number)
488 (complex-tanh number))))
490 (defun asinh (number)
492 "Return the hyperbolic arc sine of NUMBER."
493 (number-dispatch ((number number))
494 (handle-reals %asinh number)
496 (complex-asinh number))))
498 (defun acosh (number)
500 "Return the hyperbolic arc cosine of NUMBER."
501 (number-dispatch ((number number))
503 ;; acosh is complex if number < 1
505 (complex-acosh number)
506 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
507 (((foreach single-float double-float))
508 (if (< number (coerce 1 '(dispatch-type number)))
509 (complex-acosh number)
510 (coerce (%acosh (coerce number 'double-float))
511 '(dispatch-type number))))
513 (complex-acosh number))))
515 (defun atanh (number)
517 "Return the hyperbolic arc tangent of NUMBER."
518 (number-dispatch ((number number))
520 ;; atanh is complex if |number| > 1
521 (if (or (> number 1) (< number -1))
522 (complex-atanh number)
523 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
524 (((foreach single-float double-float))
525 (if (or (> number (coerce 1 '(dispatch-type number)))
526 (< number (coerce -1 '(dispatch-type number))))
527 (complex-atanh number)
528 (coerce (%atanh (coerce number 'double-float))
529 '(dispatch-type number))))
531 (complex-atanh number))))
533 ;;; HP-UX does not supply a C version of log1p, so use the definition.
535 ;;; FIXME: This is really not a good definition. As per Raymond Toy
536 ;;; working on CMU CL, "The definition really loses big-time in
537 ;;; roundoff as x gets small."
539 #!-sb-fluid (declaim (inline %log1p))
541 (defun %log1p (number)
542 (declare (double-float number)
543 (optimize (speed 3) (safety 0)))
544 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
546 ;;;; not-OLD-SPECFUN stuff
548 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
549 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
550 ;;;; the standard special function system.)
552 ;;;; This is a set of routines that implement many elementary
553 ;;;; transcendental functions as specified by ANSI Common Lisp. The
554 ;;;; implementation is based on Kahan's paper.
556 ;;;; I believe I have accurately implemented the routines and are
557 ;;;; correct, but you may want to check for your self.
559 ;;;; These functions are written for CMU Lisp and take advantage of
560 ;;;; some of the features available there. It may be possible,
561 ;;;; however, to port this to other Lisps.
563 ;;;; Some functions are significantly more accurate than the original
564 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
565 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
566 ;;;; answer is pi + i*log(2-sqrt(3)).
568 ;;;; All of the implemented functions will take any number for an
569 ;;;; input, but the result will always be a either a complex
570 ;;;; single-float or a complex double-float.
572 ;;;; general functions:
584 ;;;; utility functions:
587 ;;;; internal functions:
588 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
591 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
592 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
593 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
596 ;;;; The original CMU CL code requested:
597 ;;;; Please send any bug reports, comments, or improvements to
598 ;;;; Raymond Toy at toy@rtp.ericsson.se.
600 ;;; FIXME: In SBCL, the floating point infinity constants like
601 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
602 ;;; constants at cross-compile time, because the cross-compilation
603 ;;; host might not have support for floating point infinities. Thus,
604 ;;; they're effectively implemented as special variable references,
605 ;;; and the code below which uses them might be unnecessarily
606 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
607 ;;; should be used instead?
609 (declaim (inline square))
611 (declare (double-float x))
614 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
616 ;;; If you have these functions in libm, perhaps they should be used
617 ;;; instead of these Lisp versions. These versions are probably good
618 ;;; enough, especially since they are portable.
620 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
621 ;;; the underlying floating-point format.)
622 (declaim (inline scalb))
624 (declare (type double-float x)
625 (type double-float-exponent n))
628 ;;; This is like LOGB, but X is not infinity and non-zero and not a
629 ;;; NaN, so we can always return an integer.
630 (declaim (inline logb-finite))
631 (defun logb-finite (x)
632 (declare (type double-float x))
633 (multiple-value-bind (signif exponent sign)
635 (declare (ignore signif sign))
636 ;; DECODE-FLOAT is almost right, except that the exponent is off
640 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
641 ;;; For the special cases, the following values are used:
644 ;;; +/- infinity +infinity
647 (declare (type double-float x))
648 (cond ((float-nan-p x)
650 ((float-infinity-p x)
651 sb!ext:double-float-positive-infinity)
653 ;; The answer is negative infinity, but we are supposed to
654 ;; signal divide-by-zero, so do the actual division
660 ;;; This function is used to create a complex number of the
661 ;;; appropriate type:
662 ;;; Create complex number with real part X and imaginary part Y
663 ;;; such that has the same type as Z. If Z has type (complex
664 ;;; rational), the X and Y are coerced to single-float.
665 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
666 (error "needs work for long float support"))
667 (declaim (inline coerce-to-complex-type))
668 (defun coerce-to-complex-type (x y z)
669 (declare (double-float x y)
671 (if (subtypep (type-of (realpart z)) 'double-float)
673 ;; Convert anything that's not a DOUBLE-FLOAT to a SINGLE-FLOAT.
674 (complex (float x 1f0)
677 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
678 ;;; result is r + i*k, where k is an integer.
679 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
680 (error "needs work for long float support"))
682 (let ((x (float (realpart z) 1d0))
683 (y (float (imagpart z) 1d0)))
684 ;; Would this be better handled using an exception handler to
685 ;; catch the overflow or underflow signal? For now, we turn all
686 ;; traps off and look at the accrued exceptions to see if any
687 ;; signal would have been raised.
688 (with-float-traps-masked (:underflow :overflow)
689 (let ((rho (+ (square x) (square y))))
690 (declare (optimize (speed 3) (space 0)))
691 (cond ((and (or (float-nan-p rho)
692 (float-infinity-p rho))
693 (or (float-infinity-p (abs x))
694 (float-infinity-p (abs y))))
695 (values sb!ext:double-float-positive-infinity 0))
696 ((let ((threshold #.(/ least-positive-double-float
697 double-float-epsilon))
698 (traps (ldb sb!vm::float-sticky-bits
699 (sb!vm:floating-point-modes))))
700 ;; Overflow raised or (underflow raised and rho <
702 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
703 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
706 ;; If we're here, neither x nor y are infinity and at
707 ;; least one is non-zero.. Thus logb returns a nice
709 (let ((k (- (logb-finite (max (abs x) (abs y))))))
710 (values (+ (square (scalb x k))
711 (square (scalb y k)))
716 ;;; principal square root of Z
718 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
719 (defun complex-sqrt (z)
721 (multiple-value-bind (rho k)
723 (declare (type (or (member 0d0) (double-float 0d0)) rho)
725 (let ((x (float (realpart z) 1.0d0))
726 (y (float (imagpart z) 1.0d0))
729 (declare (double-float x y eta nu))
732 ;; space 0 to get maybe-inline functions inlined.
733 (declare (optimize (speed 3) (space 0)))
735 (if (not (float-nan-p x))
736 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
741 (setf k (1- (ash k -1)))
742 (setf rho (+ rho rho))))
744 (setf rho (scalb (sqrt rho) k))
750 (when (not (float-infinity-p (abs nu)))
751 (setf nu (/ (/ nu rho) 2d0)))
754 (setf nu (float-sign y rho))))
755 (coerce-to-complex-type eta nu z)))))
757 ;;; Compute log(2^j*z).
759 ;;; This is for use with J /= 0 only when |z| is huge.
760 (defun complex-log-scaled (z j)
763 ;; The constants t0, t1, t2 should be evaluated to machine
764 ;; precision. In addition, Kahan says the accuracy of log1p
765 ;; influences the choices of these constants but doesn't say how to
766 ;; choose them. We'll just assume his choices matches our
767 ;; implementation of log1p.
768 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
772 (x (float (realpart z) 1.0d0))
773 (y (float (imagpart z) 1.0d0)))
774 (multiple-value-bind (rho k)
776 (declare (optimize (speed 3)))
777 (let ((beta (max (abs x) (abs y)))
778 (theta (min (abs x) (abs y))))
779 (coerce-to-complex-type (if (and (zerop k)
783 (/ (%log1p (+ (* (- beta 1.0d0)
792 ;;; log of Z = log |Z| + i * arg Z
794 ;;; Z may be any number, but the result is always a complex.
795 (defun complex-log (z)
797 (complex-log-scaled z 0))
799 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
800 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
801 ;;; The reason for the imaginary part is caused by the fact that arg
802 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
803 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
804 (defun complex-atanh (z)
807 (theta (/ (sqrt most-positive-double-float) 4.0d0))
808 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
809 (half-pi (/ pi 2.0d0))
810 (rp (float (realpart z) 1.0d0))
811 (beta (float-sign rp 1.0d0))
813 (y (* beta (- (float (imagpart z) 1.0d0))))
816 ;; Shouldn't need this declare.
817 (declare (double-float x y))
819 (declare (optimize (speed 3)))
820 (cond ((or (> x theta)
822 ;; To avoid overflow...
823 (setf eta (float-sign y half-pi))
824 ;; nu is real part of 1/(x + iy). This is x/(x^2+y^2),
825 ;; which can cause overflow. Arrange this computation so
826 ;; that it won't overflow.
827 (setf nu (let* ((x-bigger (> x (abs y)))
828 (r (if x-bigger (/ y x) (/ x y)))
829 (d (+ 1.0d0 (* r r))))
834 ;; Should this be changed so that if y is zero, eta is set
835 ;; to +infinity instead of approx 176? In any case
836 ;; tanh(176) is 1.0d0 within working precision.
837 (let ((t1 (+ 4d0 (square y)))
838 (t2 (+ (abs y) rho)))
839 (setf eta (log (/ (sqrt (sqrt t1)))
843 (+ half-pi (atan (* 0.5d0 t2))))))))
845 (let ((t1 (+ (abs y) rho)))
846 ;; Normal case using log1p(x) = log(1 + x)
848 (%log1p (/ (* 4.0d0 x)
849 (+ (square (- 1.0d0 x))
856 (coerce-to-complex-type (* beta eta)
860 ;;; Compute tanh z = sinh z / cosh z.
861 (defun complex-tanh (z)
863 (let ((x (float (realpart z) 1.0d0))
864 (y (float (imagpart z) 1.0d0)))
866 ;; space 0 to get maybe-inline functions inlined
867 (declare (optimize (speed 3) (space 0)))
869 #-(or linux hpux) #.(/ (asinh most-positive-double-float) 4d0)
870 ;; This is more accurate under linux.
871 #+(or linux hpux) #.(/ (+ (log 2.0d0)
872 (log most-positive-double-float))
874 (coerce-to-complex-type (float-sign x)
878 (beta (+ 1.0d0 (* tv tv)))
880 (rho (sqrt (+ 1.0d0 (* s s)))))
881 (if (float-infinity-p (abs tv))
882 (coerce-to-complex-type (/ rho s)
885 (let ((den (+ 1.0d0 (* beta s s))))
886 (coerce-to-complex-type (/ (* beta rho s)
891 ;;; Compute acos z = pi/2 - asin z.
893 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
894 (defun complex-acos (z)
895 ;; Kahan says we should only compute the parts needed. Thus, the
896 ;; REALPART's below should only compute the real part, not the whole
897 ;; complex expression. Doing this can be important because we may get
898 ;; spurious signals that occur in the part that we are not using.
900 ;; However, we take a pragmatic approach and just use the whole
903 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
904 ;; it's the conjugate of the square root or the square root of the
905 ;; conjugate. This needs to be checked.
907 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
908 ;; same as (sqrt (conjugate z)) for all z. This follows because
910 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
912 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
914 ;; and these two expressions are equal if and only if arg conj z =
915 ;; -arg z, which is clearly true for all z.
917 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
918 (sqrt-1-z (complex-sqrt (- 1 z))))
919 (with-float-traps-masked (:divide-by-zero)
920 (complex (* 2 (atan (/ (realpart sqrt-1-z)
921 (realpart sqrt-1+z))))
922 (asinh (imagpart (* (conjugate sqrt-1+z)
925 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
927 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
928 (defun complex-acosh (z)
930 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
931 (sqrt-z+1 (complex-sqrt (+ z 1))))
932 (with-float-traps-masked (:divide-by-zero)
933 (complex (asinh (realpart (* (conjugate sqrt-z-1)
935 (* 2 (atan (/ (imagpart sqrt-z-1)
936 (realpart sqrt-z+1))))))))
938 ;;; Compute asin z = asinh(i*z)/i.
940 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
941 (defun complex-asin (z)
943 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
944 (sqrt-1+z (complex-sqrt (+ 1 z))))
945 (with-float-traps-masked (:divide-by-zero)
946 (complex (atan (/ (realpart z)
947 (realpart (* sqrt-1-z sqrt-1+z))))
948 (asinh (imagpart (* (conjugate sqrt-1-z)
951 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
953 ;;; Z may be any number, but the result is always a complex.
954 (defun complex-asinh (z)
956 ;; asinh z = -i * asin (i*z)
957 (let* ((iz (complex (- (imagpart z)) (realpart z)))
958 (result (complex-asin iz)))
959 (complex (imagpart result)
960 (- (realpart result)))))
962 ;;; Compute atan z = atanh (i*z) / i.
964 ;;; Z may be any number, but the result is always a complex.
965 (defun complex-atan (z)
967 ;; atan z = -i * atanh (i*z)
968 (let* ((iz (complex (- (imagpart z)) (realpart z)))
969 (result (complex-atanh iz)))
970 (complex (imagpart result)
971 (- (realpart result)))))
973 ;;; Compute tan z = -i * tanh(i * z)
975 ;;; Z may be any number, but the result is always a complex.
976 (defun complex-tan (z)
978 ;; tan z = -i * tanh(i*z)
979 (let* ((iz (complex (- (imagpart z)) (realpart z)))
980 (result (complex-tanh iz)))
981 (complex (imagpart result)
982 (- (realpart result)))))