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 #!+x86 ;; for constant folding
45 (macrolet ((def (name ll)
46 `(defun ,name ,ll (,name ,@ll))))
56 ;;;; stubs for the Unix math library
58 ;;;; Many of these are unnecessary on the X86 because they're built
62 #!-x86 (def-math-rtn "sin" 1)
63 #!-x86 (def-math-rtn "cos" 1)
64 #!-x86 (def-math-rtn "tan" 1)
65 (def-math-rtn "asin" 1)
66 (def-math-rtn "acos" 1)
67 #!-x86 (def-math-rtn "atan" 1)
68 #!-x86 (def-math-rtn "atan2" 2)
69 (def-math-rtn "sinh" 1)
70 (def-math-rtn "cosh" 1)
71 (def-math-rtn "tanh" 1)
72 (def-math-rtn "asinh" 1)
73 (def-math-rtn "acosh" 1)
74 (def-math-rtn "atanh" 1)
76 ;;; exponential and logarithmic
77 #!-x86 (def-math-rtn "exp" 1)
78 #!-x86 (def-math-rtn "log" 1)
79 #!-x86 (def-math-rtn "log10" 1)
80 (def-math-rtn "pow" 2)
81 #!-x86 (def-math-rtn "sqrt" 1)
82 (def-math-rtn "hypot" 2)
83 #!-(or hpux x86) (def-math-rtn "log1p" 1)
89 "Return e raised to the power NUMBER."
90 (number-dispatch ((number number))
91 (handle-reals %exp number)
93 (* (exp (realpart number))
94 (cis (imagpart number))))))
96 ;;; INTEXP -- Handle the rational base, integer power case.
98 (declaim (type (or integer null) *intexp-maximum-exponent*))
99 (defparameter *intexp-maximum-exponent* nil)
101 ;;; This function precisely calculates base raised to an integral
102 ;;; power. It separates the cases by the sign of power, for efficiency
103 ;;; reasons, as powers can be calculated more efficiently if power is
104 ;;; a positive integer. Values of power are calculated as positive
105 ;;; integers, and inverted if negative.
106 (defun intexp (base power)
107 (when (and *intexp-maximum-exponent*
108 (> (abs power) *intexp-maximum-exponent*))
109 (error "The absolute value of ~S exceeds ~S."
110 power '*intexp-maximum-exponent*))
111 (cond ((minusp power)
112 (/ (intexp base (- power))))
116 (do ((nextn (ash power -1) (ash power -1))
117 (total (if (oddp power) base 1)
118 (if (oddp power) (* base total) total)))
119 ((zerop nextn) total)
120 (setq base (* base base))
121 (setq power nextn)))))
123 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
124 ;;; floating point stuff. If both args are real, we try %POW right
125 ;;; off, assuming it will return 0 if the result may be complex. If
126 ;;; so, we call COMPLEX-POW which directly computes the complex
127 ;;; result. We also separate the complex-real and real-complex cases
128 ;;; from the general complex case.
129 (defun expt (base power)
131 "Return BASE raised to the POWER."
133 (let ((result (1+ (* base power))))
134 (if (and (floatp result) (float-nan-p result))
137 (labels (;; determine if the double float is an integer.
138 ;; 0 - not an integer
142 (declare (type (unsigned-byte 31) ihi)
143 (type (unsigned-byte 32) lo)
144 (optimize (speed 3) (safety 0)))
146 (declare (type fixnum isint))
147 (cond ((>= ihi #x43400000) ; exponent >= 53
150 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
151 (declare (type (mod 53) k))
153 (let* ((shift (- 52 k))
154 (j (logand (ash lo (- shift))))
156 (declare (type (mod 32) shift)
157 (type (unsigned-byte 32) j j2))
159 (setq isint (- 2 (logand j 1))))))
161 (let* ((shift (- 20 k))
162 (j (ash ihi (- shift)))
164 (declare (type (mod 32) shift)
165 (type (unsigned-byte 31) j j2))
167 (setq isint (- 2 (logand j 1))))))))))
169 (real-expt (x y rtype)
170 (let ((x (coerce x 'double-float))
171 (y (coerce y 'double-float)))
172 (declare (double-float x y))
173 (let* ((x-hi (sb!kernel:double-float-high-bits x))
174 (x-lo (sb!kernel:double-float-low-bits x))
175 (x-ihi (logand x-hi #x7fffffff))
176 (y-hi (sb!kernel:double-float-high-bits y))
177 (y-lo (sb!kernel:double-float-low-bits y))
178 (y-ihi (logand y-hi #x7fffffff)))
179 (declare (type (signed-byte 32) x-hi y-hi)
180 (type (unsigned-byte 31) x-ihi y-ihi)
181 (type (unsigned-byte 32) x-lo y-lo))
183 (when (zerop (logior y-ihi y-lo))
184 (return-from real-expt (coerce 1d0 rtype)))
186 (when (or (> x-ihi #x7ff00000)
187 (and (= x-ihi #x7ff00000) (/= x-lo 0))
189 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
190 (return-from real-expt (coerce (+ x y) rtype)))
191 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
192 (declare (type fixnum yisint))
193 ;; special value of y
194 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
196 (return-from real-expt
197 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
199 (coerce (- y y) rtype))
200 ((>= x-ihi #x3ff00000)
201 ;; (|x|>1)**+-inf = inf,0
206 ;; (|x|<1)**-,+inf = inf,0
209 (coerce 0 rtype))))))
211 (let ((abs-x (abs x)))
212 (declare (double-float abs-x))
213 ;; special value of x
214 (when (and (zerop x-lo)
215 (or (= x-ihi #x7ff00000) (zerop x-ihi)
216 (= x-ihi #x3ff00000)))
217 ;; x is +-0,+-inf,+-1
218 (let ((z (if (< y-hi 0)
219 (/ 1 abs-x) ; z = (1/|x|)
221 (declare (double-float z))
223 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
225 (let ((y*pi (* y pi)))
226 (declare (double-float y*pi))
227 (return-from real-expt
229 (coerce (%cos y*pi) rtype)
230 (coerce (%sin y*pi) rtype)))))
232 ;; (x<0)**odd = -(|x|**odd)
234 (return-from real-expt (coerce z rtype))))
238 (coerce (sb!kernel::%pow x y) rtype)
240 (let ((pow (sb!kernel::%pow abs-x y)))
241 (declare (double-float pow))
244 (coerce (* -1d0 pow) rtype))
248 (let ((y*pi (* y pi)))
249 (declare (double-float y*pi))
251 (coerce (* pow (%cos y*pi))
253 (coerce (* pow (%sin y*pi))
255 (declare (inline real-expt))
256 (number-dispatch ((base number) (power number))
257 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
259 (((foreach single-float double-float) rational)
260 (real-expt base power '(dispatch-type base)))
261 (((foreach fixnum (or bignum ratio) single-float)
262 (foreach ratio single-float))
263 (real-expt base power 'single-float))
264 (((foreach fixnum (or bignum ratio) single-float double-float)
266 (real-expt base power 'double-float))
267 ((double-float single-float)
268 (real-expt base power 'double-float))
269 (((foreach (complex rational) (complex float)) rational)
270 (* (expt (abs base) power)
271 (cis (* power (phase base)))))
272 (((foreach fixnum (or bignum ratio) single-float double-float)
274 (if (and (zerop base) (plusp (realpart power)))
276 (exp (* power (log base)))))
277 (((foreach (complex float) (complex rational))
278 (foreach complex double-float single-float))
279 (if (and (zerop base) (plusp (realpart power)))
281 (exp (* power (log base)))))))))
283 ;;; FIXME: Maybe rename this so that it's clearer that it only works
286 (declare (type integer x))
289 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
290 ;; log2(f). So we grab the top few bits of x and scale that
291 ;; appropriately, take the log of it and add it to n.
293 ;; Motivated by an attempt to get LOG to work better on bignums.
294 (let ((n (integer-length x)))
295 (if (< n sb!vm:double-float-digits)
296 (log (coerce x 'double-float) 2.0d0)
297 (let ((f (ldb (byte sb!vm:double-float-digits
298 (- n sb!vm:double-float-digits))
300 (+ n (log (scale-float (coerce f 'double-float)
301 (- sb!vm:double-float-digits))
304 (defun log (number &optional (base nil base-p))
306 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
309 ((zerop base) 0f0) ; FIXME: type
310 ((and (typep number '(integer (0) *))
311 (typep base '(integer (0) *)))
312 (coerce (/ (log2 number) (log2 base)) 'single-float))
313 (t (/ (log number) (log base))))
314 (number-dispatch ((number number))
315 (((foreach fixnum bignum))
317 (complex (log (- number)) (coerce pi 'single-float))
318 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
321 (complex (log (- number)) (coerce pi 'single-float))
322 (let ((numerator (numerator number))
323 (denominator (denominator number)))
324 (if (= (integer-length numerator)
325 (integer-length denominator))
326 (coerce (%log1p (coerce (- number 1) 'double-float))
328 (coerce (/ (- (log2 numerator) (log2 denominator))
329 (log (exp 1.0d0) 2.0d0))
331 (((foreach single-float double-float))
332 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
333 ;; Since this doesn't seem to be an implementation issue
334 ;; I (pw) take the Kahan result.
335 (if (< (float-sign number)
336 (coerce 0 '(dispatch-type number)))
337 (complex (log (- number)) (coerce pi '(dispatch-type number)))
338 (coerce (%log (coerce number 'double-float))
339 '(dispatch-type number))))
341 (complex-log number)))))
345 "Return the square root of NUMBER."
346 (number-dispatch ((number number))
347 (((foreach fixnum bignum ratio))
349 (complex-sqrt number)
350 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
351 (((foreach single-float double-float))
353 (complex-sqrt (complex number))
354 (coerce (%sqrt (coerce number 'double-float))
355 '(dispatch-type number))))
357 (complex-sqrt number))))
359 ;;;; trigonometic and related functions
363 "Return the absolute value of the number."
364 (number-dispatch ((number number))
365 (((foreach single-float double-float fixnum rational))
368 (let ((rx (realpart number))
369 (ix (imagpart number)))
372 (sqrt (+ (* rx rx) (* ix ix))))
374 (coerce (%hypot (coerce rx 'double-float)
375 (coerce ix 'double-float))
380 (defun phase (number)
382 "Return the angle part of the polar representation of a complex number.
383 For complex numbers, this is (atan (imagpart number) (realpart number)).
384 For non-complex positive numbers, this is 0. For non-complex negative
389 (coerce pi 'single-float)
392 (if (minusp (float-sign number))
393 (coerce pi 'single-float)
396 (if (minusp (float-sign number))
397 (coerce pi 'double-float)
400 (atan (imagpart number) (realpart number)))))
404 "Return the sine of NUMBER."
405 (number-dispatch ((number number))
406 (handle-reals %sin number)
408 (let ((x (realpart number))
409 (y (imagpart number)))
410 (complex (* (sin x) (cosh y))
411 (* (cos x) (sinh y)))))))
415 "Return the cosine of NUMBER."
416 (number-dispatch ((number number))
417 (handle-reals %cos number)
419 (let ((x (realpart number))
420 (y (imagpart number)))
421 (complex (* (cos x) (cosh y))
422 (- (* (sin x) (sinh y))))))))
426 "Return the tangent of NUMBER."
427 (number-dispatch ((number number))
428 (handle-reals %tan number)
430 (complex-tan number))))
434 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
435 (declare (type real theta))
436 (complex (cos theta) (sin theta)))
440 "Return the arc sine of NUMBER."
441 (number-dispatch ((number number))
443 (if (or (> number 1) (< number -1))
444 (complex-asin number)
445 (coerce (%asin (coerce number 'double-float)) 'single-float)))
446 (((foreach single-float double-float))
447 (if (or (> number (coerce 1 '(dispatch-type number)))
448 (< number (coerce -1 '(dispatch-type number))))
449 (complex-asin (complex number))
450 (coerce (%asin (coerce number 'double-float))
451 '(dispatch-type number))))
453 (complex-asin number))))
457 "Return the arc cosine of NUMBER."
458 (number-dispatch ((number number))
460 (if (or (> number 1) (< number -1))
461 (complex-acos number)
462 (coerce (%acos (coerce number 'double-float)) 'single-float)))
463 (((foreach single-float double-float))
464 (if (or (> number (coerce 1 '(dispatch-type number)))
465 (< number (coerce -1 '(dispatch-type number))))
466 (complex-acos (complex number))
467 (coerce (%acos (coerce number 'double-float))
468 '(dispatch-type number))))
470 (complex-acos number))))
472 (defun atan (y &optional (x nil xp))
474 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
477 (declare (type double-float y x)
478 (values double-float))
481 (if (plusp (float-sign x))
484 (float-sign y (/ pi 2)))
486 (number-dispatch ((y real) (x real))
488 (foreach double-float single-float fixnum bignum ratio))
489 (atan2 y (coerce x 'double-float)))
490 (((foreach single-float fixnum bignum ratio)
492 (atan2 (coerce y 'double-float) x))
493 (((foreach single-float fixnum bignum ratio)
494 (foreach single-float fixnum bignum ratio))
495 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
497 (number-dispatch ((y number))
498 (handle-reals %atan y)
502 ;;; It seems that every target system has a C version of sinh, cosh,
503 ;;; and tanh. Let's use these for reals because the original
504 ;;; implementations based on the definitions lose big in round-off
505 ;;; error. These bad definitions also mean that sin and cos for
506 ;;; complex numbers can also lose big.
510 "Return the hyperbolic sine of NUMBER."
511 (number-dispatch ((number number))
512 (handle-reals %sinh number)
514 (let ((x (realpart number))
515 (y (imagpart number)))
516 (complex (* (sinh x) (cos y))
517 (* (cosh x) (sin y)))))))
521 "Return the hyperbolic cosine of NUMBER."
522 (number-dispatch ((number number))
523 (handle-reals %cosh number)
525 (let ((x (realpart number))
526 (y (imagpart number)))
527 (complex (* (cosh x) (cos y))
528 (* (sinh x) (sin y)))))))
532 "Return the hyperbolic tangent of NUMBER."
533 (number-dispatch ((number number))
534 (handle-reals %tanh number)
536 (complex-tanh number))))
538 (defun asinh (number)
540 "Return the hyperbolic arc sine of NUMBER."
541 (number-dispatch ((number number))
542 (handle-reals %asinh number)
544 (complex-asinh number))))
546 (defun acosh (number)
548 "Return the hyperbolic arc cosine of NUMBER."
549 (number-dispatch ((number number))
551 ;; acosh is complex if number < 1
553 (complex-acosh number)
554 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
555 (((foreach single-float double-float))
556 (if (< number (coerce 1 '(dispatch-type number)))
557 (complex-acosh (complex number))
558 (coerce (%acosh (coerce number 'double-float))
559 '(dispatch-type number))))
561 (complex-acosh number))))
563 (defun atanh (number)
565 "Return the hyperbolic arc tangent of NUMBER."
566 (number-dispatch ((number number))
568 ;; atanh is complex if |number| > 1
569 (if (or (> number 1) (< number -1))
570 (complex-atanh number)
571 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
572 (((foreach single-float double-float))
573 (if (or (> number (coerce 1 '(dispatch-type number)))
574 (< number (coerce -1 '(dispatch-type number))))
575 (complex-atanh (complex number))
576 (coerce (%atanh (coerce number 'double-float))
577 '(dispatch-type number))))
579 (complex-atanh number))))
581 ;;; HP-UX does not supply a C version of log1p, so use the definition.
583 ;;; FIXME: This is really not a good definition. As per Raymond Toy
584 ;;; working on CMU CL, "The definition really loses big-time in
585 ;;; roundoff as x gets small."
587 #!-sb-fluid (declaim (inline %log1p))
589 (defun %log1p (number)
590 (declare (double-float number)
591 (optimize (speed 3) (safety 0)))
592 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
594 ;;;; not-OLD-SPECFUN stuff
596 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
597 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
598 ;;;; the standard special function system.)
600 ;;;; This is a set of routines that implement many elementary
601 ;;;; transcendental functions as specified by ANSI Common Lisp. The
602 ;;;; implementation is based on Kahan's paper.
604 ;;;; I believe I have accurately implemented the routines and are
605 ;;;; correct, but you may want to check for your self.
607 ;;;; These functions are written for CMU Lisp and take advantage of
608 ;;;; some of the features available there. It may be possible,
609 ;;;; however, to port this to other Lisps.
611 ;;;; Some functions are significantly more accurate than the original
612 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
613 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
614 ;;;; answer is pi + i*log(2-sqrt(3)).
616 ;;;; All of the implemented functions will take any number for an
617 ;;;; input, but the result will always be a either a complex
618 ;;;; single-float or a complex double-float.
620 ;;;; general functions:
632 ;;;; utility functions:
635 ;;;; internal functions:
636 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
639 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
640 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
641 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
644 ;;;; The original CMU CL code requested:
645 ;;;; Please send any bug reports, comments, or improvements to
646 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
648 ;;; FIXME: In SBCL, the floating point infinity constants like
649 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
650 ;;; constants at cross-compile time, because the cross-compilation
651 ;;; host might not have support for floating point infinities. Thus,
652 ;;; they're effectively implemented as special variable references,
653 ;;; and the code below which uses them might be unnecessarily
654 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
655 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
656 ;;; special variable references with (probably equally slow)
659 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
660 ;;; differ in their interpretations of the real line, IMAGPART was
661 ;;; patch, which without a certain amount of effort would have altered
662 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
663 ;;; were patched to use explicit COMPLEX, rather than implicitly
664 ;;; passing in real numbers for treatment with IMAGPART, and these
665 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
666 ;;; however, someone needs to go back to Kahan for the definitive
667 ;;; answer for treatment of negative real floating point numbers and
668 ;;; branch cuts. If adjustment is needed, it is probably the removal
669 ;;; of explicit calls to COMPLEX in the clients of irrational
670 ;;; functions. -- a slightly bitter CSR, 2004-05-16
672 (declaim (inline square))
674 (declare (double-float x))
677 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
679 ;;; If you have these functions in libm, perhaps they should be used
680 ;;; instead of these Lisp versions. These versions are probably good
681 ;;; enough, especially since they are portable.
683 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
684 ;;; the underlying floating-point format.)
685 (declaim (inline scalb))
687 (declare (type double-float x)
688 (type double-float-exponent n))
691 ;;; This is like LOGB, but X is not infinity and non-zero and not a
692 ;;; NaN, so we can always return an integer.
693 (declaim (inline logb-finite))
694 (defun logb-finite (x)
695 (declare (type double-float x))
696 (multiple-value-bind (signif exponent sign)
698 (declare (ignore signif sign))
699 ;; DECODE-FLOAT is almost right, except that the exponent is off
703 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
704 ;;; For the special cases, the following values are used:
707 ;;; +/- infinity +infinity
710 (declare (type double-float x))
711 (cond ((float-nan-p x)
713 ((float-infinity-p x)
714 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
715 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
717 ;; The answer is negative infinity, but we are supposed to
718 ;; signal divide-by-zero, so do the actual division
724 ;;; This function is used to create a complex number of the
725 ;;; appropriate type:
726 ;;; Create complex number with real part X and imaginary part Y
727 ;;; such that has the same type as Z. If Z has type (complex
728 ;;; rational), the X and Y are coerced to single-float.
729 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
730 (error "needs work for long float support"))
731 (declaim (inline coerce-to-complex-type))
732 (defun coerce-to-complex-type (x y z)
733 (declare (double-float x y)
735 (if (typep (realpart z) 'double-float)
737 ;; Convert anything that's not already a DOUBLE-FLOAT (because
738 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
739 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
740 (complex (float x 1f0)
743 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
744 ;;; result is r + i*k, where k is an integer.
745 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
746 (error "needs work for long float support"))
748 (let ((x (float (realpart z) 1d0))
749 (y (float (imagpart z) 1d0)))
750 ;; Would this be better handled using an exception handler to
751 ;; catch the overflow or underflow signal? For now, we turn all
752 ;; traps off and look at the accrued exceptions to see if any
753 ;; signal would have been raised.
754 (with-float-traps-masked (:underflow :overflow)
755 (let ((rho (+ (square x) (square y))))
756 (declare (optimize (speed 3) (space 0)))
757 (cond ((and (or (float-nan-p rho)
758 (float-infinity-p rho))
759 (or (float-infinity-p (abs x))
760 (float-infinity-p (abs y))))
761 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
763 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
765 ((let ((threshold #.(/ least-positive-double-float
766 double-float-epsilon))
767 (traps (ldb sb!vm::float-sticky-bits
768 (sb!vm:floating-point-modes))))
769 ;; Overflow raised or (underflow raised and rho <
771 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
772 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
775 ;; If we're here, neither x nor y are infinity and at
776 ;; least one is non-zero.. Thus logb returns a nice
778 (let ((k (- (logb-finite (max (abs x) (abs y))))))
779 (values (+ (square (scalb x k))
780 (square (scalb y k)))
785 ;;; principal square root of Z
787 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
788 (defun complex-sqrt (z)
789 ;; KLUDGE: Here and below, we can't just declare Z to be of type
790 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
791 ;; Since there isn't a rational negative zero, this is OK from the
792 ;; point of view of getting the right answer in the face of branch
793 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
794 ;; still ugly. -- CSR, 2004-05-16
795 (declare (type (or complex rational) z))
796 (multiple-value-bind (rho k)
798 (declare (type (or (member 0d0) (double-float 0d0)) rho)
800 (let ((x (float (realpart z) 1.0d0))
801 (y (float (imagpart z) 1.0d0))
804 (declare (double-float x y eta nu))
807 ;; space 0 to get maybe-inline functions inlined.
808 (declare (optimize (speed 3) (space 0)))
810 (if (not (float-nan-p x))
811 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
816 (setf k (1- (ash k -1)))
817 (setf rho (+ rho rho))))
819 (setf rho (scalb (sqrt rho) k))
825 (when (not (float-infinity-p (abs nu)))
826 (setf nu (/ (/ nu rho) 2d0)))
829 (setf nu (float-sign y rho))))
830 (coerce-to-complex-type eta nu z)))))
832 ;;; Compute log(2^j*z).
834 ;;; This is for use with J /= 0 only when |z| is huge.
835 (defun complex-log-scaled (z j)
836 (declare (type (or rational complex) z)
838 ;; The constants t0, t1, t2 should be evaluated to machine
839 ;; precision. In addition, Kahan says the accuracy of log1p
840 ;; influences the choices of these constants but doesn't say how to
841 ;; choose them. We'll just assume his choices matches our
842 ;; implementation of log1p.
843 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
847 (x (float (realpart z) 1.0d0))
848 (y (float (imagpart z) 1.0d0)))
849 (multiple-value-bind (rho k)
851 (declare (optimize (speed 3)))
852 (let ((beta (max (abs x) (abs y)))
853 (theta (min (abs x) (abs y))))
854 (coerce-to-complex-type (if (and (zerop k)
858 (/ (%log1p (+ (* (- beta 1.0d0)
867 ;;; log of Z = log |Z| + i * arg Z
869 ;;; Z may be any number, but the result is always a complex.
870 (defun complex-log (z)
871 (declare (type (or rational complex) z))
872 (complex-log-scaled z 0))
874 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
875 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
876 ;;; The reason for the imaginary part is caused by the fact that arg
877 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
878 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
879 (defun complex-atanh (z)
880 (declare (type (or rational complex) z))
882 (theta (/ (sqrt most-positive-double-float) 4.0d0))
883 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
884 (half-pi (/ pi 2.0d0))
885 (rp (float (realpart z) 1.0d0))
886 (beta (float-sign rp 1.0d0))
888 (y (* beta (- (float (imagpart z) 1.0d0))))
891 ;; Shouldn't need this declare.
892 (declare (double-float x y))
894 (declare (optimize (speed 3)))
895 (cond ((or (> x theta)
897 ;; To avoid overflow...
898 (setf nu (float-sign y half-pi))
899 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
900 ;; which can cause overflow. Arrange this computation so
901 ;; that it won't overflow.
902 (setf eta (let* ((x-bigger (> x (abs y)))
903 (r (if x-bigger (/ y x) (/ x y)))
904 (d (+ 1.0d0 (* r r))))
909 ;; Should this be changed so that if y is zero, eta is set
910 ;; to +infinity instead of approx 176? In any case
911 ;; tanh(176) is 1.0d0 within working precision.
912 (let ((t1 (+ 4d0 (square y)))
913 (t2 (+ (abs y) rho)))
914 (setf eta (log (/ (sqrt (sqrt t1))
918 (+ half-pi (atan (* 0.5d0 t2))))))))
920 (let ((t1 (+ (abs y) rho)))
921 ;; Normal case using log1p(x) = log(1 + x)
923 (%log1p (/ (* 4.0d0 x)
924 (+ (square (- 1.0d0 x))
931 (coerce-to-complex-type (* beta eta)
935 ;;; Compute tanh z = sinh z / cosh z.
936 (defun complex-tanh (z)
937 (declare (type (or rational complex) z))
938 (let ((x (float (realpart z) 1.0d0))
939 (y (float (imagpart z) 1.0d0)))
941 ;; space 0 to get maybe-inline functions inlined
942 (declare (optimize (speed 3) (space 0)))
944 ;; FIXME: this form is hideously broken wrt
945 ;; cross-compilation portability. Much else in this
946 ;; file is too, of course, sometimes hidden by
947 ;; constant-folding, but this one in particular clearly
948 ;; depends on host and target
949 ;; MOST-POSITIVE-DOUBLE-FLOATs being equal. -- CSR,
952 (log most-positive-double-float))
954 (coerce-to-complex-type (float-sign x)
958 (beta (+ 1.0d0 (* tv tv)))
960 (rho (sqrt (+ 1.0d0 (* s s)))))
961 (if (float-infinity-p (abs tv))
962 (coerce-to-complex-type (/ rho s)
965 (let ((den (+ 1.0d0 (* beta s s))))
966 (coerce-to-complex-type (/ (* beta rho s)
971 ;;; Compute acos z = pi/2 - asin z.
973 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
974 (defun complex-acos (z)
975 ;; Kahan says we should only compute the parts needed. Thus, the
976 ;; REALPART's below should only compute the real part, not the whole
977 ;; complex expression. Doing this can be important because we may get
978 ;; spurious signals that occur in the part that we are not using.
980 ;; However, we take a pragmatic approach and just use the whole
983 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
984 ;; it's the conjugate of the square root or the square root of the
985 ;; conjugate. This needs to be checked.
987 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
988 ;; same as (sqrt (conjugate z)) for all z. This follows because
990 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
992 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
994 ;; and these two expressions are equal if and only if arg conj z =
995 ;; -arg z, which is clearly true for all z.
996 (declare (type (or rational complex) z))
997 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
998 (sqrt-1-z (complex-sqrt (- 1 z))))
999 (with-float-traps-masked (:divide-by-zero)
1000 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1001 (realpart sqrt-1+z))))
1002 (asinh (imagpart (* (conjugate sqrt-1+z)
1005 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1007 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1008 (defun complex-acosh (z)
1009 (declare (type (or rational complex) z))
1010 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1011 (sqrt-z+1 (complex-sqrt (+ z 1))))
1012 (with-float-traps-masked (:divide-by-zero)
1013 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1015 (* 2 (atan (/ (imagpart sqrt-z-1)
1016 (realpart sqrt-z+1))))))))
1018 ;;; Compute asin z = asinh(i*z)/i.
1020 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1021 (defun complex-asin (z)
1022 (declare (type (or rational complex) z))
1023 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1024 (sqrt-1+z (complex-sqrt (+ 1 z))))
1025 (with-float-traps-masked (:divide-by-zero)
1026 (complex (atan (/ (realpart z)
1027 (realpart (* sqrt-1-z sqrt-1+z))))
1028 (asinh (imagpart (* (conjugate sqrt-1-z)
1031 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1033 ;;; Z may be any number, but the result is always a complex.
1034 (defun complex-asinh (z)
1035 (declare (type (or rational complex) z))
1036 ;; asinh z = -i * asin (i*z)
1037 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1038 (result (complex-asin iz)))
1039 (complex (imagpart result)
1040 (- (realpart result)))))
1042 ;;; Compute atan z = atanh (i*z) / i.
1044 ;;; Z may be any number, but the result is always a complex.
1045 (defun complex-atan (z)
1046 (declare (type (or rational complex) z))
1047 ;; atan z = -i * atanh (i*z)
1048 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1049 (result (complex-atanh iz)))
1050 (complex (imagpart result)
1051 (- (realpart result)))))
1053 ;;; Compute tan z = -i * tanh(i * z)
1055 ;;; Z may be any number, but the result is always a complex.
1056 (defun complex-tan (z)
1057 (declare (type (or rational complex) z))
1058 ;; tan z = -i * tanh(i*z)
1059 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1060 (result (complex-tanh iz)))
1061 (complex (imagpart result)
1062 (- (realpart result)))))