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)
81 (def-math-rtn "tanh" 1)
82 (def-math-rtn "asinh" 1)
83 (def-math-rtn "acosh" 1)
84 (def-math-rtn "atanh" 1))
87 (declaim (inline %tanh))
89 (/ (%sinh number) (%cosh number)))
90 (declaim (inline %asinh))
91 (defun %asinh (number)
92 (log (+ number (sqrt (+ (* number number) 1.0d0))) #.(exp 1.0d0)))
93 (declaim (inline %acosh))
94 (defun %acosh (number)
95 (log (+ number (sqrt (- (* number number) 1.0d0))) #.(exp 1.0d0)))
96 (declaim (inline %atanh))
97 (defun %atanh (number)
98 (let ((ratio (/ (+ 1 number) (- 1 number))))
99 ;; Were we effectively zero?
102 (/ (log ratio #.(exp 1.0d0)) 2.0d0)))))
104 ;;; exponential and logarithmic
105 #!-x86 (def-math-rtn "exp" 1)
106 #!-x86 (def-math-rtn "log" 1)
107 #!-x86 (def-math-rtn "log10" 1)
108 #!-win32(def-math-rtn "pow" 2)
109 #!-(or x86 x86-64) (def-math-rtn "sqrt" 1)
110 (def-math-rtn "hypot" 2)
111 #!-(or hpux x86) (def-math-rtn "log1p" 1)
117 "Return e raised to the power NUMBER."
118 (number-dispatch ((number number))
119 (handle-reals %exp number)
121 (* (exp (realpart number))
122 (cis (imagpart number))))))
124 ;;; INTEXP -- Handle the rational base, integer power case.
126 (declaim (type (or integer null) *intexp-maximum-exponent*))
127 (defparameter *intexp-maximum-exponent* nil)
129 ;;; This function precisely calculates base raised to an integral
130 ;;; power. It separates the cases by the sign of power, for efficiency
131 ;;; reasons, as powers can be calculated more efficiently if power is
132 ;;; a positive integer. Values of power are calculated as positive
133 ;;; integers, and inverted if negative.
134 (defun intexp (base power)
135 (when (and *intexp-maximum-exponent*
136 (> (abs power) *intexp-maximum-exponent*))
137 (error "The absolute value of ~S exceeds ~S."
138 power '*intexp-maximum-exponent*))
139 (cond ((minusp power)
140 (/ (intexp base (- power))))
144 (do ((nextn (ash power -1) (ash power -1))
145 (total (if (oddp power) base 1)
146 (if (oddp power) (* base total) total)))
147 ((zerop nextn) total)
148 (setq base (* base base))
149 (setq power nextn)))))
151 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
152 ;;; floating point stuff. If both args are real, we try %POW right
153 ;;; off, assuming it will return 0 if the result may be complex. If
154 ;;; so, we call COMPLEX-POW which directly computes the complex
155 ;;; result. We also separate the complex-real and real-complex cases
156 ;;; from the general complex case.
157 (defun expt (base power)
159 "Return BASE raised to the POWER."
161 (let ((result (1+ (* base power))))
162 (if (and (floatp result) (float-nan-p result))
165 (labels (;; determine if the double float is an integer.
166 ;; 0 - not an integer
170 (declare (type (unsigned-byte 31) ihi)
171 (type (unsigned-byte 32) lo)
172 (optimize (speed 3) (safety 0)))
174 (declare (type fixnum isint))
175 (cond ((>= ihi #x43400000) ; exponent >= 53
178 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
179 (declare (type (mod 53) k))
181 (let* ((shift (- 52 k))
182 (j (logand (ash lo (- shift))))
184 (declare (type (mod 32) shift)
185 (type (unsigned-byte 32) j j2))
187 (setq isint (- 2 (logand j 1))))))
189 (let* ((shift (- 20 k))
190 (j (ash ihi (- shift)))
192 (declare (type (mod 32) shift)
193 (type (unsigned-byte 31) j j2))
195 (setq isint (- 2 (logand j 1))))))))))
197 (real-expt (x y rtype)
198 (let ((x (coerce x 'double-float))
199 (y (coerce y 'double-float)))
200 (declare (double-float x y))
201 (let* ((x-hi (sb!kernel:double-float-high-bits x))
202 (x-lo (sb!kernel:double-float-low-bits x))
203 (x-ihi (logand x-hi #x7fffffff))
204 (y-hi (sb!kernel:double-float-high-bits y))
205 (y-lo (sb!kernel:double-float-low-bits y))
206 (y-ihi (logand y-hi #x7fffffff)))
207 (declare (type (signed-byte 32) x-hi y-hi)
208 (type (unsigned-byte 31) x-ihi y-ihi)
209 (type (unsigned-byte 32) x-lo y-lo))
211 (when (zerop (logior y-ihi y-lo))
212 (return-from real-expt (coerce 1d0 rtype)))
214 ;; FIXME: Hardcoded qNaN/sNaN values are not portable.
215 (when (or (> x-ihi #x7ff00000)
216 (and (= x-ihi #x7ff00000) (/= x-lo 0))
218 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
219 (return-from real-expt (coerce (+ x y) rtype)))
220 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
221 (declare (type fixnum yisint))
222 ;; special value of y
223 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
225 (return-from real-expt
226 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
228 (coerce (- y y) rtype))
229 ((>= x-ihi #x3ff00000)
230 ;; (|x|>1)**+-inf = inf,0
235 ;; (|x|<1)**-,+inf = inf,0
238 (coerce 0 rtype))))))
240 (let ((abs-x (abs x)))
241 (declare (double-float abs-x))
242 ;; special value of x
243 (when (and (zerop x-lo)
244 (or (= x-ihi #x7ff00000) (zerop x-ihi)
245 (= x-ihi #x3ff00000)))
246 ;; x is +-0,+-inf,+-1
247 (let ((z (if (< y-hi 0)
248 (/ 1 abs-x) ; z = (1/|x|)
250 (declare (double-float z))
252 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
254 (let ((y*pi (* y pi)))
255 (declare (double-float y*pi))
256 (return-from real-expt
258 (coerce (%cos y*pi) rtype)
259 (coerce (%sin y*pi) rtype)))))
261 ;; (x<0)**odd = -(|x|**odd)
263 (return-from real-expt (coerce z rtype))))
267 (coerce (sb!kernel::%pow x y) rtype)
269 (let ((pow (sb!kernel::%pow abs-x y)))
270 (declare (double-float pow))
273 (coerce (* -1d0 pow) rtype))
277 (let ((y*pi (* y pi)))
278 (declare (double-float y*pi))
280 (coerce (* pow (%cos y*pi))
282 (coerce (* pow (%sin y*pi))
284 (declare (inline real-expt))
285 (number-dispatch ((base number) (power number))
286 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
288 (((foreach single-float double-float) rational)
289 (real-expt base power '(dispatch-type base)))
290 (((foreach fixnum (or bignum ratio) single-float)
291 (foreach ratio single-float))
292 (real-expt base power 'single-float))
293 (((foreach fixnum (or bignum ratio) single-float double-float)
295 (real-expt base power 'double-float))
296 ((double-float single-float)
297 (real-expt base power 'double-float))
298 (((foreach (complex rational) (complex float)) rational)
299 (* (expt (abs base) power)
300 (cis (* power (phase base)))))
301 (((foreach fixnum (or bignum ratio) single-float double-float)
303 (if (and (zerop base) (plusp (realpart power)))
305 (exp (* power (log base)))))
306 (((foreach (complex float) (complex rational))
307 (foreach complex double-float single-float))
308 (if (and (zerop base) (plusp (realpart power)))
310 (exp (* power (log base)))))))))
312 ;;; FIXME: Maybe rename this so that it's clearer that it only works
315 (declare (type integer x))
318 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
319 ;; log2(f). So we grab the top few bits of x and scale that
320 ;; appropriately, take the log of it and add it to n.
322 ;; Motivated by an attempt to get LOG to work better on bignums.
323 (let ((n (integer-length x)))
324 (if (< n sb!vm:double-float-digits)
325 (log (coerce x 'double-float) 2.0d0)
326 (let ((f (ldb (byte sb!vm:double-float-digits
327 (- n sb!vm:double-float-digits))
329 (+ n (log (scale-float (coerce f 'double-float)
330 (- sb!vm:double-float-digits))
333 (defun log (number &optional (base nil base-p))
335 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
339 (if (or (typep number 'double-float) (typep base 'double-float))
342 ((and (typep number '(integer (0) *))
343 (typep base '(integer (0) *)))
344 (coerce (/ (log2 number) (log2 base)) 'single-float))
345 ((and (typep number 'integer) (typep base 'double-float))
346 ;; No single float intermediate result
347 (/ (log2 number) (log base 2.0d0)))
348 ((and (typep number 'double-float) (typep base 'integer))
349 (/ (log number 2.0d0) (log2 base)))
351 (/ (log number) (log base))))
352 (number-dispatch ((number number))
353 (((foreach fixnum bignum))
355 (complex (log (- number)) (coerce pi 'single-float))
356 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
359 (complex (log (- number)) (coerce pi 'single-float))
360 (let ((numerator (numerator number))
361 (denominator (denominator number)))
362 (if (= (integer-length numerator)
363 (integer-length denominator))
364 (coerce (%log1p (coerce (- number 1) 'double-float))
366 (coerce (/ (- (log2 numerator) (log2 denominator))
367 (log (exp 1.0d0) 2.0d0))
369 (((foreach single-float double-float))
370 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
371 ;; Since this doesn't seem to be an implementation issue
372 ;; I (pw) take the Kahan result.
373 (if (< (float-sign number)
374 (coerce 0 '(dispatch-type number)))
375 (complex (log (- number)) (coerce pi '(dispatch-type number)))
376 (coerce (%log (coerce number 'double-float))
377 '(dispatch-type number))))
379 (complex-log number)))))
383 "Return the square root of NUMBER."
384 (number-dispatch ((number number))
385 (((foreach fixnum bignum ratio))
387 (complex-sqrt number)
388 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
389 (((foreach single-float double-float))
391 (complex-sqrt (complex number))
392 (coerce (%sqrt (coerce number 'double-float))
393 '(dispatch-type number))))
395 (complex-sqrt number))))
397 ;;;; trigonometic and related functions
401 "Return the absolute value of the number."
402 (number-dispatch ((number number))
403 (((foreach single-float double-float fixnum rational))
406 (let ((rx (realpart number))
407 (ix (imagpart number)))
410 (sqrt (+ (* rx rx) (* ix ix))))
412 (coerce (%hypot (coerce rx 'double-float)
413 (coerce ix 'double-float))
418 (defun phase (number)
420 "Return the angle part of the polar representation of a complex number.
421 For complex numbers, this is (atan (imagpart number) (realpart number)).
422 For non-complex positive numbers, this is 0. For non-complex negative
427 (coerce pi 'single-float)
430 (if (minusp (float-sign number))
431 (coerce pi 'single-float)
434 (if (minusp (float-sign number))
435 (coerce pi 'double-float)
438 (atan (imagpart number) (realpart number)))))
442 "Return the sine of NUMBER."
443 (number-dispatch ((number number))
444 (handle-reals %sin number)
446 (let ((x (realpart number))
447 (y (imagpart number)))
448 (complex (* (sin x) (cosh y))
449 (* (cos x) (sinh y)))))))
453 "Return the cosine of NUMBER."
454 (number-dispatch ((number number))
455 (handle-reals %cos number)
457 (let ((x (realpart number))
458 (y (imagpart number)))
459 (complex (* (cos x) (cosh y))
460 (- (* (sin x) (sinh y))))))))
464 "Return the tangent of NUMBER."
465 (number-dispatch ((number number))
466 (handle-reals %tan number)
468 (complex-tan number))))
472 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
473 (declare (type real theta))
474 (complex (cos theta) (sin theta)))
478 "Return the arc sine of NUMBER."
479 (number-dispatch ((number number))
481 (if (or (> number 1) (< number -1))
482 (complex-asin number)
483 (coerce (%asin (coerce number 'double-float)) 'single-float)))
484 (((foreach single-float double-float))
485 (if (or (> number (coerce 1 '(dispatch-type number)))
486 (< number (coerce -1 '(dispatch-type number))))
487 (complex-asin (complex number))
488 (coerce (%asin (coerce number 'double-float))
489 '(dispatch-type number))))
491 (complex-asin number))))
495 "Return the arc cosine of NUMBER."
496 (number-dispatch ((number number))
498 (if (or (> number 1) (< number -1))
499 (complex-acos number)
500 (coerce (%acos (coerce number 'double-float)) 'single-float)))
501 (((foreach single-float double-float))
502 (if (or (> number (coerce 1 '(dispatch-type number)))
503 (< number (coerce -1 '(dispatch-type number))))
504 (complex-acos (complex number))
505 (coerce (%acos (coerce number 'double-float))
506 '(dispatch-type number))))
508 (complex-acos number))))
510 (defun atan (y &optional (x nil xp))
512 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
515 (declare (type double-float y x)
516 (values double-float))
519 (if (plusp (float-sign x))
522 (float-sign y (/ pi 2)))
524 (number-dispatch ((y real) (x real))
526 (foreach double-float single-float fixnum bignum ratio))
527 (atan2 y (coerce x 'double-float)))
528 (((foreach single-float fixnum bignum ratio)
530 (atan2 (coerce y 'double-float) x))
531 (((foreach single-float fixnum bignum ratio)
532 (foreach single-float fixnum bignum ratio))
533 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
535 (number-dispatch ((y number))
536 (handle-reals %atan y)
540 ;;; It seems that every target system has a C version of sinh, cosh,
541 ;;; and tanh. Let's use these for reals because the original
542 ;;; implementations based on the definitions lose big in round-off
543 ;;; error. These bad definitions also mean that sin and cos for
544 ;;; complex numbers can also lose big.
548 "Return the hyperbolic sine of NUMBER."
549 (number-dispatch ((number number))
550 (handle-reals %sinh number)
552 (let ((x (realpart number))
553 (y (imagpart number)))
554 (complex (* (sinh x) (cos y))
555 (* (cosh x) (sin y)))))))
559 "Return the hyperbolic cosine of NUMBER."
560 (number-dispatch ((number number))
561 (handle-reals %cosh number)
563 (let ((x (realpart number))
564 (y (imagpart number)))
565 (complex (* (cosh x) (cos y))
566 (* (sinh x) (sin y)))))))
570 "Return the hyperbolic tangent of NUMBER."
571 (number-dispatch ((number number))
572 (handle-reals %tanh number)
574 (complex-tanh number))))
576 (defun asinh (number)
578 "Return the hyperbolic arc sine of NUMBER."
579 (number-dispatch ((number number))
580 (handle-reals %asinh number)
582 (complex-asinh number))))
584 (defun acosh (number)
586 "Return the hyperbolic arc cosine of NUMBER."
587 (number-dispatch ((number number))
589 ;; acosh is complex if number < 1
591 (complex-acosh number)
592 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
593 (((foreach single-float double-float))
594 (if (< number (coerce 1 '(dispatch-type number)))
595 (complex-acosh (complex number))
596 (coerce (%acosh (coerce number 'double-float))
597 '(dispatch-type number))))
599 (complex-acosh number))))
601 (defun atanh (number)
603 "Return the hyperbolic arc tangent of NUMBER."
604 (number-dispatch ((number number))
606 ;; atanh is complex if |number| > 1
607 (if (or (> number 1) (< number -1))
608 (complex-atanh number)
609 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
610 (((foreach single-float double-float))
611 (if (or (> number (coerce 1 '(dispatch-type number)))
612 (< number (coerce -1 '(dispatch-type number))))
613 (complex-atanh (complex number))
614 (coerce (%atanh (coerce number 'double-float))
615 '(dispatch-type number))))
617 (complex-atanh number))))
619 ;;; HP-UX does not supply a C version of log1p, so use the definition.
621 ;;; FIXME: This is really not a good definition. As per Raymond Toy
622 ;;; working on CMU CL, "The definition really loses big-time in
623 ;;; roundoff as x gets small."
625 #!-sb-fluid (declaim (inline %log1p))
627 (defun %log1p (number)
628 (declare (double-float number)
629 (optimize (speed 3) (safety 0)))
630 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
632 ;;;; not-OLD-SPECFUN stuff
634 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
635 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
636 ;;;; the standard special function system.)
638 ;;;; This is a set of routines that implement many elementary
639 ;;;; transcendental functions as specified by ANSI Common Lisp. The
640 ;;;; implementation is based on Kahan's paper.
642 ;;;; I believe I have accurately implemented the routines and are
643 ;;;; correct, but you may want to check for your self.
645 ;;;; These functions are written for CMU Lisp and take advantage of
646 ;;;; some of the features available there. It may be possible,
647 ;;;; however, to port this to other Lisps.
649 ;;;; Some functions are significantly more accurate than the original
650 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
651 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
652 ;;;; answer is pi + i*log(2-sqrt(3)).
654 ;;;; All of the implemented functions will take any number for an
655 ;;;; input, but the result will always be a either a complex
656 ;;;; single-float or a complex double-float.
658 ;;;; general functions:
670 ;;;; utility functions:
673 ;;;; internal functions:
674 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
677 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
678 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
679 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
682 ;;;; The original CMU CL code requested:
683 ;;;; Please send any bug reports, comments, or improvements to
684 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
686 ;;; FIXME: In SBCL, the floating point infinity constants like
687 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
688 ;;; constants at cross-compile time, because the cross-compilation
689 ;;; host might not have support for floating point infinities. Thus,
690 ;;; they're effectively implemented as special variable references,
691 ;;; and the code below which uses them might be unnecessarily
692 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
693 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
694 ;;; special variable references with (probably equally slow)
697 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
698 ;;; differ in their interpretations of the real line, IMAGPART was
699 ;;; patch, which without a certain amount of effort would have altered
700 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
701 ;;; were patched to use explicit COMPLEX, rather than implicitly
702 ;;; passing in real numbers for treatment with IMAGPART, and these
703 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
704 ;;; however, someone needs to go back to Kahan for the definitive
705 ;;; answer for treatment of negative real floating point numbers and
706 ;;; branch cuts. If adjustment is needed, it is probably the removal
707 ;;; of explicit calls to COMPLEX in the clients of irrational
708 ;;; functions. -- a slightly bitter CSR, 2004-05-16
710 (declaim (inline square))
712 (declare (double-float x))
715 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
717 ;;; If you have these functions in libm, perhaps they should be used
718 ;;; instead of these Lisp versions. These versions are probably good
719 ;;; enough, especially since they are portable.
721 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
722 ;;; the underlying floating-point format.)
723 (declaim (inline scalb))
725 (declare (type double-float x)
726 (type double-float-exponent n))
729 ;;; This is like LOGB, but X is not infinity and non-zero and not a
730 ;;; NaN, so we can always return an integer.
731 (declaim (inline logb-finite))
732 (defun logb-finite (x)
733 (declare (type double-float x))
734 (multiple-value-bind (signif exponent sign)
736 (declare (ignore signif sign))
737 ;; DECODE-FLOAT is almost right, except that the exponent is off
741 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
742 ;;; For the special cases, the following values are used:
745 ;;; +/- infinity +infinity
748 (declare (type double-float x))
749 (cond ((float-nan-p x)
751 ((float-infinity-p x)
752 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
753 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
755 ;; The answer is negative infinity, but we are supposed to
756 ;; signal divide-by-zero, so do the actual division
762 ;;; This function is used to create a complex number of the
763 ;;; appropriate type:
764 ;;; Create complex number with real part X and imaginary part Y
765 ;;; such that has the same type as Z. If Z has type (complex
766 ;;; rational), the X and Y are coerced to single-float.
767 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
768 (error "needs work for long float support"))
769 (declaim (inline coerce-to-complex-type))
770 (defun coerce-to-complex-type (x y z)
771 (declare (double-float x y)
773 (if (typep (realpart z) 'double-float)
775 ;; Convert anything that's not already a DOUBLE-FLOAT (because
776 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
777 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
778 (complex (float x 1f0)
781 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
782 ;;; result is r + i*k, where k is an integer.
783 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
784 (error "needs work for long float support"))
786 (let ((x (float (realpart z) 1d0))
787 (y (float (imagpart z) 1d0)))
788 ;; Would this be better handled using an exception handler to
789 ;; catch the overflow or underflow signal? For now, we turn all
790 ;; traps off and look at the accrued exceptions to see if any
791 ;; signal would have been raised.
792 (with-float-traps-masked (:underflow :overflow)
793 (let ((rho (+ (square x) (square y))))
794 (declare (optimize (speed 3) (space 0)))
795 (cond ((and (or (float-nan-p rho)
796 (float-infinity-p rho))
797 (or (float-infinity-p (abs x))
798 (float-infinity-p (abs y))))
799 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
801 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
803 ((let ((threshold #.(/ least-positive-double-float
804 double-float-epsilon))
805 (traps (ldb sb!vm::float-sticky-bits
806 (sb!vm:floating-point-modes))))
807 ;; Overflow raised or (underflow raised and rho <
809 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
810 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
813 ;; If we're here, neither x nor y are infinity and at
814 ;; least one is non-zero.. Thus logb returns a nice
816 (let ((k (- (logb-finite (max (abs x) (abs y))))))
817 (values (+ (square (scalb x k))
818 (square (scalb y k)))
823 ;;; principal square root of Z
825 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
826 (defun complex-sqrt (z)
827 ;; KLUDGE: Here and below, we can't just declare Z to be of type
828 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
829 ;; Since there isn't a rational negative zero, this is OK from the
830 ;; point of view of getting the right answer in the face of branch
831 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
832 ;; still ugly. -- CSR, 2004-05-16
833 (declare (type (or complex rational) z))
834 (multiple-value-bind (rho k)
836 (declare (type (or (member 0d0) (double-float 0d0)) rho)
838 (let ((x (float (realpart z) 1.0d0))
839 (y (float (imagpart z) 1.0d0))
842 (declare (double-float x y eta nu))
845 ;; space 0 to get maybe-inline functions inlined.
846 (declare (optimize (speed 3) (space 0)))
848 (if (not (float-nan-p x))
849 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
854 (setf k (1- (ash k -1)))
855 (setf rho (+ rho rho))))
857 (setf rho (scalb (sqrt rho) k))
863 (when (not (float-infinity-p (abs nu)))
864 (setf nu (/ (/ nu rho) 2d0)))
867 (setf nu (float-sign y rho))))
868 (coerce-to-complex-type eta nu z)))))
870 ;;; Compute log(2^j*z).
872 ;;; This is for use with J /= 0 only when |z| is huge.
873 (defun complex-log-scaled (z j)
874 (declare (type (or rational complex) z)
876 ;; The constants t0, t1, t2 should be evaluated to machine
877 ;; precision. In addition, Kahan says the accuracy of log1p
878 ;; influences the choices of these constants but doesn't say how to
879 ;; choose them. We'll just assume his choices matches our
880 ;; implementation of log1p.
881 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
885 (x (float (realpart z) 1.0d0))
886 (y (float (imagpart z) 1.0d0)))
887 (multiple-value-bind (rho k)
889 (declare (optimize (speed 3)))
890 (let ((beta (max (abs x) (abs y)))
891 (theta (min (abs x) (abs y))))
892 (coerce-to-complex-type (if (and (zerop k)
896 (/ (%log1p (+ (* (- beta 1.0d0)
905 ;;; log of Z = log |Z| + i * arg Z
907 ;;; Z may be any number, but the result is always a complex.
908 (defun complex-log (z)
909 (declare (type (or rational complex) z))
910 (complex-log-scaled z 0))
912 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
913 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
914 ;;; The reason for the imaginary part is caused by the fact that arg
915 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
916 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
917 (defun complex-atanh (z)
918 (declare (type (or rational complex) z))
920 (theta (/ (sqrt most-positive-double-float) 4.0d0))
921 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
922 (half-pi (/ pi 2.0d0))
923 (rp (float (realpart z) 1.0d0))
924 (beta (float-sign rp 1.0d0))
926 (y (* beta (- (float (imagpart z) 1.0d0))))
929 ;; Shouldn't need this declare.
930 (declare (double-float x y))
932 (declare (optimize (speed 3)))
933 (cond ((or (> x theta)
935 ;; To avoid overflow...
936 (setf nu (float-sign y half-pi))
937 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
938 ;; which can cause overflow. Arrange this computation so
939 ;; that it won't overflow.
940 (setf eta (let* ((x-bigger (> x (abs y)))
941 (r (if x-bigger (/ y x) (/ x y)))
942 (d (+ 1.0d0 (* r r))))
947 ;; Should this be changed so that if y is zero, eta is set
948 ;; to +infinity instead of approx 176? In any case
949 ;; tanh(176) is 1.0d0 within working precision.
950 (let ((t1 (+ 4d0 (square y)))
951 (t2 (+ (abs y) rho)))
952 (setf eta (log (/ (sqrt (sqrt t1))
956 (+ half-pi (atan (* 0.5d0 t2))))))))
958 (let ((t1 (+ (abs y) rho)))
959 ;; Normal case using log1p(x) = log(1 + x)
961 (%log1p (/ (* 4.0d0 x)
962 (+ (square (- 1.0d0 x))
969 (coerce-to-complex-type (* beta eta)
973 ;;; Compute tanh z = sinh z / cosh z.
974 (defun complex-tanh (z)
975 (declare (type (or rational complex) z))
976 (let ((x (float (realpart z) 1.0d0))
977 (y (float (imagpart z) 1.0d0)))
979 ;; space 0 to get maybe-inline functions inlined
980 (declare (optimize (speed 3) (space 0)))
982 ;; FIXME: this form is hideously broken wrt
983 ;; cross-compilation portability. Much else in this
984 ;; file is too, of course, sometimes hidden by
985 ;; constant-folding, but this one in particular clearly
986 ;; depends on host and target
987 ;; MOST-POSITIVE-DOUBLE-FLOATs being equal. -- CSR,
990 (log most-positive-double-float))
992 (coerce-to-complex-type (float-sign x)
996 (beta (+ 1.0d0 (* tv tv)))
998 (rho (sqrt (+ 1.0d0 (* s s)))))
999 (if (float-infinity-p (abs tv))
1000 (coerce-to-complex-type (/ rho s)
1003 (let ((den (+ 1.0d0 (* beta s s))))
1004 (coerce-to-complex-type (/ (* beta rho s)
1009 ;;; Compute acos z = pi/2 - asin z.
1011 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1012 (defun complex-acos (z)
1013 ;; Kahan says we should only compute the parts needed. Thus, the
1014 ;; REALPART's below should only compute the real part, not the whole
1015 ;; complex expression. Doing this can be important because we may get
1016 ;; spurious signals that occur in the part that we are not using.
1018 ;; However, we take a pragmatic approach and just use the whole
1021 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1022 ;; it's the conjugate of the square root or the square root of the
1023 ;; conjugate. This needs to be checked.
1025 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1026 ;; same as (sqrt (conjugate z)) for all z. This follows because
1028 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1030 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1032 ;; and these two expressions are equal if and only if arg conj z =
1033 ;; -arg z, which is clearly true for all z.
1034 (declare (type (or rational complex) z))
1035 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
1036 (sqrt-1-z (complex-sqrt (- 1 z))))
1037 (with-float-traps-masked (:divide-by-zero)
1038 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1039 (realpart sqrt-1+z))))
1040 (asinh (imagpart (* (conjugate sqrt-1+z)
1043 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1045 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1046 (defun complex-acosh (z)
1047 (declare (type (or rational complex) z))
1048 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1049 (sqrt-z+1 (complex-sqrt (+ z 1))))
1050 (with-float-traps-masked (:divide-by-zero)
1051 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1053 (* 2 (atan (/ (imagpart sqrt-z-1)
1054 (realpart sqrt-z+1))))))))
1056 ;;; Compute asin z = asinh(i*z)/i.
1058 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1059 (defun complex-asin (z)
1060 (declare (type (or rational complex) z))
1061 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1062 (sqrt-1+z (complex-sqrt (+ 1 z))))
1063 (with-float-traps-masked (:divide-by-zero)
1064 (complex (atan (/ (realpart z)
1065 (realpart (* sqrt-1-z sqrt-1+z))))
1066 (asinh (imagpart (* (conjugate sqrt-1-z)
1069 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1071 ;;; Z may be any number, but the result is always a complex.
1072 (defun complex-asinh (z)
1073 (declare (type (or rational complex) z))
1074 ;; asinh z = -i * asin (i*z)
1075 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1076 (result (complex-asin iz)))
1077 (complex (imagpart result)
1078 (- (realpart result)))))
1080 ;;; Compute atan z = atanh (i*z) / i.
1082 ;;; Z may be any number, but the result is always a complex.
1083 (defun complex-atan (z)
1084 (declare (type (or rational complex) z))
1085 ;; atan z = -i * atanh (i*z)
1086 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1087 (result (complex-atanh iz)))
1088 (complex (imagpart result)
1089 (- (realpart result)))))
1091 ;;; Compute tan z = -i * tanh(i * z)
1093 ;;; Z may be any number, but the result is always a complex.
1094 (defun complex-tan (z)
1095 (declare (type (or rational complex) z))
1096 ;; tan z = -i * tanh(i*z)
1097 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1098 (result (complex-tanh iz)))
1099 (complex (imagpart result)
1100 (- (realpart result)))))