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
&optional wrapper
)
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
33 (extern-alien ,(format nil
"~:[~;sb_~]~a" wrapper name
)
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
))
45 (defun handle-complex (form)
46 `((((foreach (complex double-float
) (complex single-float
) (complex rational
)))
50 #!+x86
;; for constant folding
51 (macrolet ((def (name ll
)
52 `(defun ,name
,ll
(,name
,@ll
))))
65 #!+(or x86-64 arm-vfp arm64
) ;; for constant folding
66 (macrolet ((def (name ll
)
67 `(defun ,name
,ll
(,name
,@ll
))))
70 ;;;; stubs for the Unix math library
72 ;;;; Many of these are unnecessary on the X86 because they're built
76 #!-x86
(def-math-rtn "sin" 1)
77 #!-x86
(def-math-rtn "cos" 1)
78 #!-x86
(def-math-rtn "tan" 1)
79 #!-x86
(def-math-rtn "atan" 1)
80 #!-x86
(def-math-rtn "atan2" 2)
82 (def-math-rtn "acos" 1 #!+win32 t
)
83 (def-math-rtn "asin" 1 #!+win32 t
)
84 (def-math-rtn "cosh" 1 #!+win32 t
)
85 (def-math-rtn "sinh" 1 #!+win32 t
)
86 (def-math-rtn "tanh" 1 #!+win32 t
)
87 (def-math-rtn "asinh" 1 #!+win32 t
)
88 (def-math-rtn "acosh" 1 #!+win32 t
)
89 (def-math-rtn "atanh" 1 #!+win32 t
)
91 ;;; exponential and logarithmic
92 (def-math-rtn "hypot" 2 #!+win32 t
)
93 #!-x86
(def-math-rtn "exp" 1)
94 #!-x86
(def-math-rtn "log" 1)
95 #!-x86
(def-math-rtn "log10" 1)
96 (def-math-rtn "pow" 2)
97 #!-
(or x86 x86-64 arm-vfp arm64
) (def-math-rtn "sqrt" 1)
98 #!-x86
(def-math-rtn "log1p" 1)
104 "Return e raised to the power NUMBER."
105 (declare (explicit-check))
106 (number-dispatch ((number number
))
107 (handle-reals %exp number
)
109 (* (exp (realpart number
))
110 (cis (imagpart number
))))))
112 ;;; INTEXP -- Handle the rational base, integer power case.
113 ;;; This function precisely calculates base raised to an integral
114 ;;; power. It separates the cases by the sign of power, for efficiency
115 ;;; reasons, as powers can be calculated more efficiently if power is
116 ;;; a positive integer. Values of power are calculated as positive
117 ;;; integers, and inverted if negative.
118 (defun intexp (base power
)
126 (let ((den (denominator base
))
127 (num (numerator base
)))
129 (let ((negated (- power
)))
131 (intexp den negated
))
133 (intexp (- den
) negated
))
135 (build-ratio (intexp den negated
)
136 (intexp num negated
)))))
137 (build-ratio (intexp num power
)
138 (intexp den power
)))))
140 (/ (intexp base
(- power
))))
144 (do ((nextn (ash power -
1) (ash power -
1))
145 (total (if (oddp power
) base
1)
146 (if (oddp power
) (* base total
) total
)))
147 ((zerop nextn
) total
)
148 (setq base
(* base base
))
149 (setq power nextn
)))))
151 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
152 ;;; floating point stuff. If both args are real, we try %POW right
153 ;;; off, assuming it will return 0 if the result may be complex. If
154 ;;; so, we call COMPLEX-POW which directly computes the complex
155 ;;; result. We also separate the complex-real and real-complex cases
156 ;;; from the general complex case.
157 (defun expt (base power
)
158 "Return BASE raised to the POWER."
159 (declare (explicit-check))
161 (if (and (zerop base
) (floatp power
))
162 (error 'arguments-out-of-domain-error
163 :operands
(list base power
)
165 :references
(list '(:ansi-cl
:function expt
)))
166 (let ((result (1+ (* base power
))))
167 (if (and (floatp result
) (float-nan-p result
))
170 (labels (;; determine if the double float is an integer.
171 ;; 0 - not an integer
175 (declare (type (unsigned-byte 31) ihi
)
176 (type (unsigned-byte 32) lo
)
177 (optimize (speed 3) (safety 0)))
179 (declare (type fixnum isint
))
180 (cond ((>= ihi
#x43400000
) ; exponent >= 53
183 (let ((k (- (ash ihi -
20) #x3ff
))) ; exponent
184 (declare (type (mod 53) k
))
186 (let* ((shift (- 52 k
))
187 (j (logand (ash lo
(- shift
))))
189 (declare (type (mod 32) shift
)
190 (type (unsigned-byte 32) j j2
))
192 (setq isint
(- 2 (logand j
1))))))
194 (let* ((shift (- 20 k
))
195 (j (ash ihi
(- shift
)))
197 (declare (type (mod 32) shift
)
198 (type (unsigned-byte 31) j j2
))
200 (setq isint
(- 2 (logand j
1))))))))))
202 (real-expt (x y rtype
)
203 (let ((x (coerce x
'double-float
))
204 (y (coerce y
'double-float
)))
205 (declare (double-float x y
))
206 (let* ((x-hi (double-float-high-bits x
))
207 (x-lo (double-float-low-bits x
))
208 (x-ihi (logand x-hi
#x7fffffff
))
209 (y-hi (double-float-high-bits y
))
210 (y-lo (double-float-low-bits y
))
211 (y-ihi (logand y-hi
#x7fffffff
)))
212 (declare (type (signed-byte 32) x-hi y-hi
)
213 (type (unsigned-byte 31) x-ihi y-ihi
)
214 (type (unsigned-byte 32) x-lo y-lo
))
216 (when (zerop (logior y-ihi y-lo
))
217 (return-from real-expt
(coerce 1d0 rtype
)))
219 ;; FIXME: Hardcoded qNaN/sNaN values are not portable.
220 (when (or (> x-ihi
#x7ff00000
)
221 (and (= x-ihi
#x7ff00000
) (/= x-lo
0))
223 (and (= y-ihi
#x7ff00000
) (/= y-lo
0)))
224 (return-from real-expt
(coerce (+ x y
) rtype
)))
225 (let ((yisint (if (< x-hi
0) (isint y-ihi y-lo
) 0)))
226 (declare (type fixnum yisint
))
227 ;; special value of y
228 (when (and (zerop y-lo
) (= y-ihi
#x7ff00000
))
230 (return-from real-expt
231 (cond ((and (= x-ihi
#x3ff00000
) (zerop x-lo
))
233 (coerce (- y y
) rtype
))
234 ((>= x-ihi
#x3ff00000
)
235 ;; (|x|>1)**+-inf = inf,0
240 ;; (|x|<1)**-,+inf = inf,0
243 (coerce 0 rtype
))))))
245 (let ((abs-x (abs x
)))
246 (declare (double-float abs-x
))
247 ;; special value of x
248 (when (and (zerop x-lo
)
249 (or (= x-ihi
#x7ff00000
) (zerop x-ihi
)
250 (= x-ihi
#x3ff00000
)))
251 ;; x is +-0,+-inf,+-1
252 (let ((z (if (< y-hi
0)
253 (/ 1 abs-x
) ; z = (1/|x|)
255 (declare (double-float z
))
257 (cond ((and (= x-ihi
#x3ff00000
) (zerop yisint
))
259 (let ((y*pi
(* y pi
)))
260 (declare (double-float y
*pi
))
261 (return-from real-expt
263 (coerce (%cos y
*pi
) rtype
)
264 (coerce (%sin y
*pi
) rtype
)))))
266 ;; (x<0)**odd = -(|x|**odd)
268 (return-from real-expt
(coerce z rtype
))))
272 (coerce (%pow x y
) rtype
)
274 (let ((pow (%pow abs-x y
)))
275 (declare (double-float pow
))
278 (coerce (* -
1d0 pow
) rtype
))
282 (let ((y*pi
(* y pi
)))
283 (declare (double-float y
*pi
))
285 (coerce (* pow
(%cos y
*pi
))
287 (coerce (* pow
(%sin y
*pi
))
289 (complex-expt (base power
)
290 (if (and (zerop base
) (plusp (realpart power
)))
292 (exp (* power
(log base
))))))
293 (declare (inline real-expt complex-expt
))
294 (number-dispatch ((base number
) (power number
))
295 (((foreach fixnum
(or bignum ratio
) (complex rational
)) integer
)
297 (((foreach single-float double-float
) rational
)
298 (real-expt base power
'(dispatch-type base
)))
299 (((foreach fixnum
(or bignum ratio
) single-float
)
300 (foreach ratio single-float
))
301 (real-expt base power
'single-float
))
302 (((foreach fixnum
(or bignum ratio
) single-float double-float
)
304 (real-expt base power
'double-float
))
305 ((double-float single-float
)
306 (real-expt base power
'double-float
))
307 ;; Handle (expt <complex> <rational>), except the case dealt with
308 ;; in the first clause above, (expt <(complex rational)> <integer>).
309 (((foreach (complex rational
))
311 (* (expt (abs base
) power
)
312 (cis (* power
(phase base
)))))
313 (((foreach (complex single-float
) (complex double-float
))
314 (foreach fixnum
(or bignum ratio
)))
315 (* (expt (abs base
) power
)
316 (cis (* power
(phase base
)))))
317 ;; The next three clauses handle (expt <real> <complex>).
318 (((foreach fixnum
(or bignum ratio
) single-float
)
319 (foreach (complex single-float
) (complex rational
)))
320 (complex-expt base power
))
321 (((foreach fixnum
(or bignum ratio
) single-float
)
322 (complex double-float
))
323 (complex-expt (coerce base
'double-float
) power
))
324 ((double-float complex
)
325 (complex-expt base power
))
326 ;; The next three clauses handle (expt <complex> <float>) and
327 ;; (expt <complex> <complex>).
328 (((foreach (complex single-float
) (complex rational
))
329 (foreach (complex single-float
) (complex rational
) single-float
))
330 (complex-expt base power
))
331 (((foreach (complex single-float
) (complex rational
))
332 (foreach (complex double-float
) double-float
))
333 (complex-expt (coerce base
'(complex double-float
)) power
))
334 (((complex double-float
)
335 (foreach complex double-float single-float
))
336 (complex-expt base power
))))))
338 ;;; FIXME: Maybe rename this so that it's clearer that it only works
341 (declare (type integer x
))
344 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
345 ;; log2(f). So we grab the top few bits of x and scale that
346 ;; appropriately, take the log of it and add it to n.
348 ;; Motivated by an attempt to get LOG to work better on bignums.
349 (let ((n (integer-length x
)))
350 (if (< n sb
!vm
:double-float-digits
)
351 (log (coerce x
'double-float
) 2.0d0
)
352 (let ((f (ldb (byte sb
!vm
:double-float-digits
353 (- n sb
!vm
:double-float-digits
))
355 (+ n
(log (scale-float (coerce f
'double-float
)
356 (- sb
!vm
:double-float-digits
))
359 (defun log (number &optional
(base nil base-p
))
360 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
361 (declare (explicit-check))
365 (if (or (typep number
'double-float
) (typep base
'double-float
))
368 ((and (typep number
'(integer (0) *))
369 (typep base
'(integer (0) *)))
370 (coerce (/ (log2 number
) (log2 base
)) 'single-float
))
371 ((and (typep number
'integer
) (typep base
'double-float
))
372 ;; No single float intermediate result
373 (/ (log2 number
) (log base
2.0d0
)))
374 ((and (typep number
'double-float
) (typep base
'integer
))
375 (/ (log number
2.0d0
) (log2 base
)))
377 (/ (log number
) (log base
))))
378 (number-dispatch ((number number
))
379 (((foreach fixnum bignum
))
381 (complex (log (- number
)) (coerce pi
'single-float
))
382 (coerce (/ (log2 number
) (log (exp 1.0d0
) 2.0d0
)) 'single-float
)))
385 (complex (log (- number
)) (coerce pi
'single-float
))
386 (let ((numerator (numerator number
))
387 (denominator (denominator number
)))
388 (if (= (integer-length numerator
)
389 (integer-length denominator
))
390 (coerce (%log1p
(coerce (- number
1) 'double-float
))
392 (coerce (/ (- (log2 numerator
) (log2 denominator
))
393 (log (exp 1.0d0
) 2.0d0
))
395 (((foreach single-float double-float
))
396 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
397 ;; Since this doesn't seem to be an implementation issue
398 ;; I (pw) take the Kahan result.
399 (if (< (float-sign number
)
400 (coerce 0 '(dispatch-type number
)))
401 (complex (log (- number
)) (coerce pi
'(dispatch-type number
)))
402 (coerce (%log
(coerce number
'double-float
))
403 '(dispatch-type number
))))
405 (complex-log number
)))))
408 "Return the square root of NUMBER."
409 (declare (explicit-check))
410 (number-dispatch ((number number
))
411 (((foreach fixnum bignum ratio
))
414 (coerce (%sqrt
(- (coerce number
'double-float
))) 'single-float
))
415 (coerce (%sqrt
(coerce number
'double-float
)) 'single-float
)))
416 (((foreach single-float double-float
))
418 (complex (coerce 0.0 '(dispatch-type number
))
419 (coerce (%sqrt
(- (coerce number
'double-float
)))
420 '(dispatch-type number
)))
421 (coerce (%sqrt
(coerce number
'double-float
))
422 '(dispatch-type number
))))
424 (complex-sqrt number
))))
426 ;;;; trigonometic and related functions
429 "Return the absolute value of the number."
430 (declare (explicit-check))
431 (number-dispatch ((number number
))
432 (((foreach single-float double-float fixnum rational
))
435 (let ((rx (realpart number
))
436 (ix (imagpart number
)))
439 (sqrt (+ (* rx rx
) (* ix ix
))))
441 (coerce (%hypot
(coerce rx
'double-float
)
442 (coerce (truly-the single-float ix
) 'double-float
))
445 (%hypot rx
(truly-the double-float ix
))))))))
447 (defun phase (number)
448 "Return the angle part of the polar representation of a complex number.
449 For complex numbers, this is (atan (imagpart number) (realpart number)).
450 For non-complex positive numbers, this is 0. For non-complex negative
452 (declare (explicit-check))
453 (number-dispatch ((number number
))
456 (coerce pi
'single-float
)
459 (if (minusp (float-sign number
))
460 (coerce pi
'single-float
)
463 (if (minusp (float-sign number
))
464 (coerce pi
'double-float
)
467 (atan (imagpart number
) (realpart number
)))))
470 "Return the sine of NUMBER."
471 (declare (explicit-check))
472 (number-dispatch ((number number
))
473 (handle-reals %sin number
)
475 (let ((x (realpart number
))
476 (y (imagpart number
)))
477 (complex (* (sin x
) (cosh y
))
478 (* (cos x
) (sinh y
)))))))
481 "Return the cosine of NUMBER."
482 (declare (explicit-check))
483 (number-dispatch ((number number
))
484 (handle-reals %cos number
)
486 (let ((x (realpart number
))
487 (y (imagpart number
)))
488 (complex (* (cos x
) (cosh y
))
489 (- (* (sin x
) (sinh y
))))))))
492 "Return the tangent of NUMBER."
493 (declare (explicit-check))
494 (number-dispatch ((number number
))
495 (handle-reals %tan number
)
497 ;; tan z = -i * tanh(i*z)
498 (let* ((result (complex-tanh (complex (- (imagpart number
))
499 (realpart number
)))))
500 (complex (imagpart result
)
501 (- (realpart result
)))))))
504 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
505 (declare (explicit-check ))
506 (number-dispatch ((theta real
))
507 (((foreach single-float double-float rational
))
508 (complex (cos theta
) (sin theta
)))))
511 "Return the arc sine of NUMBER."
512 (declare (explicit-check))
513 (number-dispatch ((number number
))
515 (if (or (> number
1) (< number -
1))
516 (complex-asin number
)
517 (coerce (%asin
(coerce number
'double-float
)) 'single-float
)))
518 (((foreach single-float double-float
))
519 (if (or (> number
(coerce 1 '(dispatch-type number
)))
520 (< number
(coerce -
1 '(dispatch-type number
))))
521 (complex-asin (complex number
))
522 (coerce (%asin
(coerce number
'double-float
))
523 '(dispatch-type number
))))
525 (complex-asin number
))))
528 "Return the arc cosine of NUMBER."
529 (declare (explicit-check))
530 (number-dispatch ((number number
))
532 (if (or (> number
1) (< number -
1))
533 (complex-acos number
)
534 (coerce (%acos
(coerce number
'double-float
)) 'single-float
)))
535 (((foreach single-float double-float
))
536 (if (or (> number
(coerce 1 '(dispatch-type number
)))
537 (< number
(coerce -
1 '(dispatch-type number
))))
538 (complex-acos (complex number
))
539 (coerce (%acos
(coerce number
'double-float
))
540 '(dispatch-type number
))))
542 (complex-acos number
))))
544 (defun atan (y &optional
(x nil xp
))
545 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
546 (declare (explicit-check))
549 (declare (type double-float y x
)
550 (values double-float
))
553 (if (plusp (float-sign x
))
556 (float-sign y
(/ pi
2)))
558 (number-dispatch ((y real
) (x real
))
560 (foreach double-float single-float fixnum bignum ratio
))
561 (atan2 y
(coerce x
'double-float
)))
562 (((foreach single-float fixnum bignum ratio
)
564 (atan2 (coerce y
'double-float
) x
))
565 (((foreach single-float fixnum bignum ratio
)
566 (foreach single-float fixnum bignum ratio
))
567 (coerce (atan2 (coerce y
'double-float
) (coerce x
'double-float
))
569 (number-dispatch ((y number
))
570 (handle-reals %atan y
)
574 ;;; It seems that every target system has a C version of sinh, cosh,
575 ;;; and tanh. Let's use these for reals because the original
576 ;;; implementations based on the definitions lose big in round-off
577 ;;; error. These bad definitions also mean that sin and cos for
578 ;;; complex numbers can also lose big.
581 "Return the hyperbolic sine of NUMBER."
582 (declare (explicit-check))
583 (number-dispatch ((number number
))
584 (handle-reals %sinh number
)
586 (let ((x (realpart number
))
587 (y (imagpart number
)))
588 (complex (* (sinh x
) (cos y
))
589 (* (cosh x
) (sin y
)))))))
592 "Return the hyperbolic cosine of NUMBER."
593 (declare (explicit-check))
594 (number-dispatch ((number number
))
595 (handle-reals %cosh number
)
597 (let ((x (realpart number
))
598 (y (imagpart number
)))
599 (complex (* (cosh x
) (cos y
))
600 (* (sinh x
) (sin y
)))))))
603 "Return the hyperbolic tangent of NUMBER."
604 (declare (explicit-check))
605 (number-dispatch ((number number
))
606 (handle-reals %tanh number
)
608 (complex-tanh number
))))
610 (defun asinh (number)
611 "Return the hyperbolic arc sine of NUMBER."
612 (declare (explicit-check))
613 (number-dispatch ((number number
))
614 (handle-reals %asinh number
)
616 (complex-asinh number
))))
618 (defun acosh (number)
619 "Return the hyperbolic arc cosine of NUMBER."
620 (declare (explicit-check))
621 (number-dispatch ((number number
))
623 ;; acosh is complex if number < 1
625 (complex-acosh number
)
626 (coerce (%acosh
(coerce number
'double-float
)) 'single-float
)))
627 (((foreach single-float double-float
))
628 (if (< number
(coerce 1 '(dispatch-type number
)))
629 (complex-acosh (complex number
))
630 (coerce (%acosh
(coerce number
'double-float
))
631 '(dispatch-type number
))))
633 (complex-acosh number
))))
635 (defun atanh (number)
636 "Return the hyperbolic arc tangent of NUMBER."
637 (declare (explicit-check))
638 (number-dispatch ((number number
))
640 ;; atanh is complex if |number| > 1
641 (if (or (> number
1) (< number -
1))
642 (complex-atanh number
)
643 (coerce (%atanh
(coerce number
'double-float
)) 'single-float
)))
644 (((foreach single-float double-float
))
645 (if (or (> number
(coerce 1 '(dispatch-type number
)))
646 (< number
(coerce -
1 '(dispatch-type number
))))
647 (complex-atanh (complex number
))
648 (coerce (%atanh
(coerce number
'double-float
))
649 '(dispatch-type number
))))
651 (complex-atanh number
))))
654 ;;;; not-OLD-SPECFUN stuff
656 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
657 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
658 ;;;; the standard special function system.)
660 ;;;; This is a set of routines that implement many elementary
661 ;;;; transcendental functions as specified by ANSI Common Lisp. The
662 ;;;; implementation is based on Kahan's paper.
664 ;;;; I believe I have accurately implemented the routines and are
665 ;;;; correct, but you may want to check for your self.
667 ;;;; These functions are written for CMU Lisp and take advantage of
668 ;;;; some of the features available there. It may be possible,
669 ;;;; however, to port this to other Lisps.
671 ;;;; Some functions are significantly more accurate than the original
672 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
673 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
674 ;;;; answer is pi + i*log(2-sqrt(3)).
676 ;;;; All of the implemented functions will take any number for an
677 ;;;; input, but the result will always be a either a complex
678 ;;;; single-float or a complex double-float.
680 ;;;; general functions:
691 ;;;; utility functions:
694 ;;;; internal functions:
695 ;;;; square coerce-to-complex-type cssqs
698 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
699 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
700 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
703 ;;;; The original CMU CL code requested:
704 ;;;; Please send any bug reports, comments, or improvements to
705 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
707 ;;; FIXME: In SBCL, the floating point infinity constants like
708 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
709 ;;; constants at cross-compile time, because the cross-compilation
710 ;;; host might not have support for floating point infinities. Thus,
711 ;;; they're effectively implemented as special variable references,
712 ;;; and the code below which uses them might be unnecessarily
713 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
714 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
715 ;;; special variable references with (probably equally slow)
718 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
719 ;;; differ in their interpretations of the real line, IMAGPART was
720 ;;; patch, which without a certain amount of effort would have altered
721 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
722 ;;; were patched to use explicit COMPLEX, rather than implicitly
723 ;;; passing in real numbers for treatment with IMAGPART, and these
724 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
725 ;;; however, someone needs to go back to Kahan for the definitive
726 ;;; answer for treatment of negative real floating point numbers and
727 ;;; branch cuts. If adjustment is needed, it is probably the removal
728 ;;; of explicit calls to COMPLEX in the clients of irrational
729 ;;; functions. -- a slightly bitter CSR, 2004-05-16
731 (declaim (inline square
))
733 (declare (double-float x
))
736 ;;; original CMU CL comment, apparently re. LOGB and
738 ;;; If you have these functions in libm, perhaps they should be used
739 ;;; instead of these Lisp versions. These versions are probably good
740 ;;; enough, especially since they are portable.
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 (declare (muffle-conditions t
))
800 (let ((x (float (realpart z
) 1d0
))
801 (y (float (imagpart z
) 1d0
)))
802 ;; Would this be better handled using an exception handler to
803 ;; catch the overflow or underflow signal? For now, we turn all
804 ;; traps off and look at the accrued exceptions to see if any
805 ;; signal would have been raised.
806 (with-float-traps-masked (:underflow
:overflow
)
807 (let ((rho (+ (square x
) (square y
))))
808 (declare (optimize (speed 3) (space 0)))
809 (cond ((and (or (float-nan-p rho
)
810 (float-infinity-p rho
))
811 (or (float-infinity-p (abs x
))
812 (float-infinity-p (abs y
))))
813 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
815 (double-from-bits 0 (1+ sb
!vm
:double-float-normal-exponent-max
) 0)
818 ;; (/ least-positive-double-float double-float-epsilon)
821 (make-double-float #x1fffff
#xfffffffe
)
823 (error "(/ least-positive-long-float long-float-epsilon)")))
824 (traps (ldb sb
!vm
::float-sticky-bits
825 (sb!vm
:floating-point-modes
))))
826 ;; Overflow raised or (underflow raised and rho <
828 (or (not (zerop (logand sb
!vm
:float-overflow-trap-bit traps
)))
829 (and (not (zerop (logand sb
!vm
:float-underflow-trap-bit
832 ;; If we're here, neither x nor y are infinity and at
833 ;; least one is non-zero.. Thus logb returns a nice
835 (let ((k (- (logb-finite (max (abs x
) (abs y
))))))
836 (values (+ (square (scale-float x k
))
837 (square (scale-float y k
)))
842 ;;; principal square root of Z
844 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
845 (defun complex-sqrt (z)
846 ;; KLUDGE: Here and below, we can't just declare Z to be of type
847 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
848 ;; Since there isn't a rational negative zero, this is OK from the
849 ;; point of view of getting the right answer in the face of branch
850 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
851 ;; still ugly. -- CSR, 2004-05-16
852 (declare (type (or complex rational
) z
))
853 (multiple-value-bind (rho k
)
855 (declare (type (or (member 0d0
) (double-float 0d0
)) rho
)
857 (let ((x (float (realpart z
) 1.0d0
))
858 (y (float (imagpart z
) 1.0d0
))
861 (declare (double-float x y eta nu
)
862 ;; get maybe-inline functions inlined.
863 (optimize (space 0)))
864 (if (not (float-nan-p x
))
865 (setf rho
(+ (scale-float (abs x
) (- k
)) (sqrt rho
))))
870 (setf k
(1- (ash k -
1)))
871 (setf rho
(+ rho rho
))))
873 (setf rho
(scale-float (sqrt rho
) k
))
879 (when (not (float-infinity-p (abs nu
)))
880 (setf nu
(/ (/ nu rho
) 2d0
)))
883 (setf nu
(float-sign y rho
))))
884 (coerce-to-complex-type eta nu z
))))
886 ;;; log of Z = log |Z| + i * arg Z
888 ;;; Z may be any number, but the result is always a complex.
889 (defun complex-log (z)
890 (declare (muffle-conditions t
))
891 (declare (type (or rational complex
) z
))
892 ;; The constants t0, t1, t2 should be evaluated to machine
893 ;; precision. In addition, Kahan says the accuracy of log1p
894 ;; influences the choices of these constants but doesn't say how to
895 ;; choose them. We'll just assume his choices matches our
896 ;; implementation of log1p.
897 (let ((t0 (load-time-value
899 (make-double-float #x3fe6a09e
#x667f3bcd
)
901 (error "(/ (sqrt 2l0))")))
902 ;; KLUDGE: if repeatable fasls start failing under some weird
903 ;; xc host, this 1.2d0 might be a good place to examine: while
904 ;; it _should_ be the same in all vaguely-IEEE754 hosts, 1.2
905 ;; is not exactly representable, so something could go wrong.
908 (ln2 (load-time-value
910 (make-double-float #x3fe62e42
#xfefa39ef
)
912 (error "(log 2l0)")))
913 (x (float (realpart z
) 1.0d0
))
914 (y (float (imagpart z
) 1.0d0
)))
915 (multiple-value-bind (rho k
)
917 (declare (optimize (speed 3)))
918 (let ((beta (max (abs x
) (abs y
)))
919 (theta (min (abs x
) (abs y
))))
920 (coerce-to-complex-type (if (and (zerop k
)
924 (/ (%log1p
(+ (* (- beta
1.0d0
)
933 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
934 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
935 ;;; The reason for the imaginary part is caused by the fact that arg
936 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
937 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
938 (defun complex-atanh (z)
939 (declare (muffle-conditions t
))
940 (declare (type (or rational complex
) z
))
942 (theta (/ (sqrt most-positive-double-float
) 4.0d0
))
943 (rho (/ 4.0d0
(sqrt most-positive-double-float
)))
944 (half-pi (/ pi
2.0d0
))
945 (rp (float (realpart z
) 1.0d0
))
946 (beta (float-sign rp
1.0d0
))
948 (y (* beta
(- (float (imagpart z
) 1.0d0
))))
951 ;; Shouldn't need this declare.
952 (declare (double-float x y
))
954 (declare (optimize (speed 3)))
955 (cond ((or (> x theta
)
957 ;; To avoid overflow...
958 (setf nu
(float-sign y half-pi
))
959 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
960 ;; which can cause overflow. Arrange this computation so
961 ;; that it won't overflow.
962 (setf eta
(let* ((x-bigger (> x
(abs y
)))
963 (r (if x-bigger
(/ y x
) (/ x y
)))
964 (d (+ 1.0d0
(* r r
))))
969 ;; Should this be changed so that if y is zero, eta is set
970 ;; to +infinity instead of approx 176? In any case
971 ;; tanh(176) is 1.0d0 within working precision.
972 (let ((t1 (+ 4d0
(square y
)))
973 (t2 (+ (abs y
) rho
)))
974 (setf eta
(log (/ (sqrt (sqrt t1
))
978 (+ half-pi
(atan (* 0.5d0 t2
))))))))
980 (let ((t1 (+ (abs y
) rho
)))
981 ;; Normal case using log1p(x) = log(1 + x)
983 (%log1p
(/ (* 4.0d0 x
)
984 (+ (square (- 1.0d0 x
))
991 (coerce-to-complex-type (* beta eta
)
995 ;;; Compute tanh z = sinh z / cosh z.
996 (defun complex-tanh (z)
997 (declare (muffle-conditions t
))
998 (declare (type (or rational complex
) z
))
999 (let ((x (float (realpart z
) 1.0d0
))
1000 (y (float (imagpart z
) 1.0d0
)))
1002 ;; space 0 to get maybe-inline functions inlined
1003 (declare (optimize (speed 3) (space 0)))
1007 (make-double-float #x406633ce
#x8fb9f87e
)
1009 (error "(/ (+ (log 2l0) (log most-positive-long-float)) 4l0)")))
1010 (coerce-to-complex-type (float-sign x
)
1013 (let* ((tv (%tan y
))
1014 (beta (+ 1.0d0
(* tv tv
)))
1016 (rho (sqrt (+ 1.0d0
(* s s
)))))
1017 (if (float-infinity-p (abs tv
))
1018 (coerce-to-complex-type (/ rho s
)
1021 (let ((den (+ 1.0d0
(* beta s s
))))
1022 (coerce-to-complex-type (/ (* beta rho s
)
1027 ;;; Compute acos z = pi/2 - asin z.
1029 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1030 (defun complex-acos (z)
1031 ;; Kahan says we should only compute the parts needed. Thus, the
1032 ;; REALPART's below should only compute the real part, not the whole
1033 ;; complex expression. Doing this can be important because we may get
1034 ;; spurious signals that occur in the part that we are not using.
1036 ;; However, we take a pragmatic approach and just use the whole
1039 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1040 ;; it's the conjugate of the square root or the square root of the
1041 ;; conjugate. This needs to be checked.
1043 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1044 ;; same as (sqrt (conjugate z)) for all z. This follows because
1046 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1048 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1050 ;; and these two expressions are equal if and only if arg conj z =
1051 ;; -arg z, which is clearly true for all z.
1052 (declare (type (or rational complex
) z
))
1053 (let ((sqrt-1+z
(complex-sqrt (+ 1 z
)))
1054 (sqrt-1-z (complex-sqrt (- 1 z
))))
1055 (with-float-traps-masked (:divide-by-zero
)
1056 (complex (* 2 (atan (/ (realpart sqrt-1-z
)
1057 (realpart sqrt-1
+z
))))
1058 (asinh (imagpart (* (conjugate sqrt-1
+z
)
1061 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1063 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1064 (defun complex-acosh (z)
1065 (declare (type (or rational complex
) z
))
1066 (let ((sqrt-z-1 (complex-sqrt (- z
1)))
1067 (sqrt-z+1 (complex-sqrt (+ z
1))))
1068 (with-float-traps-masked (:divide-by-zero
)
1069 (complex (asinh (realpart (* (conjugate sqrt-z-1
)
1071 (* 2 (atan (/ (imagpart sqrt-z-1
)
1072 (realpart sqrt-z
+1))))))))
1074 ;;; Compute asin z = asinh(i*z)/i.
1076 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1077 (defun complex-asin (z)
1078 (declare (type (or rational complex
) z
))
1079 (let ((sqrt-1-z (complex-sqrt (- 1 z
)))
1080 (sqrt-1+z
(complex-sqrt (+ 1 z
))))
1081 (with-float-traps-masked (:divide-by-zero
)
1082 (complex (atan (/ (realpart z
)
1083 (realpart (* sqrt-1-z sqrt-1
+z
))))
1084 (asinh (imagpart (* (conjugate sqrt-1-z
)
1087 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1089 ;;; Z may be any number, but the result is always a complex.
1090 (defun complex-asinh (z)
1091 (declare (type (or rational complex
) z
))
1092 ;; asinh z = -i * asin (i*z)
1093 (let* ((iz (complex (- (imagpart z
)) (realpart z
)))
1094 (result (complex-asin iz
)))
1095 (complex (imagpart result
)
1096 (- (realpart result
)))))
1098 ;;; Compute atan z = atanh (i*z) / i.
1100 ;;; Z may be any number, but the result is always a complex.
1101 (defun complex-atan (z)
1102 (declare (type (or rational complex
) z
))
1103 ;; atan z = -i * atanh (i*z)
1104 (let* ((iz (complex (- (imagpart z
)) (realpart z
)))
1105 (result (complex-atanh iz
)))
1106 (complex (imagpart result
)
1107 (- (realpart result
)))))