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."
338 ((zerop base) 0f0) ; FIXME: type
339 ((and (typep number '(integer (0) *))
340 (typep base '(integer (0) *)))
341 (coerce (/ (log2 number) (log2 base)) 'single-float))
342 (t (/ (log number) (log base))))
343 (number-dispatch ((number number))
344 (((foreach fixnum bignum))
346 (complex (log (- number)) (coerce pi 'single-float))
347 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
350 (complex (log (- number)) (coerce pi 'single-float))
351 (let ((numerator (numerator number))
352 (denominator (denominator number)))
353 (if (= (integer-length numerator)
354 (integer-length denominator))
355 (coerce (%log1p (coerce (- number 1) 'double-float))
357 (coerce (/ (- (log2 numerator) (log2 denominator))
358 (log (exp 1.0d0) 2.0d0))
360 (((foreach single-float double-float))
361 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
362 ;; Since this doesn't seem to be an implementation issue
363 ;; I (pw) take the Kahan result.
364 (if (< (float-sign number)
365 (coerce 0 '(dispatch-type number)))
366 (complex (log (- number)) (coerce pi '(dispatch-type number)))
367 (coerce (%log (coerce number 'double-float))
368 '(dispatch-type number))))
370 (complex-log number)))))
374 "Return the square root of NUMBER."
375 (number-dispatch ((number number))
376 (((foreach fixnum bignum ratio))
378 (complex-sqrt number)
379 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
380 (((foreach single-float double-float))
382 (complex-sqrt (complex number))
383 (coerce (%sqrt (coerce number 'double-float))
384 '(dispatch-type number))))
386 (complex-sqrt number))))
388 ;;;; trigonometic and related functions
392 "Return the absolute value of the number."
393 (number-dispatch ((number number))
394 (((foreach single-float double-float fixnum rational))
397 (let ((rx (realpart number))
398 (ix (imagpart number)))
401 (sqrt (+ (* rx rx) (* ix ix))))
403 (coerce (%hypot (coerce rx 'double-float)
404 (coerce ix 'double-float))
409 (defun phase (number)
411 "Return the angle part of the polar representation of a complex number.
412 For complex numbers, this is (atan (imagpart number) (realpart number)).
413 For non-complex positive numbers, this is 0. For non-complex negative
418 (coerce pi 'single-float)
421 (if (minusp (float-sign number))
422 (coerce pi 'single-float)
425 (if (minusp (float-sign number))
426 (coerce pi 'double-float)
429 (atan (imagpart number) (realpart number)))))
433 "Return the sine of NUMBER."
434 (number-dispatch ((number number))
435 (handle-reals %sin number)
437 (let ((x (realpart number))
438 (y (imagpart number)))
439 (complex (* (sin x) (cosh y))
440 (* (cos x) (sinh y)))))))
444 "Return the cosine of NUMBER."
445 (number-dispatch ((number number))
446 (handle-reals %cos number)
448 (let ((x (realpart number))
449 (y (imagpart number)))
450 (complex (* (cos x) (cosh y))
451 (- (* (sin x) (sinh y))))))))
455 "Return the tangent of NUMBER."
456 (number-dispatch ((number number))
457 (handle-reals %tan number)
459 (complex-tan number))))
463 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
464 (declare (type real theta))
465 (complex (cos theta) (sin theta)))
469 "Return the arc sine of NUMBER."
470 (number-dispatch ((number number))
472 (if (or (> number 1) (< number -1))
473 (complex-asin number)
474 (coerce (%asin (coerce number 'double-float)) 'single-float)))
475 (((foreach single-float double-float))
476 (if (or (> number (coerce 1 '(dispatch-type number)))
477 (< number (coerce -1 '(dispatch-type number))))
478 (complex-asin (complex number))
479 (coerce (%asin (coerce number 'double-float))
480 '(dispatch-type number))))
482 (complex-asin number))))
486 "Return the arc cosine of NUMBER."
487 (number-dispatch ((number number))
489 (if (or (> number 1) (< number -1))
490 (complex-acos number)
491 (coerce (%acos (coerce number 'double-float)) 'single-float)))
492 (((foreach single-float double-float))
493 (if (or (> number (coerce 1 '(dispatch-type number)))
494 (< number (coerce -1 '(dispatch-type number))))
495 (complex-acos (complex number))
496 (coerce (%acos (coerce number 'double-float))
497 '(dispatch-type number))))
499 (complex-acos number))))
501 (defun atan (y &optional (x nil xp))
503 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
506 (declare (type double-float y x)
507 (values double-float))
510 (if (plusp (float-sign x))
513 (float-sign y (/ pi 2)))
515 (number-dispatch ((y real) (x real))
517 (foreach double-float single-float fixnum bignum ratio))
518 (atan2 y (coerce x 'double-float)))
519 (((foreach single-float fixnum bignum ratio)
521 (atan2 (coerce y 'double-float) x))
522 (((foreach single-float fixnum bignum ratio)
523 (foreach single-float fixnum bignum ratio))
524 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
526 (number-dispatch ((y number))
527 (handle-reals %atan y)
531 ;;; It seems that every target system has a C version of sinh, cosh,
532 ;;; and tanh. Let's use these for reals because the original
533 ;;; implementations based on the definitions lose big in round-off
534 ;;; error. These bad definitions also mean that sin and cos for
535 ;;; complex numbers can also lose big.
539 "Return the hyperbolic sine of NUMBER."
540 (number-dispatch ((number number))
541 (handle-reals %sinh number)
543 (let ((x (realpart number))
544 (y (imagpart number)))
545 (complex (* (sinh x) (cos y))
546 (* (cosh x) (sin y)))))))
550 "Return the hyperbolic cosine of NUMBER."
551 (number-dispatch ((number number))
552 (handle-reals %cosh number)
554 (let ((x (realpart number))
555 (y (imagpart number)))
556 (complex (* (cosh x) (cos y))
557 (* (sinh x) (sin y)))))))
561 "Return the hyperbolic tangent of NUMBER."
562 (number-dispatch ((number number))
563 (handle-reals %tanh number)
565 (complex-tanh number))))
567 (defun asinh (number)
569 "Return the hyperbolic arc sine of NUMBER."
570 (number-dispatch ((number number))
571 (handle-reals %asinh number)
573 (complex-asinh number))))
575 (defun acosh (number)
577 "Return the hyperbolic arc cosine of NUMBER."
578 (number-dispatch ((number number))
580 ;; acosh is complex if number < 1
582 (complex-acosh number)
583 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
584 (((foreach single-float double-float))
585 (if (< number (coerce 1 '(dispatch-type number)))
586 (complex-acosh (complex number))
587 (coerce (%acosh (coerce number 'double-float))
588 '(dispatch-type number))))
590 (complex-acosh number))))
592 (defun atanh (number)
594 "Return the hyperbolic arc tangent of NUMBER."
595 (number-dispatch ((number number))
597 ;; atanh is complex if |number| > 1
598 (if (or (> number 1) (< number -1))
599 (complex-atanh number)
600 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
601 (((foreach single-float double-float))
602 (if (or (> number (coerce 1 '(dispatch-type number)))
603 (< number (coerce -1 '(dispatch-type number))))
604 (complex-atanh (complex number))
605 (coerce (%atanh (coerce number 'double-float))
606 '(dispatch-type number))))
608 (complex-atanh number))))
610 ;;; HP-UX does not supply a C version of log1p, so use the definition.
612 ;;; FIXME: This is really not a good definition. As per Raymond Toy
613 ;;; working on CMU CL, "The definition really loses big-time in
614 ;;; roundoff as x gets small."
616 #!-sb-fluid (declaim (inline %log1p))
618 (defun %log1p (number)
619 (declare (double-float number)
620 (optimize (speed 3) (safety 0)))
621 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
623 ;;;; not-OLD-SPECFUN stuff
625 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
626 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
627 ;;;; the standard special function system.)
629 ;;;; This is a set of routines that implement many elementary
630 ;;;; transcendental functions as specified by ANSI Common Lisp. The
631 ;;;; implementation is based on Kahan's paper.
633 ;;;; I believe I have accurately implemented the routines and are
634 ;;;; correct, but you may want to check for your self.
636 ;;;; These functions are written for CMU Lisp and take advantage of
637 ;;;; some of the features available there. It may be possible,
638 ;;;; however, to port this to other Lisps.
640 ;;;; Some functions are significantly more accurate than the original
641 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
642 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
643 ;;;; answer is pi + i*log(2-sqrt(3)).
645 ;;;; All of the implemented functions will take any number for an
646 ;;;; input, but the result will always be a either a complex
647 ;;;; single-float or a complex double-float.
649 ;;;; general functions:
661 ;;;; utility functions:
664 ;;;; internal functions:
665 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
668 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
669 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
670 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
673 ;;;; The original CMU CL code requested:
674 ;;;; Please send any bug reports, comments, or improvements to
675 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
677 ;;; FIXME: In SBCL, the floating point infinity constants like
678 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
679 ;;; constants at cross-compile time, because the cross-compilation
680 ;;; host might not have support for floating point infinities. Thus,
681 ;;; they're effectively implemented as special variable references,
682 ;;; and the code below which uses them might be unnecessarily
683 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
684 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
685 ;;; special variable references with (probably equally slow)
688 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
689 ;;; differ in their interpretations of the real line, IMAGPART was
690 ;;; patch, which without a certain amount of effort would have altered
691 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
692 ;;; were patched to use explicit COMPLEX, rather than implicitly
693 ;;; passing in real numbers for treatment with IMAGPART, and these
694 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
695 ;;; however, someone needs to go back to Kahan for the definitive
696 ;;; answer for treatment of negative real floating point numbers and
697 ;;; branch cuts. If adjustment is needed, it is probably the removal
698 ;;; of explicit calls to COMPLEX in the clients of irrational
699 ;;; functions. -- a slightly bitter CSR, 2004-05-16
701 (declaim (inline square))
703 (declare (double-float x))
706 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
708 ;;; If you have these functions in libm, perhaps they should be used
709 ;;; instead of these Lisp versions. These versions are probably good
710 ;;; enough, especially since they are portable.
712 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
713 ;;; the underlying floating-point format.)
714 (declaim (inline scalb))
716 (declare (type double-float x)
717 (type double-float-exponent n))
720 ;;; This is like LOGB, but X is not infinity and non-zero and not a
721 ;;; NaN, so we can always return an integer.
722 (declaim (inline logb-finite))
723 (defun logb-finite (x)
724 (declare (type double-float x))
725 (multiple-value-bind (signif exponent sign)
727 (declare (ignore signif sign))
728 ;; DECODE-FLOAT is almost right, except that the exponent is off
732 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
733 ;;; For the special cases, the following values are used:
736 ;;; +/- infinity +infinity
739 (declare (type double-float x))
740 (cond ((float-nan-p x)
742 ((float-infinity-p x)
743 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
744 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
746 ;; The answer is negative infinity, but we are supposed to
747 ;; signal divide-by-zero, so do the actual division
753 ;;; This function is used to create a complex number of the
754 ;;; appropriate type:
755 ;;; Create complex number with real part X and imaginary part Y
756 ;;; such that has the same type as Z. If Z has type (complex
757 ;;; rational), the X and Y are coerced to single-float.
758 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
759 (error "needs work for long float support"))
760 (declaim (inline coerce-to-complex-type))
761 (defun coerce-to-complex-type (x y z)
762 (declare (double-float x y)
764 (if (typep (realpart z) 'double-float)
766 ;; Convert anything that's not already a DOUBLE-FLOAT (because
767 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
768 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
769 (complex (float x 1f0)
772 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
773 ;;; result is r + i*k, where k is an integer.
774 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
775 (error "needs work for long float support"))
777 (let ((x (float (realpart z) 1d0))
778 (y (float (imagpart z) 1d0)))
779 ;; Would this be better handled using an exception handler to
780 ;; catch the overflow or underflow signal? For now, we turn all
781 ;; traps off and look at the accrued exceptions to see if any
782 ;; signal would have been raised.
783 (with-float-traps-masked (:underflow :overflow)
784 (let ((rho (+ (square x) (square y))))
785 (declare (optimize (speed 3) (space 0)))
786 (cond ((and (or (float-nan-p rho)
787 (float-infinity-p rho))
788 (or (float-infinity-p (abs x))
789 (float-infinity-p (abs y))))
790 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
792 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
794 ((let ((threshold #.(/ least-positive-double-float
795 double-float-epsilon))
796 (traps (ldb sb!vm::float-sticky-bits
797 (sb!vm:floating-point-modes))))
798 ;; Overflow raised or (underflow raised and rho <
800 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
801 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
804 ;; If we're here, neither x nor y are infinity and at
805 ;; least one is non-zero.. Thus logb returns a nice
807 (let ((k (- (logb-finite (max (abs x) (abs y))))))
808 (values (+ (square (scalb x k))
809 (square (scalb y k)))
814 ;;; principal square root of Z
816 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
817 (defun complex-sqrt (z)
818 ;; KLUDGE: Here and below, we can't just declare Z to be of type
819 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
820 ;; Since there isn't a rational negative zero, this is OK from the
821 ;; point of view of getting the right answer in the face of branch
822 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
823 ;; still ugly. -- CSR, 2004-05-16
824 (declare (type (or complex rational) z))
825 (multiple-value-bind (rho k)
827 (declare (type (or (member 0d0) (double-float 0d0)) rho)
829 (let ((x (float (realpart z) 1.0d0))
830 (y (float (imagpart z) 1.0d0))
833 (declare (double-float x y eta nu))
836 ;; space 0 to get maybe-inline functions inlined.
837 (declare (optimize (speed 3) (space 0)))
839 (if (not (float-nan-p x))
840 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
845 (setf k (1- (ash k -1)))
846 (setf rho (+ rho rho))))
848 (setf rho (scalb (sqrt rho) k))
854 (when (not (float-infinity-p (abs nu)))
855 (setf nu (/ (/ nu rho) 2d0)))
858 (setf nu (float-sign y rho))))
859 (coerce-to-complex-type eta nu z)))))
861 ;;; Compute log(2^j*z).
863 ;;; This is for use with J /= 0 only when |z| is huge.
864 (defun complex-log-scaled (z j)
865 (declare (type (or rational complex) z)
867 ;; The constants t0, t1, t2 should be evaluated to machine
868 ;; precision. In addition, Kahan says the accuracy of log1p
869 ;; influences the choices of these constants but doesn't say how to
870 ;; choose them. We'll just assume his choices matches our
871 ;; implementation of log1p.
872 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
876 (x (float (realpart z) 1.0d0))
877 (y (float (imagpart z) 1.0d0)))
878 (multiple-value-bind (rho k)
880 (declare (optimize (speed 3)))
881 (let ((beta (max (abs x) (abs y)))
882 (theta (min (abs x) (abs y))))
883 (coerce-to-complex-type (if (and (zerop k)
887 (/ (%log1p (+ (* (- beta 1.0d0)
896 ;;; log of Z = log |Z| + i * arg Z
898 ;;; Z may be any number, but the result is always a complex.
899 (defun complex-log (z)
900 (declare (type (or rational complex) z))
901 (complex-log-scaled z 0))
903 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
904 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
905 ;;; The reason for the imaginary part is caused by the fact that arg
906 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
907 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
908 (defun complex-atanh (z)
909 (declare (type (or rational complex) z))
911 (theta (/ (sqrt most-positive-double-float) 4.0d0))
912 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
913 (half-pi (/ pi 2.0d0))
914 (rp (float (realpart z) 1.0d0))
915 (beta (float-sign rp 1.0d0))
917 (y (* beta (- (float (imagpart z) 1.0d0))))
920 ;; Shouldn't need this declare.
921 (declare (double-float x y))
923 (declare (optimize (speed 3)))
924 (cond ((or (> x theta)
926 ;; To avoid overflow...
927 (setf nu (float-sign y half-pi))
928 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
929 ;; which can cause overflow. Arrange this computation so
930 ;; that it won't overflow.
931 (setf eta (let* ((x-bigger (> x (abs y)))
932 (r (if x-bigger (/ y x) (/ x y)))
933 (d (+ 1.0d0 (* r r))))
938 ;; Should this be changed so that if y is zero, eta is set
939 ;; to +infinity instead of approx 176? In any case
940 ;; tanh(176) is 1.0d0 within working precision.
941 (let ((t1 (+ 4d0 (square y)))
942 (t2 (+ (abs y) rho)))
943 (setf eta (log (/ (sqrt (sqrt t1))
947 (+ half-pi (atan (* 0.5d0 t2))))))))
949 (let ((t1 (+ (abs y) rho)))
950 ;; Normal case using log1p(x) = log(1 + x)
952 (%log1p (/ (* 4.0d0 x)
953 (+ (square (- 1.0d0 x))
960 (coerce-to-complex-type (* beta eta)
964 ;;; Compute tanh z = sinh z / cosh z.
965 (defun complex-tanh (z)
966 (declare (type (or rational complex) z))
967 (let ((x (float (realpart z) 1.0d0))
968 (y (float (imagpart z) 1.0d0)))
970 ;; space 0 to get maybe-inline functions inlined
971 (declare (optimize (speed 3) (space 0)))
973 ;; FIXME: this form is hideously broken wrt
974 ;; cross-compilation portability. Much else in this
975 ;; file is too, of course, sometimes hidden by
976 ;; constant-folding, but this one in particular clearly
977 ;; depends on host and target
978 ;; MOST-POSITIVE-DOUBLE-FLOATs being equal. -- CSR,
981 (log most-positive-double-float))
983 (coerce-to-complex-type (float-sign x)
987 (beta (+ 1.0d0 (* tv tv)))
989 (rho (sqrt (+ 1.0d0 (* s s)))))
990 (if (float-infinity-p (abs tv))
991 (coerce-to-complex-type (/ rho s)
994 (let ((den (+ 1.0d0 (* beta s s))))
995 (coerce-to-complex-type (/ (* beta rho s)
1000 ;;; Compute acos z = pi/2 - asin z.
1002 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1003 (defun complex-acos (z)
1004 ;; Kahan says we should only compute the parts needed. Thus, the
1005 ;; REALPART's below should only compute the real part, not the whole
1006 ;; complex expression. Doing this can be important because we may get
1007 ;; spurious signals that occur in the part that we are not using.
1009 ;; However, we take a pragmatic approach and just use the whole
1012 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1013 ;; it's the conjugate of the square root or the square root of the
1014 ;; conjugate. This needs to be checked.
1016 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1017 ;; same as (sqrt (conjugate z)) for all z. This follows because
1019 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1021 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1023 ;; and these two expressions are equal if and only if arg conj z =
1024 ;; -arg z, which is clearly true for all z.
1025 (declare (type (or rational complex) z))
1026 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
1027 (sqrt-1-z (complex-sqrt (- 1 z))))
1028 (with-float-traps-masked (:divide-by-zero)
1029 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1030 (realpart sqrt-1+z))))
1031 (asinh (imagpart (* (conjugate sqrt-1+z)
1034 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1036 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1037 (defun complex-acosh (z)
1038 (declare (type (or rational complex) z))
1039 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1040 (sqrt-z+1 (complex-sqrt (+ z 1))))
1041 (with-float-traps-masked (:divide-by-zero)
1042 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1044 (* 2 (atan (/ (imagpart sqrt-z-1)
1045 (realpart sqrt-z+1))))))))
1047 ;;; Compute asin z = asinh(i*z)/i.
1049 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1050 (defun complex-asin (z)
1051 (declare (type (or rational complex) z))
1052 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1053 (sqrt-1+z (complex-sqrt (+ 1 z))))
1054 (with-float-traps-masked (:divide-by-zero)
1055 (complex (atan (/ (realpart z)
1056 (realpart (* sqrt-1-z sqrt-1+z))))
1057 (asinh (imagpart (* (conjugate sqrt-1-z)
1060 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1062 ;;; Z may be any number, but the result is always a complex.
1063 (defun complex-asinh (z)
1064 (declare (type (or rational complex) z))
1065 ;; asinh z = -i * asin (i*z)
1066 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1067 (result (complex-asin iz)))
1068 (complex (imagpart result)
1069 (- (realpart result)))))
1071 ;;; Compute atan z = atanh (i*z) / i.
1073 ;;; Z may be any number, but the result is always a complex.
1074 (defun complex-atan (z)
1075 (declare (type (or rational complex) z))
1076 ;; atan z = -i * atanh (i*z)
1077 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1078 (result (complex-atanh iz)))
1079 (complex (imagpart result)
1080 (- (realpart result)))))
1082 ;;; Compute tan z = -i * tanh(i * z)
1084 ;;; Z may be any number, but the result is always a complex.
1085 (defun complex-tan (z)
1086 (declare (type (or rational complex) z))
1087 ;; tan z = -i * tanh(i*z)
1088 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1089 (result (complex-tanh iz)))
1090 (complex (imagpart result)
1091 (- (realpart result)))))