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 ;;;; stubs for the Unix math library
46 ;;;; Many of these are unnecessary on the X86 because they're built
50 #!-x86 (def-math-rtn "sin" 1)
51 #!-x86 (def-math-rtn "cos" 1)
52 #!-x86 (def-math-rtn "tan" 1)
53 (def-math-rtn "asin" 1)
54 (def-math-rtn "acos" 1)
55 #!-x86 (def-math-rtn "atan" 1)
56 #!-x86 (def-math-rtn "atan2" 2)
57 #!+x86 ;; for constant folding
60 (def-math-rtn "sinh" 1)
61 (def-math-rtn "cosh" 1)
62 (def-math-rtn "tanh" 1)
63 (def-math-rtn "asinh" 1)
64 (def-math-rtn "acosh" 1)
65 (def-math-rtn "atanh" 1)
67 ;;; exponential and logarithmic
68 #!-x86 (def-math-rtn "exp" 1)
69 #!-x86 (def-math-rtn "log" 1)
70 #!-x86 (def-math-rtn "log10" 1)
71 (def-math-rtn "pow" 2)
72 #!-x86 (def-math-rtn "sqrt" 1)
73 (def-math-rtn "hypot" 2)
74 #!-(or hpux x86) (def-math-rtn "log1p" 1)
80 "Return e raised to the power NUMBER."
81 (number-dispatch ((number number))
82 (handle-reals %exp number)
84 (* (exp (realpart number))
85 (cis (imagpart number))))))
87 ;;; INTEXP -- Handle the rational base, integer power case.
89 (declaim (type (or integer null) *intexp-maximum-exponent*))
90 (defparameter *intexp-maximum-exponent* nil)
92 ;;; This function precisely calculates base raised to an integral
93 ;;; power. It separates the cases by the sign of power, for efficiency
94 ;;; reasons, as powers can be calculated more efficiently if power is
95 ;;; a positive integer. Values of power are calculated as positive
96 ;;; integers, and inverted if negative.
97 (defun intexp (base power)
98 (when (and *intexp-maximum-exponent*
99 (> (abs power) *intexp-maximum-exponent*))
100 (error "The absolute value of ~S exceeds ~S."
101 power '*intexp-maximum-exponent*))
102 (cond ((minusp power)
103 (/ (intexp base (- power))))
107 (do ((nextn (ash power -1) (ash power -1))
108 (total (if (oddp power) base 1)
109 (if (oddp power) (* base total) total)))
110 ((zerop nextn) total)
111 (setq base (* base base))
112 (setq power nextn)))))
114 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
115 ;;; floating point stuff. If both args are real, we try %POW right
116 ;;; off, assuming it will return 0 if the result may be complex. If
117 ;;; so, we call COMPLEX-POW which directly computes the complex
118 ;;; result. We also separate the complex-real and real-complex cases
119 ;;; from the general complex case.
120 (defun expt (base power)
122 "Return BASE raised to the POWER."
124 (let ((result (1+ (* base power))))
125 (if (and (floatp result) (float-nan-p result))
128 (labels (;; determine if the double float is an integer.
129 ;; 0 - not an integer
133 (declare (type (unsigned-byte 31) ihi)
134 (type (unsigned-byte 32) lo)
135 (optimize (speed 3) (safety 0)))
137 (declare (type fixnum isint))
138 (cond ((>= ihi #x43400000) ; exponent >= 53
141 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
142 (declare (type (mod 53) k))
144 (let* ((shift (- 52 k))
145 (j (logand (ash lo (- shift))))
147 (declare (type (mod 32) shift)
148 (type (unsigned-byte 32) j j2))
150 (setq isint (- 2 (logand j 1))))))
152 (let* ((shift (- 20 k))
153 (j (ash ihi (- shift)))
155 (declare (type (mod 32) shift)
156 (type (unsigned-byte 31) j j2))
158 (setq isint (- 2 (logand j 1))))))))))
160 (real-expt (x y rtype)
161 (let ((x (coerce x 'double-float))
162 (y (coerce y 'double-float)))
163 (declare (double-float x y))
164 (let* ((x-hi (sb!kernel:double-float-high-bits x))
165 (x-lo (sb!kernel:double-float-low-bits x))
166 (x-ihi (logand x-hi #x7fffffff))
167 (y-hi (sb!kernel:double-float-high-bits y))
168 (y-lo (sb!kernel:double-float-low-bits y))
169 (y-ihi (logand y-hi #x7fffffff)))
170 (declare (type (signed-byte 32) x-hi y-hi)
171 (type (unsigned-byte 31) x-ihi y-ihi)
172 (type (unsigned-byte 32) x-lo y-lo))
174 (when (zerop (logior y-ihi y-lo))
175 (return-from real-expt (coerce 1d0 rtype)))
177 (when (or (> x-ihi #x7ff00000)
178 (and (= x-ihi #x7ff00000) (/= x-lo 0))
180 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
181 (return-from real-expt (coerce (+ x y) rtype)))
182 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
183 (declare (type fixnum yisint))
184 ;; special value of y
185 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
187 (return-from real-expt
188 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
190 (coerce (- y y) rtype))
191 ((>= x-ihi #x3ff00000)
192 ;; (|x|>1)**+-inf = inf,0
197 ;; (|x|<1)**-,+inf = inf,0
200 (coerce 0 rtype))))))
202 (let ((abs-x (abs x)))
203 (declare (double-float abs-x))
204 ;; special value of x
205 (when (and (zerop x-lo)
206 (or (= x-ihi #x7ff00000) (zerop x-ihi)
207 (= x-ihi #x3ff00000)))
208 ;; x is +-0,+-inf,+-1
209 (let ((z (if (< y-hi 0)
210 (/ 1 abs-x) ; z = (1/|x|)
212 (declare (double-float z))
214 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
216 (let ((y*pi (* y pi)))
217 (declare (double-float y*pi))
218 (return-from real-expt
220 (coerce (%cos y*pi) rtype)
221 (coerce (%sin y*pi) rtype)))))
223 ;; (x<0)**odd = -(|x|**odd)
225 (return-from real-expt (coerce z rtype))))
229 (coerce (sb!kernel::%pow x y) rtype)
231 (let ((pow (sb!kernel::%pow abs-x y)))
232 (declare (double-float pow))
235 (coerce (* -1d0 pow) rtype))
239 (let ((y*pi (* y pi)))
240 (declare (double-float y*pi))
242 (coerce (* pow (%cos y*pi))
244 (coerce (* pow (%sin y*pi))
246 (declare (inline real-expt))
247 (number-dispatch ((base number) (power number))
248 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
250 (((foreach single-float double-float) rational)
251 (real-expt base power '(dispatch-type base)))
252 (((foreach fixnum (or bignum ratio) single-float)
253 (foreach ratio single-float))
254 (real-expt base power 'single-float))
255 (((foreach fixnum (or bignum ratio) single-float double-float)
257 (real-expt base power 'double-float))
258 ((double-float single-float)
259 (real-expt base power 'double-float))
260 (((foreach (complex rational) (complex float)) rational)
261 (* (expt (abs base) power)
262 (cis (* power (phase base)))))
263 (((foreach fixnum (or bignum ratio) single-float double-float)
265 (if (and (zerop base) (plusp (realpart power)))
267 (exp (* power (log base)))))
268 (((foreach (complex float) (complex rational))
269 (foreach complex double-float single-float))
270 (if (and (zerop base) (plusp (realpart power)))
272 (exp (* power (log base)))))))))
274 ;;; FIXME: Maybe rename this so that it's clearer that it only works
277 (declare (type integer x))
280 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
281 ;; log2(f). So we grab the top few bits of x and scale that
282 ;; appropriately, take the log of it and add it to n.
284 ;; Motivated by an attempt to get LOG to work better on bignums.
285 (let ((n (integer-length x)))
286 (if (< n sb!vm:double-float-digits)
287 (log (coerce x 'double-float) 2.0d0)
288 (let ((f (ldb (byte sb!vm:double-float-digits
289 (- n sb!vm:double-float-digits))
291 (+ n (log (scale-float (coerce f 'double-float)
292 (- sb!vm:double-float-digits))
295 (defun log (number &optional (base nil base-p))
297 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
300 ((zerop base) 0f0) ; FIXME: type
301 ((and (typep number '(integer (0) *))
302 (typep base '(integer (0) *)))
303 (coerce (/ (log2 number) (log2 base)) 'single-float))
304 (t (/ (log number) (log base))))
305 (number-dispatch ((number number))
306 (((foreach fixnum bignum))
308 (complex (log (- number)) (coerce pi 'single-float))
309 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
312 (complex (log (- number)) (coerce pi 'single-float))
313 (let ((numerator (numerator number))
314 (denominator (denominator number)))
315 (if (= (integer-length numerator)
316 (integer-length denominator))
317 (coerce (%log1p (coerce (- number 1) 'double-float))
319 (coerce (/ (- (log2 numerator) (log2 denominator))
320 (log (exp 1.0d0) 2.0d0))
322 (((foreach single-float double-float))
323 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
324 ;; Since this doesn't seem to be an implementation issue
325 ;; I (pw) take the Kahan result.
326 (if (< (float-sign number)
327 (coerce 0 '(dispatch-type number)))
328 (complex (log (- number)) (coerce pi '(dispatch-type number)))
329 (coerce (%log (coerce number 'double-float))
330 '(dispatch-type number))))
332 (complex-log number)))))
336 "Return the square root of NUMBER."
337 (number-dispatch ((number number))
338 (((foreach fixnum bignum ratio))
340 (complex-sqrt number)
341 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
342 (((foreach single-float double-float))
344 (complex-sqrt (complex number))
345 (coerce (%sqrt (coerce number 'double-float))
346 '(dispatch-type number))))
348 (complex-sqrt number))))
350 ;;;; trigonometic and related functions
354 "Return the absolute value of the number."
355 (number-dispatch ((number number))
356 (((foreach single-float double-float fixnum rational))
359 (let ((rx (realpart number))
360 (ix (imagpart number)))
363 (sqrt (+ (* rx rx) (* ix ix))))
365 (coerce (%hypot (coerce rx 'double-float)
366 (coerce ix 'double-float))
371 (defun phase (number)
373 "Return the angle part of the polar representation of a complex number.
374 For complex numbers, this is (atan (imagpart number) (realpart number)).
375 For non-complex positive numbers, this is 0. For non-complex negative
380 (coerce pi 'single-float)
383 (if (minusp (float-sign number))
384 (coerce pi 'single-float)
387 (if (minusp (float-sign number))
388 (coerce pi 'double-float)
391 (atan (imagpart number) (realpart number)))))
395 "Return the sine of NUMBER."
396 (number-dispatch ((number number))
397 (handle-reals %sin number)
399 (let ((x (realpart number))
400 (y (imagpart number)))
401 (complex (* (sin x) (cosh y))
402 (* (cos x) (sinh y)))))))
406 "Return the cosine of NUMBER."
407 (number-dispatch ((number number))
408 (handle-reals %cos number)
410 (let ((x (realpart number))
411 (y (imagpart number)))
412 (complex (* (cos x) (cosh y))
413 (- (* (sin x) (sinh y))))))))
417 "Return the tangent of NUMBER."
418 (number-dispatch ((number number))
419 (handle-reals %tan number)
421 (complex-tan number))))
425 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
426 (declare (type real theta))
427 (complex (cos theta) (sin theta)))
431 "Return the arc sine of NUMBER."
432 (number-dispatch ((number number))
434 (if (or (> number 1) (< number -1))
435 (complex-asin number)
436 (coerce (%asin (coerce number 'double-float)) 'single-float)))
437 (((foreach single-float double-float))
438 (if (or (> number (coerce 1 '(dispatch-type number)))
439 (< number (coerce -1 '(dispatch-type number))))
440 (complex-asin (complex number))
441 (coerce (%asin (coerce number 'double-float))
442 '(dispatch-type number))))
444 (complex-asin number))))
448 "Return the arc cosine of NUMBER."
449 (number-dispatch ((number number))
451 (if (or (> number 1) (< number -1))
452 (complex-acos number)
453 (coerce (%acos (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-acos (complex number))
458 (coerce (%acos (coerce number 'double-float))
459 '(dispatch-type number))))
461 (complex-acos number))))
463 (defun atan (y &optional (x nil xp))
465 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
468 (declare (type double-float y x)
469 (values double-float))
472 (if (plusp (float-sign x))
475 (float-sign y (/ pi 2)))
477 (number-dispatch ((y real) (x real))
479 (foreach double-float single-float fixnum bignum ratio))
480 (atan2 y (coerce x 'double-float)))
481 (((foreach single-float fixnum bignum ratio)
483 (atan2 (coerce y 'double-float) x))
484 (((foreach single-float fixnum bignum ratio)
485 (foreach single-float fixnum bignum ratio))
486 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
488 (number-dispatch ((y number))
489 (handle-reals %atan y)
493 ;;; It seems that every target system has a C version of sinh, cosh,
494 ;;; and tanh. Let's use these for reals because the original
495 ;;; implementations based on the definitions lose big in round-off
496 ;;; error. These bad definitions also mean that sin and cos for
497 ;;; complex numbers can also lose big.
501 "Return the hyperbolic sine of NUMBER."
502 (number-dispatch ((number number))
503 (handle-reals %sinh number)
505 (let ((x (realpart number))
506 (y (imagpart number)))
507 (complex (* (sinh x) (cos y))
508 (* (cosh x) (sin y)))))))
512 "Return the hyperbolic cosine of NUMBER."
513 (number-dispatch ((number number))
514 (handle-reals %cosh number)
516 (let ((x (realpart number))
517 (y (imagpart number)))
518 (complex (* (cosh x) (cos y))
519 (* (sinh x) (sin y)))))))
523 "Return the hyperbolic tangent of NUMBER."
524 (number-dispatch ((number number))
525 (handle-reals %tanh number)
527 (complex-tanh number))))
529 (defun asinh (number)
531 "Return the hyperbolic arc sine of NUMBER."
532 (number-dispatch ((number number))
533 (handle-reals %asinh number)
535 (complex-asinh number))))
537 (defun acosh (number)
539 "Return the hyperbolic arc cosine of NUMBER."
540 (number-dispatch ((number number))
542 ;; acosh is complex if number < 1
544 (complex-acosh number)
545 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
546 (((foreach single-float double-float))
547 (if (< number (coerce 1 '(dispatch-type number)))
548 (complex-acosh (complex number))
549 (coerce (%acosh (coerce number 'double-float))
550 '(dispatch-type number))))
552 (complex-acosh number))))
554 (defun atanh (number)
556 "Return the hyperbolic arc tangent of NUMBER."
557 (number-dispatch ((number number))
559 ;; atanh is complex if |number| > 1
560 (if (or (> number 1) (< number -1))
561 (complex-atanh number)
562 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
563 (((foreach single-float double-float))
564 (if (or (> number (coerce 1 '(dispatch-type number)))
565 (< number (coerce -1 '(dispatch-type number))))
566 (complex-atanh (complex number))
567 (coerce (%atanh (coerce number 'double-float))
568 '(dispatch-type number))))
570 (complex-atanh number))))
572 ;;; HP-UX does not supply a C version of log1p, so use the definition.
574 ;;; FIXME: This is really not a good definition. As per Raymond Toy
575 ;;; working on CMU CL, "The definition really loses big-time in
576 ;;; roundoff as x gets small."
578 #!-sb-fluid (declaim (inline %log1p))
580 (defun %log1p (number)
581 (declare (double-float number)
582 (optimize (speed 3) (safety 0)))
583 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
585 ;;;; not-OLD-SPECFUN stuff
587 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
588 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
589 ;;;; the standard special function system.)
591 ;;;; This is a set of routines that implement many elementary
592 ;;;; transcendental functions as specified by ANSI Common Lisp. The
593 ;;;; implementation is based on Kahan's paper.
595 ;;;; I believe I have accurately implemented the routines and are
596 ;;;; correct, but you may want to check for your self.
598 ;;;; These functions are written for CMU Lisp and take advantage of
599 ;;;; some of the features available there. It may be possible,
600 ;;;; however, to port this to other Lisps.
602 ;;;; Some functions are significantly more accurate than the original
603 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
604 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
605 ;;;; answer is pi + i*log(2-sqrt(3)).
607 ;;;; All of the implemented functions will take any number for an
608 ;;;; input, but the result will always be a either a complex
609 ;;;; single-float or a complex double-float.
611 ;;;; general functions:
623 ;;;; utility functions:
626 ;;;; internal functions:
627 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
630 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
631 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
632 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
635 ;;;; The original CMU CL code requested:
636 ;;;; Please send any bug reports, comments, or improvements to
637 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
639 ;;; FIXME: In SBCL, the floating point infinity constants like
640 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
641 ;;; constants at cross-compile time, because the cross-compilation
642 ;;; host might not have support for floating point infinities. Thus,
643 ;;; they're effectively implemented as special variable references,
644 ;;; and the code below which uses them might be unnecessarily
645 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
646 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
647 ;;; special variable references with (probably equally slow)
650 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
651 ;;; differ in their interpretations of the real line, IMAGPART was
652 ;;; patch, which without a certain amount of effort would have altered
653 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
654 ;;; were patched to use explicit COMPLEX, rather than implicitly
655 ;;; passing in real numbers for treatment with IMAGPART, and these
656 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
657 ;;; however, someone needs to go back to Kahan for the definitive
658 ;;; answer for treatment of negative real floating point numbers and
659 ;;; branch cuts. If adjustment is needed, it is probably the removal
660 ;;; of explicit calls to COMPLEX in the clients of irrational
661 ;;; functions. -- a slightly bitter CSR, 2004-05-16
663 (declaim (inline square))
665 (declare (double-float x))
668 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
670 ;;; If you have these functions in libm, perhaps they should be used
671 ;;; instead of these Lisp versions. These versions are probably good
672 ;;; enough, especially since they are portable.
674 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
675 ;;; the underlying floating-point format.)
676 (declaim (inline scalb))
678 (declare (type double-float x)
679 (type double-float-exponent n))
682 ;;; This is like LOGB, but X is not infinity and non-zero and not a
683 ;;; NaN, so we can always return an integer.
684 (declaim (inline logb-finite))
685 (defun logb-finite (x)
686 (declare (type double-float x))
687 (multiple-value-bind (signif exponent sign)
689 (declare (ignore signif sign))
690 ;; DECODE-FLOAT is almost right, except that the exponent is off
694 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
695 ;;; For the special cases, the following values are used:
698 ;;; +/- infinity +infinity
701 (declare (type double-float x))
702 (cond ((float-nan-p x)
704 ((float-infinity-p x)
705 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
706 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
708 ;; The answer is negative infinity, but we are supposed to
709 ;; signal divide-by-zero, so do the actual division
715 ;;; This function is used to create a complex number of the
716 ;;; appropriate type:
717 ;;; Create complex number with real part X and imaginary part Y
718 ;;; such that has the same type as Z. If Z has type (complex
719 ;;; rational), the X and Y are coerced to single-float.
720 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
721 (error "needs work for long float support"))
722 (declaim (inline coerce-to-complex-type))
723 (defun coerce-to-complex-type (x y z)
724 (declare (double-float x y)
726 (if (typep (realpart z) 'double-float)
728 ;; Convert anything that's not already a DOUBLE-FLOAT (because
729 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
730 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
731 (complex (float x 1f0)
734 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
735 ;;; result is r + i*k, where k is an integer.
736 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
737 (error "needs work for long float support"))
739 (let ((x (float (realpart z) 1d0))
740 (y (float (imagpart z) 1d0)))
741 ;; Would this be better handled using an exception handler to
742 ;; catch the overflow or underflow signal? For now, we turn all
743 ;; traps off and look at the accrued exceptions to see if any
744 ;; signal would have been raised.
745 (with-float-traps-masked (:underflow :overflow)
746 (let ((rho (+ (square x) (square y))))
747 (declare (optimize (speed 3) (space 0)))
748 (cond ((and (or (float-nan-p rho)
749 (float-infinity-p rho))
750 (or (float-infinity-p (abs x))
751 (float-infinity-p (abs y))))
752 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
754 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
756 ((let ((threshold #.(/ least-positive-double-float
757 double-float-epsilon))
758 (traps (ldb sb!vm::float-sticky-bits
759 (sb!vm:floating-point-modes))))
760 ;; Overflow raised or (underflow raised and rho <
762 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
763 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
766 ;; If we're here, neither x nor y are infinity and at
767 ;; least one is non-zero.. Thus logb returns a nice
769 (let ((k (- (logb-finite (max (abs x) (abs y))))))
770 (values (+ (square (scalb x k))
771 (square (scalb y k)))
776 ;;; principal square root of Z
778 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
779 (defun complex-sqrt (z)
780 ;; KLUDGE: Here and below, we can't just declare Z to be of type
781 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
782 ;; Since there isn't a rational negative zero, this is OK from the
783 ;; point of view of getting the right answer in the face of branch
784 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
785 ;; still ugly. -- CSR, 2004-05-16
786 (declare (type (or complex rational) z))
787 (multiple-value-bind (rho k)
789 (declare (type (or (member 0d0) (double-float 0d0)) rho)
791 (let ((x (float (realpart z) 1.0d0))
792 (y (float (imagpart z) 1.0d0))
795 (declare (double-float x y eta nu))
798 ;; space 0 to get maybe-inline functions inlined.
799 (declare (optimize (speed 3) (space 0)))
801 (if (not (float-nan-p x))
802 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
807 (setf k (1- (ash k -1)))
808 (setf rho (+ rho rho))))
810 (setf rho (scalb (sqrt rho) k))
816 (when (not (float-infinity-p (abs nu)))
817 (setf nu (/ (/ nu rho) 2d0)))
820 (setf nu (float-sign y rho))))
821 (coerce-to-complex-type eta nu z)))))
823 ;;; Compute log(2^j*z).
825 ;;; This is for use with J /= 0 only when |z| is huge.
826 (defun complex-log-scaled (z j)
827 (declare (type (or rational complex) z)
829 ;; The constants t0, t1, t2 should be evaluated to machine
830 ;; precision. In addition, Kahan says the accuracy of log1p
831 ;; influences the choices of these constants but doesn't say how to
832 ;; choose them. We'll just assume his choices matches our
833 ;; implementation of log1p.
834 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
838 (x (float (realpart z) 1.0d0))
839 (y (float (imagpart z) 1.0d0)))
840 (multiple-value-bind (rho k)
842 (declare (optimize (speed 3)))
843 (let ((beta (max (abs x) (abs y)))
844 (theta (min (abs x) (abs y))))
845 (coerce-to-complex-type (if (and (zerop k)
849 (/ (%log1p (+ (* (- beta 1.0d0)
858 ;;; log of Z = log |Z| + i * arg Z
860 ;;; Z may be any number, but the result is always a complex.
861 (defun complex-log (z)
862 (declare (type (or rational complex) z))
863 (complex-log-scaled z 0))
865 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
866 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
867 ;;; The reason for the imaginary part is caused by the fact that arg
868 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
869 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
870 (defun complex-atanh (z)
871 (declare (type (or rational complex) z))
873 (theta (/ (sqrt most-positive-double-float) 4.0d0))
874 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
875 (half-pi (/ pi 2.0d0))
876 (rp (float (realpart z) 1.0d0))
877 (beta (float-sign rp 1.0d0))
879 (y (* beta (- (float (imagpart z) 1.0d0))))
882 ;; Shouldn't need this declare.
883 (declare (double-float x y))
885 (declare (optimize (speed 3)))
886 (cond ((or (> x theta)
888 ;; To avoid overflow...
889 (setf nu (float-sign y half-pi))
890 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
891 ;; which can cause overflow. Arrange this computation so
892 ;; that it won't overflow.
893 (setf eta (let* ((x-bigger (> x (abs y)))
894 (r (if x-bigger (/ y x) (/ x y)))
895 (d (+ 1.0d0 (* r r))))
900 ;; Should this be changed so that if y is zero, eta is set
901 ;; to +infinity instead of approx 176? In any case
902 ;; tanh(176) is 1.0d0 within working precision.
903 (let ((t1 (+ 4d0 (square y)))
904 (t2 (+ (abs y) rho)))
905 (setf eta (log (/ (sqrt (sqrt t1))
909 (+ half-pi (atan (* 0.5d0 t2))))))))
911 (let ((t1 (+ (abs y) rho)))
912 ;; Normal case using log1p(x) = log(1 + x)
914 (%log1p (/ (* 4.0d0 x)
915 (+ (square (- 1.0d0 x))
922 (coerce-to-complex-type (* beta eta)
926 ;;; Compute tanh z = sinh z / cosh z.
927 (defun complex-tanh (z)
928 (declare (type (or rational complex) z))
929 (let ((x (float (realpart z) 1.0d0))
930 (y (float (imagpart z) 1.0d0)))
932 ;; space 0 to get maybe-inline functions inlined
933 (declare (optimize (speed 3) (space 0)))
935 ;; FIXME: this form is hideously broken wrt
936 ;; cross-compilation portability. Much else in this
937 ;; file is too, of course, sometimes hidden by
938 ;; constant-folding, but this one in particular clearly
939 ;; depends on host and target
940 ;; MOST-POSITIVE-DOUBLE-FLOATs being equal. -- CSR,
943 (log most-positive-double-float))
945 (coerce-to-complex-type (float-sign x)
949 (beta (+ 1.0d0 (* tv tv)))
951 (rho (sqrt (+ 1.0d0 (* s s)))))
952 (if (float-infinity-p (abs tv))
953 (coerce-to-complex-type (/ rho s)
956 (let ((den (+ 1.0d0 (* beta s s))))
957 (coerce-to-complex-type (/ (* beta rho s)
962 ;;; Compute acos z = pi/2 - asin z.
964 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
965 (defun complex-acos (z)
966 ;; Kahan says we should only compute the parts needed. Thus, the
967 ;; REALPART's below should only compute the real part, not the whole
968 ;; complex expression. Doing this can be important because we may get
969 ;; spurious signals that occur in the part that we are not using.
971 ;; However, we take a pragmatic approach and just use the whole
974 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
975 ;; it's the conjugate of the square root or the square root of the
976 ;; conjugate. This needs to be checked.
978 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
979 ;; same as (sqrt (conjugate z)) for all z. This follows because
981 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
983 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
985 ;; and these two expressions are equal if and only if arg conj z =
986 ;; -arg z, which is clearly true for all z.
987 (declare (type (or rational complex) z))
988 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
989 (sqrt-1-z (complex-sqrt (- 1 z))))
990 (with-float-traps-masked (:divide-by-zero)
991 (complex (* 2 (atan (/ (realpart sqrt-1-z)
992 (realpart sqrt-1+z))))
993 (asinh (imagpart (* (conjugate sqrt-1+z)
996 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
998 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
999 (defun complex-acosh (z)
1000 (declare (type (or rational complex) z))
1001 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1002 (sqrt-z+1 (complex-sqrt (+ z 1))))
1003 (with-float-traps-masked (:divide-by-zero)
1004 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1006 (* 2 (atan (/ (imagpart sqrt-z-1)
1007 (realpart sqrt-z+1))))))))
1009 ;;; Compute asin z = asinh(i*z)/i.
1011 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1012 (defun complex-asin (z)
1013 (declare (type (or rational complex) z))
1014 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1015 (sqrt-1+z (complex-sqrt (+ 1 z))))
1016 (with-float-traps-masked (:divide-by-zero)
1017 (complex (atan (/ (realpart z)
1018 (realpart (* sqrt-1-z sqrt-1+z))))
1019 (asinh (imagpart (* (conjugate sqrt-1-z)
1022 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1024 ;;; Z may be any number, but the result is always a complex.
1025 (defun complex-asinh (z)
1026 (declare (type (or rational complex) z))
1027 ;; asinh z = -i * asin (i*z)
1028 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1029 (result (complex-asin iz)))
1030 (complex (imagpart result)
1031 (- (realpart result)))))
1033 ;;; Compute atan z = atanh (i*z) / i.
1035 ;;; Z may be any number, but the result is always a complex.
1036 (defun complex-atan (z)
1037 (declare (type (or rational complex) z))
1038 ;; atan z = -i * atanh (i*z)
1039 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1040 (result (complex-atanh iz)))
1041 (complex (imagpart result)
1042 (- (realpart result)))))
1044 ;;; Compute tan z = -i * tanh(i * z)
1046 ;;; Z may be any number, but the result is always a complex.
1047 (defun complex-tan (z)
1048 (declare (type (or rational complex) z))
1049 ;; tan z = -i * tanh(i*z)
1050 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1051 (result (complex-tanh iz)))
1052 (complex (imagpart result)
1053 (- (realpart result)))))