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 #!-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 (if (and (zerop base) (floatp power))
182 (error 'arguments-out-of-domain-error
183 :operands (list base power)
185 :references (list '(:ansi-cl :function expt)))
186 (let ((result (1+ (* base power))))
187 (if (and (floatp result) (float-nan-p result))
190 (labels (;; determine if the double float is an integer.
191 ;; 0 - not an integer
195 (declare (type (unsigned-byte 31) ihi)
196 (type (unsigned-byte 32) lo)
197 (optimize (speed 3) (safety 0)))
199 (declare (type fixnum isint))
200 (cond ((>= ihi #x43400000) ; exponent >= 53
203 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
204 (declare (type (mod 53) k))
206 (let* ((shift (- 52 k))
207 (j (logand (ash lo (- shift))))
209 (declare (type (mod 32) shift)
210 (type (unsigned-byte 32) j j2))
212 (setq isint (- 2 (logand j 1))))))
214 (let* ((shift (- 20 k))
215 (j (ash ihi (- shift)))
217 (declare (type (mod 32) shift)
218 (type (unsigned-byte 31) j j2))
220 (setq isint (- 2 (logand j 1))))))))))
222 (real-expt (x y rtype)
223 (let ((x (coerce x 'double-float))
224 (y (coerce y 'double-float)))
225 (declare (double-float x y))
226 (let* ((x-hi (sb!kernel:double-float-high-bits x))
227 (x-lo (sb!kernel:double-float-low-bits x))
228 (x-ihi (logand x-hi #x7fffffff))
229 (y-hi (sb!kernel:double-float-high-bits y))
230 (y-lo (sb!kernel:double-float-low-bits y))
231 (y-ihi (logand y-hi #x7fffffff)))
232 (declare (type (signed-byte 32) x-hi y-hi)
233 (type (unsigned-byte 31) x-ihi y-ihi)
234 (type (unsigned-byte 32) x-lo y-lo))
236 (when (zerop (logior y-ihi y-lo))
237 (return-from real-expt (coerce 1d0 rtype)))
239 ;; FIXME: Hardcoded qNaN/sNaN values are not portable.
240 (when (or (> x-ihi #x7ff00000)
241 (and (= x-ihi #x7ff00000) (/= x-lo 0))
243 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
244 (return-from real-expt (coerce (+ x y) rtype)))
245 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
246 (declare (type fixnum yisint))
247 ;; special value of y
248 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
250 (return-from real-expt
251 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
253 (coerce (- y y) rtype))
254 ((>= x-ihi #x3ff00000)
255 ;; (|x|>1)**+-inf = inf,0
260 ;; (|x|<1)**-,+inf = inf,0
263 (coerce 0 rtype))))))
265 (let ((abs-x (abs x)))
266 (declare (double-float abs-x))
267 ;; special value of x
268 (when (and (zerop x-lo)
269 (or (= x-ihi #x7ff00000) (zerop x-ihi)
270 (= x-ihi #x3ff00000)))
271 ;; x is +-0,+-inf,+-1
272 (let ((z (if (< y-hi 0)
273 (/ 1 abs-x) ; z = (1/|x|)
275 (declare (double-float z))
277 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
279 (let ((y*pi (* y pi)))
280 (declare (double-float y*pi))
281 (return-from real-expt
283 (coerce (%cos y*pi) rtype)
284 (coerce (%sin y*pi) rtype)))))
286 ;; (x<0)**odd = -(|x|**odd)
288 (return-from real-expt (coerce z rtype))))
292 (coerce (sb!kernel::%pow x y) rtype)
294 (let ((pow (sb!kernel::%pow abs-x y)))
295 (declare (double-float pow))
298 (coerce (* -1d0 pow) rtype))
302 (let ((y*pi (* y pi)))
303 (declare (double-float y*pi))
305 (coerce (* pow (%cos y*pi))
307 (coerce (* pow (%sin y*pi))
309 (declare (inline real-expt))
310 (number-dispatch ((base number) (power number))
311 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
313 (((foreach single-float double-float) rational)
314 (real-expt base power '(dispatch-type base)))
315 (((foreach fixnum (or bignum ratio) single-float)
316 (foreach ratio single-float))
317 (real-expt base power 'single-float))
318 (((foreach fixnum (or bignum ratio) single-float double-float)
320 (real-expt base power 'double-float))
321 ((double-float single-float)
322 (real-expt base power 'double-float))
323 (((foreach (complex rational) (complex float)) rational)
324 (* (expt (abs base) power)
325 (cis (* power (phase base)))))
326 (((foreach fixnum (or bignum ratio) single-float double-float)
328 (if (and (zerop base) (plusp (realpart power)))
330 (exp (* power (log base)))))
331 (((foreach (complex float) (complex rational))
332 (foreach complex double-float single-float))
333 (if (and (zerop base) (plusp (realpart power)))
335 (exp (* power (log base)))))))))
337 ;;; FIXME: Maybe rename this so that it's clearer that it only works
340 (declare (type integer x))
343 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
344 ;; log2(f). So we grab the top few bits of x and scale that
345 ;; appropriately, take the log of it and add it to n.
347 ;; Motivated by an attempt to get LOG to work better on bignums.
348 (let ((n (integer-length x)))
349 (if (< n sb!vm:double-float-digits)
350 (log (coerce x 'double-float) 2.0d0)
351 (let ((f (ldb (byte sb!vm:double-float-digits
352 (- n sb!vm:double-float-digits))
354 (+ n (log (scale-float (coerce f 'double-float)
355 (- sb!vm:double-float-digits))
358 (defun log (number &optional (base nil base-p))
360 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
364 (if (or (typep number 'double-float) (typep base 'double-float))
367 ((and (typep number '(integer (0) *))
368 (typep base '(integer (0) *)))
369 (coerce (/ (log2 number) (log2 base)) 'single-float))
370 ((and (typep number 'integer) (typep base 'double-float))
371 ;; No single float intermediate result
372 (/ (log2 number) (log base 2.0d0)))
373 ((and (typep number 'double-float) (typep base 'integer))
374 (/ (log number 2.0d0) (log2 base)))
376 (/ (log number) (log base))))
377 (number-dispatch ((number number))
378 (((foreach fixnum bignum))
380 (complex (log (- number)) (coerce pi 'single-float))
381 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
384 (complex (log (- number)) (coerce pi 'single-float))
385 (let ((numerator (numerator number))
386 (denominator (denominator number)))
387 (if (= (integer-length numerator)
388 (integer-length denominator))
389 (coerce (%log1p (coerce (- number 1) 'double-float))
391 (coerce (/ (- (log2 numerator) (log2 denominator))
392 (log (exp 1.0d0) 2.0d0))
394 (((foreach single-float double-float))
395 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
396 ;; Since this doesn't seem to be an implementation issue
397 ;; I (pw) take the Kahan result.
398 (if (< (float-sign number)
399 (coerce 0 '(dispatch-type number)))
400 (complex (log (- number)) (coerce pi '(dispatch-type number)))
401 (coerce (%log (coerce number 'double-float))
402 '(dispatch-type number))))
404 (complex-log number)))))
408 "Return the square root of NUMBER."
409 (number-dispatch ((number number))
410 (((foreach fixnum bignum ratio))
412 (complex-sqrt number)
413 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
414 (((foreach single-float double-float))
416 (complex-sqrt (complex number))
417 (coerce (%sqrt (coerce number 'double-float))
418 '(dispatch-type number))))
420 (complex-sqrt number))))
422 ;;;; trigonometic and related functions
426 "Return the absolute value of the number."
427 (number-dispatch ((number number))
428 (((foreach single-float double-float fixnum rational))
431 (let ((rx (realpart number))
432 (ix (imagpart number)))
435 (sqrt (+ (* rx rx) (* ix ix))))
437 (coerce (%hypot (coerce rx 'double-float)
438 (coerce ix 'double-float))
443 (defun phase (number)
445 "Return the angle part of the polar representation of a complex number.
446 For complex numbers, this is (atan (imagpart number) (realpart number)).
447 For non-complex positive numbers, this is 0. For non-complex negative
452 (coerce pi 'single-float)
455 (if (minusp (float-sign number))
456 (coerce pi 'single-float)
459 (if (minusp (float-sign number))
460 (coerce pi 'double-float)
463 (atan (imagpart number) (realpart number)))))
467 "Return the sine of NUMBER."
468 (number-dispatch ((number number))
469 (handle-reals %sin number)
471 (let ((x (realpart number))
472 (y (imagpart number)))
473 (complex (* (sin x) (cosh y))
474 (* (cos x) (sinh y)))))))
478 "Return the cosine of NUMBER."
479 (number-dispatch ((number number))
480 (handle-reals %cos number)
482 (let ((x (realpart number))
483 (y (imagpart number)))
484 (complex (* (cos x) (cosh y))
485 (- (* (sin x) (sinh y))))))))
489 "Return the tangent of NUMBER."
490 (number-dispatch ((number number))
491 (handle-reals %tan number)
493 (complex-tan number))))
497 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
498 (declare (type real theta))
499 (complex (cos theta) (sin theta)))
503 "Return the arc sine of NUMBER."
504 (number-dispatch ((number number))
506 (if (or (> number 1) (< number -1))
507 (complex-asin number)
508 (coerce (%asin (coerce number 'double-float)) 'single-float)))
509 (((foreach single-float double-float))
510 (if (or (> number (coerce 1 '(dispatch-type number)))
511 (< number (coerce -1 '(dispatch-type number))))
512 (complex-asin (complex number))
513 (coerce (%asin (coerce number 'double-float))
514 '(dispatch-type number))))
516 (complex-asin number))))
520 "Return the arc cosine of NUMBER."
521 (number-dispatch ((number number))
523 (if (or (> number 1) (< number -1))
524 (complex-acos number)
525 (coerce (%acos (coerce number 'double-float)) 'single-float)))
526 (((foreach single-float double-float))
527 (if (or (> number (coerce 1 '(dispatch-type number)))
528 (< number (coerce -1 '(dispatch-type number))))
529 (complex-acos (complex number))
530 (coerce (%acos (coerce number 'double-float))
531 '(dispatch-type number))))
533 (complex-acos number))))
535 (defun atan (y &optional (x nil xp))
537 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
540 (declare (type double-float y x)
541 (values double-float))
544 (if (plusp (float-sign x))
547 (float-sign y (/ pi 2)))
549 (number-dispatch ((y real) (x real))
551 (foreach double-float single-float fixnum bignum ratio))
552 (atan2 y (coerce x 'double-float)))
553 (((foreach single-float fixnum bignum ratio)
555 (atan2 (coerce y 'double-float) x))
556 (((foreach single-float fixnum bignum ratio)
557 (foreach single-float fixnum bignum ratio))
558 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
560 (number-dispatch ((y number))
561 (handle-reals %atan y)
565 ;;; It seems that every target system has a C version of sinh, cosh,
566 ;;; and tanh. Let's use these for reals because the original
567 ;;; implementations based on the definitions lose big in round-off
568 ;;; error. These bad definitions also mean that sin and cos for
569 ;;; complex numbers can also lose big.
573 "Return the hyperbolic sine of NUMBER."
574 (number-dispatch ((number number))
575 (handle-reals %sinh number)
577 (let ((x (realpart number))
578 (y (imagpart number)))
579 (complex (* (sinh x) (cos y))
580 (* (cosh x) (sin y)))))))
584 "Return the hyperbolic cosine of NUMBER."
585 (number-dispatch ((number number))
586 (handle-reals %cosh number)
588 (let ((x (realpart number))
589 (y (imagpart number)))
590 (complex (* (cosh x) (cos y))
591 (* (sinh x) (sin y)))))))
595 "Return the hyperbolic tangent of NUMBER."
596 (number-dispatch ((number number))
597 (handle-reals %tanh number)
599 (complex-tanh number))))
601 (defun asinh (number)
603 "Return the hyperbolic arc sine of NUMBER."
604 (number-dispatch ((number number))
605 (handle-reals %asinh number)
607 (complex-asinh number))))
609 (defun acosh (number)
611 "Return the hyperbolic arc cosine of NUMBER."
612 (number-dispatch ((number number))
614 ;; acosh is complex if number < 1
616 (complex-acosh number)
617 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
618 (((foreach single-float double-float))
619 (if (< number (coerce 1 '(dispatch-type number)))
620 (complex-acosh (complex number))
621 (coerce (%acosh (coerce number 'double-float))
622 '(dispatch-type number))))
624 (complex-acosh number))))
626 (defun atanh (number)
628 "Return the hyperbolic arc tangent of NUMBER."
629 (number-dispatch ((number number))
631 ;; atanh is complex if |number| > 1
632 (if (or (> number 1) (< number -1))
633 (complex-atanh number)
634 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
635 (((foreach single-float double-float))
636 (if (or (> number (coerce 1 '(dispatch-type number)))
637 (< number (coerce -1 '(dispatch-type number))))
638 (complex-atanh (complex number))
639 (coerce (%atanh (coerce number 'double-float))
640 '(dispatch-type number))))
642 (complex-atanh number))))
645 ;;;; not-OLD-SPECFUN stuff
647 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
648 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
649 ;;;; the standard special function system.)
651 ;;;; This is a set of routines that implement many elementary
652 ;;;; transcendental functions as specified by ANSI Common Lisp. The
653 ;;;; implementation is based on Kahan's paper.
655 ;;;; I believe I have accurately implemented the routines and are
656 ;;;; correct, but you may want to check for your self.
658 ;;;; These functions are written for CMU Lisp and take advantage of
659 ;;;; some of the features available there. It may be possible,
660 ;;;; however, to port this to other Lisps.
662 ;;;; Some functions are significantly more accurate than the original
663 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
664 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
665 ;;;; answer is pi + i*log(2-sqrt(3)).
667 ;;;; All of the implemented functions will take any number for an
668 ;;;; input, but the result will always be a either a complex
669 ;;;; single-float or a complex double-float.
671 ;;;; general functions:
683 ;;;; utility functions:
686 ;;;; internal functions:
687 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
690 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
691 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
692 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
695 ;;;; The original CMU CL code requested:
696 ;;;; Please send any bug reports, comments, or improvements to
697 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
699 ;;; FIXME: In SBCL, the floating point infinity constants like
700 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
701 ;;; constants at cross-compile time, because the cross-compilation
702 ;;; host might not have support for floating point infinities. Thus,
703 ;;; they're effectively implemented as special variable references,
704 ;;; and the code below which uses them might be unnecessarily
705 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
706 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
707 ;;; special variable references with (probably equally slow)
710 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
711 ;;; differ in their interpretations of the real line, IMAGPART was
712 ;;; patch, which without a certain amount of effort would have altered
713 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
714 ;;; were patched to use explicit COMPLEX, rather than implicitly
715 ;;; passing in real numbers for treatment with IMAGPART, and these
716 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
717 ;;; however, someone needs to go back to Kahan for the definitive
718 ;;; answer for treatment of negative real floating point numbers and
719 ;;; branch cuts. If adjustment is needed, it is probably the removal
720 ;;; of explicit calls to COMPLEX in the clients of irrational
721 ;;; functions. -- a slightly bitter CSR, 2004-05-16
723 (declaim (inline square))
725 (declare (double-float x))
728 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
730 ;;; If you have these functions in libm, perhaps they should be used
731 ;;; instead of these Lisp versions. These versions are probably good
732 ;;; enough, especially since they are portable.
734 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
735 ;;; the underlying floating-point format.)
736 (declaim (inline scalb))
738 (declare (type double-float x)
739 (type double-float-exponent n))
742 ;;; This is like LOGB, but X is not infinity and non-zero and not a
743 ;;; NaN, so we can always return an integer.
744 (declaim (inline logb-finite))
745 (defun logb-finite (x)
746 (declare (type double-float x))
747 (multiple-value-bind (signif exponent sign)
749 (declare (ignore signif sign))
750 ;; DECODE-FLOAT is almost right, except that the exponent is off
754 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
755 ;;; For the special cases, the following values are used:
758 ;;; +/- infinity +infinity
761 (declare (type double-float x))
762 (cond ((float-nan-p x)
764 ((float-infinity-p x)
765 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
766 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
768 ;; The answer is negative infinity, but we are supposed to
769 ;; signal divide-by-zero, so do the actual division
775 ;;; This function is used to create a complex number of the
776 ;;; appropriate type:
777 ;;; Create complex number with real part X and imaginary part Y
778 ;;; such that has the same type as Z. If Z has type (complex
779 ;;; rational), the X and Y are coerced to single-float.
780 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
781 (error "needs work for long float support"))
782 (declaim (inline coerce-to-complex-type))
783 (defun coerce-to-complex-type (x y z)
784 (declare (double-float x y)
786 (if (typep (realpart z) 'double-float)
788 ;; Convert anything that's not already a DOUBLE-FLOAT (because
789 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
790 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
791 (complex (float x 1f0)
794 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
795 ;;; result is r + i*k, where k is an integer.
796 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
797 (error "needs work for long float support"))
799 (let ((x (float (realpart z) 1d0))
800 (y (float (imagpart z) 1d0)))
801 ;; Would this be better handled using an exception handler to
802 ;; catch the overflow or underflow signal? For now, we turn all
803 ;; traps off and look at the accrued exceptions to see if any
804 ;; signal would have been raised.
805 (with-float-traps-masked (:underflow :overflow)
806 (let ((rho (+ (square x) (square y))))
807 (declare (optimize (speed 3) (space 0)))
808 (cond ((and (or (float-nan-p rho)
809 (float-infinity-p rho))
810 (or (float-infinity-p (abs x))
811 (float-infinity-p (abs y))))
812 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
814 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
817 ;; (/ least-positive-double-float double-float-epsilon)
820 (sb!kernel:make-double-float #x1fffff #xfffffffe)
822 (error "(/ least-positive-long-float long-float-epsilon)")))
823 (traps (ldb sb!vm::float-sticky-bits
824 (sb!vm:floating-point-modes))))
825 ;; Overflow raised or (underflow raised and rho <
827 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
828 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
831 ;; If we're here, neither x nor y are infinity and at
832 ;; least one is non-zero.. Thus logb returns a nice
834 (let ((k (- (logb-finite (max (abs x) (abs y))))))
835 (values (+ (square (scalb x k))
836 (square (scalb y k)))
841 ;;; principal square root of Z
843 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
844 (defun complex-sqrt (z)
845 ;; KLUDGE: Here and below, we can't just declare Z to be of type
846 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
847 ;; Since there isn't a rational negative zero, this is OK from the
848 ;; point of view of getting the right answer in the face of branch
849 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
850 ;; still ugly. -- CSR, 2004-05-16
851 (declare (type (or complex rational) z))
852 (multiple-value-bind (rho k)
854 (declare (type (or (member 0d0) (double-float 0d0)) rho)
856 (let ((x (float (realpart z) 1.0d0))
857 (y (float (imagpart z) 1.0d0))
860 (declare (double-float x y eta nu))
863 ;; space 0 to get maybe-inline functions inlined.
864 (declare (optimize (speed 3) (space 0)))
866 (if (not (float-nan-p x))
867 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
872 (setf k (1- (ash k -1)))
873 (setf rho (+ rho rho))))
875 (setf rho (scalb (sqrt rho) k))
881 (when (not (float-infinity-p (abs nu)))
882 (setf nu (/ (/ nu rho) 2d0)))
885 (setf nu (float-sign y rho))))
886 (coerce-to-complex-type eta nu z)))))
888 ;;; Compute log(2^j*z).
890 ;;; This is for use with J /= 0 only when |z| is huge.
891 (defun complex-log-scaled (z j)
892 (declare (type (or rational complex) z)
894 ;; The constants t0, t1, t2 should be evaluated to machine
895 ;; precision. In addition, Kahan says the accuracy of log1p
896 ;; influences the choices of these constants but doesn't say how to
897 ;; choose them. We'll just assume his choices matches our
898 ;; implementation of log1p.
899 (let ((t0 (load-time-value
901 (sb!kernel:make-double-float #x3fe6a09e #x667f3bcd)
903 (error "(/ (sqrt 2l0))")))
904 ;; KLUDGE: if repeatable fasls start failing under some weird
905 ;; xc host, this 1.2d0 might be a good place to examine: while
906 ;; it _should_ be the same in all vaguely-IEEE754 hosts, 1.2
907 ;; is not exactly representable, so something could go wrong.
910 (ln2 (load-time-value
912 (sb!kernel:make-double-float #x3fe62e42 #xfefa39ef)
914 (error "(log 2l0)")))
915 (x (float (realpart z) 1.0d0))
916 (y (float (imagpart z) 1.0d0)))
917 (multiple-value-bind (rho k)
919 (declare (optimize (speed 3)))
920 (let ((beta (max (abs x) (abs y)))
921 (theta (min (abs x) (abs y))))
922 (coerce-to-complex-type (if (and (zerop k)
926 (/ (%log1p (+ (* (- beta 1.0d0)
935 ;;; log of Z = log |Z| + i * arg Z
937 ;;; Z may be any number, but the result is always a complex.
938 (defun complex-log (z)
939 (declare (type (or rational complex) z))
940 (complex-log-scaled z 0))
942 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
943 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
944 ;;; The reason for the imaginary part is caused by the fact that arg
945 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
946 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
947 (defun complex-atanh (z)
948 (declare (type (or rational complex) z))
950 (theta (/ (sqrt most-positive-double-float) 4.0d0))
951 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
952 (half-pi (/ pi 2.0d0))
953 (rp (float (realpart z) 1.0d0))
954 (beta (float-sign rp 1.0d0))
956 (y (* beta (- (float (imagpart z) 1.0d0))))
959 ;; Shouldn't need this declare.
960 (declare (double-float x y))
962 (declare (optimize (speed 3)))
963 (cond ((or (> x theta)
965 ;; To avoid overflow...
966 (setf nu (float-sign y half-pi))
967 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
968 ;; which can cause overflow. Arrange this computation so
969 ;; that it won't overflow.
970 (setf eta (let* ((x-bigger (> x (abs y)))
971 (r (if x-bigger (/ y x) (/ x y)))
972 (d (+ 1.0d0 (* r r))))
977 ;; Should this be changed so that if y is zero, eta is set
978 ;; to +infinity instead of approx 176? In any case
979 ;; tanh(176) is 1.0d0 within working precision.
980 (let ((t1 (+ 4d0 (square y)))
981 (t2 (+ (abs y) rho)))
982 (setf eta (log (/ (sqrt (sqrt t1))
986 (+ half-pi (atan (* 0.5d0 t2))))))))
988 (let ((t1 (+ (abs y) rho)))
989 ;; Normal case using log1p(x) = log(1 + x)
991 (%log1p (/ (* 4.0d0 x)
992 (+ (square (- 1.0d0 x))
999 (coerce-to-complex-type (* beta eta)
1003 ;;; Compute tanh z = sinh z / cosh z.
1004 (defun complex-tanh (z)
1005 (declare (type (or rational complex) z))
1006 (let ((x (float (realpart z) 1.0d0))
1007 (y (float (imagpart z) 1.0d0)))
1009 ;; space 0 to get maybe-inline functions inlined
1010 (declare (optimize (speed 3) (space 0)))
1014 (sb!kernel:make-double-float #x406633ce #x8fb9f87e)
1016 (error "(/ (+ (log 2l0) (log most-positive-long-float)) 4l0)")))
1017 (coerce-to-complex-type (float-sign x)
1020 (let* ((tv (%tan y))
1021 (beta (+ 1.0d0 (* tv tv)))
1023 (rho (sqrt (+ 1.0d0 (* s s)))))
1024 (if (float-infinity-p (abs tv))
1025 (coerce-to-complex-type (/ rho s)
1028 (let ((den (+ 1.0d0 (* beta s s))))
1029 (coerce-to-complex-type (/ (* beta rho s)
1034 ;;; Compute acos z = pi/2 - asin z.
1036 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1037 (defun complex-acos (z)
1038 ;; Kahan says we should only compute the parts needed. Thus, the
1039 ;; REALPART's below should only compute the real part, not the whole
1040 ;; complex expression. Doing this can be important because we may get
1041 ;; spurious signals that occur in the part that we are not using.
1043 ;; However, we take a pragmatic approach and just use the whole
1046 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1047 ;; it's the conjugate of the square root or the square root of the
1048 ;; conjugate. This needs to be checked.
1050 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1051 ;; same as (sqrt (conjugate z)) for all z. This follows because
1053 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1055 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1057 ;; and these two expressions are equal if and only if arg conj z =
1058 ;; -arg z, which is clearly true for all z.
1059 (declare (type (or rational complex) z))
1060 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
1061 (sqrt-1-z (complex-sqrt (- 1 z))))
1062 (with-float-traps-masked (:divide-by-zero)
1063 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1064 (realpart sqrt-1+z))))
1065 (asinh (imagpart (* (conjugate sqrt-1+z)
1068 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1070 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1071 (defun complex-acosh (z)
1072 (declare (type (or rational complex) z))
1073 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1074 (sqrt-z+1 (complex-sqrt (+ z 1))))
1075 (with-float-traps-masked (:divide-by-zero)
1076 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1078 (* 2 (atan (/ (imagpart sqrt-z-1)
1079 (realpart sqrt-z+1))))))))
1081 ;;; Compute asin z = asinh(i*z)/i.
1083 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1084 (defun complex-asin (z)
1085 (declare (type (or rational complex) z))
1086 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1087 (sqrt-1+z (complex-sqrt (+ 1 z))))
1088 (with-float-traps-masked (:divide-by-zero)
1089 (complex (atan (/ (realpart z)
1090 (realpart (* sqrt-1-z sqrt-1+z))))
1091 (asinh (imagpart (* (conjugate sqrt-1-z)
1094 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1096 ;;; Z may be any number, but the result is always a complex.
1097 (defun complex-asinh (z)
1098 (declare (type (or rational complex) z))
1099 ;; asinh z = -i * asin (i*z)
1100 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1101 (result (complex-asin iz)))
1102 (complex (imagpart result)
1103 (- (realpart result)))))
1105 ;;; Compute atan z = atanh (i*z) / i.
1107 ;;; Z may be any number, but the result is always a complex.
1108 (defun complex-atan (z)
1109 (declare (type (or rational complex) z))
1110 ;; atan z = -i * atanh (i*z)
1111 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1112 (result (complex-atanh iz)))
1113 (complex (imagpart result)
1114 (- (realpart result)))))
1116 ;;; Compute tan z = -i * tanh(i * z)
1118 ;;; Z may be any number, but the result is always a complex.
1119 (defun complex-tan (z)
1120 (declare (type (or rational complex) z))
1121 ;; tan z = -i * tanh(i*z)
1122 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1123 (result (complex-tanh iz)))
1124 (complex (imagpart result)
1125 (- (realpart result)))))