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."
122 (labels (;; determine if the double float is an integer.
123 ;; 0 - not an integer
127 (declare (type (unsigned-byte 31) ihi)
128 (type (unsigned-byte 32) lo)
129 (optimize (speed 3) (safety 0)))
131 (declare (type fixnum isint))
132 (cond ((>= ihi #x43400000) ; exponent >= 53
135 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
136 (declare (type (mod 53) k))
138 (let* ((shift (- 52 k))
139 (j (logand (ash lo (- shift))))
141 (declare (type (mod 32) shift)
142 (type (unsigned-byte 32) j j2))
144 (setq isint (- 2 (logand j 1))))))
146 (let* ((shift (- 20 k))
147 (j (ash ihi (- shift)))
149 (declare (type (mod 32) shift)
150 (type (unsigned-byte 31) j j2))
152 (setq isint (- 2 (logand j 1))))))))))
154 (real-expt (x y rtype)
155 (let ((x (coerce x 'double-float))
156 (y (coerce y 'double-float)))
157 (declare (double-float x y))
158 (let* ((x-hi (sb!kernel:double-float-high-bits x))
159 (x-lo (sb!kernel:double-float-low-bits x))
160 (x-ihi (logand x-hi #x7fffffff))
161 (y-hi (sb!kernel:double-float-high-bits y))
162 (y-lo (sb!kernel:double-float-low-bits y))
163 (y-ihi (logand y-hi #x7fffffff)))
164 (declare (type (signed-byte 32) x-hi y-hi)
165 (type (unsigned-byte 31) x-ihi y-ihi)
166 (type (unsigned-byte 32) x-lo y-lo))
168 (when (zerop (logior y-ihi y-lo))
169 (return-from real-expt (coerce 1d0 rtype)))
171 (when (or (> x-ihi #x7ff00000)
172 (and (= x-ihi #x7ff00000) (/= x-lo 0))
174 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
175 (return-from real-expt (coerce (+ x y) rtype)))
176 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
177 (declare (type fixnum yisint))
178 ;; special value of y
179 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
181 (return-from real-expt
182 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
184 (coerce (- y y) rtype))
185 ((>= x-ihi #x3ff00000)
186 ;; (|x|>1)**+-inf = inf,0
191 ;; (|x|<1)**-,+inf = inf,0
194 (coerce 0 rtype))))))
196 (let ((abs-x (abs x)))
197 (declare (double-float abs-x))
198 ;; special value of x
199 (when (and (zerop x-lo)
200 (or (= x-ihi #x7ff00000) (zerop x-ihi)
201 (= x-ihi #x3ff00000)))
202 ;; x is +-0,+-inf,+-1
203 (let ((z (if (< y-hi 0)
204 (/ 1 abs-x) ; z = (1/|x|)
206 (declare (double-float z))
208 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
210 (let ((y*pi (* y pi)))
211 (declare (double-float y*pi))
212 (return-from real-expt
214 (coerce (%cos y*pi) rtype)
215 (coerce (%sin y*pi) rtype)))))
217 ;; (x<0)**odd = -(|x|**odd)
219 (return-from real-expt (coerce z rtype))))
223 (coerce (sb!kernel::%pow x y) rtype)
225 (let ((pow (sb!kernel::%pow abs-x y)))
226 (declare (double-float pow))
229 (coerce (* -1d0 pow) rtype))
233 (let ((y*pi (* y pi)))
234 (declare (double-float y*pi))
236 (coerce (* pow (%cos y*pi))
238 (coerce (* pow (%sin y*pi))
240 (declare (inline real-expt))
241 (number-dispatch ((base number) (power number))
242 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
244 (((foreach single-float double-float) rational)
245 (real-expt base power '(dispatch-type base)))
246 (((foreach fixnum (or bignum ratio) single-float)
247 (foreach ratio single-float))
248 (real-expt base power 'single-float))
249 (((foreach fixnum (or bignum ratio) single-float double-float)
251 (real-expt base power 'double-float))
252 ((double-float single-float)
253 (real-expt base power 'double-float))
254 (((foreach (complex rational) (complex float)) rational)
255 (* (expt (abs base) power)
256 (cis (* power (phase base)))))
257 (((foreach fixnum (or bignum ratio) single-float double-float)
259 (if (and (zerop base) (plusp (realpart power)))
261 (exp (* power (log base)))))
262 (((foreach (complex float) (complex rational))
263 (foreach complex double-float single-float))
264 (if (and (zerop base) (plusp (realpart power)))
266 (exp (* power (log base)))))))))
268 ;;; FIXME: Maybe rename this so that it's clearer that it only works
271 (declare (type integer x))
274 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
275 ;; log2(f). So we grab the top few bits of x and scale that
276 ;; appropriately, take the log of it and add it to n.
278 ;; Motivated by an attempt to get LOG to work better on bignums.
279 (let ((n (integer-length x)))
280 (if (< n sb!vm:double-float-digits)
281 (log (coerce x 'double-float) 2.0d0)
282 (let ((f (ldb (byte sb!vm:double-float-digits
283 (- n sb!vm:double-float-digits))
285 (+ n (log (scale-float (coerce f 'double-float)
286 (- sb!vm:double-float-digits))
289 (defun log (number &optional (base nil base-p))
291 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
294 ((zerop base) 0f0) ; FIXME: type
295 ((and (typep number '(integer (0) *))
296 (typep base '(integer (0) *)))
297 (coerce (/ (log2 number) (log2 base)) 'single-float))
298 (t (/ (log number) (log base))))
299 (number-dispatch ((number number))
300 (((foreach fixnum bignum))
302 (complex (log (- number)) (coerce pi 'single-float))
303 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
306 (complex (log (- number)) (coerce pi 'single-float))
307 (let ((numerator (numerator number))
308 (denominator (denominator number)))
309 (if (= (integer-length numerator)
310 (integer-length denominator))
311 (coerce (%log1p (coerce (- number 1) 'double-float))
313 (coerce (/ (- (log2 numerator) (log2 denominator))
314 (log (exp 1.0d0) 2.0d0))
316 (((foreach single-float double-float))
317 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
318 ;; Since this doesn't seem to be an implementation issue
319 ;; I (pw) take the Kahan result.
320 (if (< (float-sign number)
321 (coerce 0 '(dispatch-type number)))
322 (complex (log (- number)) (coerce pi '(dispatch-type number)))
323 (coerce (%log (coerce number 'double-float))
324 '(dispatch-type number))))
326 (complex-log number)))))
330 "Return the square root of NUMBER."
331 (number-dispatch ((number number))
332 (((foreach fixnum bignum ratio))
334 (complex-sqrt number)
335 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
336 (((foreach single-float double-float))
338 (complex-sqrt number)
339 (coerce (%sqrt (coerce number 'double-float))
340 '(dispatch-type number))))
342 (complex-sqrt number))))
344 ;;;; trigonometic and related functions
348 "Return the absolute value of the number."
349 (number-dispatch ((number number))
350 (((foreach single-float double-float fixnum rational))
353 (let ((rx (realpart number))
354 (ix (imagpart number)))
357 (sqrt (+ (* rx rx) (* ix ix))))
359 (coerce (%hypot (coerce rx 'double-float)
360 (coerce ix 'double-float))
365 (defun phase (number)
367 "Return the angle part of the polar representation of a complex number.
368 For complex numbers, this is (atan (imagpart number) (realpart number)).
369 For non-complex positive numbers, this is 0. For non-complex negative
374 (coerce pi 'single-float)
377 (if (minusp (float-sign number))
378 (coerce pi 'single-float)
381 (if (minusp (float-sign number))
382 (coerce pi 'double-float)
385 (atan (imagpart number) (realpart number)))))
389 "Return the sine of NUMBER."
390 (number-dispatch ((number number))
391 (handle-reals %sin number)
393 (let ((x (realpart number))
394 (y (imagpart number)))
395 (complex (* (sin x) (cosh y))
396 (* (cos x) (sinh y)))))))
400 "Return the cosine of NUMBER."
401 (number-dispatch ((number number))
402 (handle-reals %cos number)
404 (let ((x (realpart number))
405 (y (imagpart number)))
406 (complex (* (cos x) (cosh y))
407 (- (* (sin x) (sinh y))))))))
411 "Return the tangent of NUMBER."
412 (number-dispatch ((number number))
413 (handle-reals %tan number)
415 (complex-tan number))))
419 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
420 (declare (type real theta))
421 (complex (cos theta) (sin theta)))
425 "Return the arc sine of NUMBER."
426 (number-dispatch ((number number))
428 (if (or (> number 1) (< number -1))
429 (complex-asin number)
430 (coerce (%asin (coerce number 'double-float)) 'single-float)))
431 (((foreach single-float double-float))
432 (if (or (> number (coerce 1 '(dispatch-type number)))
433 (< number (coerce -1 '(dispatch-type number))))
434 (complex-asin number)
435 (coerce (%asin (coerce number 'double-float))
436 '(dispatch-type number))))
438 (complex-asin number))))
442 "Return the arc cosine of NUMBER."
443 (number-dispatch ((number number))
445 (if (or (> number 1) (< number -1))
446 (complex-acos number)
447 (coerce (%acos (coerce number 'double-float)) 'single-float)))
448 (((foreach single-float double-float))
449 (if (or (> number (coerce 1 '(dispatch-type number)))
450 (< number (coerce -1 '(dispatch-type number))))
451 (complex-acos number)
452 (coerce (%acos (coerce number 'double-float))
453 '(dispatch-type number))))
455 (complex-acos number))))
457 (defun atan (y &optional (x nil xp))
459 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
462 (declare (type double-float y x)
463 (values double-float))
466 (if (plusp (float-sign x))
469 (float-sign y (/ pi 2)))
471 (number-dispatch ((y real) (x real))
473 (foreach double-float single-float fixnum bignum ratio))
474 (atan2 y (coerce x 'double-float)))
475 (((foreach single-float fixnum bignum ratio)
477 (atan2 (coerce y 'double-float) x))
478 (((foreach single-float fixnum bignum ratio)
479 (foreach single-float fixnum bignum ratio))
480 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
482 (number-dispatch ((y number))
483 (handle-reals %atan y)
487 ;;; It seems that every target system has a C version of sinh, cosh,
488 ;;; and tanh. Let's use these for reals because the original
489 ;;; implementations based on the definitions lose big in round-off
490 ;;; error. These bad definitions also mean that sin and cos for
491 ;;; complex numbers can also lose big.
495 "Return the hyperbolic sine of NUMBER."
496 (number-dispatch ((number number))
497 (handle-reals %sinh number)
499 (let ((x (realpart number))
500 (y (imagpart number)))
501 (complex (* (sinh x) (cos y))
502 (* (cosh x) (sin y)))))))
506 "Return the hyperbolic cosine of NUMBER."
507 (number-dispatch ((number number))
508 (handle-reals %cosh number)
510 (let ((x (realpart number))
511 (y (imagpart number)))
512 (complex (* (cosh x) (cos y))
513 (* (sinh x) (sin y)))))))
517 "Return the hyperbolic tangent of NUMBER."
518 (number-dispatch ((number number))
519 (handle-reals %tanh number)
521 (complex-tanh number))))
523 (defun asinh (number)
525 "Return the hyperbolic arc sine of NUMBER."
526 (number-dispatch ((number number))
527 (handle-reals %asinh number)
529 (complex-asinh number))))
531 (defun acosh (number)
533 "Return the hyperbolic arc cosine of NUMBER."
534 (number-dispatch ((number number))
536 ;; acosh is complex if number < 1
538 (complex-acosh number)
539 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
540 (((foreach single-float double-float))
541 (if (< number (coerce 1 '(dispatch-type number)))
542 (complex-acosh number)
543 (coerce (%acosh (coerce number 'double-float))
544 '(dispatch-type number))))
546 (complex-acosh number))))
548 (defun atanh (number)
550 "Return the hyperbolic arc tangent of NUMBER."
551 (number-dispatch ((number number))
553 ;; atanh is complex if |number| > 1
554 (if (or (> number 1) (< number -1))
555 (complex-atanh number)
556 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
557 (((foreach single-float double-float))
558 (if (or (> number (coerce 1 '(dispatch-type number)))
559 (< number (coerce -1 '(dispatch-type number))))
560 (complex-atanh number)
561 (coerce (%atanh (coerce number 'double-float))
562 '(dispatch-type number))))
564 (complex-atanh number))))
566 ;;; HP-UX does not supply a C version of log1p, so use the definition.
568 ;;; FIXME: This is really not a good definition. As per Raymond Toy
569 ;;; working on CMU CL, "The definition really loses big-time in
570 ;;; roundoff as x gets small."
572 #!-sb-fluid (declaim (inline %log1p))
574 (defun %log1p (number)
575 (declare (double-float number)
576 (optimize (speed 3) (safety 0)))
577 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
579 ;;;; not-OLD-SPECFUN stuff
581 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
582 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
583 ;;;; the standard special function system.)
585 ;;;; This is a set of routines that implement many elementary
586 ;;;; transcendental functions as specified by ANSI Common Lisp. The
587 ;;;; implementation is based on Kahan's paper.
589 ;;;; I believe I have accurately implemented the routines and are
590 ;;;; correct, but you may want to check for your self.
592 ;;;; These functions are written for CMU Lisp and take advantage of
593 ;;;; some of the features available there. It may be possible,
594 ;;;; however, to port this to other Lisps.
596 ;;;; Some functions are significantly more accurate than the original
597 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
598 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
599 ;;;; answer is pi + i*log(2-sqrt(3)).
601 ;;;; All of the implemented functions will take any number for an
602 ;;;; input, but the result will always be a either a complex
603 ;;;; single-float or a complex double-float.
605 ;;;; general functions:
617 ;;;; utility functions:
620 ;;;; internal functions:
621 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
624 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
625 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
626 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
629 ;;;; The original CMU CL code requested:
630 ;;;; Please send any bug reports, comments, or improvements to
631 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
633 ;;; FIXME: In SBCL, the floating point infinity constants like
634 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
635 ;;; constants at cross-compile time, because the cross-compilation
636 ;;; host might not have support for floating point infinities. Thus,
637 ;;; they're effectively implemented as special variable references,
638 ;;; and the code below which uses them might be unnecessarily
639 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
640 ;;; should be used instead?
642 (declaim (inline square))
644 (declare (double-float x))
647 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
649 ;;; If you have these functions in libm, perhaps they should be used
650 ;;; instead of these Lisp versions. These versions are probably good
651 ;;; enough, especially since they are portable.
653 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
654 ;;; the underlying floating-point format.)
655 (declaim (inline scalb))
657 (declare (type double-float x)
658 (type double-float-exponent n))
661 ;;; This is like LOGB, but X is not infinity and non-zero and not a
662 ;;; NaN, so we can always return an integer.
663 (declaim (inline logb-finite))
664 (defun logb-finite (x)
665 (declare (type double-float x))
666 (multiple-value-bind (signif exponent sign)
668 (declare (ignore signif sign))
669 ;; DECODE-FLOAT is almost right, except that the exponent is off
673 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
674 ;;; For the special cases, the following values are used:
677 ;;; +/- infinity +infinity
680 (declare (type double-float x))
681 (cond ((float-nan-p x)
683 ((float-infinity-p x)
684 sb!ext:double-float-positive-infinity)
686 ;; The answer is negative infinity, but we are supposed to
687 ;; signal divide-by-zero, so do the actual division
693 ;;; This function is used to create a complex number of the
694 ;;; appropriate type:
695 ;;; Create complex number with real part X and imaginary part Y
696 ;;; such that has the same type as Z. If Z has type (complex
697 ;;; rational), the X and Y are coerced to single-float.
698 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
699 (error "needs work for long float support"))
700 (declaim (inline coerce-to-complex-type))
701 (defun coerce-to-complex-type (x y z)
702 (declare (double-float x y)
704 (if (typep (realpart z) 'double-float)
706 ;; Convert anything that's not already a DOUBLE-FLOAT (because
707 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
708 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
709 (complex (float x 1f0)
712 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
713 ;;; result is r + i*k, where k is an integer.
714 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
715 (error "needs work for long float support"))
717 (let ((x (float (realpart z) 1d0))
718 (y (float (imagpart z) 1d0)))
719 ;; Would this be better handled using an exception handler to
720 ;; catch the overflow or underflow signal? For now, we turn all
721 ;; traps off and look at the accrued exceptions to see if any
722 ;; signal would have been raised.
723 (with-float-traps-masked (:underflow :overflow)
724 (let ((rho (+ (square x) (square y))))
725 (declare (optimize (speed 3) (space 0)))
726 (cond ((and (or (float-nan-p rho)
727 (float-infinity-p rho))
728 (or (float-infinity-p (abs x))
729 (float-infinity-p (abs y))))
730 (values sb!ext:double-float-positive-infinity 0))
731 ((let ((threshold #.(/ least-positive-double-float
732 double-float-epsilon))
733 (traps (ldb sb!vm::float-sticky-bits
734 (sb!vm:floating-point-modes))))
735 ;; Overflow raised or (underflow raised and rho <
737 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
738 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
741 ;; If we're here, neither x nor y are infinity and at
742 ;; least one is non-zero.. Thus logb returns a nice
744 (let ((k (- (logb-finite (max (abs x) (abs y))))))
745 (values (+ (square (scalb x k))
746 (square (scalb y k)))
751 ;;; principal square root of Z
753 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
754 (defun complex-sqrt (z)
756 (multiple-value-bind (rho k)
758 (declare (type (or (member 0d0) (double-float 0d0)) rho)
760 (let ((x (float (realpart z) 1.0d0))
761 (y (float (imagpart z) 1.0d0))
764 (declare (double-float x y eta nu))
767 ;; space 0 to get maybe-inline functions inlined.
768 (declare (optimize (speed 3) (space 0)))
770 (if (not (float-nan-p x))
771 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
776 (setf k (1- (ash k -1)))
777 (setf rho (+ rho rho))))
779 (setf rho (scalb (sqrt rho) k))
785 (when (not (float-infinity-p (abs nu)))
786 (setf nu (/ (/ nu rho) 2d0)))
789 (setf nu (float-sign y rho))))
790 (coerce-to-complex-type eta nu z)))))
792 ;;; Compute log(2^j*z).
794 ;;; This is for use with J /= 0 only when |z| is huge.
795 (defun complex-log-scaled (z j)
798 ;; The constants t0, t1, t2 should be evaluated to machine
799 ;; precision. In addition, Kahan says the accuracy of log1p
800 ;; influences the choices of these constants but doesn't say how to
801 ;; choose them. We'll just assume his choices matches our
802 ;; implementation of log1p.
803 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
807 (x (float (realpart z) 1.0d0))
808 (y (float (imagpart z) 1.0d0)))
809 (multiple-value-bind (rho k)
811 (declare (optimize (speed 3)))
812 (let ((beta (max (abs x) (abs y)))
813 (theta (min (abs x) (abs y))))
814 (coerce-to-complex-type (if (and (zerop k)
818 (/ (%log1p (+ (* (- beta 1.0d0)
827 ;;; log of Z = log |Z| + i * arg Z
829 ;;; Z may be any number, but the result is always a complex.
830 (defun complex-log (z)
832 (complex-log-scaled z 0))
834 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
835 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
836 ;;; The reason for the imaginary part is caused by the fact that arg
837 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
838 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
839 (defun complex-atanh (z)
842 (theta (/ (sqrt most-positive-double-float) 4.0d0))
843 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
844 (half-pi (/ pi 2.0d0))
845 (rp (float (realpart z) 1.0d0))
846 (beta (float-sign rp 1.0d0))
848 (y (* beta (- (float (imagpart z) 1.0d0))))
851 ;; Shouldn't need this declare.
852 (declare (double-float x y))
854 (declare (optimize (speed 3)))
855 (cond ((or (> x theta)
857 ;; To avoid overflow...
858 (setf eta (float-sign y half-pi))
859 ;; nu is real part of 1/(x + iy). This is x/(x^2+y^2),
860 ;; which can cause overflow. Arrange this computation so
861 ;; that it won't overflow.
862 (setf nu (let* ((x-bigger (> x (abs y)))
863 (r (if x-bigger (/ y x) (/ x y)))
864 (d (+ 1.0d0 (* r r))))
869 ;; Should this be changed so that if y is zero, eta is set
870 ;; to +infinity instead of approx 176? In any case
871 ;; tanh(176) is 1.0d0 within working precision.
872 (let ((t1 (+ 4d0 (square y)))
873 (t2 (+ (abs y) rho)))
874 (setf eta (log (/ (sqrt (sqrt t1)))
878 (+ half-pi (atan (* 0.5d0 t2))))))))
880 (let ((t1 (+ (abs y) rho)))
881 ;; Normal case using log1p(x) = log(1 + x)
883 (%log1p (/ (* 4.0d0 x)
884 (+ (square (- 1.0d0 x))
891 (coerce-to-complex-type (* beta eta)
895 ;;; Compute tanh z = sinh z / cosh z.
896 (defun complex-tanh (z)
898 (let ((x (float (realpart z) 1.0d0))
899 (y (float (imagpart z) 1.0d0)))
901 ;; space 0 to get maybe-inline functions inlined
902 (declare (optimize (speed 3) (space 0)))
904 ;; FIXME: this form is hideously broken wrt
905 ;; cross-compilation portability. Much else in this
906 ;; file is too, of course, sometimes hidden by
907 ;; constant-folding, but this one in particular clearly
908 ;; depends on host and target
909 ;; MOST-POSITIVE-DOUBLE-FLOATs being equal. -- CSR,
912 (log most-positive-double-float))
914 (coerce-to-complex-type (float-sign x)
918 (beta (+ 1.0d0 (* tv tv)))
920 (rho (sqrt (+ 1.0d0 (* s s)))))
921 (if (float-infinity-p (abs tv))
922 (coerce-to-complex-type (/ rho s)
925 (let ((den (+ 1.0d0 (* beta s s))))
926 (coerce-to-complex-type (/ (* beta rho s)
931 ;;; Compute acos z = pi/2 - asin z.
933 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
934 (defun complex-acos (z)
935 ;; Kahan says we should only compute the parts needed. Thus, the
936 ;; REALPART's below should only compute the real part, not the whole
937 ;; complex expression. Doing this can be important because we may get
938 ;; spurious signals that occur in the part that we are not using.
940 ;; However, we take a pragmatic approach and just use the whole
943 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
944 ;; it's the conjugate of the square root or the square root of the
945 ;; conjugate. This needs to be checked.
947 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
948 ;; same as (sqrt (conjugate z)) for all z. This follows because
950 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
952 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
954 ;; and these two expressions are equal if and only if arg conj z =
955 ;; -arg z, which is clearly true for all z.
957 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
958 (sqrt-1-z (complex-sqrt (- 1 z))))
959 (with-float-traps-masked (:divide-by-zero)
960 (complex (* 2 (atan (/ (realpart sqrt-1-z)
961 (realpart sqrt-1+z))))
962 (asinh (imagpart (* (conjugate sqrt-1+z)
965 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
967 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
968 (defun complex-acosh (z)
970 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
971 (sqrt-z+1 (complex-sqrt (+ z 1))))
972 (with-float-traps-masked (:divide-by-zero)
973 (complex (asinh (realpart (* (conjugate sqrt-z-1)
975 (* 2 (atan (/ (imagpart sqrt-z-1)
976 (realpart sqrt-z+1))))))))
978 ;;; Compute asin z = asinh(i*z)/i.
980 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
981 (defun complex-asin (z)
983 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
984 (sqrt-1+z (complex-sqrt (+ 1 z))))
985 (with-float-traps-masked (:divide-by-zero)
986 (complex (atan (/ (realpart z)
987 (realpart (* sqrt-1-z sqrt-1+z))))
988 (asinh (imagpart (* (conjugate sqrt-1-z)
991 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
993 ;;; Z may be any number, but the result is always a complex.
994 (defun complex-asinh (z)
996 ;; asinh z = -i * asin (i*z)
997 (let* ((iz (complex (- (imagpart z)) (realpart z)))
998 (result (complex-asin iz)))
999 (complex (imagpart result)
1000 (- (realpart result)))))
1002 ;;; Compute atan z = atanh (i*z) / i.
1004 ;;; Z may be any number, but the result is always a complex.
1005 (defun complex-atan (z)
1006 (declare (number z))
1007 ;; atan z = -i * atanh (i*z)
1008 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1009 (result (complex-atanh iz)))
1010 (complex (imagpart result)
1011 (- (realpart result)))))
1013 ;;; Compute tan z = -i * tanh(i * z)
1015 ;;; Z may be any number, but the result is always a complex.
1016 (defun complex-tan (z)
1017 (declare (number z))
1018 ;; tan z = -i * tanh(i*z)
1019 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1020 (result (complex-tanh iz)))
1021 (complex (imagpart result)
1022 (- (realpart result)))))