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 (proclaim '(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 ;;; FIXME: As long as the system dies on stack overflow or memory
87 ;;; exhaustion, it seems reasonable to have this, but its default
88 ;;; should be NIL, and when it's NIL, anything should be accepted.
89 (defparameter *intexp-maximum-exponent* 10000)
91 ;;; This function precisely calculates base raised to an integral
92 ;;; power. It separates the cases by the sign of power, for efficiency
93 ;;; reasons, as powers can be calculated more efficiently if power is
94 ;;; a positive integer. Values of power are calculated as positive
95 ;;; integers, and inverted if negative.
96 (defun intexp (base power)
97 (when (> (abs power) *intexp-maximum-exponent*)
98 ;; FIXME: should be ordinary error, not CERROR. (Once we set the
99 ;; default for the variable to NIL, the un-continuable error will
100 ;; be less obnoxious.)
101 (cerror "Continue with calculation."
102 "The absolute value of ~S exceeds ~S."
103 power '*intexp-maximum-exponent* base power))
104 (cond ((minusp power)
105 (/ (intexp base (- power))))
109 (do ((nextn (ash power -1) (ash power -1))
110 (total (if (oddp power) base 1)
111 (if (oddp power) (* base total) total)))
112 ((zerop nextn) total)
113 (setq base (* base base))
114 (setq power nextn)))))
116 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
117 ;;; floating point stuff. If both args are real, we try %POW right
118 ;;; off, assuming it will return 0 if the result may be complex. If
119 ;;; so, we call COMPLEX-POW which directly computes the complex
120 ;;; result. We also separate the complex-real and real-complex cases
121 ;;; from the general complex case.
122 (defun expt (base power)
124 "Return BASE raised to the POWER."
127 (labels (;; determine if the double float is an integer.
128 ;; 0 - not an integer
132 (declare (type (unsigned-byte 31) ihi)
133 (type (unsigned-byte 32) lo)
134 (optimize (speed 3) (safety 0)))
136 (declare (type fixnum isint))
137 (cond ((>= ihi #x43400000) ; exponent >= 53
140 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
141 (declare (type (mod 53) k))
143 (let* ((shift (- 52 k))
144 (j (logand (ash lo (- shift))))
146 (declare (type (mod 32) shift)
147 (type (unsigned-byte 32) j j2))
149 (setq isint (- 2 (logand j 1))))))
151 (let* ((shift (- 20 k))
152 (j (ash ihi (- shift)))
154 (declare (type (mod 32) shift)
155 (type (unsigned-byte 31) j j2))
157 (setq isint (- 2 (logand j 1))))))))))
159 (real-expt (x y rtype)
160 (let ((x (coerce x 'double-float))
161 (y (coerce y 'double-float)))
162 (declare (double-float x y))
163 (let* ((x-hi (sb!kernel:double-float-high-bits x))
164 (x-lo (sb!kernel:double-float-low-bits x))
165 (x-ihi (logand x-hi #x7fffffff))
166 (y-hi (sb!kernel:double-float-high-bits y))
167 (y-lo (sb!kernel:double-float-low-bits y))
168 (y-ihi (logand y-hi #x7fffffff)))
169 (declare (type (signed-byte 32) x-hi y-hi)
170 (type (unsigned-byte 31) x-ihi y-ihi)
171 (type (unsigned-byte 32) x-lo y-lo))
173 (when (zerop (logior y-ihi y-lo))
174 (return-from real-expt (coerce 1d0 rtype)))
176 (when (or (> x-ihi #x7ff00000)
177 (and (= x-ihi #x7ff00000) (/= x-lo 0))
179 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
180 (return-from real-expt (coerce (+ x y) rtype)))
181 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
182 (declare (type fixnum yisint))
183 ;; special value of y
184 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
186 (return-from real-expt
187 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
189 (coerce (- y y) rtype))
190 ((>= x-ihi #x3ff00000)
191 ;; (|x|>1)**+-inf = inf,0
196 ;; (|x|<1)**-,+inf = inf,0
199 (coerce 0 rtype))))))
201 (let ((abs-x (abs x)))
202 (declare (double-float abs-x))
203 ;; special value of x
204 (when (and (zerop x-lo)
205 (or (= x-ihi #x7ff00000) (zerop x-ihi)
206 (= x-ihi #x3ff00000)))
207 ;; x is +-0,+-inf,+-1
208 (let ((z (if (< y-hi 0)
209 (/ 1 abs-x) ; z = (1/|x|)
211 (declare (double-float z))
213 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
215 (let ((y*pi (* y pi)))
216 (declare (double-float y*pi))
217 (return-from real-expt
219 (coerce (%cos y*pi) rtype)
220 (coerce (%sin y*pi) rtype)))))
222 ;; (x<0)**odd = -(|x|**odd)
224 (return-from real-expt (coerce z rtype))))
228 (coerce (sb!kernel::%pow x y) rtype)
230 (let ((pow (sb!kernel::%pow abs-x y)))
231 (declare (double-float pow))
234 (coerce (* -1d0 pow) rtype))
238 (let ((y*pi (* y pi)))
239 (declare (double-float y*pi))
241 (coerce (* pow (%cos y*pi))
243 (coerce (* pow (%sin y*pi))
245 (declare (inline real-expt))
246 (number-dispatch ((base number) (power number))
247 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
249 (((foreach single-float double-float) rational)
250 (real-expt base power '(dispatch-type base)))
251 (((foreach fixnum (or bignum ratio) single-float)
252 (foreach ratio single-float))
253 (real-expt base power 'single-float))
254 (((foreach fixnum (or bignum ratio) single-float double-float)
256 (real-expt base power 'double-float))
257 ((double-float single-float)
258 (real-expt base power 'double-float))
259 (((foreach (complex rational) (complex float)) rational)
260 (* (expt (abs base) power)
261 (cis (* power (phase base)))))
262 (((foreach fixnum (or bignum ratio) single-float double-float)
264 (if (and (zerop base) (plusp (realpart power)))
266 (exp (* power (log base)))))
267 (((foreach (complex float) (complex rational))
268 (foreach complex double-float single-float))
269 (if (and (zerop base) (plusp (realpart power)))
271 (exp (* power (log base)))))))))
273 ;;; FIXME: Maybe rename this so that it's clearer that it only works
276 (declare (type integer x))
279 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
280 ;; log2(f). So we grab the top few bits of x and scale that
281 ;; appropriately, take the log of it and add it to n.
283 ;; Motivated by an attempt to get LOG to work better on bignums.
284 (let ((n (integer-length x)))
285 (if (< n sb!vm:double-float-digits)
286 (log (coerce x 'double-float) 2.0d0)
287 (let ((f (ldb (byte sb!vm:double-float-digits
288 (- n sb!vm:double-float-digits))
290 (+ n (log (scale-float (coerce f 'double-float)
291 (- sb!vm:double-float-digits))
294 (defun log (number &optional (base nil base-p))
296 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
299 ((zerop base) 0f0) ; FIXME: type
300 ((and (typep number '(integer (0) *))
301 (typep base '(integer (0) *)))
302 (coerce (/ (log2 number) (log2 base)) 'single-float))
303 (t (/ (log number) (log base))))
304 (number-dispatch ((number number))
305 (((foreach fixnum bignum))
307 (complex (log (- number)) (coerce pi 'single-float))
308 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
311 (complex (log (- number)) (coerce pi 'single-float))
312 (let ((numerator (numerator number))
313 (denominator (denominator number)))
314 (if (= (integer-length numerator)
315 (integer-length denominator))
316 (coerce (%log1p (coerce (- number 1) 'double-float))
318 (coerce (/ (- (log2 numerator) (log2 denominator))
319 (log (exp 1.0d0) 2.0d0))
321 (((foreach single-float double-float))
322 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
323 ;; Since this doesn't seem to be an implementation issue
324 ;; I (pw) take the Kahan result.
325 (if (< (float-sign number)
326 (coerce 0 '(dispatch-type number)))
327 (complex (log (- number)) (coerce pi '(dispatch-type number)))
328 (coerce (%log (coerce number 'double-float))
329 '(dispatch-type number))))
331 (complex-log number)))))
335 "Return the square root of NUMBER."
336 (number-dispatch ((number number))
337 (((foreach fixnum bignum ratio))
339 (complex-sqrt number)
340 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
341 (((foreach single-float double-float))
343 (complex-sqrt number)
344 (coerce (%sqrt (coerce number 'double-float))
345 '(dispatch-type number))))
347 (complex-sqrt number))))
349 ;;;; trigonometic and related functions
353 "Return the absolute value of the number."
354 (number-dispatch ((number number))
355 (((foreach single-float double-float fixnum rational))
358 (let ((rx (realpart number))
359 (ix (imagpart number)))
362 (sqrt (+ (* rx rx) (* ix ix))))
364 (coerce (%hypot (coerce rx 'double-float)
365 (coerce ix 'double-float))
370 (defun phase (number)
372 "Return the angle part of the polar representation of a complex number.
373 For complex numbers, this is (atan (imagpart number) (realpart number)).
374 For non-complex positive numbers, this is 0. For non-complex negative
379 (coerce pi 'single-float)
382 (if (minusp (float-sign number))
383 (coerce pi 'single-float)
386 (if (minusp (float-sign number))
387 (coerce pi 'double-float)
390 (atan (imagpart number) (realpart number)))))
394 "Return the sine of NUMBER."
395 (number-dispatch ((number number))
396 (handle-reals %sin number)
398 (let ((x (realpart number))
399 (y (imagpart number)))
400 (complex (* (sin x) (cosh y))
401 (* (cos x) (sinh y)))))))
405 "Return the cosine of NUMBER."
406 (number-dispatch ((number number))
407 (handle-reals %cos number)
409 (let ((x (realpart number))
410 (y (imagpart number)))
411 (complex (* (cos x) (cosh y))
412 (- (* (sin x) (sinh y))))))))
416 "Return the tangent of NUMBER."
417 (number-dispatch ((number number))
418 (handle-reals %tan number)
420 (complex-tan number))))
424 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
425 (declare (type real theta))
426 (complex (cos theta) (sin theta)))
430 "Return the arc sine of NUMBER."
431 (number-dispatch ((number number))
433 (if (or (> number 1) (< number -1))
434 (complex-asin number)
435 (coerce (%asin (coerce number 'double-float)) 'single-float)))
436 (((foreach single-float double-float))
437 (if (or (> number (coerce 1 '(dispatch-type number)))
438 (< number (coerce -1 '(dispatch-type number))))
439 (complex-asin number)
440 (coerce (%asin (coerce number 'double-float))
441 '(dispatch-type number))))
443 (complex-asin number))))
447 "Return the arc cosine of NUMBER."
448 (number-dispatch ((number number))
450 (if (or (> number 1) (< number -1))
451 (complex-acos number)
452 (coerce (%acos (coerce number 'double-float)) 'single-float)))
453 (((foreach single-float double-float))
454 (if (or (> number (coerce 1 '(dispatch-type number)))
455 (< number (coerce -1 '(dispatch-type number))))
456 (complex-acos number)
457 (coerce (%acos (coerce number 'double-float))
458 '(dispatch-type number))))
460 (complex-acos number))))
462 (defun atan (y &optional (x nil xp))
464 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
467 (declare (type double-float y x)
468 (values double-float))
471 (if (plusp (float-sign x))
474 (float-sign y (/ pi 2)))
476 (number-dispatch ((y real) (x real))
478 (foreach double-float single-float fixnum bignum ratio))
479 (atan2 y (coerce x 'double-float)))
480 (((foreach single-float fixnum bignum ratio)
482 (atan2 (coerce y 'double-float) x))
483 (((foreach single-float fixnum bignum ratio)
484 (foreach single-float fixnum bignum ratio))
485 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
487 (number-dispatch ((y number))
488 (handle-reals %atan y)
492 ;;; It seems that every target system has a C version of sinh, cosh,
493 ;;; and tanh. Let's use these for reals because the original
494 ;;; implementations based on the definitions lose big in round-off
495 ;;; error. These bad definitions also mean that sin and cos for
496 ;;; complex numbers can also lose big.
500 "Return the hyperbolic sine of NUMBER."
501 (number-dispatch ((number number))
502 (handle-reals %sinh number)
504 (let ((x (realpart number))
505 (y (imagpart number)))
506 (complex (* (sinh x) (cos y))
507 (* (cosh x) (sin y)))))))
511 "Return the hyperbolic cosine of NUMBER."
512 (number-dispatch ((number number))
513 (handle-reals %cosh number)
515 (let ((x (realpart number))
516 (y (imagpart number)))
517 (complex (* (cosh x) (cos y))
518 (* (sinh x) (sin y)))))))
522 "Return the hyperbolic tangent of NUMBER."
523 (number-dispatch ((number number))
524 (handle-reals %tanh number)
526 (complex-tanh number))))
528 (defun asinh (number)
530 "Return the hyperbolic arc sine of NUMBER."
531 (number-dispatch ((number number))
532 (handle-reals %asinh number)
534 (complex-asinh number))))
536 (defun acosh (number)
538 "Return the hyperbolic arc cosine of NUMBER."
539 (number-dispatch ((number number))
541 ;; acosh is complex if number < 1
543 (complex-acosh number)
544 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
545 (((foreach single-float double-float))
546 (if (< number (coerce 1 '(dispatch-type number)))
547 (complex-acosh number)
548 (coerce (%acosh (coerce number 'double-float))
549 '(dispatch-type number))))
551 (complex-acosh number))))
553 (defun atanh (number)
555 "Return the hyperbolic arc tangent of NUMBER."
556 (number-dispatch ((number number))
558 ;; atanh is complex if |number| > 1
559 (if (or (> number 1) (< number -1))
560 (complex-atanh number)
561 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
562 (((foreach single-float double-float))
563 (if (or (> number (coerce 1 '(dispatch-type number)))
564 (< number (coerce -1 '(dispatch-type number))))
565 (complex-atanh number)
566 (coerce (%atanh (coerce number 'double-float))
567 '(dispatch-type number))))
569 (complex-atanh number))))
571 ;;; HP-UX does not supply a C version of log1p, so use the definition.
573 ;;; FIXME: This is really not a good definition. As per Raymond Toy
574 ;;; working on CMU CL, "The definition really loses big-time in
575 ;;; roundoff as x gets small."
577 #!-sb-fluid (declaim (inline %log1p))
579 (defun %log1p (number)
580 (declare (double-float number)
581 (optimize (speed 3) (safety 0)))
582 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
584 ;;;; not-OLD-SPECFUN stuff
586 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
587 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
588 ;;;; the standard special function system.)
590 ;;;; This is a set of routines that implement many elementary
591 ;;;; transcendental functions as specified by ANSI Common Lisp. The
592 ;;;; implementation is based on Kahan's paper.
594 ;;;; I believe I have accurately implemented the routines and are
595 ;;;; correct, but you may want to check for your self.
597 ;;;; These functions are written for CMU Lisp and take advantage of
598 ;;;; some of the features available there. It may be possible,
599 ;;;; however, to port this to other Lisps.
601 ;;;; Some functions are significantly more accurate than the original
602 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
603 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
604 ;;;; answer is pi + i*log(2-sqrt(3)).
606 ;;;; All of the implemented functions will take any number for an
607 ;;;; input, but the result will always be a either a complex
608 ;;;; single-float or a complex double-float.
610 ;;;; general functions:
622 ;;;; utility functions:
625 ;;;; internal functions:
626 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
629 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
630 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
631 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
634 ;;;; The original CMU CL code requested:
635 ;;;; Please send any bug reports, comments, or improvements to
636 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
638 ;;; FIXME: In SBCL, the floating point infinity constants like
639 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
640 ;;; constants at cross-compile time, because the cross-compilation
641 ;;; host might not have support for floating point infinities. Thus,
642 ;;; they're effectively implemented as special variable references,
643 ;;; and the code below which uses them might be unnecessarily
644 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
645 ;;; should be used instead?
647 (declaim (inline square))
649 (declare (double-float x))
652 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
654 ;;; If you have these functions in libm, perhaps they should be used
655 ;;; instead of these Lisp versions. These versions are probably good
656 ;;; enough, especially since they are portable.
658 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
659 ;;; the underlying floating-point format.)
660 (declaim (inline scalb))
662 (declare (type double-float x)
663 (type double-float-exponent n))
666 ;;; This is like LOGB, but X is not infinity and non-zero and not a
667 ;;; NaN, so we can always return an integer.
668 (declaim (inline logb-finite))
669 (defun logb-finite (x)
670 (declare (type double-float x))
671 (multiple-value-bind (signif exponent sign)
673 (declare (ignore signif sign))
674 ;; DECODE-FLOAT is almost right, except that the exponent is off
678 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
679 ;;; For the special cases, the following values are used:
682 ;;; +/- infinity +infinity
685 (declare (type double-float x))
686 (cond ((float-nan-p x)
688 ((float-infinity-p x)
689 sb!ext:double-float-positive-infinity)
691 ;; The answer is negative infinity, but we are supposed to
692 ;; signal divide-by-zero, so do the actual division
698 ;;; This function is used to create a complex number of the
699 ;;; appropriate type:
700 ;;; Create complex number with real part X and imaginary part Y
701 ;;; such that has the same type as Z. If Z has type (complex
702 ;;; rational), the X and Y are coerced to single-float.
703 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
704 (error "needs work for long float support"))
705 (declaim (inline coerce-to-complex-type))
706 (defun coerce-to-complex-type (x y z)
707 (declare (double-float x y)
709 (if (subtypep (type-of (realpart z)) 'double-float)
711 ;; Convert anything that's not a DOUBLE-FLOAT to a SINGLE-FLOAT.
712 (complex (float x 1f0)
715 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
716 ;;; result is r + i*k, where k is an integer.
717 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
718 (error "needs work for long float support"))
720 (let ((x (float (realpart z) 1d0))
721 (y (float (imagpart z) 1d0)))
722 ;; Would this be better handled using an exception handler to
723 ;; catch the overflow or underflow signal? For now, we turn all
724 ;; traps off and look at the accrued exceptions to see if any
725 ;; signal would have been raised.
726 (with-float-traps-masked (:underflow :overflow)
727 (let ((rho (+ (square x) (square y))))
728 (declare (optimize (speed 3) (space 0)))
729 (cond ((and (or (float-nan-p rho)
730 (float-infinity-p rho))
731 (or (float-infinity-p (abs x))
732 (float-infinity-p (abs y))))
733 (values sb!ext:double-float-positive-infinity 0))
734 ((let ((threshold #.(/ least-positive-double-float
735 double-float-epsilon))
736 (traps (ldb sb!vm::float-sticky-bits
737 (sb!vm:floating-point-modes))))
738 ;; Overflow raised or (underflow raised and rho <
740 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
741 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
744 ;; If we're here, neither x nor y are infinity and at
745 ;; least one is non-zero.. Thus logb returns a nice
747 (let ((k (- (logb-finite (max (abs x) (abs y))))))
748 (values (+ (square (scalb x k))
749 (square (scalb y k)))
754 ;;; principal square root of Z
756 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
757 (defun complex-sqrt (z)
759 (multiple-value-bind (rho k)
761 (declare (type (or (member 0d0) (double-float 0d0)) rho)
763 (let ((x (float (realpart z) 1.0d0))
764 (y (float (imagpart z) 1.0d0))
767 (declare (double-float x y eta nu))
770 ;; space 0 to get maybe-inline functions inlined.
771 (declare (optimize (speed 3) (space 0)))
773 (if (not (float-nan-p x))
774 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
779 (setf k (1- (ash k -1)))
780 (setf rho (+ rho rho))))
782 (setf rho (scalb (sqrt rho) k))
788 (when (not (float-infinity-p (abs nu)))
789 (setf nu (/ (/ nu rho) 2d0)))
792 (setf nu (float-sign y rho))))
793 (coerce-to-complex-type eta nu z)))))
795 ;;; Compute log(2^j*z).
797 ;;; This is for use with J /= 0 only when |z| is huge.
798 (defun complex-log-scaled (z j)
801 ;; The constants t0, t1, t2 should be evaluated to machine
802 ;; precision. In addition, Kahan says the accuracy of log1p
803 ;; influences the choices of these constants but doesn't say how to
804 ;; choose them. We'll just assume his choices matches our
805 ;; implementation of log1p.
806 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
810 (x (float (realpart z) 1.0d0))
811 (y (float (imagpart z) 1.0d0)))
812 (multiple-value-bind (rho k)
814 (declare (optimize (speed 3)))
815 (let ((beta (max (abs x) (abs y)))
816 (theta (min (abs x) (abs y))))
817 (coerce-to-complex-type (if (and (zerop k)
821 (/ (%log1p (+ (* (- beta 1.0d0)
830 ;;; log of Z = log |Z| + i * arg Z
832 ;;; Z may be any number, but the result is always a complex.
833 (defun complex-log (z)
835 (complex-log-scaled z 0))
837 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
838 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
839 ;;; The reason for the imaginary part is caused by the fact that arg
840 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
841 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
842 (defun complex-atanh (z)
845 (theta (/ (sqrt most-positive-double-float) 4.0d0))
846 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
847 (half-pi (/ pi 2.0d0))
848 (rp (float (realpart z) 1.0d0))
849 (beta (float-sign rp 1.0d0))
851 (y (* beta (- (float (imagpart z) 1.0d0))))
854 ;; Shouldn't need this declare.
855 (declare (double-float x y))
857 (declare (optimize (speed 3)))
858 (cond ((or (> x theta)
860 ;; To avoid overflow...
861 (setf eta (float-sign y half-pi))
862 ;; nu is real part of 1/(x + iy). This is x/(x^2+y^2),
863 ;; which can cause overflow. Arrange this computation so
864 ;; that it won't overflow.
865 (setf nu (let* ((x-bigger (> x (abs y)))
866 (r (if x-bigger (/ y x) (/ x y)))
867 (d (+ 1.0d0 (* r r))))
872 ;; Should this be changed so that if y is zero, eta is set
873 ;; to +infinity instead of approx 176? In any case
874 ;; tanh(176) is 1.0d0 within working precision.
875 (let ((t1 (+ 4d0 (square y)))
876 (t2 (+ (abs y) rho)))
877 (setf eta (log (/ (sqrt (sqrt t1)))
881 (+ half-pi (atan (* 0.5d0 t2))))))))
883 (let ((t1 (+ (abs y) rho)))
884 ;; Normal case using log1p(x) = log(1 + x)
886 (%log1p (/ (* 4.0d0 x)
887 (+ (square (- 1.0d0 x))
894 (coerce-to-complex-type (* beta eta)
898 ;;; Compute tanh z = sinh z / cosh z.
899 (defun complex-tanh (z)
901 (let ((x (float (realpart z) 1.0d0))
902 (y (float (imagpart z) 1.0d0)))
904 ;; space 0 to get maybe-inline functions inlined
905 (declare (optimize (speed 3) (space 0)))
907 ;; FIXME: this form is hideously broken wrt
908 ;; cross-compilation portability. Much else in this
909 ;; file is too, of course, sometimes hidden by
910 ;; constant-folding, but this one in particular clearly
911 ;; depends on host and target
912 ;; MOST-POSITIVE-DOUBLE-FLOATs being equal. -- CSR,
915 (log most-positive-double-float))
917 (coerce-to-complex-type (float-sign x)
921 (beta (+ 1.0d0 (* tv tv)))
923 (rho (sqrt (+ 1.0d0 (* s s)))))
924 (if (float-infinity-p (abs tv))
925 (coerce-to-complex-type (/ rho s)
928 (let ((den (+ 1.0d0 (* beta s s))))
929 (coerce-to-complex-type (/ (* beta rho s)
934 ;;; Compute acos z = pi/2 - asin z.
936 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
937 (defun complex-acos (z)
938 ;; Kahan says we should only compute the parts needed. Thus, the
939 ;; REALPART's below should only compute the real part, not the whole
940 ;; complex expression. Doing this can be important because we may get
941 ;; spurious signals that occur in the part that we are not using.
943 ;; However, we take a pragmatic approach and just use the whole
946 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
947 ;; it's the conjugate of the square root or the square root of the
948 ;; conjugate. This needs to be checked.
950 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
951 ;; same as (sqrt (conjugate z)) for all z. This follows because
953 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
955 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
957 ;; and these two expressions are equal if and only if arg conj z =
958 ;; -arg z, which is clearly true for all z.
960 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
961 (sqrt-1-z (complex-sqrt (- 1 z))))
962 (with-float-traps-masked (:divide-by-zero)
963 (complex (* 2 (atan (/ (realpart sqrt-1-z)
964 (realpart sqrt-1+z))))
965 (asinh (imagpart (* (conjugate sqrt-1+z)
968 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
970 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
971 (defun complex-acosh (z)
973 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
974 (sqrt-z+1 (complex-sqrt (+ z 1))))
975 (with-float-traps-masked (:divide-by-zero)
976 (complex (asinh (realpart (* (conjugate sqrt-z-1)
978 (* 2 (atan (/ (imagpart sqrt-z-1)
979 (realpart sqrt-z+1))))))))
981 ;;; Compute asin z = asinh(i*z)/i.
983 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
984 (defun complex-asin (z)
986 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
987 (sqrt-1+z (complex-sqrt (+ 1 z))))
988 (with-float-traps-masked (:divide-by-zero)
989 (complex (atan (/ (realpart z)
990 (realpart (* sqrt-1-z sqrt-1+z))))
991 (asinh (imagpart (* (conjugate sqrt-1-z)
994 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
996 ;;; Z may be any number, but the result is always a complex.
997 (defun complex-asinh (z)
999 ;; asinh z = -i * asin (i*z)
1000 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1001 (result (complex-asin iz)))
1002 (complex (imagpart result)
1003 (- (realpart result)))))
1005 ;;; Compute atan z = atanh (i*z) / i.
1007 ;;; Z may be any number, but the result is always a complex.
1008 (defun complex-atan (z)
1009 (declare (number z))
1010 ;; atan z = -i * atanh (i*z)
1011 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1012 (result (complex-atanh iz)))
1013 (complex (imagpart result)
1014 (- (realpart result)))))
1016 ;;; Compute tan z = -i * tanh(i * z)
1018 ;;; Z may be any number, but the result is always a complex.
1019 (defun complex-tan (z)
1020 (declare (number z))
1021 ;; tan z = -i * tanh(i*z)
1022 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1023 (result (complex-tanh iz)))
1024 (complex (imagpart result)
1025 (- (realpart result)))))