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 ;; This is written in a peculiar way to avoid overflow. Note that in
131 ;; sqrt(x^2 + y^2), either square or the sum can overflow.
133 ;; Factoring x^2 out of sqrt(x^2 + y^2) gives us the expression
134 ;; |x|sqrt(1 + (y/x)^2), which, assuming |x| >= |y|, can only overflow
135 ;; if |x| is sufficiently large.
137 ;; The ZEROP test suffices (y is non-negative) to guard against
138 ;; divisions by zero: x >= y > 0.
139 (declaim (inline %hypot))
141 (declare (type double-float x y))
149 (* x (sqrt (1+ (* y/x y/x)))))))))
155 "Return e raised to the power NUMBER."
156 (number-dispatch ((number number))
157 (handle-reals %exp number)
159 (* (exp (realpart number))
160 (cis (imagpart number))))))
162 ;;; INTEXP -- Handle the rational base, integer power case.
164 (declaim (type (or integer null) *intexp-maximum-exponent*))
165 (defparameter *intexp-maximum-exponent* nil)
167 ;;; This function precisely calculates base raised to an integral
168 ;;; power. It separates the cases by the sign of power, for efficiency
169 ;;; reasons, as powers can be calculated more efficiently if power is
170 ;;; a positive integer. Values of power are calculated as positive
171 ;;; integers, and inverted if negative.
172 (defun intexp (base power)
173 (when (and *intexp-maximum-exponent*
174 (> (abs power) *intexp-maximum-exponent*))
175 (error "The absolute value of ~S exceeds ~S."
176 power '*intexp-maximum-exponent*))
177 (cond ((minusp power)
178 (/ (intexp base (- power))))
182 (do ((nextn (ash power -1) (ash power -1))
183 (total (if (oddp power) base 1)
184 (if (oddp power) (* base total) total)))
185 ((zerop nextn) total)
186 (setq base (* base base))
187 (setq power nextn)))))
189 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
190 ;;; floating point stuff. If both args are real, we try %POW right
191 ;;; off, assuming it will return 0 if the result may be complex. If
192 ;;; so, we call COMPLEX-POW which directly computes the complex
193 ;;; result. We also separate the complex-real and real-complex cases
194 ;;; from the general complex case.
195 (defun expt (base power)
197 "Return BASE raised to the POWER."
199 (if (and (zerop base) (floatp power))
200 (error 'arguments-out-of-domain-error
201 :operands (list base power)
203 :references (list '(:ansi-cl :function expt)))
204 (let ((result (1+ (* base power))))
205 (if (and (floatp result) (float-nan-p result))
208 (labels (;; determine if the double float is an integer.
209 ;; 0 - not an integer
213 (declare (type (unsigned-byte 31) ihi)
214 (type (unsigned-byte 32) lo)
215 (optimize (speed 3) (safety 0)))
217 (declare (type fixnum isint))
218 (cond ((>= ihi #x43400000) ; exponent >= 53
221 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
222 (declare (type (mod 53) k))
224 (let* ((shift (- 52 k))
225 (j (logand (ash lo (- shift))))
227 (declare (type (mod 32) shift)
228 (type (unsigned-byte 32) j j2))
230 (setq isint (- 2 (logand j 1))))))
232 (let* ((shift (- 20 k))
233 (j (ash ihi (- shift)))
235 (declare (type (mod 32) shift)
236 (type (unsigned-byte 31) j j2))
238 (setq isint (- 2 (logand j 1))))))))))
240 (real-expt (x y rtype)
241 (let ((x (coerce x 'double-float))
242 (y (coerce y 'double-float)))
243 (declare (double-float x y))
244 (let* ((x-hi (sb!kernel:double-float-high-bits x))
245 (x-lo (sb!kernel:double-float-low-bits x))
246 (x-ihi (logand x-hi #x7fffffff))
247 (y-hi (sb!kernel:double-float-high-bits y))
248 (y-lo (sb!kernel:double-float-low-bits y))
249 (y-ihi (logand y-hi #x7fffffff)))
250 (declare (type (signed-byte 32) x-hi y-hi)
251 (type (unsigned-byte 31) x-ihi y-ihi)
252 (type (unsigned-byte 32) x-lo y-lo))
254 (when (zerop (logior y-ihi y-lo))
255 (return-from real-expt (coerce 1d0 rtype)))
257 ;; FIXME: Hardcoded qNaN/sNaN values are not portable.
258 (when (or (> x-ihi #x7ff00000)
259 (and (= x-ihi #x7ff00000) (/= x-lo 0))
261 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
262 (return-from real-expt (coerce (+ x y) rtype)))
263 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
264 (declare (type fixnum yisint))
265 ;; special value of y
266 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
268 (return-from real-expt
269 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
271 (coerce (- y y) rtype))
272 ((>= x-ihi #x3ff00000)
273 ;; (|x|>1)**+-inf = inf,0
278 ;; (|x|<1)**-,+inf = inf,0
281 (coerce 0 rtype))))))
283 (let ((abs-x (abs x)))
284 (declare (double-float abs-x))
285 ;; special value of x
286 (when (and (zerop x-lo)
287 (or (= x-ihi #x7ff00000) (zerop x-ihi)
288 (= x-ihi #x3ff00000)))
289 ;; x is +-0,+-inf,+-1
290 (let ((z (if (< y-hi 0)
291 (/ 1 abs-x) ; z = (1/|x|)
293 (declare (double-float z))
295 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
297 (let ((y*pi (* y pi)))
298 (declare (double-float y*pi))
299 (return-from real-expt
301 (coerce (%cos y*pi) rtype)
302 (coerce (%sin y*pi) rtype)))))
304 ;; (x<0)**odd = -(|x|**odd)
306 (return-from real-expt (coerce z rtype))))
310 (coerce (sb!kernel::%pow x y) rtype)
312 (let ((pow (sb!kernel::%pow abs-x y)))
313 (declare (double-float pow))
316 (coerce (* -1d0 pow) rtype))
320 (let ((y*pi (* y pi)))
321 (declare (double-float y*pi))
323 (coerce (* pow (%cos y*pi))
325 (coerce (* pow (%sin y*pi))
327 (complex-expt (base power)
328 (if (and (zerop base) (plusp (realpart power)))
330 (exp (* power (log base))))))
331 (declare (inline real-expt complex-expt))
332 (number-dispatch ((base number) (power number))
333 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
335 (((foreach single-float double-float) rational)
336 (real-expt base power '(dispatch-type base)))
337 (((foreach fixnum (or bignum ratio) single-float)
338 (foreach ratio single-float))
339 (real-expt base power 'single-float))
340 (((foreach fixnum (or bignum ratio) single-float double-float)
342 (real-expt base power 'double-float))
343 ((double-float single-float)
344 (real-expt base power 'double-float))
345 ;; Handle (expt <complex> <rational>), except the case dealt with
346 ;; in the first clause above, (expt <(complex rational)> <integer>).
347 (((foreach (complex rational) (complex single-float)
348 (complex double-float))
350 (* (expt (abs base) power)
351 (cis (* power (phase base)))))
352 ;; The next three clauses handle (expt <real> <complex>).
353 (((foreach fixnum (or bignum ratio) single-float)
354 (foreach (complex single-float) (complex rational)))
355 (complex-expt base power))
356 (((foreach fixnum (or bignum ratio) single-float)
357 (complex double-float))
358 (complex-expt (coerce base 'double-float) power))
359 ((double-float complex)
360 (complex-expt base power))
361 ;; The next three clauses handle (expt <complex> <float>) and
362 ;; (expt <complex> <complex>).
363 (((foreach (complex single-float) (complex rational))
364 (foreach (complex single-float) (complex rational) single-float))
365 (complex-expt base power))
366 (((foreach (complex single-float) (complex rational))
367 (foreach (complex double-float) double-float))
368 (complex-expt (coerce base '(complex double-float)) power))
369 (((complex double-float)
370 (foreach complex double-float single-float))
371 (complex-expt base power))))))
373 ;;; FIXME: Maybe rename this so that it's clearer that it only works
376 (declare (type integer x))
379 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
380 ;; log2(f). So we grab the top few bits of x and scale that
381 ;; appropriately, take the log of it and add it to n.
383 ;; Motivated by an attempt to get LOG to work better on bignums.
384 (let ((n (integer-length x)))
385 (if (< n sb!vm:double-float-digits)
386 (log (coerce x 'double-float) 2.0d0)
387 (let ((f (ldb (byte sb!vm:double-float-digits
388 (- n sb!vm:double-float-digits))
390 (+ n (log (scale-float (coerce f 'double-float)
391 (- sb!vm:double-float-digits))
394 (defun log (number &optional (base nil base-p))
396 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
400 (if (or (typep number 'double-float) (typep base 'double-float))
403 ((and (typep number '(integer (0) *))
404 (typep base '(integer (0) *)))
405 (coerce (/ (log2 number) (log2 base)) 'single-float))
406 ((and (typep number 'integer) (typep base 'double-float))
407 ;; No single float intermediate result
408 (/ (log2 number) (log base 2.0d0)))
409 ((and (typep number 'double-float) (typep base 'integer))
410 (/ (log number 2.0d0) (log2 base)))
412 (/ (log number) (log base))))
413 (number-dispatch ((number number))
414 (((foreach fixnum bignum))
416 (complex (log (- number)) (coerce pi 'single-float))
417 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
420 (complex (log (- number)) (coerce pi 'single-float))
421 (let ((numerator (numerator number))
422 (denominator (denominator number)))
423 (if (= (integer-length numerator)
424 (integer-length denominator))
425 (coerce (%log1p (coerce (- number 1) 'double-float))
427 (coerce (/ (- (log2 numerator) (log2 denominator))
428 (log (exp 1.0d0) 2.0d0))
430 (((foreach single-float double-float))
431 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
432 ;; Since this doesn't seem to be an implementation issue
433 ;; I (pw) take the Kahan result.
434 (if (< (float-sign number)
435 (coerce 0 '(dispatch-type number)))
436 (complex (log (- number)) (coerce pi '(dispatch-type number)))
437 (coerce (%log (coerce number 'double-float))
438 '(dispatch-type number))))
440 (complex-log number)))))
444 "Return the square root of NUMBER."
445 (number-dispatch ((number number))
446 (((foreach fixnum bignum ratio))
448 (complex-sqrt number)
449 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
450 (((foreach single-float double-float))
452 (complex-sqrt (complex number))
453 (coerce (%sqrt (coerce number 'double-float))
454 '(dispatch-type number))))
456 (complex-sqrt number))))
458 ;;;; trigonometic and related functions
462 "Return the absolute value of the number."
463 (number-dispatch ((number number))
464 (((foreach single-float double-float fixnum rational))
467 (let ((rx (realpart number))
468 (ix (imagpart number)))
471 (sqrt (+ (* rx rx) (* ix ix))))
473 (coerce (%hypot (coerce rx 'double-float)
474 (coerce ix 'double-float))
479 (defun phase (number)
481 "Return the angle part of the polar representation of a complex number.
482 For complex numbers, this is (atan (imagpart number) (realpart number)).
483 For non-complex positive numbers, this is 0. For non-complex negative
488 (coerce pi 'single-float)
491 (if (minusp (float-sign number))
492 (coerce pi 'single-float)
495 (if (minusp (float-sign number))
496 (coerce pi 'double-float)
499 (atan (imagpart number) (realpart number)))))
503 "Return the sine of NUMBER."
504 (number-dispatch ((number number))
505 (handle-reals %sin number)
507 (let ((x (realpart number))
508 (y (imagpart number)))
509 (complex (* (sin x) (cosh y))
510 (* (cos x) (sinh y)))))))
514 "Return the cosine of NUMBER."
515 (number-dispatch ((number number))
516 (handle-reals %cos number)
518 (let ((x (realpart number))
519 (y (imagpart number)))
520 (complex (* (cos x) (cosh y))
521 (- (* (sin x) (sinh y))))))))
525 "Return the tangent of NUMBER."
526 (number-dispatch ((number number))
527 (handle-reals %tan number)
529 (complex-tan number))))
533 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
534 (declare (type real theta))
535 (complex (cos theta) (sin theta)))
539 "Return the arc sine of NUMBER."
540 (number-dispatch ((number number))
542 (if (or (> number 1) (< number -1))
543 (complex-asin number)
544 (coerce (%asin (coerce number 'double-float)) 'single-float)))
545 (((foreach single-float double-float))
546 (if (or (> number (coerce 1 '(dispatch-type number)))
547 (< number (coerce -1 '(dispatch-type number))))
548 (complex-asin (complex number))
549 (coerce (%asin (coerce number 'double-float))
550 '(dispatch-type number))))
552 (complex-asin number))))
556 "Return the arc cosine of NUMBER."
557 (number-dispatch ((number number))
559 (if (or (> number 1) (< number -1))
560 (complex-acos number)
561 (coerce (%acos (coerce number 'double-float)) 'single-float)))
562 (((foreach single-float double-float))
563 (if (or (> number (coerce 1 '(dispatch-type number)))
564 (< number (coerce -1 '(dispatch-type number))))
565 (complex-acos (complex number))
566 (coerce (%acos (coerce number 'double-float))
567 '(dispatch-type number))))
569 (complex-acos number))))
571 (defun atan (y &optional (x nil xp))
573 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
576 (declare (type double-float y x)
577 (values double-float))
580 (if (plusp (float-sign x))
583 (float-sign y (/ pi 2)))
585 (number-dispatch ((y real) (x real))
587 (foreach double-float single-float fixnum bignum ratio))
588 (atan2 y (coerce x 'double-float)))
589 (((foreach single-float fixnum bignum ratio)
591 (atan2 (coerce y 'double-float) x))
592 (((foreach single-float fixnum bignum ratio)
593 (foreach single-float fixnum bignum ratio))
594 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
596 (number-dispatch ((y number))
597 (handle-reals %atan y)
601 ;;; It seems that every target system has a C version of sinh, cosh,
602 ;;; and tanh. Let's use these for reals because the original
603 ;;; implementations based on the definitions lose big in round-off
604 ;;; error. These bad definitions also mean that sin and cos for
605 ;;; complex numbers can also lose big.
609 "Return the hyperbolic sine of NUMBER."
610 (number-dispatch ((number number))
611 (handle-reals %sinh number)
613 (let ((x (realpart number))
614 (y (imagpart number)))
615 (complex (* (sinh x) (cos y))
616 (* (cosh x) (sin y)))))))
620 "Return the hyperbolic cosine of NUMBER."
621 (number-dispatch ((number number))
622 (handle-reals %cosh number)
624 (let ((x (realpart number))
625 (y (imagpart number)))
626 (complex (* (cosh x) (cos y))
627 (* (sinh x) (sin y)))))))
631 "Return the hyperbolic tangent of NUMBER."
632 (number-dispatch ((number number))
633 (handle-reals %tanh number)
635 (complex-tanh number))))
637 (defun asinh (number)
639 "Return the hyperbolic arc sine of NUMBER."
640 (number-dispatch ((number number))
641 (handle-reals %asinh number)
643 (complex-asinh number))))
645 (defun acosh (number)
647 "Return the hyperbolic arc cosine of NUMBER."
648 (number-dispatch ((number number))
650 ;; acosh is complex if number < 1
652 (complex-acosh number)
653 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
654 (((foreach single-float double-float))
655 (if (< number (coerce 1 '(dispatch-type number)))
656 (complex-acosh (complex number))
657 (coerce (%acosh (coerce number 'double-float))
658 '(dispatch-type number))))
660 (complex-acosh number))))
662 (defun atanh (number)
664 "Return the hyperbolic arc tangent of NUMBER."
665 (number-dispatch ((number number))
667 ;; atanh is complex if |number| > 1
668 (if (or (> number 1) (< number -1))
669 (complex-atanh number)
670 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
671 (((foreach single-float double-float))
672 (if (or (> number (coerce 1 '(dispatch-type number)))
673 (< number (coerce -1 '(dispatch-type number))))
674 (complex-atanh (complex number))
675 (coerce (%atanh (coerce number 'double-float))
676 '(dispatch-type number))))
678 (complex-atanh number))))
681 ;;;; not-OLD-SPECFUN stuff
683 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
684 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
685 ;;;; the standard special function system.)
687 ;;;; This is a set of routines that implement many elementary
688 ;;;; transcendental functions as specified by ANSI Common Lisp. The
689 ;;;; implementation is based on Kahan's paper.
691 ;;;; I believe I have accurately implemented the routines and are
692 ;;;; correct, but you may want to check for your self.
694 ;;;; These functions are written for CMU Lisp and take advantage of
695 ;;;; some of the features available there. It may be possible,
696 ;;;; however, to port this to other Lisps.
698 ;;;; Some functions are significantly more accurate than the original
699 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
700 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
701 ;;;; answer is pi + i*log(2-sqrt(3)).
703 ;;;; All of the implemented functions will take any number for an
704 ;;;; input, but the result will always be a either a complex
705 ;;;; single-float or a complex double-float.
707 ;;;; general functions:
719 ;;;; utility functions:
722 ;;;; internal functions:
723 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
726 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
727 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
728 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
731 ;;;; The original CMU CL code requested:
732 ;;;; Please send any bug reports, comments, or improvements to
733 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
735 ;;; FIXME: In SBCL, the floating point infinity constants like
736 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
737 ;;; constants at cross-compile time, because the cross-compilation
738 ;;; host might not have support for floating point infinities. Thus,
739 ;;; they're effectively implemented as special variable references,
740 ;;; and the code below which uses them might be unnecessarily
741 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
742 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
743 ;;; special variable references with (probably equally slow)
746 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
747 ;;; differ in their interpretations of the real line, IMAGPART was
748 ;;; patch, which without a certain amount of effort would have altered
749 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
750 ;;; were patched to use explicit COMPLEX, rather than implicitly
751 ;;; passing in real numbers for treatment with IMAGPART, and these
752 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
753 ;;; however, someone needs to go back to Kahan for the definitive
754 ;;; answer for treatment of negative real floating point numbers and
755 ;;; branch cuts. If adjustment is needed, it is probably the removal
756 ;;; of explicit calls to COMPLEX in the clients of irrational
757 ;;; functions. -- a slightly bitter CSR, 2004-05-16
759 (declaim (inline square))
761 (declare (double-float x))
764 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
766 ;;; If you have these functions in libm, perhaps they should be used
767 ;;; instead of these Lisp versions. These versions are probably good
768 ;;; enough, especially since they are portable.
770 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
771 ;;; the underlying floating-point format.)
772 (declaim (inline scalb))
774 (declare (type double-float x)
775 (type double-float-exponent n))
778 ;;; This is like LOGB, but X is not infinity and non-zero and not a
779 ;;; NaN, so we can always return an integer.
780 (declaim (inline logb-finite))
781 (defun logb-finite (x)
782 (declare (type double-float x))
783 (multiple-value-bind (signif exponent sign)
785 (declare (ignore signif sign))
786 ;; DECODE-FLOAT is almost right, except that the exponent is off
790 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
791 ;;; For the special cases, the following values are used:
794 ;;; +/- infinity +infinity
797 (declare (type double-float x))
798 (cond ((float-nan-p x)
800 ((float-infinity-p x)
801 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
802 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
804 ;; The answer is negative infinity, but we are supposed to
805 ;; signal divide-by-zero, so do the actual division
811 ;;; This function is used to create a complex number of the
812 ;;; appropriate type:
813 ;;; Create complex number with real part X and imaginary part Y
814 ;;; such that has the same type as Z. If Z has type (complex
815 ;;; rational), the X and Y are coerced to single-float.
816 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
817 (error "needs work for long float support"))
818 (declaim (inline coerce-to-complex-type))
819 (defun coerce-to-complex-type (x y z)
820 (declare (double-float x y)
822 (if (typep (realpart z) 'double-float)
824 ;; Convert anything that's not already a DOUBLE-FLOAT (because
825 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
826 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
827 (complex (float x 1f0)
830 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
831 ;;; result is r + i*k, where k is an integer.
832 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
833 (error "needs work for long float support"))
835 (let ((x (float (realpart z) 1d0))
836 (y (float (imagpart z) 1d0)))
837 ;; Would this be better handled using an exception handler to
838 ;; catch the overflow or underflow signal? For now, we turn all
839 ;; traps off and look at the accrued exceptions to see if any
840 ;; signal would have been raised.
841 (with-float-traps-masked (:underflow :overflow)
842 (let ((rho (+ (square x) (square y))))
843 (declare (optimize (speed 3) (space 0)))
844 (cond ((and (or (float-nan-p rho)
845 (float-infinity-p rho))
846 (or (float-infinity-p (abs x))
847 (float-infinity-p (abs y))))
848 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
850 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
853 ;; (/ least-positive-double-float double-float-epsilon)
856 (sb!kernel:make-double-float #x1fffff #xfffffffe)
858 (error "(/ least-positive-long-float long-float-epsilon)")))
859 (traps (ldb sb!vm::float-sticky-bits
860 (sb!vm:floating-point-modes))))
861 ;; Overflow raised or (underflow raised and rho <
863 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
864 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
867 ;; If we're here, neither x nor y are infinity and at
868 ;; least one is non-zero.. Thus logb returns a nice
870 (let ((k (- (logb-finite (max (abs x) (abs y))))))
871 (values (+ (square (scalb x k))
872 (square (scalb y k)))
877 ;;; principal square root of Z
879 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
880 (defun complex-sqrt (z)
881 ;; KLUDGE: Here and below, we can't just declare Z to be of type
882 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
883 ;; Since there isn't a rational negative zero, this is OK from the
884 ;; point of view of getting the right answer in the face of branch
885 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
886 ;; still ugly. -- CSR, 2004-05-16
887 (declare (type (or complex rational) z))
888 (multiple-value-bind (rho k)
890 (declare (type (or (member 0d0) (double-float 0d0)) rho)
892 (let ((x (float (realpart z) 1.0d0))
893 (y (float (imagpart z) 1.0d0))
896 (declare (double-float x y eta nu))
899 ;; space 0 to get maybe-inline functions inlined.
900 (declare (optimize (speed 3) (space 0)))
902 (if (not (float-nan-p x))
903 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
908 (setf k (1- (ash k -1)))
909 (setf rho (+ rho rho))))
911 (setf rho (scalb (sqrt rho) k))
917 (when (not (float-infinity-p (abs nu)))
918 (setf nu (/ (/ nu rho) 2d0)))
921 (setf nu (float-sign y rho))))
922 (coerce-to-complex-type eta nu z)))))
924 ;;; Compute log(2^j*z).
926 ;;; This is for use with J /= 0 only when |z| is huge.
927 (defun complex-log-scaled (z j)
928 (declare (type (or rational complex) z)
930 ;; The constants t0, t1, t2 should be evaluated to machine
931 ;; precision. In addition, Kahan says the accuracy of log1p
932 ;; influences the choices of these constants but doesn't say how to
933 ;; choose them. We'll just assume his choices matches our
934 ;; implementation of log1p.
935 (let ((t0 (load-time-value
937 (sb!kernel:make-double-float #x3fe6a09e #x667f3bcd)
939 (error "(/ (sqrt 2l0))")))
940 ;; KLUDGE: if repeatable fasls start failing under some weird
941 ;; xc host, this 1.2d0 might be a good place to examine: while
942 ;; it _should_ be the same in all vaguely-IEEE754 hosts, 1.2
943 ;; is not exactly representable, so something could go wrong.
946 (ln2 (load-time-value
948 (sb!kernel:make-double-float #x3fe62e42 #xfefa39ef)
950 (error "(log 2l0)")))
951 (x (float (realpart z) 1.0d0))
952 (y (float (imagpart z) 1.0d0)))
953 (multiple-value-bind (rho k)
955 (declare (optimize (speed 3)))
956 (let ((beta (max (abs x) (abs y)))
957 (theta (min (abs x) (abs y))))
958 (coerce-to-complex-type (if (and (zerop k)
962 (/ (%log1p (+ (* (- beta 1.0d0)
971 ;;; log of Z = log |Z| + i * arg Z
973 ;;; Z may be any number, but the result is always a complex.
974 (defun complex-log (z)
975 (declare (type (or rational complex) z))
976 (complex-log-scaled z 0))
978 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
979 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
980 ;;; The reason for the imaginary part is caused by the fact that arg
981 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
982 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
983 (defun complex-atanh (z)
984 (declare (type (or rational complex) z))
986 (theta (/ (sqrt most-positive-double-float) 4.0d0))
987 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
988 (half-pi (/ pi 2.0d0))
989 (rp (float (realpart z) 1.0d0))
990 (beta (float-sign rp 1.0d0))
992 (y (* beta (- (float (imagpart z) 1.0d0))))
995 ;; Shouldn't need this declare.
996 (declare (double-float x y))
998 (declare (optimize (speed 3)))
999 (cond ((or (> x theta)
1001 ;; To avoid overflow...
1002 (setf nu (float-sign y half-pi))
1003 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
1004 ;; which can cause overflow. Arrange this computation so
1005 ;; that it won't overflow.
1006 (setf eta (let* ((x-bigger (> x (abs y)))
1007 (r (if x-bigger (/ y x) (/ x y)))
1008 (d (+ 1.0d0 (* r r))))
1013 ;; Should this be changed so that if y is zero, eta is set
1014 ;; to +infinity instead of approx 176? In any case
1015 ;; tanh(176) is 1.0d0 within working precision.
1016 (let ((t1 (+ 4d0 (square y)))
1017 (t2 (+ (abs y) rho)))
1018 (setf eta (log (/ (sqrt (sqrt t1))
1022 (+ half-pi (atan (* 0.5d0 t2))))))))
1024 (let ((t1 (+ (abs y) rho)))
1025 ;; Normal case using log1p(x) = log(1 + x)
1027 (%log1p (/ (* 4.0d0 x)
1028 (+ (square (- 1.0d0 x))
1035 (coerce-to-complex-type (* beta eta)
1039 ;;; Compute tanh z = sinh z / cosh z.
1040 (defun complex-tanh (z)
1041 (declare (type (or rational complex) z))
1042 (let ((x (float (realpart z) 1.0d0))
1043 (y (float (imagpart z) 1.0d0)))
1045 ;; space 0 to get maybe-inline functions inlined
1046 (declare (optimize (speed 3) (space 0)))
1050 (sb!kernel:make-double-float #x406633ce #x8fb9f87e)
1052 (error "(/ (+ (log 2l0) (log most-positive-long-float)) 4l0)")))
1053 (coerce-to-complex-type (float-sign x)
1056 (let* ((tv (%tan y))
1057 (beta (+ 1.0d0 (* tv tv)))
1059 (rho (sqrt (+ 1.0d0 (* s s)))))
1060 (if (float-infinity-p (abs tv))
1061 (coerce-to-complex-type (/ rho s)
1064 (let ((den (+ 1.0d0 (* beta s s))))
1065 (coerce-to-complex-type (/ (* beta rho s)
1070 ;;; Compute acos z = pi/2 - asin z.
1072 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1073 (defun complex-acos (z)
1074 ;; Kahan says we should only compute the parts needed. Thus, the
1075 ;; REALPART's below should only compute the real part, not the whole
1076 ;; complex expression. Doing this can be important because we may get
1077 ;; spurious signals that occur in the part that we are not using.
1079 ;; However, we take a pragmatic approach and just use the whole
1082 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1083 ;; it's the conjugate of the square root or the square root of the
1084 ;; conjugate. This needs to be checked.
1086 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1087 ;; same as (sqrt (conjugate z)) for all z. This follows because
1089 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1091 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1093 ;; and these two expressions are equal if and only if arg conj z =
1094 ;; -arg z, which is clearly true for all z.
1095 (declare (type (or rational complex) z))
1096 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
1097 (sqrt-1-z (complex-sqrt (- 1 z))))
1098 (with-float-traps-masked (:divide-by-zero)
1099 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1100 (realpart sqrt-1+z))))
1101 (asinh (imagpart (* (conjugate sqrt-1+z)
1104 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1106 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1107 (defun complex-acosh (z)
1108 (declare (type (or rational complex) z))
1109 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1110 (sqrt-z+1 (complex-sqrt (+ z 1))))
1111 (with-float-traps-masked (:divide-by-zero)
1112 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1114 (* 2 (atan (/ (imagpart sqrt-z-1)
1115 (realpart sqrt-z+1))))))))
1117 ;;; Compute asin z = asinh(i*z)/i.
1119 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1120 (defun complex-asin (z)
1121 (declare (type (or rational complex) z))
1122 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1123 (sqrt-1+z (complex-sqrt (+ 1 z))))
1124 (with-float-traps-masked (:divide-by-zero)
1125 (complex (atan (/ (realpart z)
1126 (realpart (* sqrt-1-z sqrt-1+z))))
1127 (asinh (imagpart (* (conjugate sqrt-1-z)
1130 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1132 ;;; Z may be any number, but the result is always a complex.
1133 (defun complex-asinh (z)
1134 (declare (type (or rational complex) z))
1135 ;; asinh z = -i * asin (i*z)
1136 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1137 (result (complex-asin iz)))
1138 (complex (imagpart result)
1139 (- (realpart result)))))
1141 ;;; Compute atan z = atanh (i*z) / i.
1143 ;;; Z may be any number, but the result is always a complex.
1144 (defun complex-atan (z)
1145 (declare (type (or rational complex) z))
1146 ;; atan z = -i * atanh (i*z)
1147 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1148 (result (complex-atanh iz)))
1149 (complex (imagpart result)
1150 (- (realpart result)))))
1152 ;;; Compute tan z = -i * tanh(i * z)
1154 ;;; Z may be any number, but the result is always a complex.
1155 (defun complex-tan (z)
1156 (declare (type (or rational complex) z))
1157 ;; tan z = -i * tanh(i*z)
1158 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1159 (result (complex-tanh iz)))
1160 (complex (imagpart result)
1161 (- (realpart result)))))