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)))
27 (args (loop for i below num-args
28 collect (intern (format nil "ARG~D" i)))))
30 (declaim (inline ,function))
31 (defun ,function ,args
34 (function double-float
35 ,@(loop repeat num-args
36 collect 'double-float)))
39 (defun handle-reals (function var)
40 `((((foreach fixnum single-float bignum ratio))
41 (coerce (,function (coerce ,var 'double-float)) 'single-float))
47 #!+x86 ;; for constant folding
48 (macrolet ((def (name ll)
49 `(defun ,name ,ll (,name ,@ll))))
62 #!+x86-64 ;; for constant folding
63 (macrolet ((def (name ll)
64 `(defun ,name ,ll (,name ,@ll))))
67 ;;;; stubs for the Unix math library
69 ;;;; Many of these are unnecessary on the X86 because they're built
73 #!-x86 (def-math-rtn "sin" 1)
74 #!-x86 (def-math-rtn "cos" 1)
75 #!-x86 (def-math-rtn "tan" 1)
76 #!-x86 (def-math-rtn "atan" 1)
77 #!-x86 (def-math-rtn "atan2" 2)
80 (def-math-rtn "acos" 1)
81 (def-math-rtn "asin" 1)
82 (def-math-rtn "cosh" 1)
83 (def-math-rtn "sinh" 1)
84 (def-math-rtn "tanh" 1)
85 (def-math-rtn "asinh" 1)
86 (def-math-rtn "acosh" 1)
87 (def-math-rtn "atanh" 1))
90 (declaim (inline %asin))
92 (%atan (/ number (sqrt (- 1 (* number number))))))
93 (declaim (inline %acos))
95 (- (/ pi 2) (%asin number)))
96 (declaim (inline %cosh))
98 (/ (+ (exp number) (exp (- number))) 2))
99 (declaim (inline %sinh))
100 (defun %sinh (number)
101 (/ (- (exp number) (exp (- number))) 2))
102 (declaim (inline %tanh))
103 (defun %tanh (number)
104 (/ (%sinh number) (%cosh number)))
105 (declaim (inline %asinh))
106 (defun %asinh (number)
107 (log (+ number (sqrt (+ (* number number) 1.0d0))) #.(exp 1.0d0)))
108 (declaim (inline %acosh))
109 (defun %acosh (number)
110 (log (+ number (sqrt (- (* number number) 1.0d0))) #.(exp 1.0d0)))
111 (declaim (inline %atanh))
112 (defun %atanh (number)
113 (let ((ratio (/ (+ 1 number) (- 1 number))))
114 ;; Were we effectively zero?
117 (/ (log ratio #.(exp 1.0d0)) 2.0d0)))))
119 ;;; exponential and logarithmic
120 #!-x86 (def-math-rtn "exp" 1)
121 #!-x86 (def-math-rtn "log" 1)
122 #!-x86 (def-math-rtn "log10" 1)
123 #!-win32(def-math-rtn "pow" 2)
124 #!-(or x86 x86-64) (def-math-rtn "sqrt" 1)
125 #!-win32 (def-math-rtn "hypot" 2)
126 #!-x86 (def-math-rtn "log1p" 1)
130 ;; FIXME: libc hypot "computes the sqrt(x*x+y*y) without undue overflow or underflow"
131 ;; ...we just do the stupid simple thing.
132 (declaim (inline %hypot))
134 (sqrt (+ (* x x) (* y y)))))
140 "Return e raised to the power NUMBER."
141 (number-dispatch ((number number))
142 (handle-reals %exp number)
144 (* (exp (realpart number))
145 (cis (imagpart number))))))
147 ;;; INTEXP -- Handle the rational base, integer power case.
149 (declaim (type (or integer null) *intexp-maximum-exponent*))
150 (defparameter *intexp-maximum-exponent* nil)
152 ;;; This function precisely calculates base raised to an integral
153 ;;; power. It separates the cases by the sign of power, for efficiency
154 ;;; reasons, as powers can be calculated more efficiently if power is
155 ;;; a positive integer. Values of power are calculated as positive
156 ;;; integers, and inverted if negative.
157 (defun intexp (base power)
158 (when (and *intexp-maximum-exponent*
159 (> (abs power) *intexp-maximum-exponent*))
160 (error "The absolute value of ~S exceeds ~S."
161 power '*intexp-maximum-exponent*))
162 (cond ((minusp power)
163 (/ (intexp base (- power))))
167 (do ((nextn (ash power -1) (ash power -1))
168 (total (if (oddp power) base 1)
169 (if (oddp power) (* base total) total)))
170 ((zerop nextn) total)
171 (setq base (* base base))
172 (setq power nextn)))))
174 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
175 ;;; floating point stuff. If both args are real, we try %POW right
176 ;;; off, assuming it will return 0 if the result may be complex. If
177 ;;; so, we call COMPLEX-POW which directly computes the complex
178 ;;; result. We also separate the complex-real and real-complex cases
179 ;;; from the general complex case.
180 (defun expt (base power)
182 "Return BASE raised to the POWER."
184 (if (and (zerop base) (floatp power))
185 (error 'arguments-out-of-domain-error
186 :operands (list base power)
188 :references (list '(:ansi-cl :function expt)))
189 (let ((result (1+ (* base power))))
190 (if (and (floatp result) (float-nan-p result))
193 (labels (;; determine if the double float is an integer.
194 ;; 0 - not an integer
198 (declare (type (unsigned-byte 31) ihi)
199 (type (unsigned-byte 32) lo)
200 (optimize (speed 3) (safety 0)))
202 (declare (type fixnum isint))
203 (cond ((>= ihi #x43400000) ; exponent >= 53
206 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
207 (declare (type (mod 53) k))
209 (let* ((shift (- 52 k))
210 (j (logand (ash lo (- shift))))
212 (declare (type (mod 32) shift)
213 (type (unsigned-byte 32) j j2))
215 (setq isint (- 2 (logand j 1))))))
217 (let* ((shift (- 20 k))
218 (j (ash ihi (- shift)))
220 (declare (type (mod 32) shift)
221 (type (unsigned-byte 31) j j2))
223 (setq isint (- 2 (logand j 1))))))))))
225 (real-expt (x y rtype)
226 (let ((x (coerce x 'double-float))
227 (y (coerce y 'double-float)))
228 (declare (double-float x y))
229 (let* ((x-hi (sb!kernel:double-float-high-bits x))
230 (x-lo (sb!kernel:double-float-low-bits x))
231 (x-ihi (logand x-hi #x7fffffff))
232 (y-hi (sb!kernel:double-float-high-bits y))
233 (y-lo (sb!kernel:double-float-low-bits y))
234 (y-ihi (logand y-hi #x7fffffff)))
235 (declare (type (signed-byte 32) x-hi y-hi)
236 (type (unsigned-byte 31) x-ihi y-ihi)
237 (type (unsigned-byte 32) x-lo y-lo))
239 (when (zerop (logior y-ihi y-lo))
240 (return-from real-expt (coerce 1d0 rtype)))
242 ;; FIXME: Hardcoded qNaN/sNaN values are not portable.
243 (when (or (> x-ihi #x7ff00000)
244 (and (= x-ihi #x7ff00000) (/= x-lo 0))
246 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
247 (return-from real-expt (coerce (+ x y) rtype)))
248 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
249 (declare (type fixnum yisint))
250 ;; special value of y
251 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
253 (return-from real-expt
254 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
256 (coerce (- y y) rtype))
257 ((>= x-ihi #x3ff00000)
258 ;; (|x|>1)**+-inf = inf,0
263 ;; (|x|<1)**-,+inf = inf,0
266 (coerce 0 rtype))))))
268 (let ((abs-x (abs x)))
269 (declare (double-float abs-x))
270 ;; special value of x
271 (when (and (zerop x-lo)
272 (or (= x-ihi #x7ff00000) (zerop x-ihi)
273 (= x-ihi #x3ff00000)))
274 ;; x is +-0,+-inf,+-1
275 (let ((z (if (< y-hi 0)
276 (/ 1 abs-x) ; z = (1/|x|)
278 (declare (double-float z))
280 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
282 (let ((y*pi (* y pi)))
283 (declare (double-float y*pi))
284 (return-from real-expt
286 (coerce (%cos y*pi) rtype)
287 (coerce (%sin y*pi) rtype)))))
289 ;; (x<0)**odd = -(|x|**odd)
291 (return-from real-expt (coerce z rtype))))
295 (coerce (sb!kernel::%pow x y) rtype)
297 (let ((pow (sb!kernel::%pow abs-x y)))
298 (declare (double-float pow))
301 (coerce (* -1d0 pow) rtype))
305 (let ((y*pi (* y pi)))
306 (declare (double-float y*pi))
308 (coerce (* pow (%cos y*pi))
310 (coerce (* pow (%sin y*pi))
312 (declare (inline real-expt))
313 (number-dispatch ((base number) (power number))
314 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
316 (((foreach single-float double-float) rational)
317 (real-expt base power '(dispatch-type base)))
318 (((foreach fixnum (or bignum ratio) single-float)
319 (foreach ratio single-float))
320 (real-expt base power 'single-float))
321 (((foreach fixnum (or bignum ratio) single-float double-float)
323 (real-expt base power 'double-float))
324 ((double-float single-float)
325 (real-expt base power 'double-float))
326 (((foreach (complex rational) (complex float)) rational)
327 (* (expt (abs base) power)
328 (cis (* power (phase base)))))
329 (((foreach fixnum (or bignum ratio) single-float double-float)
331 (if (and (zerop base) (plusp (realpart power)))
333 (exp (* power (log base)))))
334 (((foreach (complex float) (complex rational))
335 (foreach complex double-float single-float))
336 (if (and (zerop base) (plusp (realpart power)))
338 (exp (* power (log base)))))))))
340 ;;; FIXME: Maybe rename this so that it's clearer that it only works
343 (declare (type integer x))
346 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
347 ;; log2(f). So we grab the top few bits of x and scale that
348 ;; appropriately, take the log of it and add it to n.
350 ;; Motivated by an attempt to get LOG to work better on bignums.
351 (let ((n (integer-length x)))
352 (if (< n sb!vm:double-float-digits)
353 (log (coerce x 'double-float) 2.0d0)
354 (let ((f (ldb (byte sb!vm:double-float-digits
355 (- n sb!vm:double-float-digits))
357 (+ n (log (scale-float (coerce f 'double-float)
358 (- sb!vm:double-float-digits))
361 (defun log (number &optional (base nil base-p))
363 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
367 (if (or (typep number 'double-float) (typep base 'double-float))
370 ((and (typep number '(integer (0) *))
371 (typep base '(integer (0) *)))
372 (coerce (/ (log2 number) (log2 base)) 'single-float))
373 ((and (typep number 'integer) (typep base 'double-float))
374 ;; No single float intermediate result
375 (/ (log2 number) (log base 2.0d0)))
376 ((and (typep number 'double-float) (typep base 'integer))
377 (/ (log number 2.0d0) (log2 base)))
379 (/ (log number) (log base))))
380 (number-dispatch ((number number))
381 (((foreach fixnum bignum))
383 (complex (log (- number)) (coerce pi 'single-float))
384 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
387 (complex (log (- number)) (coerce pi 'single-float))
388 (let ((numerator (numerator number))
389 (denominator (denominator number)))
390 (if (= (integer-length numerator)
391 (integer-length denominator))
392 (coerce (%log1p (coerce (- number 1) 'double-float))
394 (coerce (/ (- (log2 numerator) (log2 denominator))
395 (log (exp 1.0d0) 2.0d0))
397 (((foreach single-float double-float))
398 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
399 ;; Since this doesn't seem to be an implementation issue
400 ;; I (pw) take the Kahan result.
401 (if (< (float-sign number)
402 (coerce 0 '(dispatch-type number)))
403 (complex (log (- number)) (coerce pi '(dispatch-type number)))
404 (coerce (%log (coerce number 'double-float))
405 '(dispatch-type number))))
407 (complex-log number)))))
411 "Return the square root of NUMBER."
412 (number-dispatch ((number number))
413 (((foreach fixnum bignum ratio))
415 (complex-sqrt number)
416 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
417 (((foreach single-float double-float))
419 (complex-sqrt (complex number))
420 (coerce (%sqrt (coerce number 'double-float))
421 '(dispatch-type number))))
423 (complex-sqrt number))))
425 ;;;; trigonometic and related functions
429 "Return the absolute value of the number."
430 (number-dispatch ((number number))
431 (((foreach single-float double-float fixnum rational))
434 (let ((rx (realpart number))
435 (ix (imagpart number)))
438 (sqrt (+ (* rx rx) (* ix ix))))
440 (coerce (%hypot (coerce rx 'double-float)
441 (coerce ix 'double-float))
446 (defun phase (number)
448 "Return the angle part of the polar representation of a complex number.
449 For complex numbers, this is (atan (imagpart number) (realpart number)).
450 For non-complex positive numbers, this is 0. For non-complex negative
455 (coerce pi 'single-float)
458 (if (minusp (float-sign number))
459 (coerce pi 'single-float)
462 (if (minusp (float-sign number))
463 (coerce pi 'double-float)
466 (atan (imagpart number) (realpart number)))))
470 "Return the sine of NUMBER."
471 (number-dispatch ((number number))
472 (handle-reals %sin number)
474 (let ((x (realpart number))
475 (y (imagpart number)))
476 (complex (* (sin x) (cosh y))
477 (* (cos x) (sinh y)))))))
481 "Return the cosine of NUMBER."
482 (number-dispatch ((number number))
483 (handle-reals %cos number)
485 (let ((x (realpart number))
486 (y (imagpart number)))
487 (complex (* (cos x) (cosh y))
488 (- (* (sin x) (sinh y))))))))
492 "Return the tangent of NUMBER."
493 (number-dispatch ((number number))
494 (handle-reals %tan number)
496 (complex-tan number))))
500 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
501 (declare (type real theta))
502 (complex (cos theta) (sin theta)))
506 "Return the arc sine of NUMBER."
507 (number-dispatch ((number number))
509 (if (or (> number 1) (< number -1))
510 (complex-asin number)
511 (coerce (%asin (coerce number 'double-float)) 'single-float)))
512 (((foreach single-float double-float))
513 (if (or (> number (coerce 1 '(dispatch-type number)))
514 (< number (coerce -1 '(dispatch-type number))))
515 (complex-asin (complex number))
516 (coerce (%asin (coerce number 'double-float))
517 '(dispatch-type number))))
519 (complex-asin number))))
523 "Return the arc cosine of NUMBER."
524 (number-dispatch ((number number))
526 (if (or (> number 1) (< number -1))
527 (complex-acos number)
528 (coerce (%acos (coerce number 'double-float)) 'single-float)))
529 (((foreach single-float double-float))
530 (if (or (> number (coerce 1 '(dispatch-type number)))
531 (< number (coerce -1 '(dispatch-type number))))
532 (complex-acos (complex number))
533 (coerce (%acos (coerce number 'double-float))
534 '(dispatch-type number))))
536 (complex-acos number))))
538 (defun atan (y &optional (x nil xp))
540 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
543 (declare (type double-float y x)
544 (values double-float))
547 (if (plusp (float-sign x))
550 (float-sign y (/ pi 2)))
552 (number-dispatch ((y real) (x real))
554 (foreach double-float single-float fixnum bignum ratio))
555 (atan2 y (coerce x 'double-float)))
556 (((foreach single-float fixnum bignum ratio)
558 (atan2 (coerce y 'double-float) x))
559 (((foreach single-float fixnum bignum ratio)
560 (foreach single-float fixnum bignum ratio))
561 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
563 (number-dispatch ((y number))
564 (handle-reals %atan y)
568 ;;; It seems that every target system has a C version of sinh, cosh,
569 ;;; and tanh. Let's use these for reals because the original
570 ;;; implementations based on the definitions lose big in round-off
571 ;;; error. These bad definitions also mean that sin and cos for
572 ;;; complex numbers can also lose big.
576 "Return the hyperbolic sine of NUMBER."
577 (number-dispatch ((number number))
578 (handle-reals %sinh number)
580 (let ((x (realpart number))
581 (y (imagpart number)))
582 (complex (* (sinh x) (cos y))
583 (* (cosh x) (sin y)))))))
587 "Return the hyperbolic cosine of NUMBER."
588 (number-dispatch ((number number))
589 (handle-reals %cosh number)
591 (let ((x (realpart number))
592 (y (imagpart number)))
593 (complex (* (cosh x) (cos y))
594 (* (sinh x) (sin y)))))))
598 "Return the hyperbolic tangent of NUMBER."
599 (number-dispatch ((number number))
600 (handle-reals %tanh number)
602 (complex-tanh number))))
604 (defun asinh (number)
606 "Return the hyperbolic arc sine of NUMBER."
607 (number-dispatch ((number number))
608 (handle-reals %asinh number)
610 (complex-asinh number))))
612 (defun acosh (number)
614 "Return the hyperbolic arc cosine of NUMBER."
615 (number-dispatch ((number number))
617 ;; acosh is complex if number < 1
619 (complex-acosh number)
620 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
621 (((foreach single-float double-float))
622 (if (< number (coerce 1 '(dispatch-type number)))
623 (complex-acosh (complex number))
624 (coerce (%acosh (coerce number 'double-float))
625 '(dispatch-type number))))
627 (complex-acosh number))))
629 (defun atanh (number)
631 "Return the hyperbolic arc tangent of NUMBER."
632 (number-dispatch ((number number))
634 ;; atanh is complex if |number| > 1
635 (if (or (> number 1) (< number -1))
636 (complex-atanh number)
637 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
638 (((foreach single-float double-float))
639 (if (or (> number (coerce 1 '(dispatch-type number)))
640 (< number (coerce -1 '(dispatch-type number))))
641 (complex-atanh (complex number))
642 (coerce (%atanh (coerce number 'double-float))
643 '(dispatch-type number))))
645 (complex-atanh number))))
648 ;;;; not-OLD-SPECFUN stuff
650 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
651 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
652 ;;;; the standard special function system.)
654 ;;;; This is a set of routines that implement many elementary
655 ;;;; transcendental functions as specified by ANSI Common Lisp. The
656 ;;;; implementation is based on Kahan's paper.
658 ;;;; I believe I have accurately implemented the routines and are
659 ;;;; correct, but you may want to check for your self.
661 ;;;; These functions are written for CMU Lisp and take advantage of
662 ;;;; some of the features available there. It may be possible,
663 ;;;; however, to port this to other Lisps.
665 ;;;; Some functions are significantly more accurate than the original
666 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
667 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
668 ;;;; answer is pi + i*log(2-sqrt(3)).
670 ;;;; All of the implemented functions will take any number for an
671 ;;;; input, but the result will always be a either a complex
672 ;;;; single-float or a complex double-float.
674 ;;;; general functions:
686 ;;;; utility functions:
689 ;;;; internal functions:
690 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
693 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
694 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
695 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
698 ;;;; The original CMU CL code requested:
699 ;;;; Please send any bug reports, comments, or improvements to
700 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
702 ;;; FIXME: In SBCL, the floating point infinity constants like
703 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
704 ;;; constants at cross-compile time, because the cross-compilation
705 ;;; host might not have support for floating point infinities. Thus,
706 ;;; they're effectively implemented as special variable references,
707 ;;; and the code below which uses them might be unnecessarily
708 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
709 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
710 ;;; special variable references with (probably equally slow)
713 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
714 ;;; differ in their interpretations of the real line, IMAGPART was
715 ;;; patch, which without a certain amount of effort would have altered
716 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
717 ;;; were patched to use explicit COMPLEX, rather than implicitly
718 ;;; passing in real numbers for treatment with IMAGPART, and these
719 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
720 ;;; however, someone needs to go back to Kahan for the definitive
721 ;;; answer for treatment of negative real floating point numbers and
722 ;;; branch cuts. If adjustment is needed, it is probably the removal
723 ;;; of explicit calls to COMPLEX in the clients of irrational
724 ;;; functions. -- a slightly bitter CSR, 2004-05-16
726 (declaim (inline square))
728 (declare (double-float x))
731 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
733 ;;; If you have these functions in libm, perhaps they should be used
734 ;;; instead of these Lisp versions. These versions are probably good
735 ;;; enough, especially since they are portable.
737 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
738 ;;; the underlying floating-point format.)
739 (declaim (inline scalb))
741 (declare (type double-float x)
742 (type double-float-exponent n))
745 ;;; This is like LOGB, but X is not infinity and non-zero and not a
746 ;;; NaN, so we can always return an integer.
747 (declaim (inline logb-finite))
748 (defun logb-finite (x)
749 (declare (type double-float x))
750 (multiple-value-bind (signif exponent sign)
752 (declare (ignore signif sign))
753 ;; DECODE-FLOAT is almost right, except that the exponent is off
757 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
758 ;;; For the special cases, the following values are used:
761 ;;; +/- infinity +infinity
764 (declare (type double-float x))
765 (cond ((float-nan-p x)
767 ((float-infinity-p x)
768 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
769 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
771 ;; The answer is negative infinity, but we are supposed to
772 ;; signal divide-by-zero, so do the actual division
778 ;;; This function is used to create a complex number of the
779 ;;; appropriate type:
780 ;;; Create complex number with real part X and imaginary part Y
781 ;;; such that has the same type as Z. If Z has type (complex
782 ;;; rational), the X and Y are coerced to single-float.
783 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
784 (error "needs work for long float support"))
785 (declaim (inline coerce-to-complex-type))
786 (defun coerce-to-complex-type (x y z)
787 (declare (double-float x y)
789 (if (typep (realpart z) 'double-float)
791 ;; Convert anything that's not already a DOUBLE-FLOAT (because
792 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
793 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
794 (complex (float x 1f0)
797 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
798 ;;; result is r + i*k, where k is an integer.
799 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
800 (error "needs work for long float support"))
802 (let ((x (float (realpart z) 1d0))
803 (y (float (imagpart z) 1d0)))
804 ;; Would this be better handled using an exception handler to
805 ;; catch the overflow or underflow signal? For now, we turn all
806 ;; traps off and look at the accrued exceptions to see if any
807 ;; signal would have been raised.
808 (with-float-traps-masked (:underflow :overflow)
809 (let ((rho (+ (square x) (square y))))
810 (declare (optimize (speed 3) (space 0)))
811 (cond ((and (or (float-nan-p rho)
812 (float-infinity-p rho))
813 (or (float-infinity-p (abs x))
814 (float-infinity-p (abs y))))
815 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
817 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
820 ;; (/ least-positive-double-float double-float-epsilon)
823 (sb!kernel:make-double-float #x1fffff #xfffffffe)
825 (error "(/ least-positive-long-float long-float-epsilon)")))
826 (traps (ldb sb!vm::float-sticky-bits
827 (sb!vm:floating-point-modes))))
828 ;; Overflow raised or (underflow raised and rho <
830 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
831 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
834 ;; If we're here, neither x nor y are infinity and at
835 ;; least one is non-zero.. Thus logb returns a nice
837 (let ((k (- (logb-finite (max (abs x) (abs y))))))
838 (values (+ (square (scalb x k))
839 (square (scalb y k)))
844 ;;; principal square root of Z
846 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
847 (defun complex-sqrt (z)
848 ;; KLUDGE: Here and below, we can't just declare Z to be of type
849 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
850 ;; Since there isn't a rational negative zero, this is OK from the
851 ;; point of view of getting the right answer in the face of branch
852 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
853 ;; still ugly. -- CSR, 2004-05-16
854 (declare (type (or complex rational) z))
855 (multiple-value-bind (rho k)
857 (declare (type (or (member 0d0) (double-float 0d0)) rho)
859 (let ((x (float (realpart z) 1.0d0))
860 (y (float (imagpart z) 1.0d0))
863 (declare (double-float x y eta nu))
866 ;; space 0 to get maybe-inline functions inlined.
867 (declare (optimize (speed 3) (space 0)))
869 (if (not (float-nan-p x))
870 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
875 (setf k (1- (ash k -1)))
876 (setf rho (+ rho rho))))
878 (setf rho (scalb (sqrt rho) k))
884 (when (not (float-infinity-p (abs nu)))
885 (setf nu (/ (/ nu rho) 2d0)))
888 (setf nu (float-sign y rho))))
889 (coerce-to-complex-type eta nu z)))))
891 ;;; Compute log(2^j*z).
893 ;;; This is for use with J /= 0 only when |z| is huge.
894 (defun complex-log-scaled (z j)
895 (declare (type (or rational complex) z)
897 ;; The constants t0, t1, t2 should be evaluated to machine
898 ;; precision. In addition, Kahan says the accuracy of log1p
899 ;; influences the choices of these constants but doesn't say how to
900 ;; choose them. We'll just assume his choices matches our
901 ;; implementation of log1p.
902 (let ((t0 (load-time-value
904 (sb!kernel:make-double-float #x3fe6a09e #x667f3bcd)
906 (error "(/ (sqrt 2l0))")))
907 ;; KLUDGE: if repeatable fasls start failing under some weird
908 ;; xc host, this 1.2d0 might be a good place to examine: while
909 ;; it _should_ be the same in all vaguely-IEEE754 hosts, 1.2
910 ;; is not exactly representable, so something could go wrong.
913 (ln2 (load-time-value
915 (sb!kernel:make-double-float #x3fe62e42 #xfefa39ef)
917 (error "(log 2l0)")))
918 (x (float (realpart z) 1.0d0))
919 (y (float (imagpart z) 1.0d0)))
920 (multiple-value-bind (rho k)
922 (declare (optimize (speed 3)))
923 (let ((beta (max (abs x) (abs y)))
924 (theta (min (abs x) (abs y))))
925 (coerce-to-complex-type (if (and (zerop k)
929 (/ (%log1p (+ (* (- beta 1.0d0)
938 ;;; log of Z = log |Z| + i * arg Z
940 ;;; Z may be any number, but the result is always a complex.
941 (defun complex-log (z)
942 (declare (type (or rational complex) z))
943 (complex-log-scaled z 0))
945 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
946 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
947 ;;; The reason for the imaginary part is caused by the fact that arg
948 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
949 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
950 (defun complex-atanh (z)
951 (declare (type (or rational complex) z))
953 (theta (/ (sqrt most-positive-double-float) 4.0d0))
954 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
955 (half-pi (/ pi 2.0d0))
956 (rp (float (realpart z) 1.0d0))
957 (beta (float-sign rp 1.0d0))
959 (y (* beta (- (float (imagpart z) 1.0d0))))
962 ;; Shouldn't need this declare.
963 (declare (double-float x y))
965 (declare (optimize (speed 3)))
966 (cond ((or (> x theta)
968 ;; To avoid overflow...
969 (setf nu (float-sign y half-pi))
970 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
971 ;; which can cause overflow. Arrange this computation so
972 ;; that it won't overflow.
973 (setf eta (let* ((x-bigger (> x (abs y)))
974 (r (if x-bigger (/ y x) (/ x y)))
975 (d (+ 1.0d0 (* r r))))
980 ;; Should this be changed so that if y is zero, eta is set
981 ;; to +infinity instead of approx 176? In any case
982 ;; tanh(176) is 1.0d0 within working precision.
983 (let ((t1 (+ 4d0 (square y)))
984 (t2 (+ (abs y) rho)))
985 (setf eta (log (/ (sqrt (sqrt t1))
989 (+ half-pi (atan (* 0.5d0 t2))))))))
991 (let ((t1 (+ (abs y) rho)))
992 ;; Normal case using log1p(x) = log(1 + x)
994 (%log1p (/ (* 4.0d0 x)
995 (+ (square (- 1.0d0 x))
1002 (coerce-to-complex-type (* beta eta)
1006 ;;; Compute tanh z = sinh z / cosh z.
1007 (defun complex-tanh (z)
1008 (declare (type (or rational complex) z))
1009 (let ((x (float (realpart z) 1.0d0))
1010 (y (float (imagpart z) 1.0d0)))
1012 ;; space 0 to get maybe-inline functions inlined
1013 (declare (optimize (speed 3) (space 0)))
1017 (sb!kernel:make-double-float #x406633ce #x8fb9f87e)
1019 (error "(/ (+ (log 2l0) (log most-positive-long-float)) 4l0)")))
1020 (coerce-to-complex-type (float-sign x)
1023 (let* ((tv (%tan y))
1024 (beta (+ 1.0d0 (* tv tv)))
1026 (rho (sqrt (+ 1.0d0 (* s s)))))
1027 (if (float-infinity-p (abs tv))
1028 (coerce-to-complex-type (/ rho s)
1031 (let ((den (+ 1.0d0 (* beta s s))))
1032 (coerce-to-complex-type (/ (* beta rho s)
1037 ;;; Compute acos z = pi/2 - asin z.
1039 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1040 (defun complex-acos (z)
1041 ;; Kahan says we should only compute the parts needed. Thus, the
1042 ;; REALPART's below should only compute the real part, not the whole
1043 ;; complex expression. Doing this can be important because we may get
1044 ;; spurious signals that occur in the part that we are not using.
1046 ;; However, we take a pragmatic approach and just use the whole
1049 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1050 ;; it's the conjugate of the square root or the square root of the
1051 ;; conjugate. This needs to be checked.
1053 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1054 ;; same as (sqrt (conjugate z)) for all z. This follows because
1056 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1058 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1060 ;; and these two expressions are equal if and only if arg conj z =
1061 ;; -arg z, which is clearly true for all z.
1062 (declare (type (or rational complex) z))
1063 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
1064 (sqrt-1-z (complex-sqrt (- 1 z))))
1065 (with-float-traps-masked (:divide-by-zero)
1066 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1067 (realpart sqrt-1+z))))
1068 (asinh (imagpart (* (conjugate sqrt-1+z)
1071 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1073 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1074 (defun complex-acosh (z)
1075 (declare (type (or rational complex) z))
1076 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1077 (sqrt-z+1 (complex-sqrt (+ z 1))))
1078 (with-float-traps-masked (:divide-by-zero)
1079 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1081 (* 2 (atan (/ (imagpart sqrt-z-1)
1082 (realpart sqrt-z+1))))))))
1084 ;;; Compute asin z = asinh(i*z)/i.
1086 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1087 (defun complex-asin (z)
1088 (declare (type (or rational complex) z))
1089 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1090 (sqrt-1+z (complex-sqrt (+ 1 z))))
1091 (with-float-traps-masked (:divide-by-zero)
1092 (complex (atan (/ (realpart z)
1093 (realpart (* sqrt-1-z sqrt-1+z))))
1094 (asinh (imagpart (* (conjugate sqrt-1-z)
1097 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1099 ;;; Z may be any number, but the result is always a complex.
1100 (defun complex-asinh (z)
1101 (declare (type (or rational complex) z))
1102 ;; asinh z = -i * asin (i*z)
1103 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1104 (result (complex-asin iz)))
1105 (complex (imagpart result)
1106 (- (realpart result)))))
1108 ;;; Compute atan z = atanh (i*z) / i.
1110 ;;; Z may be any number, but the result is always a complex.
1111 (defun complex-atan (z)
1112 (declare (type (or rational complex) z))
1113 ;; atan z = -i * atanh (i*z)
1114 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1115 (result (complex-atanh iz)))
1116 (complex (imagpart result)
1117 (- (realpart result)))))
1119 ;;; Compute tan z = -i * tanh(i * z)
1121 ;;; Z may be any number, but the result is always a complex.
1122 (defun complex-tan (z)
1123 (declare (type (or rational complex) z))
1124 ;; tan z = -i * tanh(i*z)
1125 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1126 (result (complex-tanh iz)))
1127 (complex (imagpart result)
1128 (- (realpart result)))))