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))))
59 #!+x86-64 ;; for constant folding
60 (macrolet ((def (name ll)
61 `(defun ,name ,ll (,name ,@ll))))
64 ;;;; stubs for the Unix math library
66 ;;;; Many of these are unnecessary on the X86 because they're built
70 #!-x86 (def-math-rtn "sin" 1)
71 #!-x86 (def-math-rtn "cos" 1)
72 #!-x86 (def-math-rtn "tan" 1)
73 (def-math-rtn "asin" 1)
74 (def-math-rtn "acos" 1)
75 #!-x86 (def-math-rtn "atan" 1)
76 #!-x86 (def-math-rtn "atan2" 2)
77 (def-math-rtn "sinh" 1)
78 (def-math-rtn "cosh" 1)
79 #!-win32(def-math-rtn "tanh" 1)
80 #!-win32(def-math-rtn "asinh" 1)
81 #!-win32(def-math-rtn "acosh" 1)
82 #!-win32(def-math-rtn "atanh" 1)
84 ;;; exponential and logarithmic
85 #!-x86 (def-math-rtn "exp" 1)
86 #!-x86 (def-math-rtn "log" 1)
87 #!-x86 (def-math-rtn "log10" 1)
88 #!-win32(def-math-rtn "pow" 2)
89 #!-(or x86 x86-64) (def-math-rtn "sqrt" 1)
90 (def-math-rtn "hypot" 2)
91 #!-(or hpux x86) (def-math-rtn "log1p" 1)
97 "Return e raised to the power NUMBER."
98 (number-dispatch ((number number))
99 (handle-reals %exp number)
101 (* (exp (realpart number))
102 (cis (imagpart number))))))
104 ;;; INTEXP -- Handle the rational base, integer power case.
106 (declaim (type (or integer null) *intexp-maximum-exponent*))
107 (defparameter *intexp-maximum-exponent* nil)
109 ;;; This function precisely calculates base raised to an integral
110 ;;; power. It separates the cases by the sign of power, for efficiency
111 ;;; reasons, as powers can be calculated more efficiently if power is
112 ;;; a positive integer. Values of power are calculated as positive
113 ;;; integers, and inverted if negative.
114 (defun intexp (base power)
115 (when (and *intexp-maximum-exponent*
116 (> (abs power) *intexp-maximum-exponent*))
117 (error "The absolute value of ~S exceeds ~S."
118 power '*intexp-maximum-exponent*))
119 (cond ((minusp power)
120 (/ (intexp base (- power))))
124 (do ((nextn (ash power -1) (ash power -1))
125 (total (if (oddp power) base 1)
126 (if (oddp power) (* base total) total)))
127 ((zerop nextn) total)
128 (setq base (* base base))
129 (setq power nextn)))))
131 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
132 ;;; floating point stuff. If both args are real, we try %POW right
133 ;;; off, assuming it will return 0 if the result may be complex. If
134 ;;; so, we call COMPLEX-POW which directly computes the complex
135 ;;; result. We also separate the complex-real and real-complex cases
136 ;;; from the general complex case.
137 (defun expt (base power)
139 "Return BASE raised to the POWER."
141 (let ((result (1+ (* base power))))
142 (if (and (floatp result) (float-nan-p result))
145 (labels (;; determine if the double float is an integer.
146 ;; 0 - not an integer
150 (declare (type (unsigned-byte 31) ihi)
151 (type (unsigned-byte 32) lo)
152 (optimize (speed 3) (safety 0)))
154 (declare (type fixnum isint))
155 (cond ((>= ihi #x43400000) ; exponent >= 53
158 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
159 (declare (type (mod 53) k))
161 (let* ((shift (- 52 k))
162 (j (logand (ash lo (- shift))))
164 (declare (type (mod 32) shift)
165 (type (unsigned-byte 32) j j2))
167 (setq isint (- 2 (logand j 1))))))
169 (let* ((shift (- 20 k))
170 (j (ash ihi (- shift)))
172 (declare (type (mod 32) shift)
173 (type (unsigned-byte 31) j j2))
175 (setq isint (- 2 (logand j 1))))))))))
177 (real-expt (x y rtype)
178 (let ((x (coerce x 'double-float))
179 (y (coerce y 'double-float)))
180 (declare (double-float x y))
181 (let* ((x-hi (sb!kernel:double-float-high-bits x))
182 (x-lo (sb!kernel:double-float-low-bits x))
183 (x-ihi (logand x-hi #x7fffffff))
184 (y-hi (sb!kernel:double-float-high-bits y))
185 (y-lo (sb!kernel:double-float-low-bits y))
186 (y-ihi (logand y-hi #x7fffffff)))
187 (declare (type (signed-byte 32) x-hi y-hi)
188 (type (unsigned-byte 31) x-ihi y-ihi)
189 (type (unsigned-byte 32) x-lo y-lo))
191 (when (zerop (logior y-ihi y-lo))
192 (return-from real-expt (coerce 1d0 rtype)))
194 (when (or (> x-ihi #x7ff00000)
195 (and (= x-ihi #x7ff00000) (/= x-lo 0))
197 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
198 (return-from real-expt (coerce (+ x y) rtype)))
199 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
200 (declare (type fixnum yisint))
201 ;; special value of y
202 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
204 (return-from real-expt
205 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
207 (coerce (- y y) rtype))
208 ((>= x-ihi #x3ff00000)
209 ;; (|x|>1)**+-inf = inf,0
214 ;; (|x|<1)**-,+inf = inf,0
217 (coerce 0 rtype))))))
219 (let ((abs-x (abs x)))
220 (declare (double-float abs-x))
221 ;; special value of x
222 (when (and (zerop x-lo)
223 (or (= x-ihi #x7ff00000) (zerop x-ihi)
224 (= x-ihi #x3ff00000)))
225 ;; x is +-0,+-inf,+-1
226 (let ((z (if (< y-hi 0)
227 (/ 1 abs-x) ; z = (1/|x|)
229 (declare (double-float z))
231 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
233 (let ((y*pi (* y pi)))
234 (declare (double-float y*pi))
235 (return-from real-expt
237 (coerce (%cos y*pi) rtype)
238 (coerce (%sin y*pi) rtype)))))
240 ;; (x<0)**odd = -(|x|**odd)
242 (return-from real-expt (coerce z rtype))))
246 (coerce (sb!kernel::%pow x y) rtype)
248 (let ((pow (sb!kernel::%pow abs-x y)))
249 (declare (double-float pow))
252 (coerce (* -1d0 pow) rtype))
256 (let ((y*pi (* y pi)))
257 (declare (double-float y*pi))
259 (coerce (* pow (%cos y*pi))
261 (coerce (* pow (%sin y*pi))
263 (declare (inline real-expt))
264 (number-dispatch ((base number) (power number))
265 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
267 (((foreach single-float double-float) rational)
268 (real-expt base power '(dispatch-type base)))
269 (((foreach fixnum (or bignum ratio) single-float)
270 (foreach ratio single-float))
271 (real-expt base power 'single-float))
272 (((foreach fixnum (or bignum ratio) single-float double-float)
274 (real-expt base power 'double-float))
275 ((double-float single-float)
276 (real-expt base power 'double-float))
277 (((foreach (complex rational) (complex float)) rational)
278 (* (expt (abs base) power)
279 (cis (* power (phase base)))))
280 (((foreach fixnum (or bignum ratio) single-float double-float)
282 (if (and (zerop base) (plusp (realpart power)))
284 (exp (* power (log base)))))
285 (((foreach (complex float) (complex rational))
286 (foreach complex double-float single-float))
287 (if (and (zerop base) (plusp (realpart power)))
289 (exp (* power (log base)))))))))
291 ;;; FIXME: Maybe rename this so that it's clearer that it only works
294 (declare (type integer x))
297 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
298 ;; log2(f). So we grab the top few bits of x and scale that
299 ;; appropriately, take the log of it and add it to n.
301 ;; Motivated by an attempt to get LOG to work better on bignums.
302 (let ((n (integer-length x)))
303 (if (< n sb!vm:double-float-digits)
304 (log (coerce x 'double-float) 2.0d0)
305 (let ((f (ldb (byte sb!vm:double-float-digits
306 (- n sb!vm:double-float-digits))
308 (+ n (log (scale-float (coerce f 'double-float)
309 (- sb!vm:double-float-digits))
312 (defun log (number &optional (base nil base-p))
314 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
317 ((zerop base) 0f0) ; FIXME: type
318 ((and (typep number '(integer (0) *))
319 (typep base '(integer (0) *)))
320 (coerce (/ (log2 number) (log2 base)) 'single-float))
321 (t (/ (log number) (log base))))
322 (number-dispatch ((number number))
323 (((foreach fixnum bignum))
325 (complex (log (- number)) (coerce pi 'single-float))
326 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
329 (complex (log (- number)) (coerce pi 'single-float))
330 (let ((numerator (numerator number))
331 (denominator (denominator number)))
332 (if (= (integer-length numerator)
333 (integer-length denominator))
334 (coerce (%log1p (coerce (- number 1) 'double-float))
336 (coerce (/ (- (log2 numerator) (log2 denominator))
337 (log (exp 1.0d0) 2.0d0))
339 (((foreach single-float double-float))
340 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
341 ;; Since this doesn't seem to be an implementation issue
342 ;; I (pw) take the Kahan result.
343 (if (< (float-sign number)
344 (coerce 0 '(dispatch-type number)))
345 (complex (log (- number)) (coerce pi '(dispatch-type number)))
346 (coerce (%log (coerce number 'double-float))
347 '(dispatch-type number))))
349 (complex-log number)))))
353 "Return the square root of NUMBER."
354 (number-dispatch ((number number))
355 (((foreach fixnum bignum ratio))
357 (complex-sqrt number)
358 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
359 (((foreach single-float double-float))
361 (complex-sqrt (complex number))
362 (coerce (%sqrt (coerce number 'double-float))
363 '(dispatch-type number))))
365 (complex-sqrt number))))
367 ;;;; trigonometic and related functions
371 "Return the absolute value of the number."
372 (number-dispatch ((number number))
373 (((foreach single-float double-float fixnum rational))
376 (let ((rx (realpart number))
377 (ix (imagpart number)))
380 (sqrt (+ (* rx rx) (* ix ix))))
382 (coerce (%hypot (coerce rx 'double-float)
383 (coerce ix 'double-float))
388 (defun phase (number)
390 "Return the angle part of the polar representation of a complex number.
391 For complex numbers, this is (atan (imagpart number) (realpart number)).
392 For non-complex positive numbers, this is 0. For non-complex negative
397 (coerce pi 'single-float)
400 (if (minusp (float-sign number))
401 (coerce pi 'single-float)
404 (if (minusp (float-sign number))
405 (coerce pi 'double-float)
408 (atan (imagpart number) (realpart number)))))
412 "Return the sine of NUMBER."
413 (number-dispatch ((number number))
414 (handle-reals %sin number)
416 (let ((x (realpart number))
417 (y (imagpart number)))
418 (complex (* (sin x) (cosh y))
419 (* (cos x) (sinh y)))))))
423 "Return the cosine of NUMBER."
424 (number-dispatch ((number number))
425 (handle-reals %cos number)
427 (let ((x (realpart number))
428 (y (imagpart number)))
429 (complex (* (cos x) (cosh y))
430 (- (* (sin x) (sinh y))))))))
434 "Return the tangent of NUMBER."
435 (number-dispatch ((number number))
436 (handle-reals %tan number)
438 (complex-tan number))))
442 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
443 (declare (type real theta))
444 (complex (cos theta) (sin theta)))
448 "Return the arc sine of NUMBER."
449 (number-dispatch ((number number))
451 (if (or (> number 1) (< number -1))
452 (complex-asin number)
453 (coerce (%asin (coerce number 'double-float)) 'single-float)))
454 (((foreach single-float double-float))
455 (if (or (> number (coerce 1 '(dispatch-type number)))
456 (< number (coerce -1 '(dispatch-type number))))
457 (complex-asin (complex number))
458 (coerce (%asin (coerce number 'double-float))
459 '(dispatch-type number))))
461 (complex-asin number))))
465 "Return the arc cosine of NUMBER."
466 (number-dispatch ((number number))
468 (if (or (> number 1) (< number -1))
469 (complex-acos number)
470 (coerce (%acos (coerce number 'double-float)) 'single-float)))
471 (((foreach single-float double-float))
472 (if (or (> number (coerce 1 '(dispatch-type number)))
473 (< number (coerce -1 '(dispatch-type number))))
474 (complex-acos (complex number))
475 (coerce (%acos (coerce number 'double-float))
476 '(dispatch-type number))))
478 (complex-acos number))))
480 (defun atan (y &optional (x nil xp))
482 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
485 (declare (type double-float y x)
486 (values double-float))
489 (if (plusp (float-sign x))
492 (float-sign y (/ pi 2)))
494 (number-dispatch ((y real) (x real))
496 (foreach double-float single-float fixnum bignum ratio))
497 (atan2 y (coerce x 'double-float)))
498 (((foreach single-float fixnum bignum ratio)
500 (atan2 (coerce y 'double-float) x))
501 (((foreach single-float fixnum bignum ratio)
502 (foreach single-float fixnum bignum ratio))
503 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
505 (number-dispatch ((y number))
506 (handle-reals %atan y)
510 ;;; It seems that every target system has a C version of sinh, cosh,
511 ;;; and tanh. Let's use these for reals because the original
512 ;;; implementations based on the definitions lose big in round-off
513 ;;; error. These bad definitions also mean that sin and cos for
514 ;;; complex numbers can also lose big.
518 "Return the hyperbolic sine of NUMBER."
519 (number-dispatch ((number number))
520 (handle-reals %sinh number)
522 (let ((x (realpart number))
523 (y (imagpart number)))
524 (complex (* (sinh x) (cos y))
525 (* (cosh x) (sin y)))))))
529 "Return the hyperbolic cosine of NUMBER."
530 (number-dispatch ((number number))
531 (handle-reals %cosh number)
533 (let ((x (realpart number))
534 (y (imagpart number)))
535 (complex (* (cosh x) (cos y))
536 (* (sinh x) (sin y)))))))
540 "Return the hyperbolic tangent of NUMBER."
541 (number-dispatch ((number number))
542 (handle-reals %tanh number)
544 (complex-tanh number))))
546 (defun asinh (number)
548 "Return the hyperbolic arc sine of NUMBER."
549 (number-dispatch ((number number))
550 (handle-reals %asinh number)
552 (complex-asinh number))))
554 (defun acosh (number)
556 "Return the hyperbolic arc cosine of NUMBER."
557 (number-dispatch ((number number))
559 ;; acosh is complex if number < 1
561 (complex-acosh number)
562 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
563 (((foreach single-float double-float))
564 (if (< number (coerce 1 '(dispatch-type number)))
565 (complex-acosh (complex number))
566 (coerce (%acosh (coerce number 'double-float))
567 '(dispatch-type number))))
569 (complex-acosh number))))
571 (defun atanh (number)
573 "Return the hyperbolic arc tangent of NUMBER."
574 (number-dispatch ((number number))
576 ;; atanh is complex if |number| > 1
577 (if (or (> number 1) (< number -1))
578 (complex-atanh number)
579 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
580 (((foreach single-float double-float))
581 (if (or (> number (coerce 1 '(dispatch-type number)))
582 (< number (coerce -1 '(dispatch-type number))))
583 (complex-atanh (complex number))
584 (coerce (%atanh (coerce number 'double-float))
585 '(dispatch-type number))))
587 (complex-atanh number))))
589 ;;; HP-UX does not supply a C version of log1p, so use the definition.
591 ;;; FIXME: This is really not a good definition. As per Raymond Toy
592 ;;; working on CMU CL, "The definition really loses big-time in
593 ;;; roundoff as x gets small."
595 #!-sb-fluid (declaim (inline %log1p))
597 (defun %log1p (number)
598 (declare (double-float number)
599 (optimize (speed 3) (safety 0)))
600 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
602 ;;;; not-OLD-SPECFUN stuff
604 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
605 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
606 ;;;; the standard special function system.)
608 ;;;; This is a set of routines that implement many elementary
609 ;;;; transcendental functions as specified by ANSI Common Lisp. The
610 ;;;; implementation is based on Kahan's paper.
612 ;;;; I believe I have accurately implemented the routines and are
613 ;;;; correct, but you may want to check for your self.
615 ;;;; These functions are written for CMU Lisp and take advantage of
616 ;;;; some of the features available there. It may be possible,
617 ;;;; however, to port this to other Lisps.
619 ;;;; Some functions are significantly more accurate than the original
620 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
621 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
622 ;;;; answer is pi + i*log(2-sqrt(3)).
624 ;;;; All of the implemented functions will take any number for an
625 ;;;; input, but the result will always be a either a complex
626 ;;;; single-float or a complex double-float.
628 ;;;; general functions:
640 ;;;; utility functions:
643 ;;;; internal functions:
644 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
647 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
648 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
649 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
652 ;;;; The original CMU CL code requested:
653 ;;;; Please send any bug reports, comments, or improvements to
654 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
656 ;;; FIXME: In SBCL, the floating point infinity constants like
657 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
658 ;;; constants at cross-compile time, because the cross-compilation
659 ;;; host might not have support for floating point infinities. Thus,
660 ;;; they're effectively implemented as special variable references,
661 ;;; and the code below which uses them might be unnecessarily
662 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
663 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
664 ;;; special variable references with (probably equally slow)
667 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
668 ;;; differ in their interpretations of the real line, IMAGPART was
669 ;;; patch, which without a certain amount of effort would have altered
670 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
671 ;;; were patched to use explicit COMPLEX, rather than implicitly
672 ;;; passing in real numbers for treatment with IMAGPART, and these
673 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
674 ;;; however, someone needs to go back to Kahan for the definitive
675 ;;; answer for treatment of negative real floating point numbers and
676 ;;; branch cuts. If adjustment is needed, it is probably the removal
677 ;;; of explicit calls to COMPLEX in the clients of irrational
678 ;;; functions. -- a slightly bitter CSR, 2004-05-16
680 (declaim (inline square))
682 (declare (double-float x))
685 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
687 ;;; If you have these functions in libm, perhaps they should be used
688 ;;; instead of these Lisp versions. These versions are probably good
689 ;;; enough, especially since they are portable.
691 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
692 ;;; the underlying floating-point format.)
693 (declaim (inline scalb))
695 (declare (type double-float x)
696 (type double-float-exponent n))
699 ;;; This is like LOGB, but X is not infinity and non-zero and not a
700 ;;; NaN, so we can always return an integer.
701 (declaim (inline logb-finite))
702 (defun logb-finite (x)
703 (declare (type double-float x))
704 (multiple-value-bind (signif exponent sign)
706 (declare (ignore signif sign))
707 ;; DECODE-FLOAT is almost right, except that the exponent is off
711 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
712 ;;; For the special cases, the following values are used:
715 ;;; +/- infinity +infinity
718 (declare (type double-float x))
719 (cond ((float-nan-p x)
721 ((float-infinity-p x)
722 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
723 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
725 ;; The answer is negative infinity, but we are supposed to
726 ;; signal divide-by-zero, so do the actual division
732 ;;; This function is used to create a complex number of the
733 ;;; appropriate type:
734 ;;; Create complex number with real part X and imaginary part Y
735 ;;; such that has the same type as Z. If Z has type (complex
736 ;;; rational), the X and Y are coerced to single-float.
737 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
738 (error "needs work for long float support"))
739 (declaim (inline coerce-to-complex-type))
740 (defun coerce-to-complex-type (x y z)
741 (declare (double-float x y)
743 (if (typep (realpart z) 'double-float)
745 ;; Convert anything that's not already a DOUBLE-FLOAT (because
746 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
747 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
748 (complex (float x 1f0)
751 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
752 ;;; result is r + i*k, where k is an integer.
753 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
754 (error "needs work for long float support"))
756 (let ((x (float (realpart z) 1d0))
757 (y (float (imagpart z) 1d0)))
758 ;; Would this be better handled using an exception handler to
759 ;; catch the overflow or underflow signal? For now, we turn all
760 ;; traps off and look at the accrued exceptions to see if any
761 ;; signal would have been raised.
762 (with-float-traps-masked (:underflow :overflow)
763 (let ((rho (+ (square x) (square y))))
764 (declare (optimize (speed 3) (space 0)))
765 (cond ((and (or (float-nan-p rho)
766 (float-infinity-p rho))
767 (or (float-infinity-p (abs x))
768 (float-infinity-p (abs y))))
769 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
771 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
773 ((let ((threshold #.(/ least-positive-double-float
774 double-float-epsilon))
775 (traps (ldb sb!vm::float-sticky-bits
776 (sb!vm:floating-point-modes))))
777 ;; Overflow raised or (underflow raised and rho <
779 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
780 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
783 ;; If we're here, neither x nor y are infinity and at
784 ;; least one is non-zero.. Thus logb returns a nice
786 (let ((k (- (logb-finite (max (abs x) (abs y))))))
787 (values (+ (square (scalb x k))
788 (square (scalb y k)))
793 ;;; principal square root of Z
795 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
796 (defun complex-sqrt (z)
797 ;; KLUDGE: Here and below, we can't just declare Z to be of type
798 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
799 ;; Since there isn't a rational negative zero, this is OK from the
800 ;; point of view of getting the right answer in the face of branch
801 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
802 ;; still ugly. -- CSR, 2004-05-16
803 (declare (type (or complex rational) z))
804 (multiple-value-bind (rho k)
806 (declare (type (or (member 0d0) (double-float 0d0)) rho)
808 (let ((x (float (realpart z) 1.0d0))
809 (y (float (imagpart z) 1.0d0))
812 (declare (double-float x y eta nu))
815 ;; space 0 to get maybe-inline functions inlined.
816 (declare (optimize (speed 3) (space 0)))
818 (if (not (float-nan-p x))
819 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
824 (setf k (1- (ash k -1)))
825 (setf rho (+ rho rho))))
827 (setf rho (scalb (sqrt rho) k))
833 (when (not (float-infinity-p (abs nu)))
834 (setf nu (/ (/ nu rho) 2d0)))
837 (setf nu (float-sign y rho))))
838 (coerce-to-complex-type eta nu z)))))
840 ;;; Compute log(2^j*z).
842 ;;; This is for use with J /= 0 only when |z| is huge.
843 (defun complex-log-scaled (z j)
844 (declare (type (or rational complex) z)
846 ;; The constants t0, t1, t2 should be evaluated to machine
847 ;; precision. In addition, Kahan says the accuracy of log1p
848 ;; influences the choices of these constants but doesn't say how to
849 ;; choose them. We'll just assume his choices matches our
850 ;; implementation of log1p.
851 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
855 (x (float (realpart z) 1.0d0))
856 (y (float (imagpart z) 1.0d0)))
857 (multiple-value-bind (rho k)
859 (declare (optimize (speed 3)))
860 (let ((beta (max (abs x) (abs y)))
861 (theta (min (abs x) (abs y))))
862 (coerce-to-complex-type (if (and (zerop k)
866 (/ (%log1p (+ (* (- beta 1.0d0)
875 ;;; log of Z = log |Z| + i * arg Z
877 ;;; Z may be any number, but the result is always a complex.
878 (defun complex-log (z)
879 (declare (type (or rational complex) z))
880 (complex-log-scaled z 0))
882 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
883 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
884 ;;; The reason for the imaginary part is caused by the fact that arg
885 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
886 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
887 (defun complex-atanh (z)
888 (declare (type (or rational complex) z))
890 (theta (/ (sqrt most-positive-double-float) 4.0d0))
891 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
892 (half-pi (/ pi 2.0d0))
893 (rp (float (realpart z) 1.0d0))
894 (beta (float-sign rp 1.0d0))
896 (y (* beta (- (float (imagpart z) 1.0d0))))
899 ;; Shouldn't need this declare.
900 (declare (double-float x y))
902 (declare (optimize (speed 3)))
903 (cond ((or (> x theta)
905 ;; To avoid overflow...
906 (setf nu (float-sign y half-pi))
907 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
908 ;; which can cause overflow. Arrange this computation so
909 ;; that it won't overflow.
910 (setf eta (let* ((x-bigger (> x (abs y)))
911 (r (if x-bigger (/ y x) (/ x y)))
912 (d (+ 1.0d0 (* r r))))
917 ;; Should this be changed so that if y is zero, eta is set
918 ;; to +infinity instead of approx 176? In any case
919 ;; tanh(176) is 1.0d0 within working precision.
920 (let ((t1 (+ 4d0 (square y)))
921 (t2 (+ (abs y) rho)))
922 (setf eta (log (/ (sqrt (sqrt t1))
926 (+ half-pi (atan (* 0.5d0 t2))))))))
928 (let ((t1 (+ (abs y) rho)))
929 ;; Normal case using log1p(x) = log(1 + x)
931 (%log1p (/ (* 4.0d0 x)
932 (+ (square (- 1.0d0 x))
939 (coerce-to-complex-type (* beta eta)
943 ;;; Compute tanh z = sinh z / cosh z.
944 (defun complex-tanh (z)
945 (declare (type (or rational complex) z))
946 (let ((x (float (realpart z) 1.0d0))
947 (y (float (imagpart z) 1.0d0)))
949 ;; space 0 to get maybe-inline functions inlined
950 (declare (optimize (speed 3) (space 0)))
952 ;; FIXME: this form is hideously broken wrt
953 ;; cross-compilation portability. Much else in this
954 ;; file is too, of course, sometimes hidden by
955 ;; constant-folding, but this one in particular clearly
956 ;; depends on host and target
957 ;; MOST-POSITIVE-DOUBLE-FLOATs being equal. -- CSR,
960 (log most-positive-double-float))
962 (coerce-to-complex-type (float-sign x)
966 (beta (+ 1.0d0 (* tv tv)))
968 (rho (sqrt (+ 1.0d0 (* s s)))))
969 (if (float-infinity-p (abs tv))
970 (coerce-to-complex-type (/ rho s)
973 (let ((den (+ 1.0d0 (* beta s s))))
974 (coerce-to-complex-type (/ (* beta rho s)
979 ;;; Compute acos z = pi/2 - asin z.
981 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
982 (defun complex-acos (z)
983 ;; Kahan says we should only compute the parts needed. Thus, the
984 ;; REALPART's below should only compute the real part, not the whole
985 ;; complex expression. Doing this can be important because we may get
986 ;; spurious signals that occur in the part that we are not using.
988 ;; However, we take a pragmatic approach and just use the whole
991 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
992 ;; it's the conjugate of the square root or the square root of the
993 ;; conjugate. This needs to be checked.
995 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
996 ;; same as (sqrt (conjugate z)) for all z. This follows because
998 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1000 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1002 ;; and these two expressions are equal if and only if arg conj z =
1003 ;; -arg z, which is clearly true for all z.
1004 (declare (type (or rational complex) z))
1005 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
1006 (sqrt-1-z (complex-sqrt (- 1 z))))
1007 (with-float-traps-masked (:divide-by-zero)
1008 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1009 (realpart sqrt-1+z))))
1010 (asinh (imagpart (* (conjugate sqrt-1+z)
1013 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1015 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1016 (defun complex-acosh (z)
1017 (declare (type (or rational complex) z))
1018 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1019 (sqrt-z+1 (complex-sqrt (+ z 1))))
1020 (with-float-traps-masked (:divide-by-zero)
1021 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1023 (* 2 (atan (/ (imagpart sqrt-z-1)
1024 (realpart sqrt-z+1))))))))
1026 ;;; Compute asin z = asinh(i*z)/i.
1028 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1029 (defun complex-asin (z)
1030 (declare (type (or rational complex) z))
1031 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1032 (sqrt-1+z (complex-sqrt (+ 1 z))))
1033 (with-float-traps-masked (:divide-by-zero)
1034 (complex (atan (/ (realpart z)
1035 (realpart (* sqrt-1-z sqrt-1+z))))
1036 (asinh (imagpart (* (conjugate sqrt-1-z)
1039 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1041 ;;; Z may be any number, but the result is always a complex.
1042 (defun complex-asinh (z)
1043 (declare (type (or rational complex) z))
1044 ;; asinh z = -i * asin (i*z)
1045 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1046 (result (complex-asin iz)))
1047 (complex (imagpart result)
1048 (- (realpart result)))))
1050 ;;; Compute atan z = atanh (i*z) / i.
1052 ;;; Z may be any number, but the result is always a complex.
1053 (defun complex-atan (z)
1054 (declare (type (or rational complex) z))
1055 ;; atan z = -i * atanh (i*z)
1056 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1057 (result (complex-atanh iz)))
1058 (complex (imagpart result)
1059 (- (realpart result)))))
1061 ;;; Compute tan z = -i * tanh(i * z)
1063 ;;; Z may be any number, but the result is always a complex.
1064 (defun complex-tan (z)
1065 (declare (type (or rational complex) z))
1066 ;; tan z = -i * tanh(i*z)
1067 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1068 (result (complex-tanh iz)))
1069 (complex (imagpart result)
1070 (- (realpart result)))))