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 (let ((result (1+ (* base power
))))
182 (if (and (floatp result
) (float-nan-p result
))
185 (labels (;; determine if the double float is an integer.
186 ;; 0 - not an integer
190 (declare (type (unsigned-byte 31) ihi
)
191 (type (unsigned-byte 32) lo
)
192 (optimize (speed 3) (safety 0)))
194 (declare (type fixnum isint
))
195 (cond ((>= ihi
#x43400000
) ; exponent >= 53
198 (let ((k (- (ash ihi -
20) #x3ff
))) ; exponent
199 (declare (type (mod 53) k
))
201 (let* ((shift (- 52 k
))
202 (j (logand (ash lo
(- shift
))))
204 (declare (type (mod 32) shift
)
205 (type (unsigned-byte 32) j j2
))
207 (setq isint
(- 2 (logand j
1))))))
209 (let* ((shift (- 20 k
))
210 (j (ash ihi
(- shift
)))
212 (declare (type (mod 32) shift
)
213 (type (unsigned-byte 31) j j2
))
215 (setq isint
(- 2 (logand j
1))))))))))
217 (real-expt (x y rtype
)
218 (let ((x (coerce x
'double-float
))
219 (y (coerce y
'double-float
)))
220 (declare (double-float x y
))
221 (let* ((x-hi (sb!kernel
:double-float-high-bits x
))
222 (x-lo (sb!kernel
:double-float-low-bits x
))
223 (x-ihi (logand x-hi
#x7fffffff
))
224 (y-hi (sb!kernel
:double-float-high-bits y
))
225 (y-lo (sb!kernel
:double-float-low-bits y
))
226 (y-ihi (logand y-hi
#x7fffffff
)))
227 (declare (type (signed-byte 32) x-hi y-hi
)
228 (type (unsigned-byte 31) x-ihi y-ihi
)
229 (type (unsigned-byte 32) x-lo y-lo
))
231 (when (zerop (logior y-ihi y-lo
))
232 (return-from real-expt
(coerce 1d0 rtype
)))
234 ;; FIXME: Hardcoded qNaN/sNaN values are not portable.
235 (when (or (> x-ihi
#x7ff00000
)
236 (and (= x-ihi
#x7ff00000
) (/= x-lo
0))
238 (and (= y-ihi
#x7ff00000
) (/= y-lo
0)))
239 (return-from real-expt
(coerce (+ x y
) rtype
)))
240 (let ((yisint (if (< x-hi
0) (isint y-ihi y-lo
) 0)))
241 (declare (type fixnum yisint
))
242 ;; special value of y
243 (when (and (zerop y-lo
) (= y-ihi
#x7ff00000
))
245 (return-from real-expt
246 (cond ((and (= x-ihi
#x3ff00000
) (zerop x-lo
))
248 (coerce (- y y
) rtype
))
249 ((>= x-ihi
#x3ff00000
)
250 ;; (|x|>1)**+-inf = inf,0
255 ;; (|x|<1)**-,+inf = inf,0
258 (coerce 0 rtype
))))))
260 (let ((abs-x (abs x
)))
261 (declare (double-float abs-x
))
262 ;; special value of x
263 (when (and (zerop x-lo
)
264 (or (= x-ihi
#x7ff00000
) (zerop x-ihi
)
265 (= x-ihi
#x3ff00000
)))
266 ;; x is +-0,+-inf,+-1
267 (let ((z (if (< y-hi
0)
268 (/ 1 abs-x
) ; z = (1/|x|)
270 (declare (double-float z
))
272 (cond ((and (= x-ihi
#x3ff00000
) (zerop yisint
))
274 (let ((y*pi
(* y pi
)))
275 (declare (double-float y
*pi
))
276 (return-from real-expt
278 (coerce (%cos y
*pi
) rtype
)
279 (coerce (%sin y
*pi
) rtype
)))))
281 ;; (x<0)**odd = -(|x|**odd)
283 (return-from real-expt
(coerce z rtype
))))
287 (coerce (sb!kernel
::%pow x y
) rtype
)
289 (let ((pow (sb!kernel
::%pow abs-x y
)))
290 (declare (double-float pow
))
293 (coerce (* -
1d0 pow
) rtype
))
297 (let ((y*pi
(* y pi
)))
298 (declare (double-float y
*pi
))
300 (coerce (* pow
(%cos y
*pi
))
302 (coerce (* pow
(%sin y
*pi
))
304 (declare (inline real-expt
))
305 (number-dispatch ((base number
) (power number
))
306 (((foreach fixnum
(or bignum ratio
) (complex rational
)) integer
)
308 (((foreach single-float double-float
) rational
)
309 (real-expt base power
'(dispatch-type base
)))
310 (((foreach fixnum
(or bignum ratio
) single-float
)
311 (foreach ratio single-float
))
312 (real-expt base power
'single-float
))
313 (((foreach fixnum
(or bignum ratio
) single-float double-float
)
315 (real-expt base power
'double-float
))
316 ((double-float single-float
)
317 (real-expt base power
'double-float
))
318 (((foreach (complex rational
) (complex float
)) rational
)
319 (* (expt (abs base
) power
)
320 (cis (* power
(phase base
)))))
321 (((foreach fixnum
(or bignum ratio
) single-float double-float
)
323 (if (and (zerop base
) (plusp (realpart power
)))
325 (exp (* power
(log base
)))))
326 (((foreach (complex float
) (complex rational
))
327 (foreach complex double-float single-float
))
328 (if (and (zerop base
) (plusp (realpart power
)))
330 (exp (* power
(log base
)))))))))
332 ;;; FIXME: Maybe rename this so that it's clearer that it only works
335 (declare (type integer x
))
338 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
339 ;; log2(f). So we grab the top few bits of x and scale that
340 ;; appropriately, take the log of it and add it to n.
342 ;; Motivated by an attempt to get LOG to work better on bignums.
343 (let ((n (integer-length x
)))
344 (if (< n sb
!vm
:double-float-digits
)
345 (log (coerce x
'double-float
) 2.0d0
)
346 (let ((f (ldb (byte sb
!vm
:double-float-digits
347 (- n sb
!vm
:double-float-digits
))
349 (+ n
(log (scale-float (coerce f
'double-float
)
350 (- sb
!vm
:double-float-digits
))
353 (defun log (number &optional
(base nil base-p
))
355 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
359 (if (or (typep number
'double-float
) (typep base
'double-float
))
362 ((and (typep number
'(integer (0) *))
363 (typep base
'(integer (0) *)))
364 (coerce (/ (log2 number
) (log2 base
)) 'single-float
))
365 ((and (typep number
'integer
) (typep base
'double-float
))
366 ;; No single float intermediate result
367 (/ (log2 number
) (log base
2.0d0
)))
368 ((and (typep number
'double-float
) (typep base
'integer
))
369 (/ (log number
2.0d0
) (log2 base
)))
371 (/ (log number
) (log base
))))
372 (number-dispatch ((number number
))
373 (((foreach fixnum bignum
))
375 (complex (log (- number
)) (coerce pi
'single-float
))
376 (coerce (/ (log2 number
) (log (exp 1.0d0
) 2.0d0
)) 'single-float
)))
379 (complex (log (- number
)) (coerce pi
'single-float
))
380 (let ((numerator (numerator number
))
381 (denominator (denominator number
)))
382 (if (= (integer-length numerator
)
383 (integer-length denominator
))
384 (coerce (%log1p
(coerce (- number
1) 'double-float
))
386 (coerce (/ (- (log2 numerator
) (log2 denominator
))
387 (log (exp 1.0d0
) 2.0d0
))
389 (((foreach single-float double-float
))
390 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
391 ;; Since this doesn't seem to be an implementation issue
392 ;; I (pw) take the Kahan result.
393 (if (< (float-sign number
)
394 (coerce 0 '(dispatch-type number
)))
395 (complex (log (- number
)) (coerce pi
'(dispatch-type number
)))
396 (coerce (%log
(coerce number
'double-float
))
397 '(dispatch-type number
))))
399 (complex-log number
)))))
403 "Return the square root of NUMBER."
404 (number-dispatch ((number number
))
405 (((foreach fixnum bignum ratio
))
407 (complex-sqrt number
)
408 (coerce (%sqrt
(coerce number
'double-float
)) 'single-float
)))
409 (((foreach single-float double-float
))
411 (complex-sqrt (complex number
))
412 (coerce (%sqrt
(coerce number
'double-float
))
413 '(dispatch-type number
))))
415 (complex-sqrt number
))))
417 ;;;; trigonometic and related functions
421 "Return the absolute value of the number."
422 (number-dispatch ((number number
))
423 (((foreach single-float double-float fixnum rational
))
426 (let ((rx (realpart number
))
427 (ix (imagpart number
)))
430 (sqrt (+ (* rx rx
) (* ix ix
))))
432 (coerce (%hypot
(coerce rx
'double-float
)
433 (coerce ix
'double-float
))
438 (defun phase (number)
440 "Return the angle part of the polar representation of a complex number.
441 For complex numbers, this is (atan (imagpart number) (realpart number)).
442 For non-complex positive numbers, this is 0. For non-complex negative
447 (coerce pi
'single-float
)
450 (if (minusp (float-sign number
))
451 (coerce pi
'single-float
)
454 (if (minusp (float-sign number
))
455 (coerce pi
'double-float
)
458 (atan (imagpart number
) (realpart number
)))))
462 "Return the sine of NUMBER."
463 (number-dispatch ((number number
))
464 (handle-reals %sin number
)
466 (let ((x (realpart number
))
467 (y (imagpart number
)))
468 (complex (* (sin x
) (cosh y
))
469 (* (cos x
) (sinh y
)))))))
473 "Return the cosine of NUMBER."
474 (number-dispatch ((number number
))
475 (handle-reals %cos number
)
477 (let ((x (realpart number
))
478 (y (imagpart number
)))
479 (complex (* (cos x
) (cosh y
))
480 (- (* (sin x
) (sinh y
))))))))
484 "Return the tangent of NUMBER."
485 (number-dispatch ((number number
))
486 (handle-reals %tan number
)
488 (complex-tan number
))))
492 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
493 (declare (type real theta
))
494 (complex (cos theta
) (sin theta
)))
498 "Return the arc sine of NUMBER."
499 (number-dispatch ((number number
))
501 (if (or (> number
1) (< number -
1))
502 (complex-asin number
)
503 (coerce (%asin
(coerce number
'double-float
)) 'single-float
)))
504 (((foreach single-float double-float
))
505 (if (or (> number
(coerce 1 '(dispatch-type number
)))
506 (< number
(coerce -
1 '(dispatch-type number
))))
507 (complex-asin (complex number
))
508 (coerce (%asin
(coerce number
'double-float
))
509 '(dispatch-type number
))))
511 (complex-asin number
))))
515 "Return the arc cosine of NUMBER."
516 (number-dispatch ((number number
))
518 (if (or (> number
1) (< number -
1))
519 (complex-acos number
)
520 (coerce (%acos
(coerce number
'double-float
)) 'single-float
)))
521 (((foreach single-float double-float
))
522 (if (or (> number
(coerce 1 '(dispatch-type number
)))
523 (< number
(coerce -
1 '(dispatch-type number
))))
524 (complex-acos (complex number
))
525 (coerce (%acos
(coerce number
'double-float
))
526 '(dispatch-type number
))))
528 (complex-acos number
))))
530 (defun atan (y &optional
(x nil xp
))
532 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
535 (declare (type double-float y x
)
536 (values double-float
))
539 (if (plusp (float-sign x
))
542 (float-sign y
(/ pi
2)))
544 (number-dispatch ((y real
) (x real
))
546 (foreach double-float single-float fixnum bignum ratio
))
547 (atan2 y
(coerce x
'double-float
)))
548 (((foreach single-float fixnum bignum ratio
)
550 (atan2 (coerce y
'double-float
) x
))
551 (((foreach single-float fixnum bignum ratio
)
552 (foreach single-float fixnum bignum ratio
))
553 (coerce (atan2 (coerce y
'double-float
) (coerce x
'double-float
))
555 (number-dispatch ((y number
))
556 (handle-reals %atan y
)
560 ;;; It seems that every target system has a C version of sinh, cosh,
561 ;;; and tanh. Let's use these for reals because the original
562 ;;; implementations based on the definitions lose big in round-off
563 ;;; error. These bad definitions also mean that sin and cos for
564 ;;; complex numbers can also lose big.
568 "Return the hyperbolic sine of NUMBER."
569 (number-dispatch ((number number
))
570 (handle-reals %sinh number
)
572 (let ((x (realpart number
))
573 (y (imagpart number
)))
574 (complex (* (sinh x
) (cos y
))
575 (* (cosh x
) (sin y
)))))))
579 "Return the hyperbolic cosine of NUMBER."
580 (number-dispatch ((number number
))
581 (handle-reals %cosh number
)
583 (let ((x (realpart number
))
584 (y (imagpart number
)))
585 (complex (* (cosh x
) (cos y
))
586 (* (sinh x
) (sin y
)))))))
590 "Return the hyperbolic tangent of NUMBER."
591 (number-dispatch ((number number
))
592 (handle-reals %tanh number
)
594 (complex-tanh number
))))
596 (defun asinh (number)
598 "Return the hyperbolic arc sine of NUMBER."
599 (number-dispatch ((number number
))
600 (handle-reals %asinh number
)
602 (complex-asinh number
))))
604 (defun acosh (number)
606 "Return the hyperbolic arc cosine of NUMBER."
607 (number-dispatch ((number number
))
609 ;; acosh is complex if number < 1
611 (complex-acosh number
)
612 (coerce (%acosh
(coerce number
'double-float
)) 'single-float
)))
613 (((foreach single-float double-float
))
614 (if (< number
(coerce 1 '(dispatch-type number
)))
615 (complex-acosh (complex number
))
616 (coerce (%acosh
(coerce number
'double-float
))
617 '(dispatch-type number
))))
619 (complex-acosh number
))))
621 (defun atanh (number)
623 "Return the hyperbolic arc tangent of NUMBER."
624 (number-dispatch ((number number
))
626 ;; atanh is complex if |number| > 1
627 (if (or (> number
1) (< number -
1))
628 (complex-atanh number
)
629 (coerce (%atanh
(coerce number
'double-float
)) 'single-float
)))
630 (((foreach single-float double-float
))
631 (if (or (> number
(coerce 1 '(dispatch-type number
)))
632 (< number
(coerce -
1 '(dispatch-type number
))))
633 (complex-atanh (complex number
))
634 (coerce (%atanh
(coerce number
'double-float
))
635 '(dispatch-type number
))))
637 (complex-atanh number
))))
640 ;;;; not-OLD-SPECFUN stuff
642 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
643 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
644 ;;;; the standard special function system.)
646 ;;;; This is a set of routines that implement many elementary
647 ;;;; transcendental functions as specified by ANSI Common Lisp. The
648 ;;;; implementation is based on Kahan's paper.
650 ;;;; I believe I have accurately implemented the routines and are
651 ;;;; correct, but you may want to check for your self.
653 ;;;; These functions are written for CMU Lisp and take advantage of
654 ;;;; some of the features available there. It may be possible,
655 ;;;; however, to port this to other Lisps.
657 ;;;; Some functions are significantly more accurate than the original
658 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
659 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
660 ;;;; answer is pi + i*log(2-sqrt(3)).
662 ;;;; All of the implemented functions will take any number for an
663 ;;;; input, but the result will always be a either a complex
664 ;;;; single-float or a complex double-float.
666 ;;;; general functions:
678 ;;;; utility functions:
681 ;;;; internal functions:
682 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
685 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
686 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
687 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
690 ;;;; The original CMU CL code requested:
691 ;;;; Please send any bug reports, comments, or improvements to
692 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
694 ;;; FIXME: In SBCL, the floating point infinity constants like
695 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
696 ;;; constants at cross-compile time, because the cross-compilation
697 ;;; host might not have support for floating point infinities. Thus,
698 ;;; they're effectively implemented as special variable references,
699 ;;; and the code below which uses them might be unnecessarily
700 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
701 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
702 ;;; special variable references with (probably equally slow)
705 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
706 ;;; differ in their interpretations of the real line, IMAGPART was
707 ;;; patch, which without a certain amount of effort would have altered
708 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
709 ;;; were patched to use explicit COMPLEX, rather than implicitly
710 ;;; passing in real numbers for treatment with IMAGPART, and these
711 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
712 ;;; however, someone needs to go back to Kahan for the definitive
713 ;;; answer for treatment of negative real floating point numbers and
714 ;;; branch cuts. If adjustment is needed, it is probably the removal
715 ;;; of explicit calls to COMPLEX in the clients of irrational
716 ;;; functions. -- a slightly bitter CSR, 2004-05-16
718 (declaim (inline square
))
720 (declare (double-float x
))
723 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
725 ;;; If you have these functions in libm, perhaps they should be used
726 ;;; instead of these Lisp versions. These versions are probably good
727 ;;; enough, especially since they are portable.
729 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
730 ;;; the underlying floating-point format.)
731 (declaim (inline scalb
))
733 (declare (type double-float x
)
734 (type double-float-exponent n
))
737 ;;; This is like LOGB, but X is not infinity and non-zero and not a
738 ;;; NaN, so we can always return an integer.
739 (declaim (inline logb-finite
))
740 (defun logb-finite (x)
741 (declare (type double-float x
))
742 (multiple-value-bind (signif exponent sign
)
744 (declare (ignore signif sign
))
745 ;; DECODE-FLOAT is almost right, except that the exponent is off
749 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
750 ;;; For the special cases, the following values are used:
753 ;;; +/- infinity +infinity
756 (declare (type double-float x
))
757 (cond ((float-nan-p x
)
759 ((float-infinity-p x
)
760 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
761 (double-from-bits 0 (1+ sb
!vm
:double-float-normal-exponent-max
) 0))
763 ;; The answer is negative infinity, but we are supposed to
764 ;; signal divide-by-zero, so do the actual division
770 ;;; This function is used to create a complex number of the
771 ;;; appropriate type:
772 ;;; Create complex number with real part X and imaginary part Y
773 ;;; such that has the same type as Z. If Z has type (complex
774 ;;; rational), the X and Y are coerced to single-float.
775 #!+long-float
(eval-when (:compile-toplevel
:load-toplevel
:execute
)
776 (error "needs work for long float support"))
777 (declaim (inline coerce-to-complex-type
))
778 (defun coerce-to-complex-type (x y z
)
779 (declare (double-float x y
)
781 (if (typep (realpart z
) 'double-float
)
783 ;; Convert anything that's not already a DOUBLE-FLOAT (because
784 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
785 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
786 (complex (float x
1f0
)
789 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
790 ;;; result is r + i*k, where k is an integer.
791 #!+long-float
(eval-when (:compile-toplevel
:load-toplevel
:execute
)
792 (error "needs work for long float support"))
794 (let ((x (float (realpart z
) 1d0
))
795 (y (float (imagpart z
) 1d0
)))
796 ;; Would this be better handled using an exception handler to
797 ;; catch the overflow or underflow signal? For now, we turn all
798 ;; traps off and look at the accrued exceptions to see if any
799 ;; signal would have been raised.
800 (with-float-traps-masked (:underflow
:overflow
)
801 (let ((rho (+ (square x
) (square y
))))
802 (declare (optimize (speed 3) (space 0)))
803 (cond ((and (or (float-nan-p rho
)
804 (float-infinity-p rho
))
805 (or (float-infinity-p (abs x
))
806 (float-infinity-p (abs y
))))
807 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
809 (double-from-bits 0 (1+ sb
!vm
:double-float-normal-exponent-max
) 0)
811 ((let ((threshold #.
(/ least-positive-double-float
812 double-float-epsilon
))
813 (traps (ldb sb
!vm
::float-sticky-bits
814 (sb!vm
:floating-point-modes
))))
815 ;; Overflow raised or (underflow raised and rho <
817 (or (not (zerop (logand sb
!vm
:float-overflow-trap-bit traps
)))
818 (and (not (zerop (logand sb
!vm
:float-underflow-trap-bit
821 ;; If we're here, neither x nor y are infinity and at
822 ;; least one is non-zero.. Thus logb returns a nice
824 (let ((k (- (logb-finite (max (abs x
) (abs y
))))))
825 (values (+ (square (scalb x k
))
826 (square (scalb y k
)))
831 ;;; principal square root of Z
833 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
834 (defun complex-sqrt (z)
835 ;; KLUDGE: Here and below, we can't just declare Z to be of type
836 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
837 ;; Since there isn't a rational negative zero, this is OK from the
838 ;; point of view of getting the right answer in the face of branch
839 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
840 ;; still ugly. -- CSR, 2004-05-16
841 (declare (type (or complex rational
) z
))
842 (multiple-value-bind (rho k
)
844 (declare (type (or (member 0d0
) (double-float 0d0
)) rho
)
846 (let ((x (float (realpart z
) 1.0d0
))
847 (y (float (imagpart z
) 1.0d0
))
850 (declare (double-float x y eta nu
))
853 ;; space 0 to get maybe-inline functions inlined.
854 (declare (optimize (speed 3) (space 0)))
856 (if (not (float-nan-p x
))
857 (setf rho
(+ (scalb (abs x
) (- k
)) (sqrt rho
))))
862 (setf k
(1- (ash k -
1)))
863 (setf rho
(+ rho rho
))))
865 (setf rho
(scalb (sqrt rho
) k
))
871 (when (not (float-infinity-p (abs nu
)))
872 (setf nu
(/ (/ nu rho
) 2d0
)))
875 (setf nu
(float-sign y rho
))))
876 (coerce-to-complex-type eta nu z
)))))
878 ;;; Compute log(2^j*z).
880 ;;; This is for use with J /= 0 only when |z| is huge.
881 (defun complex-log-scaled (z j
)
882 (declare (type (or rational complex
) z
)
884 ;; The constants t0, t1, t2 should be evaluated to machine
885 ;; precision. In addition, Kahan says the accuracy of log1p
886 ;; influences the choices of these constants but doesn't say how to
887 ;; choose them. We'll just assume his choices matches our
888 ;; implementation of log1p.
889 (let ((t0 #.
(/ 1 (sqrt 2.0d0
)))
893 (x (float (realpart z
) 1.0d0
))
894 (y (float (imagpart z
) 1.0d0
)))
895 (multiple-value-bind (rho k
)
897 (declare (optimize (speed 3)))
898 (let ((beta (max (abs x
) (abs y
)))
899 (theta (min (abs x
) (abs y
))))
900 (coerce-to-complex-type (if (and (zerop k
)
904 (/ (%log1p
(+ (* (- beta
1.0d0
)
913 ;;; log of Z = log |Z| + i * arg Z
915 ;;; Z may be any number, but the result is always a complex.
916 (defun complex-log (z)
917 (declare (type (or rational complex
) z
))
918 (complex-log-scaled z
0))
920 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
921 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
922 ;;; The reason for the imaginary part is caused by the fact that arg
923 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
924 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
925 (defun complex-atanh (z)
926 (declare (type (or rational complex
) z
))
928 (theta (/ (sqrt most-positive-double-float
) 4.0d0
))
929 (rho (/ 4.0d0
(sqrt most-positive-double-float
)))
930 (half-pi (/ pi
2.0d0
))
931 (rp (float (realpart z
) 1.0d0
))
932 (beta (float-sign rp
1.0d0
))
934 (y (* beta
(- (float (imagpart z
) 1.0d0
))))
937 ;; Shouldn't need this declare.
938 (declare (double-float x y
))
940 (declare (optimize (speed 3)))
941 (cond ((or (> x theta
)
943 ;; To avoid overflow...
944 (setf nu
(float-sign y half-pi
))
945 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
946 ;; which can cause overflow. Arrange this computation so
947 ;; that it won't overflow.
948 (setf eta
(let* ((x-bigger (> x
(abs y
)))
949 (r (if x-bigger
(/ y x
) (/ x y
)))
950 (d (+ 1.0d0
(* r r
))))
955 ;; Should this be changed so that if y is zero, eta is set
956 ;; to +infinity instead of approx 176? In any case
957 ;; tanh(176) is 1.0d0 within working precision.
958 (let ((t1 (+ 4d0
(square y
)))
959 (t2 (+ (abs y
) rho
)))
960 (setf eta
(log (/ (sqrt (sqrt t1
))
964 (+ half-pi
(atan (* 0.5d0 t2
))))))))
966 (let ((t1 (+ (abs y
) rho
)))
967 ;; Normal case using log1p(x) = log(1 + x)
969 (%log1p
(/ (* 4.0d0 x
)
970 (+ (square (- 1.0d0 x
))
977 (coerce-to-complex-type (* beta eta
)
981 ;;; Compute tanh z = sinh z / cosh z.
982 (defun complex-tanh (z)
983 (declare (type (or rational complex
) z
))
984 (let ((x (float (realpart z
) 1.0d0
))
985 (y (float (imagpart z
) 1.0d0
)))
987 ;; space 0 to get maybe-inline functions inlined
988 (declare (optimize (speed 3) (space 0)))
990 ;; FIXME: this form is hideously broken wrt
991 ;; cross-compilation portability. Much else in this
992 ;; file is too, of course, sometimes hidden by
993 ;; constant-folding, but this one in particular clearly
994 ;; depends on host and target
995 ;; MOST-POSITIVE-DOUBLE-FLOATs being equal. -- CSR,
998 (log most-positive-double-float
))
1000 (coerce-to-complex-type (float-sign x
)
1003 (let* ((tv (%tan y
))
1004 (beta (+ 1.0d0
(* tv tv
)))
1006 (rho (sqrt (+ 1.0d0
(* s s
)))))
1007 (if (float-infinity-p (abs tv
))
1008 (coerce-to-complex-type (/ rho s
)
1011 (let ((den (+ 1.0d0
(* beta s s
))))
1012 (coerce-to-complex-type (/ (* beta rho s
)
1017 ;;; Compute acos z = pi/2 - asin z.
1019 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1020 (defun complex-acos (z)
1021 ;; Kahan says we should only compute the parts needed. Thus, the
1022 ;; REALPART's below should only compute the real part, not the whole
1023 ;; complex expression. Doing this can be important because we may get
1024 ;; spurious signals that occur in the part that we are not using.
1026 ;; However, we take a pragmatic approach and just use the whole
1029 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1030 ;; it's the conjugate of the square root or the square root of the
1031 ;; conjugate. This needs to be checked.
1033 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1034 ;; same as (sqrt (conjugate z)) for all z. This follows because
1036 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1038 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1040 ;; and these two expressions are equal if and only if arg conj z =
1041 ;; -arg z, which is clearly true for all z.
1042 (declare (type (or rational complex
) z
))
1043 (let ((sqrt-1+z
(complex-sqrt (+ 1 z
)))
1044 (sqrt-1-z (complex-sqrt (- 1 z
))))
1045 (with-float-traps-masked (:divide-by-zero
)
1046 (complex (* 2 (atan (/ (realpart sqrt-1-z
)
1047 (realpart sqrt-1
+z
))))
1048 (asinh (imagpart (* (conjugate sqrt-1
+z
)
1051 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1053 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1054 (defun complex-acosh (z)
1055 (declare (type (or rational complex
) z
))
1056 (let ((sqrt-z-1 (complex-sqrt (- z
1)))
1057 (sqrt-z+1 (complex-sqrt (+ z
1))))
1058 (with-float-traps-masked (:divide-by-zero
)
1059 (complex (asinh (realpart (* (conjugate sqrt-z-1
)
1061 (* 2 (atan (/ (imagpart sqrt-z-1
)
1062 (realpart sqrt-z
+1))))))))
1064 ;;; Compute asin z = asinh(i*z)/i.
1066 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1067 (defun complex-asin (z)
1068 (declare (type (or rational complex
) z
))
1069 (let ((sqrt-1-z (complex-sqrt (- 1 z
)))
1070 (sqrt-1+z
(complex-sqrt (+ 1 z
))))
1071 (with-float-traps-masked (:divide-by-zero
)
1072 (complex (atan (/ (realpart z
)
1073 (realpart (* sqrt-1-z sqrt-1
+z
))))
1074 (asinh (imagpart (* (conjugate sqrt-1-z
)
1077 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1079 ;;; Z may be any number, but the result is always a complex.
1080 (defun complex-asinh (z)
1081 (declare (type (or rational complex
) z
))
1082 ;; asinh z = -i * asin (i*z)
1083 (let* ((iz (complex (- (imagpart z
)) (realpart z
)))
1084 (result (complex-asin iz
)))
1085 (complex (imagpart result
)
1086 (- (realpart result
)))))
1088 ;;; Compute atan z = atanh (i*z) / i.
1090 ;;; Z may be any number, but the result is always a complex.
1091 (defun complex-atan (z)
1092 (declare (type (or rational complex
) z
))
1093 ;; atan z = -i * atanh (i*z)
1094 (let* ((iz (complex (- (imagpart z
)) (realpart z
)))
1095 (result (complex-atanh iz
)))
1096 (complex (imagpart result
)
1097 (- (realpart result
)))))
1099 ;;; Compute tan z = -i * tanh(i * z)
1101 ;;; Z may be any number, but the result is always a complex.
1102 (defun complex-tan (z)
1103 (declare (type (or rational complex
) z
))
1104 ;; tan z = -i * tanh(i*z)
1105 (let* ((iz (complex (- (imagpart z
)) (realpart z
)))
1106 (result (complex-tanh iz
)))
1107 (complex (imagpart result
)
1108 (- (realpart result
)))))