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 #!+x86-64 ;; for constant folding
57 (macrolet ((def (name ll)
58 `(defun ,name ,ll (,name ,@ll))))
61 ;;;; stubs for the Unix math library
63 ;;;; Many of these are unnecessary on the X86 because they're built
67 #!-x86 (def-math-rtn "sin" 1)
68 #!-x86 (def-math-rtn "cos" 1)
69 #!-x86 (def-math-rtn "tan" 1)
70 (def-math-rtn "asin" 1)
71 (def-math-rtn "acos" 1)
72 #!-x86 (def-math-rtn "atan" 1)
73 #!-x86 (def-math-rtn "atan2" 2)
74 (def-math-rtn "sinh" 1)
75 (def-math-rtn "cosh" 1)
76 (def-math-rtn "tanh" 1)
77 (def-math-rtn "asinh" 1)
78 (def-math-rtn "acosh" 1)
79 (def-math-rtn "atanh" 1)
81 ;;; exponential and logarithmic
82 #!-x86 (def-math-rtn "exp" 1)
83 #!-x86 (def-math-rtn "log" 1)
84 #!-x86 (def-math-rtn "log10" 1)
85 (def-math-rtn "pow" 2)
86 #!-(or x86 x86-64) (def-math-rtn "sqrt" 1)
87 (def-math-rtn "hypot" 2)
88 #!-(or hpux x86) (def-math-rtn "log1p" 1)
94 "Return e raised to the power NUMBER."
95 (number-dispatch ((number number))
96 (handle-reals %exp number)
98 (* (exp (realpart number))
99 (cis (imagpart number))))))
101 ;;; INTEXP -- Handle the rational base, integer power case.
103 (declaim (type (or integer null) *intexp-maximum-exponent*))
104 (defparameter *intexp-maximum-exponent* nil)
106 ;;; This function precisely calculates base raised to an integral
107 ;;; power. It separates the cases by the sign of power, for efficiency
108 ;;; reasons, as powers can be calculated more efficiently if power is
109 ;;; a positive integer. Values of power are calculated as positive
110 ;;; integers, and inverted if negative.
111 (defun intexp (base power)
112 (when (and *intexp-maximum-exponent*
113 (> (abs power) *intexp-maximum-exponent*))
114 (error "The absolute value of ~S exceeds ~S."
115 power '*intexp-maximum-exponent*))
116 (cond ((minusp power)
117 (/ (intexp base (- power))))
121 (do ((nextn (ash power -1) (ash power -1))
122 (total (if (oddp power) base 1)
123 (if (oddp power) (* base total) total)))
124 ((zerop nextn) total)
125 (setq base (* base base))
126 (setq power nextn)))))
128 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
129 ;;; floating point stuff. If both args are real, we try %POW right
130 ;;; off, assuming it will return 0 if the result may be complex. If
131 ;;; so, we call COMPLEX-POW which directly computes the complex
132 ;;; result. We also separate the complex-real and real-complex cases
133 ;;; from the general complex case.
134 (defun expt (base power)
136 "Return BASE raised to the POWER."
138 (let ((result (1+ (* base power))))
139 (if (and (floatp result) (float-nan-p result))
142 (labels (;; determine if the double float is an integer.
143 ;; 0 - not an integer
147 (declare (type (unsigned-byte 31) ihi)
148 (type (unsigned-byte 32) lo)
149 (optimize (speed 3) (safety 0)))
151 (declare (type fixnum isint))
152 (cond ((>= ihi #x43400000) ; exponent >= 53
155 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
156 (declare (type (mod 53) k))
158 (let* ((shift (- 52 k))
159 (j (logand (ash lo (- shift))))
161 (declare (type (mod 32) shift)
162 (type (unsigned-byte 32) j j2))
164 (setq isint (- 2 (logand j 1))))))
166 (let* ((shift (- 20 k))
167 (j (ash ihi (- shift)))
169 (declare (type (mod 32) shift)
170 (type (unsigned-byte 31) j j2))
172 (setq isint (- 2 (logand j 1))))))))))
174 (real-expt (x y rtype)
175 (let ((x (coerce x 'double-float))
176 (y (coerce y 'double-float)))
177 (declare (double-float x y))
178 (let* ((x-hi (sb!kernel:double-float-high-bits x))
179 (x-lo (sb!kernel:double-float-low-bits x))
180 (x-ihi (logand x-hi #x7fffffff))
181 (y-hi (sb!kernel:double-float-high-bits y))
182 (y-lo (sb!kernel:double-float-low-bits y))
183 (y-ihi (logand y-hi #x7fffffff)))
184 (declare (type (signed-byte 32) x-hi y-hi)
185 (type (unsigned-byte 31) x-ihi y-ihi)
186 (type (unsigned-byte 32) x-lo y-lo))
188 (when (zerop (logior y-ihi y-lo))
189 (return-from real-expt (coerce 1d0 rtype)))
191 (when (or (> x-ihi #x7ff00000)
192 (and (= x-ihi #x7ff00000) (/= x-lo 0))
194 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
195 (return-from real-expt (coerce (+ x y) rtype)))
196 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
197 (declare (type fixnum yisint))
198 ;; special value of y
199 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
201 (return-from real-expt
202 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
204 (coerce (- y y) rtype))
205 ((>= x-ihi #x3ff00000)
206 ;; (|x|>1)**+-inf = inf,0
211 ;; (|x|<1)**-,+inf = inf,0
214 (coerce 0 rtype))))))
216 (let ((abs-x (abs x)))
217 (declare (double-float abs-x))
218 ;; special value of x
219 (when (and (zerop x-lo)
220 (or (= x-ihi #x7ff00000) (zerop x-ihi)
221 (= x-ihi #x3ff00000)))
222 ;; x is +-0,+-inf,+-1
223 (let ((z (if (< y-hi 0)
224 (/ 1 abs-x) ; z = (1/|x|)
226 (declare (double-float z))
228 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
230 (let ((y*pi (* y pi)))
231 (declare (double-float y*pi))
232 (return-from real-expt
234 (coerce (%cos y*pi) rtype)
235 (coerce (%sin y*pi) rtype)))))
237 ;; (x<0)**odd = -(|x|**odd)
239 (return-from real-expt (coerce z rtype))))
243 (coerce (sb!kernel::%pow x y) rtype)
245 (let ((pow (sb!kernel::%pow abs-x y)))
246 (declare (double-float pow))
249 (coerce (* -1d0 pow) rtype))
253 (let ((y*pi (* y pi)))
254 (declare (double-float y*pi))
256 (coerce (* pow (%cos y*pi))
258 (coerce (* pow (%sin y*pi))
260 (declare (inline real-expt))
261 (number-dispatch ((base number) (power number))
262 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
264 (((foreach single-float double-float) rational)
265 (real-expt base power '(dispatch-type base)))
266 (((foreach fixnum (or bignum ratio) single-float)
267 (foreach ratio single-float))
268 (real-expt base power 'single-float))
269 (((foreach fixnum (or bignum ratio) single-float double-float)
271 (real-expt base power 'double-float))
272 ((double-float single-float)
273 (real-expt base power 'double-float))
274 (((foreach (complex rational) (complex float)) rational)
275 (* (expt (abs base) power)
276 (cis (* power (phase base)))))
277 (((foreach fixnum (or bignum ratio) single-float double-float)
279 (if (and (zerop base) (plusp (realpart power)))
281 (exp (* power (log base)))))
282 (((foreach (complex float) (complex rational))
283 (foreach complex double-float single-float))
284 (if (and (zerop base) (plusp (realpart power)))
286 (exp (* power (log base)))))))))
288 ;;; FIXME: Maybe rename this so that it's clearer that it only works
291 (declare (type integer x))
294 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
295 ;; log2(f). So we grab the top few bits of x and scale that
296 ;; appropriately, take the log of it and add it to n.
298 ;; Motivated by an attempt to get LOG to work better on bignums.
299 (let ((n (integer-length x)))
300 (if (< n sb!vm:double-float-digits)
301 (log (coerce x 'double-float) 2.0d0)
302 (let ((f (ldb (byte sb!vm:double-float-digits
303 (- n sb!vm:double-float-digits))
305 (+ n (log (scale-float (coerce f 'double-float)
306 (- sb!vm:double-float-digits))
309 (defun log (number &optional (base nil base-p))
311 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
314 ((zerop base) 0f0) ; FIXME: type
315 ((and (typep number '(integer (0) *))
316 (typep base '(integer (0) *)))
317 (coerce (/ (log2 number) (log2 base)) 'single-float))
318 (t (/ (log number) (log base))))
319 (number-dispatch ((number number))
320 (((foreach fixnum bignum))
322 (complex (log (- number)) (coerce pi 'single-float))
323 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
326 (complex (log (- number)) (coerce pi 'single-float))
327 (let ((numerator (numerator number))
328 (denominator (denominator number)))
329 (if (= (integer-length numerator)
330 (integer-length denominator))
331 (coerce (%log1p (coerce (- number 1) 'double-float))
333 (coerce (/ (- (log2 numerator) (log2 denominator))
334 (log (exp 1.0d0) 2.0d0))
336 (((foreach single-float double-float))
337 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
338 ;; Since this doesn't seem to be an implementation issue
339 ;; I (pw) take the Kahan result.
340 (if (< (float-sign number)
341 (coerce 0 '(dispatch-type number)))
342 (complex (log (- number)) (coerce pi '(dispatch-type number)))
343 (coerce (%log (coerce number 'double-float))
344 '(dispatch-type number))))
346 (complex-log number)))))
350 "Return the square root of NUMBER."
351 (number-dispatch ((number number))
352 (((foreach fixnum bignum ratio))
354 (complex-sqrt number)
355 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
356 (((foreach single-float double-float))
358 (complex-sqrt (complex number))
359 (coerce (%sqrt (coerce number 'double-float))
360 '(dispatch-type number))))
362 (complex-sqrt number))))
364 ;;;; trigonometic and related functions
368 "Return the absolute value of the number."
369 (number-dispatch ((number number))
370 (((foreach single-float double-float fixnum rational))
373 (let ((rx (realpart number))
374 (ix (imagpart number)))
377 (sqrt (+ (* rx rx) (* ix ix))))
379 (coerce (%hypot (coerce rx 'double-float)
380 (coerce ix 'double-float))
385 (defun phase (number)
387 "Return the angle part of the polar representation of a complex number.
388 For complex numbers, this is (atan (imagpart number) (realpart number)).
389 For non-complex positive numbers, this is 0. For non-complex negative
394 (coerce pi 'single-float)
397 (if (minusp (float-sign number))
398 (coerce pi 'single-float)
401 (if (minusp (float-sign number))
402 (coerce pi 'double-float)
405 (atan (imagpart number) (realpart number)))))
409 "Return the sine of NUMBER."
410 (number-dispatch ((number number))
411 (handle-reals %sin number)
413 (let ((x (realpart number))
414 (y (imagpart number)))
415 (complex (* (sin x) (cosh y))
416 (* (cos x) (sinh y)))))))
420 "Return the cosine of NUMBER."
421 (number-dispatch ((number number))
422 (handle-reals %cos number)
424 (let ((x (realpart number))
425 (y (imagpart number)))
426 (complex (* (cos x) (cosh y))
427 (- (* (sin x) (sinh y))))))))
431 "Return the tangent of NUMBER."
432 (number-dispatch ((number number))
433 (handle-reals %tan number)
435 (complex-tan number))))
439 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
440 (declare (type real theta))
441 (complex (cos theta) (sin theta)))
445 "Return the arc sine of NUMBER."
446 (number-dispatch ((number number))
448 (if (or (> number 1) (< number -1))
449 (complex-asin number)
450 (coerce (%asin (coerce number 'double-float)) 'single-float)))
451 (((foreach single-float double-float))
452 (if (or (> number (coerce 1 '(dispatch-type number)))
453 (< number (coerce -1 '(dispatch-type number))))
454 (complex-asin (complex number))
455 (coerce (%asin (coerce number 'double-float))
456 '(dispatch-type number))))
458 (complex-asin number))))
462 "Return the arc cosine of NUMBER."
463 (number-dispatch ((number number))
465 (if (or (> number 1) (< number -1))
466 (complex-acos number)
467 (coerce (%acos (coerce number 'double-float)) 'single-float)))
468 (((foreach single-float double-float))
469 (if (or (> number (coerce 1 '(dispatch-type number)))
470 (< number (coerce -1 '(dispatch-type number))))
471 (complex-acos (complex number))
472 (coerce (%acos (coerce number 'double-float))
473 '(dispatch-type number))))
475 (complex-acos number))))
477 (defun atan (y &optional (x nil xp))
479 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
482 (declare (type double-float y x)
483 (values double-float))
486 (if (plusp (float-sign x))
489 (float-sign y (/ pi 2)))
491 (number-dispatch ((y real) (x real))
493 (foreach double-float single-float fixnum bignum ratio))
494 (atan2 y (coerce x 'double-float)))
495 (((foreach single-float fixnum bignum ratio)
497 (atan2 (coerce y 'double-float) x))
498 (((foreach single-float fixnum bignum ratio)
499 (foreach single-float fixnum bignum ratio))
500 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
502 (number-dispatch ((y number))
503 (handle-reals %atan y)
507 ;;; It seems that every target system has a C version of sinh, cosh,
508 ;;; and tanh. Let's use these for reals because the original
509 ;;; implementations based on the definitions lose big in round-off
510 ;;; error. These bad definitions also mean that sin and cos for
511 ;;; complex numbers can also lose big.
515 "Return the hyperbolic sine of NUMBER."
516 (number-dispatch ((number number))
517 (handle-reals %sinh number)
519 (let ((x (realpart number))
520 (y (imagpart number)))
521 (complex (* (sinh x) (cos y))
522 (* (cosh x) (sin y)))))))
526 "Return the hyperbolic cosine of NUMBER."
527 (number-dispatch ((number number))
528 (handle-reals %cosh number)
530 (let ((x (realpart number))
531 (y (imagpart number)))
532 (complex (* (cosh x) (cos y))
533 (* (sinh x) (sin y)))))))
537 "Return the hyperbolic tangent of NUMBER."
538 (number-dispatch ((number number))
539 (handle-reals %tanh number)
541 (complex-tanh number))))
543 (defun asinh (number)
545 "Return the hyperbolic arc sine of NUMBER."
546 (number-dispatch ((number number))
547 (handle-reals %asinh number)
549 (complex-asinh number))))
551 (defun acosh (number)
553 "Return the hyperbolic arc cosine of NUMBER."
554 (number-dispatch ((number number))
556 ;; acosh is complex if number < 1
558 (complex-acosh number)
559 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
560 (((foreach single-float double-float))
561 (if (< number (coerce 1 '(dispatch-type number)))
562 (complex-acosh (complex number))
563 (coerce (%acosh (coerce number 'double-float))
564 '(dispatch-type number))))
566 (complex-acosh number))))
568 (defun atanh (number)
570 "Return the hyperbolic arc tangent of NUMBER."
571 (number-dispatch ((number number))
573 ;; atanh is complex if |number| > 1
574 (if (or (> number 1) (< number -1))
575 (complex-atanh number)
576 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
577 (((foreach single-float double-float))
578 (if (or (> number (coerce 1 '(dispatch-type number)))
579 (< number (coerce -1 '(dispatch-type number))))
580 (complex-atanh (complex number))
581 (coerce (%atanh (coerce number 'double-float))
582 '(dispatch-type number))))
584 (complex-atanh number))))
586 ;;; HP-UX does not supply a C version of log1p, so use the definition.
588 ;;; FIXME: This is really not a good definition. As per Raymond Toy
589 ;;; working on CMU CL, "The definition really loses big-time in
590 ;;; roundoff as x gets small."
592 #!-sb-fluid (declaim (inline %log1p))
594 (defun %log1p (number)
595 (declare (double-float number)
596 (optimize (speed 3) (safety 0)))
597 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
599 ;;;; not-OLD-SPECFUN stuff
601 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
602 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
603 ;;;; the standard special function system.)
605 ;;;; This is a set of routines that implement many elementary
606 ;;;; transcendental functions as specified by ANSI Common Lisp. The
607 ;;;; implementation is based on Kahan's paper.
609 ;;;; I believe I have accurately implemented the routines and are
610 ;;;; correct, but you may want to check for your self.
612 ;;;; These functions are written for CMU Lisp and take advantage of
613 ;;;; some of the features available there. It may be possible,
614 ;;;; however, to port this to other Lisps.
616 ;;;; Some functions are significantly more accurate than the original
617 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
618 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
619 ;;;; answer is pi + i*log(2-sqrt(3)).
621 ;;;; All of the implemented functions will take any number for an
622 ;;;; input, but the result will always be a either a complex
623 ;;;; single-float or a complex double-float.
625 ;;;; general functions:
637 ;;;; utility functions:
640 ;;;; internal functions:
641 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
644 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
645 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
646 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
649 ;;;; The original CMU CL code requested:
650 ;;;; Please send any bug reports, comments, or improvements to
651 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
653 ;;; FIXME: In SBCL, the floating point infinity constants like
654 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
655 ;;; constants at cross-compile time, because the cross-compilation
656 ;;; host might not have support for floating point infinities. Thus,
657 ;;; they're effectively implemented as special variable references,
658 ;;; and the code below which uses them might be unnecessarily
659 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
660 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
661 ;;; special variable references with (probably equally slow)
664 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
665 ;;; differ in their interpretations of the real line, IMAGPART was
666 ;;; patch, which without a certain amount of effort would have altered
667 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
668 ;;; were patched to use explicit COMPLEX, rather than implicitly
669 ;;; passing in real numbers for treatment with IMAGPART, and these
670 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
671 ;;; however, someone needs to go back to Kahan for the definitive
672 ;;; answer for treatment of negative real floating point numbers and
673 ;;; branch cuts. If adjustment is needed, it is probably the removal
674 ;;; of explicit calls to COMPLEX in the clients of irrational
675 ;;; functions. -- a slightly bitter CSR, 2004-05-16
677 (declaim (inline square))
679 (declare (double-float x))
682 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
684 ;;; If you have these functions in libm, perhaps they should be used
685 ;;; instead of these Lisp versions. These versions are probably good
686 ;;; enough, especially since they are portable.
688 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
689 ;;; the underlying floating-point format.)
690 (declaim (inline scalb))
692 (declare (type double-float x)
693 (type double-float-exponent n))
696 ;;; This is like LOGB, but X is not infinity and non-zero and not a
697 ;;; NaN, so we can always return an integer.
698 (declaim (inline logb-finite))
699 (defun logb-finite (x)
700 (declare (type double-float x))
701 (multiple-value-bind (signif exponent sign)
703 (declare (ignore signif sign))
704 ;; DECODE-FLOAT is almost right, except that the exponent is off
708 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
709 ;;; For the special cases, the following values are used:
712 ;;; +/- infinity +infinity
715 (declare (type double-float x))
716 (cond ((float-nan-p x)
718 ((float-infinity-p x)
719 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
720 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
722 ;; The answer is negative infinity, but we are supposed to
723 ;; signal divide-by-zero, so do the actual division
729 ;;; This function is used to create a complex number of the
730 ;;; appropriate type:
731 ;;; Create complex number with real part X and imaginary part Y
732 ;;; such that has the same type as Z. If Z has type (complex
733 ;;; rational), the X and Y are coerced to single-float.
734 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
735 (error "needs work for long float support"))
736 (declaim (inline coerce-to-complex-type))
737 (defun coerce-to-complex-type (x y z)
738 (declare (double-float x y)
740 (if (typep (realpart z) 'double-float)
742 ;; Convert anything that's not already a DOUBLE-FLOAT (because
743 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
744 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
745 (complex (float x 1f0)
748 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
749 ;;; result is r + i*k, where k is an integer.
750 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
751 (error "needs work for long float support"))
753 (let ((x (float (realpart z) 1d0))
754 (y (float (imagpart z) 1d0)))
755 ;; Would this be better handled using an exception handler to
756 ;; catch the overflow or underflow signal? For now, we turn all
757 ;; traps off and look at the accrued exceptions to see if any
758 ;; signal would have been raised.
759 (with-float-traps-masked (:underflow :overflow)
760 (let ((rho (+ (square x) (square y))))
761 (declare (optimize (speed 3) (space 0)))
762 (cond ((and (or (float-nan-p rho)
763 (float-infinity-p rho))
764 (or (float-infinity-p (abs x))
765 (float-infinity-p (abs y))))
766 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
768 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
770 ((let ((threshold #.(/ least-positive-double-float
771 double-float-epsilon))
772 (traps (ldb sb!vm::float-sticky-bits
773 (sb!vm:floating-point-modes))))
774 ;; Overflow raised or (underflow raised and rho <
776 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
777 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
780 ;; If we're here, neither x nor y are infinity and at
781 ;; least one is non-zero.. Thus logb returns a nice
783 (let ((k (- (logb-finite (max (abs x) (abs y))))))
784 (values (+ (square (scalb x k))
785 (square (scalb y k)))
790 ;;; principal square root of Z
792 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
793 (defun complex-sqrt (z)
794 ;; KLUDGE: Here and below, we can't just declare Z to be of type
795 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
796 ;; Since there isn't a rational negative zero, this is OK from the
797 ;; point of view of getting the right answer in the face of branch
798 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
799 ;; still ugly. -- CSR, 2004-05-16
800 (declare (type (or complex rational) z))
801 (multiple-value-bind (rho k)
803 (declare (type (or (member 0d0) (double-float 0d0)) rho)
805 (let ((x (float (realpart z) 1.0d0))
806 (y (float (imagpart z) 1.0d0))
809 (declare (double-float x y eta nu))
812 ;; space 0 to get maybe-inline functions inlined.
813 (declare (optimize (speed 3) (space 0)))
815 (if (not (float-nan-p x))
816 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
821 (setf k (1- (ash k -1)))
822 (setf rho (+ rho rho))))
824 (setf rho (scalb (sqrt rho) k))
830 (when (not (float-infinity-p (abs nu)))
831 (setf nu (/ (/ nu rho) 2d0)))
834 (setf nu (float-sign y rho))))
835 (coerce-to-complex-type eta nu z)))))
837 ;;; Compute log(2^j*z).
839 ;;; This is for use with J /= 0 only when |z| is huge.
840 (defun complex-log-scaled (z j)
841 (declare (type (or rational complex) z)
843 ;; The constants t0, t1, t2 should be evaluated to machine
844 ;; precision. In addition, Kahan says the accuracy of log1p
845 ;; influences the choices of these constants but doesn't say how to
846 ;; choose them. We'll just assume his choices matches our
847 ;; implementation of log1p.
848 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
852 (x (float (realpart z) 1.0d0))
853 (y (float (imagpart z) 1.0d0)))
854 (multiple-value-bind (rho k)
856 (declare (optimize (speed 3)))
857 (let ((beta (max (abs x) (abs y)))
858 (theta (min (abs x) (abs y))))
859 (coerce-to-complex-type (if (and (zerop k)
863 (/ (%log1p (+ (* (- beta 1.0d0)
872 ;;; log of Z = log |Z| + i * arg Z
874 ;;; Z may be any number, but the result is always a complex.
875 (defun complex-log (z)
876 (declare (type (or rational complex) z))
877 (complex-log-scaled z 0))
879 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
880 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
881 ;;; The reason for the imaginary part is caused by the fact that arg
882 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
883 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
884 (defun complex-atanh (z)
885 (declare (type (or rational complex) z))
887 (theta (/ (sqrt most-positive-double-float) 4.0d0))
888 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
889 (half-pi (/ pi 2.0d0))
890 (rp (float (realpart z) 1.0d0))
891 (beta (float-sign rp 1.0d0))
893 (y (* beta (- (float (imagpart z) 1.0d0))))
896 ;; Shouldn't need this declare.
897 (declare (double-float x y))
899 (declare (optimize (speed 3)))
900 (cond ((or (> x theta)
902 ;; To avoid overflow...
903 (setf nu (float-sign y half-pi))
904 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
905 ;; which can cause overflow. Arrange this computation so
906 ;; that it won't overflow.
907 (setf eta (let* ((x-bigger (> x (abs y)))
908 (r (if x-bigger (/ y x) (/ x y)))
909 (d (+ 1.0d0 (* r r))))
914 ;; Should this be changed so that if y is zero, eta is set
915 ;; to +infinity instead of approx 176? In any case
916 ;; tanh(176) is 1.0d0 within working precision.
917 (let ((t1 (+ 4d0 (square y)))
918 (t2 (+ (abs y) rho)))
919 (setf eta (log (/ (sqrt (sqrt t1))
923 (+ half-pi (atan (* 0.5d0 t2))))))))
925 (let ((t1 (+ (abs y) rho)))
926 ;; Normal case using log1p(x) = log(1 + x)
928 (%log1p (/ (* 4.0d0 x)
929 (+ (square (- 1.0d0 x))
936 (coerce-to-complex-type (* beta eta)
940 ;;; Compute tanh z = sinh z / cosh z.
941 (defun complex-tanh (z)
942 (declare (type (or rational complex) z))
943 (let ((x (float (realpart z) 1.0d0))
944 (y (float (imagpart z) 1.0d0)))
946 ;; space 0 to get maybe-inline functions inlined
947 (declare (optimize (speed 3) (space 0)))
949 ;; FIXME: this form is hideously broken wrt
950 ;; cross-compilation portability. Much else in this
951 ;; file is too, of course, sometimes hidden by
952 ;; constant-folding, but this one in particular clearly
953 ;; depends on host and target
954 ;; MOST-POSITIVE-DOUBLE-FLOATs being equal. -- CSR,
957 (log most-positive-double-float))
959 (coerce-to-complex-type (float-sign x)
963 (beta (+ 1.0d0 (* tv tv)))
965 (rho (sqrt (+ 1.0d0 (* s s)))))
966 (if (float-infinity-p (abs tv))
967 (coerce-to-complex-type (/ rho s)
970 (let ((den (+ 1.0d0 (* beta s s))))
971 (coerce-to-complex-type (/ (* beta rho s)
976 ;;; Compute acos z = pi/2 - asin z.
978 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
979 (defun complex-acos (z)
980 ;; Kahan says we should only compute the parts needed. Thus, the
981 ;; REALPART's below should only compute the real part, not the whole
982 ;; complex expression. Doing this can be important because we may get
983 ;; spurious signals that occur in the part that we are not using.
985 ;; However, we take a pragmatic approach and just use the whole
988 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
989 ;; it's the conjugate of the square root or the square root of the
990 ;; conjugate. This needs to be checked.
992 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
993 ;; same as (sqrt (conjugate z)) for all z. This follows because
995 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
997 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
999 ;; and these two expressions are equal if and only if arg conj z =
1000 ;; -arg z, which is clearly true for all z.
1001 (declare (type (or rational complex) z))
1002 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
1003 (sqrt-1-z (complex-sqrt (- 1 z))))
1004 (with-float-traps-masked (:divide-by-zero)
1005 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1006 (realpart sqrt-1+z))))
1007 (asinh (imagpart (* (conjugate sqrt-1+z)
1010 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1012 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1013 (defun complex-acosh (z)
1014 (declare (type (or rational complex) z))
1015 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1016 (sqrt-z+1 (complex-sqrt (+ z 1))))
1017 (with-float-traps-masked (:divide-by-zero)
1018 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1020 (* 2 (atan (/ (imagpart sqrt-z-1)
1021 (realpart sqrt-z+1))))))))
1023 ;;; Compute asin z = asinh(i*z)/i.
1025 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1026 (defun complex-asin (z)
1027 (declare (type (or rational complex) z))
1028 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1029 (sqrt-1+z (complex-sqrt (+ 1 z))))
1030 (with-float-traps-masked (:divide-by-zero)
1031 (complex (atan (/ (realpart z)
1032 (realpart (* sqrt-1-z sqrt-1+z))))
1033 (asinh (imagpart (* (conjugate sqrt-1-z)
1036 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1038 ;;; Z may be any number, but the result is always a complex.
1039 (defun complex-asinh (z)
1040 (declare (type (or rational complex) z))
1041 ;; asinh z = -i * asin (i*z)
1042 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1043 (result (complex-asin iz)))
1044 (complex (imagpart result)
1045 (- (realpart result)))))
1047 ;;; Compute atan z = atanh (i*z) / i.
1049 ;;; Z may be any number, but the result is always a complex.
1050 (defun complex-atan (z)
1051 (declare (type (or rational complex) z))
1052 ;; atan z = -i * atanh (i*z)
1053 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1054 (result (complex-atanh iz)))
1055 (complex (imagpart result)
1056 (- (realpart result)))))
1058 ;;; Compute tan z = -i * tanh(i * z)
1060 ;;; Z may be any number, but the result is always a complex.
1061 (defun complex-tan (z)
1062 (declare (type (or rational complex) z))
1063 ;; tan z = -i * tanh(i*z)
1064 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1065 (result (complex-tanh iz)))
1066 (complex (imagpart result)
1067 (- (realpart result)))))