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 #!-x86 (def-math-rtn "atan" 1)
74 #!-x86 (def-math-rtn "atan2" 2)
77 (def-math-rtn "acos" 1)
78 (def-math-rtn "asin" 1)
79 (def-math-rtn "cosh" 1)
80 (def-math-rtn "sinh" 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 %asin))
89 (%atan (/ number (sqrt (- 1 (* number number))))))
90 (declaim (inline %acos))
92 (- (/ pi 2) (%asin number)))
93 (declaim (inline %cosh))
95 (/ (+ (exp number) (exp (- number))) 2))
96 (declaim (inline %sinh))
98 (/ (- (exp number) (exp (- number))) 2))
99 (declaim (inline %tanh))
100 (defun %tanh (number)
101 (/ (%sinh number) (%cosh number)))
102 (declaim (inline %asinh))
103 (defun %asinh (number)
104 (log (+ number (sqrt (+ (* number number) 1.0d0))) #.(exp 1.0d0)))
105 (declaim (inline %acosh))
106 (defun %acosh (number)
107 (log (+ number (sqrt (- (* number number) 1.0d0))) #.(exp 1.0d0)))
108 (declaim (inline %atanh))
109 (defun %atanh (number)
110 (let ((ratio (/ (+ 1 number) (- 1 number))))
111 ;; Were we effectively zero?
114 (/ (log ratio #.(exp 1.0d0)) 2.0d0)))))
116 ;;; exponential and logarithmic
117 #!-x86 (def-math-rtn "exp" 1)
118 #!-x86 (def-math-rtn "log" 1)
119 #!-x86 (def-math-rtn "log10" 1)
120 #!-win32(def-math-rtn "pow" 2)
121 #!-(or x86 x86-64) (def-math-rtn "sqrt" 1)
122 #!-win32 (def-math-rtn "hypot" 2)
123 #!-(or hpux x86) (def-math-rtn "log1p" 1)
127 ;; FIXME: libc hypot "computes the sqrt(x*x+y*y) without undue overflow or underflow"
128 ;; ...we just do the stupid simple thing.
129 (declaim (inline %hypot))
131 (sqrt (+ (* x x) (* y y)))))
137 "Return e raised to the power NUMBER."
138 (number-dispatch ((number number))
139 (handle-reals %exp number)
141 (* (exp (realpart number))
142 (cis (imagpart number))))))
144 ;;; INTEXP -- Handle the rational base, integer power case.
146 (declaim (type (or integer null) *intexp-maximum-exponent*))
147 (defparameter *intexp-maximum-exponent* nil)
149 ;;; This function precisely calculates base raised to an integral
150 ;;; power. It separates the cases by the sign of power, for efficiency
151 ;;; reasons, as powers can be calculated more efficiently if power is
152 ;;; a positive integer. Values of power are calculated as positive
153 ;;; integers, and inverted if negative.
154 (defun intexp (base power)
155 (when (and *intexp-maximum-exponent*
156 (> (abs power) *intexp-maximum-exponent*))
157 (error "The absolute value of ~S exceeds ~S."
158 power '*intexp-maximum-exponent*))
159 (cond ((minusp power)
160 (/ (intexp base (- power))))
164 (do ((nextn (ash power -1) (ash power -1))
165 (total (if (oddp power) base 1)
166 (if (oddp power) (* base total) total)))
167 ((zerop nextn) total)
168 (setq base (* base base))
169 (setq power nextn)))))
171 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
172 ;;; floating point stuff. If both args are real, we try %POW right
173 ;;; off, assuming it will return 0 if the result may be complex. If
174 ;;; so, we call COMPLEX-POW which directly computes the complex
175 ;;; result. We also separate the complex-real and real-complex cases
176 ;;; from the general complex case.
177 (defun expt (base power)
179 "Return BASE raised to the POWER."
181 (let ((result (1+ (* base power))))
182 (if (and (floatp result) (float-nan-p result))
185 (labels (;; determine if the double float is an integer.
186 ;; 0 - not an integer
190 (declare (type (unsigned-byte 31) ihi)
191 (type (unsigned-byte 32) lo)
192 (optimize (speed 3) (safety 0)))
194 (declare (type fixnum isint))
195 (cond ((>= ihi #x43400000) ; exponent >= 53
198 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
199 (declare (type (mod 53) k))
201 (let* ((shift (- 52 k))
202 (j (logand (ash lo (- shift))))
204 (declare (type (mod 32) shift)
205 (type (unsigned-byte 32) j j2))
207 (setq isint (- 2 (logand j 1))))))
209 (let* ((shift (- 20 k))
210 (j (ash ihi (- shift)))
212 (declare (type (mod 32) shift)
213 (type (unsigned-byte 31) j j2))
215 (setq isint (- 2 (logand j 1))))))))))
217 (real-expt (x y rtype)
218 (let ((x (coerce x 'double-float))
219 (y (coerce y 'double-float)))
220 (declare (double-float x y))
221 (let* ((x-hi (sb!kernel:double-float-high-bits x))
222 (x-lo (sb!kernel:double-float-low-bits x))
223 (x-ihi (logand x-hi #x7fffffff))
224 (y-hi (sb!kernel:double-float-high-bits y))
225 (y-lo (sb!kernel:double-float-low-bits y))
226 (y-ihi (logand y-hi #x7fffffff)))
227 (declare (type (signed-byte 32) x-hi y-hi)
228 (type (unsigned-byte 31) x-ihi y-ihi)
229 (type (unsigned-byte 32) x-lo y-lo))
231 (when (zerop (logior y-ihi y-lo))
232 (return-from real-expt (coerce 1d0 rtype)))
234 ;; FIXME: Hardcoded qNaN/sNaN values are not portable.
235 (when (or (> x-ihi #x7ff00000)
236 (and (= x-ihi #x7ff00000) (/= x-lo 0))
238 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
239 (return-from real-expt (coerce (+ x y) rtype)))
240 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
241 (declare (type fixnum yisint))
242 ;; special value of y
243 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
245 (return-from real-expt
246 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
248 (coerce (- y y) rtype))
249 ((>= x-ihi #x3ff00000)
250 ;; (|x|>1)**+-inf = inf,0
255 ;; (|x|<1)**-,+inf = inf,0
258 (coerce 0 rtype))))))
260 (let ((abs-x (abs x)))
261 (declare (double-float abs-x))
262 ;; special value of x
263 (when (and (zerop x-lo)
264 (or (= x-ihi #x7ff00000) (zerop x-ihi)
265 (= x-ihi #x3ff00000)))
266 ;; x is +-0,+-inf,+-1
267 (let ((z (if (< y-hi 0)
268 (/ 1 abs-x) ; z = (1/|x|)
270 (declare (double-float z))
272 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
274 (let ((y*pi (* y pi)))
275 (declare (double-float y*pi))
276 (return-from real-expt
278 (coerce (%cos y*pi) rtype)
279 (coerce (%sin y*pi) rtype)))))
281 ;; (x<0)**odd = -(|x|**odd)
283 (return-from real-expt (coerce z rtype))))
287 (coerce (sb!kernel::%pow x y) rtype)
289 (let ((pow (sb!kernel::%pow abs-x y)))
290 (declare (double-float pow))
293 (coerce (* -1d0 pow) rtype))
297 (let ((y*pi (* y pi)))
298 (declare (double-float y*pi))
300 (coerce (* pow (%cos y*pi))
302 (coerce (* pow (%sin y*pi))
304 (declare (inline real-expt))
305 (number-dispatch ((base number) (power number))
306 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
308 (((foreach single-float double-float) rational)
309 (real-expt base power '(dispatch-type base)))
310 (((foreach fixnum (or bignum ratio) single-float)
311 (foreach ratio single-float))
312 (real-expt base power 'single-float))
313 (((foreach fixnum (or bignum ratio) single-float double-float)
315 (real-expt base power 'double-float))
316 ((double-float single-float)
317 (real-expt base power 'double-float))
318 (((foreach (complex rational) (complex float)) rational)
319 (* (expt (abs base) power)
320 (cis (* power (phase base)))))
321 (((foreach fixnum (or bignum ratio) single-float double-float)
323 (if (and (zerop base) (plusp (realpart power)))
325 (exp (* power (log base)))))
326 (((foreach (complex float) (complex rational))
327 (foreach complex double-float single-float))
328 (if (and (zerop base) (plusp (realpart power)))
330 (exp (* power (log base)))))))))
332 ;;; FIXME: Maybe rename this so that it's clearer that it only works
335 (declare (type integer x))
338 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
339 ;; log2(f). So we grab the top few bits of x and scale that
340 ;; appropriately, take the log of it and add it to n.
342 ;; Motivated by an attempt to get LOG to work better on bignums.
343 (let ((n (integer-length x)))
344 (if (< n sb!vm:double-float-digits)
345 (log (coerce x 'double-float) 2.0d0)
346 (let ((f (ldb (byte sb!vm:double-float-digits
347 (- n sb!vm:double-float-digits))
349 (+ n (log (scale-float (coerce f 'double-float)
350 (- sb!vm:double-float-digits))
353 (defun log (number &optional (base nil base-p))
355 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
359 (if (or (typep number 'double-float) (typep base 'double-float))
362 ((and (typep number '(integer (0) *))
363 (typep base '(integer (0) *)))
364 (coerce (/ (log2 number) (log2 base)) 'single-float))
365 ((and (typep number 'integer) (typep base 'double-float))
366 ;; No single float intermediate result
367 (/ (log2 number) (log base 2.0d0)))
368 ((and (typep number 'double-float) (typep base 'integer))
369 (/ (log number 2.0d0) (log2 base)))
371 (/ (log number) (log base))))
372 (number-dispatch ((number number))
373 (((foreach fixnum bignum))
375 (complex (log (- number)) (coerce pi 'single-float))
376 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
379 (complex (log (- number)) (coerce pi 'single-float))
380 (let ((numerator (numerator number))
381 (denominator (denominator number)))
382 (if (= (integer-length numerator)
383 (integer-length denominator))
384 (coerce (%log1p (coerce (- number 1) 'double-float))
386 (coerce (/ (- (log2 numerator) (log2 denominator))
387 (log (exp 1.0d0) 2.0d0))
389 (((foreach single-float double-float))
390 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
391 ;; Since this doesn't seem to be an implementation issue
392 ;; I (pw) take the Kahan result.
393 (if (< (float-sign number)
394 (coerce 0 '(dispatch-type number)))
395 (complex (log (- number)) (coerce pi '(dispatch-type number)))
396 (coerce (%log (coerce number 'double-float))
397 '(dispatch-type number))))
399 (complex-log number)))))
403 "Return the square root of NUMBER."
404 (number-dispatch ((number number))
405 (((foreach fixnum bignum ratio))
407 (complex-sqrt number)
408 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
409 (((foreach single-float double-float))
411 (complex-sqrt (complex number))
412 (coerce (%sqrt (coerce number 'double-float))
413 '(dispatch-type number))))
415 (complex-sqrt number))))
417 ;;;; trigonometic and related functions
421 "Return the absolute value of the number."
422 (number-dispatch ((number number))
423 (((foreach single-float double-float fixnum rational))
426 (let ((rx (realpart number))
427 (ix (imagpart number)))
430 (sqrt (+ (* rx rx) (* ix ix))))
432 (coerce (%hypot (coerce rx 'double-float)
433 (coerce ix 'double-float))
438 (defun phase (number)
440 "Return the angle part of the polar representation of a complex number.
441 For complex numbers, this is (atan (imagpart number) (realpart number)).
442 For non-complex positive numbers, this is 0. For non-complex negative
447 (coerce pi 'single-float)
450 (if (minusp (float-sign number))
451 (coerce pi 'single-float)
454 (if (minusp (float-sign number))
455 (coerce pi 'double-float)
458 (atan (imagpart number) (realpart number)))))
462 "Return the sine of NUMBER."
463 (number-dispatch ((number number))
464 (handle-reals %sin number)
466 (let ((x (realpart number))
467 (y (imagpart number)))
468 (complex (* (sin x) (cosh y))
469 (* (cos x) (sinh y)))))))
473 "Return the cosine of NUMBER."
474 (number-dispatch ((number number))
475 (handle-reals %cos number)
477 (let ((x (realpart number))
478 (y (imagpart number)))
479 (complex (* (cos x) (cosh y))
480 (- (* (sin x) (sinh y))))))))
484 "Return the tangent of NUMBER."
485 (number-dispatch ((number number))
486 (handle-reals %tan number)
488 (complex-tan number))))
492 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
493 (declare (type real theta))
494 (complex (cos theta) (sin theta)))
498 "Return the arc sine of NUMBER."
499 (number-dispatch ((number number))
501 (if (or (> number 1) (< number -1))
502 (complex-asin number)
503 (coerce (%asin (coerce number 'double-float)) 'single-float)))
504 (((foreach single-float double-float))
505 (if (or (> number (coerce 1 '(dispatch-type number)))
506 (< number (coerce -1 '(dispatch-type number))))
507 (complex-asin (complex number))
508 (coerce (%asin (coerce number 'double-float))
509 '(dispatch-type number))))
511 (complex-asin number))))
515 "Return the arc cosine of NUMBER."
516 (number-dispatch ((number number))
518 (if (or (> number 1) (< number -1))
519 (complex-acos number)
520 (coerce (%acos (coerce number 'double-float)) 'single-float)))
521 (((foreach single-float double-float))
522 (if (or (> number (coerce 1 '(dispatch-type number)))
523 (< number (coerce -1 '(dispatch-type number))))
524 (complex-acos (complex number))
525 (coerce (%acos (coerce number 'double-float))
526 '(dispatch-type number))))
528 (complex-acos number))))
530 (defun atan (y &optional (x nil xp))
532 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
535 (declare (type double-float y x)
536 (values double-float))
539 (if (plusp (float-sign x))
542 (float-sign y (/ pi 2)))
544 (number-dispatch ((y real) (x real))
546 (foreach double-float single-float fixnum bignum ratio))
547 (atan2 y (coerce x 'double-float)))
548 (((foreach single-float fixnum bignum ratio)
550 (atan2 (coerce y 'double-float) x))
551 (((foreach single-float fixnum bignum ratio)
552 (foreach single-float fixnum bignum ratio))
553 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
555 (number-dispatch ((y number))
556 (handle-reals %atan y)
560 ;;; It seems that every target system has a C version of sinh, cosh,
561 ;;; and tanh. Let's use these for reals because the original
562 ;;; implementations based on the definitions lose big in round-off
563 ;;; error. These bad definitions also mean that sin and cos for
564 ;;; complex numbers can also lose big.
568 "Return the hyperbolic sine of NUMBER."
569 (number-dispatch ((number number))
570 (handle-reals %sinh number)
572 (let ((x (realpart number))
573 (y (imagpart number)))
574 (complex (* (sinh x) (cos y))
575 (* (cosh x) (sin y)))))))
579 "Return the hyperbolic cosine of NUMBER."
580 (number-dispatch ((number number))
581 (handle-reals %cosh number)
583 (let ((x (realpart number))
584 (y (imagpart number)))
585 (complex (* (cosh x) (cos y))
586 (* (sinh x) (sin y)))))))
590 "Return the hyperbolic tangent of NUMBER."
591 (number-dispatch ((number number))
592 (handle-reals %tanh number)
594 (complex-tanh number))))
596 (defun asinh (number)
598 "Return the hyperbolic arc sine of NUMBER."
599 (number-dispatch ((number number))
600 (handle-reals %asinh number)
602 (complex-asinh number))))
604 (defun acosh (number)
606 "Return the hyperbolic arc cosine of NUMBER."
607 (number-dispatch ((number number))
609 ;; acosh is complex if number < 1
611 (complex-acosh number)
612 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
613 (((foreach single-float double-float))
614 (if (< number (coerce 1 '(dispatch-type number)))
615 (complex-acosh (complex number))
616 (coerce (%acosh (coerce number 'double-float))
617 '(dispatch-type number))))
619 (complex-acosh number))))
621 (defun atanh (number)
623 "Return the hyperbolic arc tangent of NUMBER."
624 (number-dispatch ((number number))
626 ;; atanh is complex if |number| > 1
627 (if (or (> number 1) (< number -1))
628 (complex-atanh number)
629 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
630 (((foreach single-float double-float))
631 (if (or (> number (coerce 1 '(dispatch-type number)))
632 (< number (coerce -1 '(dispatch-type number))))
633 (complex-atanh (complex number))
634 (coerce (%atanh (coerce number 'double-float))
635 '(dispatch-type number))))
637 (complex-atanh number))))
639 ;;; HP-UX does not supply a C version of log1p, so use the definition.
641 ;;; FIXME: This is really not a good definition. As per Raymond Toy
642 ;;; working on CMU CL, "The definition really loses big-time in
643 ;;; roundoff as x gets small."
645 #!-sb-fluid (declaim (inline %log1p))
647 (defun %log1p (number)
648 (declare (double-float number)
649 (optimize (speed 3) (safety 0)))
650 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
652 ;;;; not-OLD-SPECFUN stuff
654 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
655 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
656 ;;;; the standard special function system.)
658 ;;;; This is a set of routines that implement many elementary
659 ;;;; transcendental functions as specified by ANSI Common Lisp. The
660 ;;;; implementation is based on Kahan's paper.
662 ;;;; I believe I have accurately implemented the routines and are
663 ;;;; correct, but you may want to check for your self.
665 ;;;; These functions are written for CMU Lisp and take advantage of
666 ;;;; some of the features available there. It may be possible,
667 ;;;; however, to port this to other Lisps.
669 ;;;; Some functions are significantly more accurate than the original
670 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
671 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
672 ;;;; answer is pi + i*log(2-sqrt(3)).
674 ;;;; All of the implemented functions will take any number for an
675 ;;;; input, but the result will always be a either a complex
676 ;;;; single-float or a complex double-float.
678 ;;;; general functions:
690 ;;;; utility functions:
693 ;;;; internal functions:
694 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
697 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
698 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
699 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
702 ;;;; The original CMU CL code requested:
703 ;;;; Please send any bug reports, comments, or improvements to
704 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
706 ;;; FIXME: In SBCL, the floating point infinity constants like
707 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
708 ;;; constants at cross-compile time, because the cross-compilation
709 ;;; host might not have support for floating point infinities. Thus,
710 ;;; they're effectively implemented as special variable references,
711 ;;; and the code below which uses them might be unnecessarily
712 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
713 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
714 ;;; special variable references with (probably equally slow)
717 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
718 ;;; differ in their interpretations of the real line, IMAGPART was
719 ;;; patch, which without a certain amount of effort would have altered
720 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
721 ;;; were patched to use explicit COMPLEX, rather than implicitly
722 ;;; passing in real numbers for treatment with IMAGPART, and these
723 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
724 ;;; however, someone needs to go back to Kahan for the definitive
725 ;;; answer for treatment of negative real floating point numbers and
726 ;;; branch cuts. If adjustment is needed, it is probably the removal
727 ;;; of explicit calls to COMPLEX in the clients of irrational
728 ;;; functions. -- a slightly bitter CSR, 2004-05-16
730 (declaim (inline square))
732 (declare (double-float x))
735 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
737 ;;; If you have these functions in libm, perhaps they should be used
738 ;;; instead of these Lisp versions. These versions are probably good
739 ;;; enough, especially since they are portable.
741 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
742 ;;; the underlying floating-point format.)
743 (declaim (inline scalb))
745 (declare (type double-float x)
746 (type double-float-exponent n))
749 ;;; This is like LOGB, but X is not infinity and non-zero and not a
750 ;;; NaN, so we can always return an integer.
751 (declaim (inline logb-finite))
752 (defun logb-finite (x)
753 (declare (type double-float x))
754 (multiple-value-bind (signif exponent sign)
756 (declare (ignore signif sign))
757 ;; DECODE-FLOAT is almost right, except that the exponent is off
761 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
762 ;;; For the special cases, the following values are used:
765 ;;; +/- infinity +infinity
768 (declare (type double-float x))
769 (cond ((float-nan-p x)
771 ((float-infinity-p x)
772 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
773 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
775 ;; The answer is negative infinity, but we are supposed to
776 ;; signal divide-by-zero, so do the actual division
782 ;;; This function is used to create a complex number of the
783 ;;; appropriate type:
784 ;;; Create complex number with real part X and imaginary part Y
785 ;;; such that has the same type as Z. If Z has type (complex
786 ;;; rational), the X and Y are coerced to single-float.
787 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
788 (error "needs work for long float support"))
789 (declaim (inline coerce-to-complex-type))
790 (defun coerce-to-complex-type (x y z)
791 (declare (double-float x y)
793 (if (typep (realpart z) 'double-float)
795 ;; Convert anything that's not already a DOUBLE-FLOAT (because
796 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
797 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
798 (complex (float x 1f0)
801 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
802 ;;; result is r + i*k, where k is an integer.
803 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
804 (error "needs work for long float support"))
806 (let ((x (float (realpart z) 1d0))
807 (y (float (imagpart z) 1d0)))
808 ;; Would this be better handled using an exception handler to
809 ;; catch the overflow or underflow signal? For now, we turn all
810 ;; traps off and look at the accrued exceptions to see if any
811 ;; signal would have been raised.
812 (with-float-traps-masked (:underflow :overflow)
813 (let ((rho (+ (square x) (square y))))
814 (declare (optimize (speed 3) (space 0)))
815 (cond ((and (or (float-nan-p rho)
816 (float-infinity-p rho))
817 (or (float-infinity-p (abs x))
818 (float-infinity-p (abs y))))
819 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
821 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
823 ((let ((threshold #.(/ least-positive-double-float
824 double-float-epsilon))
825 (traps (ldb sb!vm::float-sticky-bits
826 (sb!vm:floating-point-modes))))
827 ;; Overflow raised or (underflow raised and rho <
829 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
830 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
833 ;; If we're here, neither x nor y are infinity and at
834 ;; least one is non-zero.. Thus logb returns a nice
836 (let ((k (- (logb-finite (max (abs x) (abs y))))))
837 (values (+ (square (scalb x k))
838 (square (scalb y k)))
843 ;;; principal square root of Z
845 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
846 (defun complex-sqrt (z)
847 ;; KLUDGE: Here and below, we can't just declare Z to be of type
848 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
849 ;; Since there isn't a rational negative zero, this is OK from the
850 ;; point of view of getting the right answer in the face of branch
851 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
852 ;; still ugly. -- CSR, 2004-05-16
853 (declare (type (or complex rational) z))
854 (multiple-value-bind (rho k)
856 (declare (type (or (member 0d0) (double-float 0d0)) rho)
858 (let ((x (float (realpart z) 1.0d0))
859 (y (float (imagpart z) 1.0d0))
862 (declare (double-float x y eta nu))
865 ;; space 0 to get maybe-inline functions inlined.
866 (declare (optimize (speed 3) (space 0)))
868 (if (not (float-nan-p x))
869 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
874 (setf k (1- (ash k -1)))
875 (setf rho (+ rho rho))))
877 (setf rho (scalb (sqrt rho) k))
883 (when (not (float-infinity-p (abs nu)))
884 (setf nu (/ (/ nu rho) 2d0)))
887 (setf nu (float-sign y rho))))
888 (coerce-to-complex-type eta nu z)))))
890 ;;; Compute log(2^j*z).
892 ;;; This is for use with J /= 0 only when |z| is huge.
893 (defun complex-log-scaled (z j)
894 (declare (type (or rational complex) z)
896 ;; The constants t0, t1, t2 should be evaluated to machine
897 ;; precision. In addition, Kahan says the accuracy of log1p
898 ;; influences the choices of these constants but doesn't say how to
899 ;; choose them. We'll just assume his choices matches our
900 ;; implementation of log1p.
901 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
905 (x (float (realpart z) 1.0d0))
906 (y (float (imagpart z) 1.0d0)))
907 (multiple-value-bind (rho k)
909 (declare (optimize (speed 3)))
910 (let ((beta (max (abs x) (abs y)))
911 (theta (min (abs x) (abs y))))
912 (coerce-to-complex-type (if (and (zerop k)
916 (/ (%log1p (+ (* (- beta 1.0d0)
925 ;;; log of Z = log |Z| + i * arg Z
927 ;;; Z may be any number, but the result is always a complex.
928 (defun complex-log (z)
929 (declare (type (or rational complex) z))
930 (complex-log-scaled z 0))
932 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
933 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
934 ;;; The reason for the imaginary part is caused by the fact that arg
935 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
936 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
937 (defun complex-atanh (z)
938 (declare (type (or rational complex) z))
940 (theta (/ (sqrt most-positive-double-float) 4.0d0))
941 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
942 (half-pi (/ pi 2.0d0))
943 (rp (float (realpart z) 1.0d0))
944 (beta (float-sign rp 1.0d0))
946 (y (* beta (- (float (imagpart z) 1.0d0))))
949 ;; Shouldn't need this declare.
950 (declare (double-float x y))
952 (declare (optimize (speed 3)))
953 (cond ((or (> x theta)
955 ;; To avoid overflow...
956 (setf nu (float-sign y half-pi))
957 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
958 ;; which can cause overflow. Arrange this computation so
959 ;; that it won't overflow.
960 (setf eta (let* ((x-bigger (> x (abs y)))
961 (r (if x-bigger (/ y x) (/ x y)))
962 (d (+ 1.0d0 (* r r))))
967 ;; Should this be changed so that if y is zero, eta is set
968 ;; to +infinity instead of approx 176? In any case
969 ;; tanh(176) is 1.0d0 within working precision.
970 (let ((t1 (+ 4d0 (square y)))
971 (t2 (+ (abs y) rho)))
972 (setf eta (log (/ (sqrt (sqrt t1))
976 (+ half-pi (atan (* 0.5d0 t2))))))))
978 (let ((t1 (+ (abs y) rho)))
979 ;; Normal case using log1p(x) = log(1 + x)
981 (%log1p (/ (* 4.0d0 x)
982 (+ (square (- 1.0d0 x))
989 (coerce-to-complex-type (* beta eta)
993 ;;; Compute tanh z = sinh z / cosh z.
994 (defun complex-tanh (z)
995 (declare (type (or rational complex) z))
996 (let ((x (float (realpart z) 1.0d0))
997 (y (float (imagpart z) 1.0d0)))
999 ;; space 0 to get maybe-inline functions inlined
1000 (declare (optimize (speed 3) (space 0)))
1002 ;; FIXME: this form is hideously broken wrt
1003 ;; cross-compilation portability. Much else in this
1004 ;; file is too, of course, sometimes hidden by
1005 ;; constant-folding, but this one in particular clearly
1006 ;; depends on host and target
1007 ;; MOST-POSITIVE-DOUBLE-FLOATs being equal. -- CSR,
1010 (log most-positive-double-float))
1012 (coerce-to-complex-type (float-sign x)
1015 (let* ((tv (%tan y))
1016 (beta (+ 1.0d0 (* tv tv)))
1018 (rho (sqrt (+ 1.0d0 (* s s)))))
1019 (if (float-infinity-p (abs tv))
1020 (coerce-to-complex-type (/ rho s)
1023 (let ((den (+ 1.0d0 (* beta s s))))
1024 (coerce-to-complex-type (/ (* beta rho s)
1029 ;;; Compute acos z = pi/2 - asin z.
1031 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1032 (defun complex-acos (z)
1033 ;; Kahan says we should only compute the parts needed. Thus, the
1034 ;; REALPART's below should only compute the real part, not the whole
1035 ;; complex expression. Doing this can be important because we may get
1036 ;; spurious signals that occur in the part that we are not using.
1038 ;; However, we take a pragmatic approach and just use the whole
1041 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1042 ;; it's the conjugate of the square root or the square root of the
1043 ;; conjugate. This needs to be checked.
1045 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1046 ;; same as (sqrt (conjugate z)) for all z. This follows because
1048 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1050 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1052 ;; and these two expressions are equal if and only if arg conj z =
1053 ;; -arg z, which is clearly true for all z.
1054 (declare (type (or rational complex) z))
1055 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
1056 (sqrt-1-z (complex-sqrt (- 1 z))))
1057 (with-float-traps-masked (:divide-by-zero)
1058 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1059 (realpart sqrt-1+z))))
1060 (asinh (imagpart (* (conjugate sqrt-1+z)
1063 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1065 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1066 (defun complex-acosh (z)
1067 (declare (type (or rational complex) z))
1068 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1069 (sqrt-z+1 (complex-sqrt (+ z 1))))
1070 (with-float-traps-masked (:divide-by-zero)
1071 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1073 (* 2 (atan (/ (imagpart sqrt-z-1)
1074 (realpart sqrt-z+1))))))))
1076 ;;; Compute asin z = asinh(i*z)/i.
1078 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1079 (defun complex-asin (z)
1080 (declare (type (or rational complex) z))
1081 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1082 (sqrt-1+z (complex-sqrt (+ 1 z))))
1083 (with-float-traps-masked (:divide-by-zero)
1084 (complex (atan (/ (realpart z)
1085 (realpart (* sqrt-1-z sqrt-1+z))))
1086 (asinh (imagpart (* (conjugate sqrt-1-z)
1089 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1091 ;;; Z may be any number, but the result is always a complex.
1092 (defun complex-asinh (z)
1093 (declare (type (or rational complex) z))
1094 ;; asinh z = -i * asin (i*z)
1095 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1096 (result (complex-asin iz)))
1097 (complex (imagpart result)
1098 (- (realpart result)))))
1100 ;;; Compute atan z = atanh (i*z) / i.
1102 ;;; Z may be any number, but the result is always a complex.
1103 (defun complex-atan (z)
1104 (declare (type (or rational complex) z))
1105 ;; atan z = -i * atanh (i*z)
1106 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1107 (result (complex-atanh iz)))
1108 (complex (imagpart result)
1109 (- (realpart result)))))
1111 ;;; Compute tan z = -i * tanh(i * z)
1113 ;;; Z may be any number, but the result is always a complex.
1114 (defun complex-tan (z)
1115 (declare (type (or rational complex) z))
1116 ;; tan z = -i * tanh(i*z)
1117 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1118 (result (complex-tanh iz)))
1119 (complex (imagpart result)
1120 (- (realpart result)))))