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
))
47 #!+x86
;; for constant folding
48 (macrolet ((def (name ll
)
49 `(defun ,name
,ll
(,name
,@ll
))))
62 #!+(or x86-64 arm-vfp arm64
) ;; 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)
79 (def-math-rtn "acos" 1 #!+win32 t
)
80 (def-math-rtn "asin" 1 #!+win32 t
)
81 (def-math-rtn "cosh" 1 #!+win32 t
)
82 (def-math-rtn "sinh" 1 #!+win32 t
)
83 (def-math-rtn "tanh" 1 #!+win32 t
)
84 (def-math-rtn "asinh" 1 #!+win32 t
)
85 (def-math-rtn "acosh" 1 #!+win32 t
)
86 (def-math-rtn "atanh" 1 #!+win32 t
)
88 ;;; exponential and logarithmic
89 (def-math-rtn "hypot" 2 #!+win32 t
)
90 #!-x86
(def-math-rtn "exp" 1)
91 #!-x86
(def-math-rtn "log" 1)
92 #!-x86
(def-math-rtn "log10" 1)
93 (def-math-rtn "pow" 2)
94 #!-
(or x86 x86-64 arm-vfp arm64
) (def-math-rtn "sqrt" 1)
95 #!-x86
(def-math-rtn "log1p" 1)
102 "Return e raised to the power NUMBER."
103 (declare (explicit-check))
104 (number-dispatch ((number number
))
105 (handle-reals %exp number
)
107 (* (exp (realpart number
))
108 (cis (imagpart number
))))))
110 ;;; INTEXP -- Handle the rational base, integer power case.
112 (declaim (type (or integer null
) *intexp-maximum-exponent
*))
113 (defparameter *intexp-maximum-exponent
* nil
)
115 ;;; This function precisely calculates base raised to an integral
116 ;;; power. It separates the cases by the sign of power, for efficiency
117 ;;; reasons, as powers can be calculated more efficiently if power is
118 ;;; a positive integer. Values of power are calculated as positive
119 ;;; integers, and inverted if negative.
120 (defun intexp (base power
)
121 (when (and *intexp-maximum-exponent
*
122 (> (abs power
) *intexp-maximum-exponent
*))
123 (error "The absolute value of ~S exceeds ~S."
124 power
'*intexp-maximum-exponent
*))
125 (cond ((minusp power
)
126 (/ (intexp base
(- power
))))
130 (do ((nextn (ash power -
1) (ash power -
1))
131 (total (if (oddp power
) base
1)
132 (if (oddp power
) (* base total
) total
)))
133 ((zerop nextn
) total
)
134 (setq base
(* base base
))
135 (setq power nextn
)))))
137 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
138 ;;; floating point stuff. If both args are real, we try %POW right
139 ;;; off, assuming it will return 0 if the result may be complex. If
140 ;;; so, we call COMPLEX-POW which directly computes the complex
141 ;;; result. We also separate the complex-real and real-complex cases
142 ;;; from the general complex case.
143 (defun expt (base power
)
145 "Return BASE raised to the POWER."
146 (declare (explicit-check))
148 (if (and (zerop base
) (floatp power
))
149 (error 'arguments-out-of-domain-error
150 :operands
(list base power
)
152 :references
(list '(:ansi-cl
:function expt
)))
153 (let ((result (1+ (* base power
))))
154 (if (and (floatp result
) (float-nan-p result
))
157 (labels (;; determine if the double float is an integer.
158 ;; 0 - not an integer
162 (declare (type (unsigned-byte 31) ihi
)
163 (type (unsigned-byte 32) lo
)
164 (optimize (speed 3) (safety 0)))
166 (declare (type fixnum isint
))
167 (cond ((>= ihi
#x43400000
) ; exponent >= 53
170 (let ((k (- (ash ihi -
20) #x3ff
))) ; exponent
171 (declare (type (mod 53) k
))
173 (let* ((shift (- 52 k
))
174 (j (logand (ash lo
(- shift
))))
176 (declare (type (mod 32) shift
)
177 (type (unsigned-byte 32) j j2
))
179 (setq isint
(- 2 (logand j
1))))))
181 (let* ((shift (- 20 k
))
182 (j (ash ihi
(- shift
)))
184 (declare (type (mod 32) shift
)
185 (type (unsigned-byte 31) j j2
))
187 (setq isint
(- 2 (logand j
1))))))))))
189 (real-expt (x y rtype
)
190 (let ((x (coerce x
'double-float
))
191 (y (coerce y
'double-float
)))
192 (declare (double-float x y
))
193 (let* ((x-hi (double-float-high-bits x
))
194 (x-lo (double-float-low-bits x
))
195 (x-ihi (logand x-hi
#x7fffffff
))
196 (y-hi (double-float-high-bits y
))
197 (y-lo (double-float-low-bits y
))
198 (y-ihi (logand y-hi
#x7fffffff
)))
199 (declare (type (signed-byte 32) x-hi y-hi
)
200 (type (unsigned-byte 31) x-ihi y-ihi
)
201 (type (unsigned-byte 32) x-lo y-lo
))
203 (when (zerop (logior y-ihi y-lo
))
204 (return-from real-expt
(coerce 1d0 rtype
)))
206 ;; FIXME: Hardcoded qNaN/sNaN values are not portable.
207 (when (or (> x-ihi
#x7ff00000
)
208 (and (= x-ihi
#x7ff00000
) (/= x-lo
0))
210 (and (= y-ihi
#x7ff00000
) (/= y-lo
0)))
211 (return-from real-expt
(coerce (+ x y
) rtype
)))
212 (let ((yisint (if (< x-hi
0) (isint y-ihi y-lo
) 0)))
213 (declare (type fixnum yisint
))
214 ;; special value of y
215 (when (and (zerop y-lo
) (= y-ihi
#x7ff00000
))
217 (return-from real-expt
218 (cond ((and (= x-ihi
#x3ff00000
) (zerop x-lo
))
220 (coerce (- y y
) rtype
))
221 ((>= x-ihi
#x3ff00000
)
222 ;; (|x|>1)**+-inf = inf,0
227 ;; (|x|<1)**-,+inf = inf,0
230 (coerce 0 rtype
))))))
232 (let ((abs-x (abs x
)))
233 (declare (double-float abs-x
))
234 ;; special value of x
235 (when (and (zerop x-lo
)
236 (or (= x-ihi
#x7ff00000
) (zerop x-ihi
)
237 (= x-ihi
#x3ff00000
)))
238 ;; x is +-0,+-inf,+-1
239 (let ((z (if (< y-hi
0)
240 (/ 1 abs-x
) ; z = (1/|x|)
242 (declare (double-float z
))
244 (cond ((and (= x-ihi
#x3ff00000
) (zerop yisint
))
246 (let ((y*pi
(* y pi
)))
247 (declare (double-float y
*pi
))
248 (return-from real-expt
250 (coerce (%cos y
*pi
) rtype
)
251 (coerce (%sin y
*pi
) rtype
)))))
253 ;; (x<0)**odd = -(|x|**odd)
255 (return-from real-expt
(coerce z rtype
))))
259 (coerce (%pow x y
) rtype
)
261 (let ((pow (%pow abs-x y
)))
262 (declare (double-float pow
))
265 (coerce (* -
1d0 pow
) rtype
))
269 (let ((y*pi
(* y pi
)))
270 (declare (double-float y
*pi
))
272 (coerce (* pow
(%cos y
*pi
))
274 (coerce (* pow
(%sin y
*pi
))
276 (complex-expt (base power
)
277 (if (and (zerop base
) (plusp (realpart power
)))
279 (exp (* power
(log base
))))))
280 (declare (inline real-expt complex-expt
))
281 (number-dispatch ((base number
) (power number
))
282 (((foreach fixnum
(or bignum ratio
) (complex rational
)) integer
)
284 (((foreach single-float double-float
) rational
)
285 (real-expt base power
'(dispatch-type base
)))
286 (((foreach fixnum
(or bignum ratio
) single-float
)
287 (foreach ratio single-float
))
288 (real-expt base power
'single-float
))
289 (((foreach fixnum
(or bignum ratio
) single-float double-float
)
291 (real-expt base power
'double-float
))
292 ((double-float single-float
)
293 (real-expt base power
'double-float
))
294 ;; Handle (expt <complex> <rational>), except the case dealt with
295 ;; in the first clause above, (expt <(complex rational)> <integer>).
296 (((foreach (complex rational
) (complex single-float
)
297 (complex double-float
))
299 (* (expt (abs base
) power
)
300 (cis (* power
(phase base
)))))
301 ;; The next three clauses handle (expt <real> <complex>).
302 (((foreach fixnum
(or bignum ratio
) single-float
)
303 (foreach (complex single-float
) (complex rational
)))
304 (complex-expt base power
))
305 (((foreach fixnum
(or bignum ratio
) single-float
)
306 (complex double-float
))
307 (complex-expt (coerce base
'double-float
) power
))
308 ((double-float complex
)
309 (complex-expt base power
))
310 ;; The next three clauses handle (expt <complex> <float>) and
311 ;; (expt <complex> <complex>).
312 (((foreach (complex single-float
) (complex rational
))
313 (foreach (complex single-float
) (complex rational
) single-float
))
314 (complex-expt base power
))
315 (((foreach (complex single-float
) (complex rational
))
316 (foreach (complex double-float
) double-float
))
317 (complex-expt (coerce base
'(complex double-float
)) power
))
318 (((complex double-float
)
319 (foreach complex double-float single-float
))
320 (complex-expt base power
))))))
322 ;;; FIXME: Maybe rename this so that it's clearer that it only works
325 (declare (type integer x
))
328 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
329 ;; log2(f). So we grab the top few bits of x and scale that
330 ;; appropriately, take the log of it and add it to n.
332 ;; Motivated by an attempt to get LOG to work better on bignums.
333 (let ((n (integer-length x
)))
334 (if (< n sb
!vm
:double-float-digits
)
335 (log (coerce x
'double-float
) 2.0d0
)
336 (let ((f (ldb (byte sb
!vm
:double-float-digits
337 (- n sb
!vm
:double-float-digits
))
339 (+ n
(log (scale-float (coerce f
'double-float
)
340 (- sb
!vm
:double-float-digits
))
343 (defun log (number &optional
(base nil base-p
))
345 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
346 (declare (explicit-check))
350 (if (or (typep number
'double-float
) (typep base
'double-float
))
353 ((and (typep number
'(integer (0) *))
354 (typep base
'(integer (0) *)))
355 (coerce (/ (log2 number
) (log2 base
)) 'single-float
))
356 ((and (typep number
'integer
) (typep base
'double-float
))
357 ;; No single float intermediate result
358 (/ (log2 number
) (log base
2.0d0
)))
359 ((and (typep number
'double-float
) (typep base
'integer
))
360 (/ (log number
2.0d0
) (log2 base
)))
362 (/ (log number
) (log base
))))
363 (number-dispatch ((number number
))
364 (((foreach fixnum bignum
))
366 (complex (log (- number
)) (coerce pi
'single-float
))
367 (coerce (/ (log2 number
) (log (exp 1.0d0
) 2.0d0
)) 'single-float
)))
370 (complex (log (- number
)) (coerce pi
'single-float
))
371 (let ((numerator (numerator number
))
372 (denominator (denominator number
)))
373 (if (= (integer-length numerator
)
374 (integer-length denominator
))
375 (coerce (%log1p
(coerce (- number
1) 'double-float
))
377 (coerce (/ (- (log2 numerator
) (log2 denominator
))
378 (log (exp 1.0d0
) 2.0d0
))
380 (((foreach single-float double-float
))
381 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
382 ;; Since this doesn't seem to be an implementation issue
383 ;; I (pw) take the Kahan result.
384 (if (< (float-sign number
)
385 (coerce 0 '(dispatch-type number
)))
386 (complex (log (- number
)) (coerce pi
'(dispatch-type number
)))
387 (coerce (%log
(coerce number
'double-float
))
388 '(dispatch-type number
))))
390 (complex-log number
)))))
394 "Return the square root of NUMBER."
395 (declare (explicit-check))
396 (number-dispatch ((number number
))
397 (((foreach fixnum bignum ratio
))
399 (complex-sqrt number
)
400 (coerce (%sqrt
(coerce number
'double-float
)) 'single-float
)))
401 (((foreach single-float double-float
))
403 (complex-sqrt (complex number
))
404 (coerce (%sqrt
(coerce number
'double-float
))
405 '(dispatch-type number
))))
407 (complex-sqrt number
))))
409 ;;;; trigonometic and related functions
413 "Return the absolute value of the number."
414 (declare (explicit-check))
415 (number-dispatch ((number number
))
416 (((foreach single-float double-float fixnum rational
))
419 (let ((rx (realpart number
))
420 (ix (imagpart number
)))
423 (sqrt (+ (* rx rx
) (* ix ix
))))
425 (coerce (%hypot
(coerce rx
'double-float
)
426 (coerce (truly-the single-float ix
) 'double-float
))
429 (%hypot rx
(truly-the double-float ix
))))))))
431 (defun phase (number)
433 "Return the angle part of the polar representation of a complex number.
434 For complex numbers, this is (atan (imagpart number) (realpart number)).
435 For non-complex positive numbers, this is 0. For non-complex negative
437 (declare (explicit-check))
441 (coerce pi
'single-float
)
444 (if (minusp (float-sign number
))
445 (coerce pi
'single-float
)
448 (if (minusp (float-sign number
))
449 (coerce pi
'double-float
)
452 (atan (imagpart number
) (realpart number
)))))
456 "Return the sine of NUMBER."
457 (declare (explicit-check))
458 (number-dispatch ((number number
))
459 (handle-reals %sin number
)
461 (let ((x (realpart number
))
462 (y (imagpart number
)))
463 (complex (* (sin x
) (cosh y
))
464 (* (cos x
) (sinh y
)))))))
468 "Return the cosine of NUMBER."
469 (declare (explicit-check))
470 (number-dispatch ((number number
))
471 (handle-reals %cos number
)
473 (let ((x (realpart number
))
474 (y (imagpart number
)))
475 (complex (* (cos x
) (cosh y
))
476 (- (* (sin x
) (sinh y
))))))))
480 "Return the tangent of NUMBER."
481 (declare (explicit-check))
482 (number-dispatch ((number number
))
483 (handle-reals %tan number
)
485 (complex-tan number
))))
489 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
490 (declare (type real theta
) (explicit-check))
491 (complex (cos theta
) (sin theta
)))
495 "Return the arc sine of NUMBER."
496 (declare (explicit-check))
497 (number-dispatch ((number number
))
499 (if (or (> number
1) (< number -
1))
500 (complex-asin number
)
501 (coerce (%asin
(coerce number
'double-float
)) 'single-float
)))
502 (((foreach single-float double-float
))
503 (if (or (> number
(coerce 1 '(dispatch-type number
)))
504 (< number
(coerce -
1 '(dispatch-type number
))))
505 (complex-asin (complex number
))
506 (coerce (%asin
(coerce number
'double-float
))
507 '(dispatch-type number
))))
509 (complex-asin number
))))
513 "Return the arc cosine of NUMBER."
514 (declare (explicit-check))
515 (number-dispatch ((number number
))
517 (if (or (> number
1) (< number -
1))
518 (complex-acos number
)
519 (coerce (%acos
(coerce number
'double-float
)) 'single-float
)))
520 (((foreach single-float double-float
))
521 (if (or (> number
(coerce 1 '(dispatch-type number
)))
522 (< number
(coerce -
1 '(dispatch-type number
))))
523 (complex-acos (complex number
))
524 (coerce (%acos
(coerce number
'double-float
))
525 '(dispatch-type number
))))
527 (complex-acos number
))))
529 (defun atan (y &optional
(x nil xp
))
531 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
532 (declare (explicit-check))
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 (declare (explicit-check))
570 (number-dispatch ((number number
))
571 (handle-reals %sinh number
)
573 (let ((x (realpart number
))
574 (y (imagpart number
)))
575 (complex (* (sinh x
) (cos y
))
576 (* (cosh x
) (sin y
)))))))
580 "Return the hyperbolic cosine of NUMBER."
581 (declare (explicit-check))
582 (number-dispatch ((number number
))
583 (handle-reals %cosh number
)
585 (let ((x (realpart number
))
586 (y (imagpart number
)))
587 (complex (* (cosh x
) (cos y
))
588 (* (sinh x
) (sin y
)))))))
592 "Return the hyperbolic tangent of NUMBER."
593 (declare (explicit-check))
594 (number-dispatch ((number number
))
595 (handle-reals %tanh number
)
597 (complex-tanh number
))))
599 (defun asinh (number)
601 "Return the hyperbolic arc sine of NUMBER."
602 (declare (explicit-check))
603 (number-dispatch ((number number
))
604 (handle-reals %asinh number
)
606 (complex-asinh number
))))
608 (defun acosh (number)
610 "Return the hyperbolic arc cosine of NUMBER."
611 (declare (explicit-check))
612 (number-dispatch ((number number
))
614 ;; acosh is complex if number < 1
616 (complex-acosh number
)
617 (coerce (%acosh
(coerce number
'double-float
)) 'single-float
)))
618 (((foreach single-float double-float
))
619 (if (< number
(coerce 1 '(dispatch-type number
)))
620 (complex-acosh (complex number
))
621 (coerce (%acosh
(coerce number
'double-float
))
622 '(dispatch-type number
))))
624 (complex-acosh number
))))
626 (defun atanh (number)
628 "Return the hyperbolic arc tangent of NUMBER."
629 (declare (explicit-check))
630 (number-dispatch ((number number
))
632 ;; atanh is complex if |number| > 1
633 (if (or (> number
1) (< number -
1))
634 (complex-atanh number
)
635 (coerce (%atanh
(coerce number
'double-float
)) 'single-float
)))
636 (((foreach single-float double-float
))
637 (if (or (> number
(coerce 1 '(dispatch-type number
)))
638 (< number
(coerce -
1 '(dispatch-type number
))))
639 (complex-atanh (complex number
))
640 (coerce (%atanh
(coerce number
'double-float
))
641 '(dispatch-type number
))))
643 (complex-atanh number
))))
646 ;;;; not-OLD-SPECFUN stuff
648 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
649 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
650 ;;;; the standard special function system.)
652 ;;;; This is a set of routines that implement many elementary
653 ;;;; transcendental functions as specified by ANSI Common Lisp. The
654 ;;;; implementation is based on Kahan's paper.
656 ;;;; I believe I have accurately implemented the routines and are
657 ;;;; correct, but you may want to check for your self.
659 ;;;; These functions are written for CMU Lisp and take advantage of
660 ;;;; some of the features available there. It may be possible,
661 ;;;; however, to port this to other Lisps.
663 ;;;; Some functions are significantly more accurate than the original
664 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
665 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
666 ;;;; answer is pi + i*log(2-sqrt(3)).
668 ;;;; All of the implemented functions will take any number for an
669 ;;;; input, but the result will always be a either a complex
670 ;;;; single-float or a complex double-float.
672 ;;;; general functions:
684 ;;;; utility functions:
687 ;;;; internal functions:
688 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
691 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
692 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
693 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
696 ;;;; The original CMU CL code requested:
697 ;;;; Please send any bug reports, comments, or improvements to
698 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
700 ;;; FIXME: In SBCL, the floating point infinity constants like
701 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
702 ;;; constants at cross-compile time, because the cross-compilation
703 ;;; host might not have support for floating point infinities. Thus,
704 ;;; they're effectively implemented as special variable references,
705 ;;; and the code below which uses them might be unnecessarily
706 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
707 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
708 ;;; special variable references with (probably equally slow)
711 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
712 ;;; differ in their interpretations of the real line, IMAGPART was
713 ;;; patch, which without a certain amount of effort would have altered
714 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
715 ;;; were patched to use explicit COMPLEX, rather than implicitly
716 ;;; passing in real numbers for treatment with IMAGPART, and these
717 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
718 ;;; however, someone needs to go back to Kahan for the definitive
719 ;;; answer for treatment of negative real floating point numbers and
720 ;;; branch cuts. If adjustment is needed, it is probably the removal
721 ;;; of explicit calls to COMPLEX in the clients of irrational
722 ;;; functions. -- a slightly bitter CSR, 2004-05-16
724 (declaim (inline square
))
726 (declare (double-float x
))
729 ;;; original CMU CL comment, apparently re. LOGB and
731 ;;; If you have these functions in libm, perhaps they should be used
732 ;;; instead of these Lisp versions. These versions are probably good
733 ;;; enough, especially since they are portable.
735 ;;; This is like LOGB, but X is not infinity and non-zero and not a
736 ;;; NaN, so we can always return an integer.
737 (declaim (inline logb-finite
))
738 (defun logb-finite (x)
739 (declare (type double-float x
))
740 (multiple-value-bind (signif exponent sign
)
742 (declare (ignore signif sign
))
743 ;; DECODE-FLOAT is almost right, except that the exponent is off
747 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
748 ;;; For the special cases, the following values are used:
751 ;;; +/- infinity +infinity
754 (declare (type double-float x
))
755 (cond ((float-nan-p x
)
757 ((float-infinity-p x
)
758 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
759 (double-from-bits 0 (1+ sb
!vm
:double-float-normal-exponent-max
) 0))
761 ;; The answer is negative infinity, but we are supposed to
762 ;; signal divide-by-zero, so do the actual division
768 ;;; This function is used to create a complex number of the
769 ;;; appropriate type:
770 ;;; Create complex number with real part X and imaginary part Y
771 ;;; such that has the same type as Z. If Z has type (complex
772 ;;; rational), the X and Y are coerced to single-float.
773 #!+long-float
(eval-when (:compile-toplevel
:load-toplevel
:execute
)
774 (error "needs work for long float support"))
775 (declaim (inline coerce-to-complex-type
))
776 (defun coerce-to-complex-type (x y z
)
777 (declare (double-float x y
)
779 (if (typep (realpart z
) 'double-float
)
781 ;; Convert anything that's not already a DOUBLE-FLOAT (because
782 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
783 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
784 (complex (float x
1f0
)
787 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
788 ;;; result is r + i*k, where k is an integer.
789 #!+long-float
(eval-when (:compile-toplevel
:load-toplevel
:execute
)
790 (error "needs work for long float support"))
792 (let ((x (float (realpart z
) 1d0
))
793 (y (float (imagpart z
) 1d0
)))
794 ;; Would this be better handled using an exception handler to
795 ;; catch the overflow or underflow signal? For now, we turn all
796 ;; traps off and look at the accrued exceptions to see if any
797 ;; signal would have been raised.
798 (with-float-traps-masked (:underflow
:overflow
)
799 (let ((rho (+ (square x
) (square y
))))
800 (declare (optimize (speed 3) (space 0)))
801 (cond ((and (or (float-nan-p rho
)
802 (float-infinity-p rho
))
803 (or (float-infinity-p (abs x
))
804 (float-infinity-p (abs y
))))
805 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
807 (double-from-bits 0 (1+ sb
!vm
:double-float-normal-exponent-max
) 0)
810 ;; (/ least-positive-double-float double-float-epsilon)
813 (make-double-float #x1fffff
#xfffffffe
)
815 (error "(/ least-positive-long-float long-float-epsilon)")))
816 (traps (ldb sb
!vm
::float-sticky-bits
817 (sb!vm
:floating-point-modes
))))
818 ;; Overflow raised or (underflow raised and rho <
820 (or (not (zerop (logand sb
!vm
:float-overflow-trap-bit traps
)))
821 (and (not (zerop (logand sb
!vm
:float-underflow-trap-bit
824 ;; If we're here, neither x nor y are infinity and at
825 ;; least one is non-zero.. Thus logb returns a nice
827 (let ((k (- (logb-finite (max (abs x
) (abs y
))))))
828 (values (+ (square (scale-float x k
))
829 (square (scale-float y k
)))
834 ;;; principal square root of Z
836 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
837 (defun complex-sqrt (z)
838 ;; KLUDGE: Here and below, we can't just declare Z to be of type
839 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
840 ;; Since there isn't a rational negative zero, this is OK from the
841 ;; point of view of getting the right answer in the face of branch
842 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
843 ;; still ugly. -- CSR, 2004-05-16
844 (declare (type (or complex rational
) z
))
845 (multiple-value-bind (rho k
)
847 (declare (type (or (member 0d0
) (double-float 0d0
)) rho
)
849 (let ((x (float (realpart z
) 1.0d0
))
850 (y (float (imagpart z
) 1.0d0
))
853 (declare (double-float x y eta nu
)
854 ;; get maybe-inline functions inlined.
855 (optimize (space 0)))
856 (if (not (float-nan-p x
))
857 (setf rho
(+ (scale-float (abs x
) (- k
)) (sqrt rho
))))
862 (setf k
(1- (ash k -
1)))
863 (setf rho
(+ rho rho
))))
865 (setf rho
(scale-float (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 (load-time-value
891 (make-double-float #x3fe6a09e
#x667f3bcd
)
893 (error "(/ (sqrt 2l0))")))
894 ;; KLUDGE: if repeatable fasls start failing under some weird
895 ;; xc host, this 1.2d0 might be a good place to examine: while
896 ;; it _should_ be the same in all vaguely-IEEE754 hosts, 1.2
897 ;; is not exactly representable, so something could go wrong.
900 (ln2 (load-time-value
902 (make-double-float #x3fe62e42
#xfefa39ef
)
904 (error "(log 2l0)")))
905 (x (float (realpart z
) 1.0d0
))
906 (y (float (imagpart z
) 1.0d0
)))
907 (multiple-value-bind (rho k
)
909 (declare (optimize (speed 3)))
910 (let ((beta (max (abs x
) (abs y
)))
911 (theta (min (abs x
) (abs y
))))
912 (coerce-to-complex-type (if (and (zerop k
)
916 (/ (%log1p
(+ (* (- beta
1.0d0
)
925 ;;; log of Z = log |Z| + i * arg Z
927 ;;; Z may be any number, but the result is always a complex.
928 (defun complex-log (z)
929 (declare (type (or rational complex
) z
))
930 (complex-log-scaled z
0))
932 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
933 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
934 ;;; The reason for the imaginary part is caused by the fact that arg
935 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
936 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
937 (defun complex-atanh (z)
938 (declare (type (or rational complex
) z
))
940 (theta (/ (sqrt most-positive-double-float
) 4.0d0
))
941 (rho (/ 4.0d0
(sqrt most-positive-double-float
)))
942 (half-pi (/ pi
2.0d0
))
943 (rp (float (realpart z
) 1.0d0
))
944 (beta (float-sign rp
1.0d0
))
946 (y (* beta
(- (float (imagpart z
) 1.0d0
))))
949 ;; Shouldn't need this declare.
950 (declare (double-float x y
))
952 (declare (optimize (speed 3)))
953 (cond ((or (> x theta
)
955 ;; To avoid overflow...
956 (setf nu
(float-sign y half-pi
))
957 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
958 ;; which can cause overflow. Arrange this computation so
959 ;; that it won't overflow.
960 (setf eta
(let* ((x-bigger (> x
(abs y
)))
961 (r (if x-bigger
(/ y x
) (/ x y
)))
962 (d (+ 1.0d0
(* r r
))))
967 ;; Should this be changed so that if y is zero, eta is set
968 ;; to +infinity instead of approx 176? In any case
969 ;; tanh(176) is 1.0d0 within working precision.
970 (let ((t1 (+ 4d0
(square y
)))
971 (t2 (+ (abs y
) rho
)))
972 (setf eta
(log (/ (sqrt (sqrt t1
))
976 (+ half-pi
(atan (* 0.5d0 t2
))))))))
978 (let ((t1 (+ (abs y
) rho
)))
979 ;; Normal case using log1p(x) = log(1 + x)
981 (%log1p
(/ (* 4.0d0 x
)
982 (+ (square (- 1.0d0 x
))
989 (coerce-to-complex-type (* beta eta
)
993 ;;; Compute tanh z = sinh z / cosh z.
994 (defun complex-tanh (z)
995 (declare (type (or rational complex
) z
))
996 (let ((x (float (realpart z
) 1.0d0
))
997 (y (float (imagpart z
) 1.0d0
)))
999 ;; space 0 to get maybe-inline functions inlined
1000 (declare (optimize (speed 3) (space 0)))
1004 (make-double-float #x406633ce
#x8fb9f87e
)
1006 (error "(/ (+ (log 2l0) (log most-positive-long-float)) 4l0)")))
1007 (coerce-to-complex-type (float-sign x
)
1010 (let* ((tv (%tan y
))
1011 (beta (+ 1.0d0
(* tv tv
)))
1013 (rho (sqrt (+ 1.0d0
(* s s
)))))
1014 (if (float-infinity-p (abs tv
))
1015 (coerce-to-complex-type (/ rho s
)
1018 (let ((den (+ 1.0d0
(* beta s s
))))
1019 (coerce-to-complex-type (/ (* beta rho s
)
1024 ;;; Compute acos z = pi/2 - asin z.
1026 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1027 (defun complex-acos (z)
1028 ;; Kahan says we should only compute the parts needed. Thus, the
1029 ;; REALPART's below should only compute the real part, not the whole
1030 ;; complex expression. Doing this can be important because we may get
1031 ;; spurious signals that occur in the part that we are not using.
1033 ;; However, we take a pragmatic approach and just use the whole
1036 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1037 ;; it's the conjugate of the square root or the square root of the
1038 ;; conjugate. This needs to be checked.
1040 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1041 ;; same as (sqrt (conjugate z)) for all z. This follows because
1043 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1045 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1047 ;; and these two expressions are equal if and only if arg conj z =
1048 ;; -arg z, which is clearly true for all z.
1049 (declare (type (or rational complex
) z
))
1050 (let ((sqrt-1+z
(complex-sqrt (+ 1 z
)))
1051 (sqrt-1-z (complex-sqrt (- 1 z
))))
1052 (with-float-traps-masked (:divide-by-zero
)
1053 (complex (* 2 (atan (/ (realpart sqrt-1-z
)
1054 (realpart sqrt-1
+z
))))
1055 (asinh (imagpart (* (conjugate sqrt-1
+z
)
1058 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1060 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1061 (defun complex-acosh (z)
1062 (declare (type (or rational complex
) z
))
1063 (let ((sqrt-z-1 (complex-sqrt (- z
1)))
1064 (sqrt-z+1 (complex-sqrt (+ z
1))))
1065 (with-float-traps-masked (:divide-by-zero
)
1066 (complex (asinh (realpart (* (conjugate sqrt-z-1
)
1068 (* 2 (atan (/ (imagpart sqrt-z-1
)
1069 (realpart sqrt-z
+1))))))))
1071 ;;; Compute asin z = asinh(i*z)/i.
1073 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1074 (defun complex-asin (z)
1075 (declare (type (or rational complex
) z
))
1076 (let ((sqrt-1-z (complex-sqrt (- 1 z
)))
1077 (sqrt-1+z
(complex-sqrt (+ 1 z
))))
1078 (with-float-traps-masked (:divide-by-zero
)
1079 (complex (atan (/ (realpart z
)
1080 (realpart (* sqrt-1-z sqrt-1
+z
))))
1081 (asinh (imagpart (* (conjugate sqrt-1-z
)
1084 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1086 ;;; Z may be any number, but the result is always a complex.
1087 (defun complex-asinh (z)
1088 (declare (type (or rational complex
) z
))
1089 ;; asinh z = -i * asin (i*z)
1090 (let* ((iz (complex (- (imagpart z
)) (realpart z
)))
1091 (result (complex-asin iz
)))
1092 (complex (imagpart result
)
1093 (- (realpart result
)))))
1095 ;;; Compute atan z = atanh (i*z) / i.
1097 ;;; Z may be any number, but the result is always a complex.
1098 (defun complex-atan (z)
1099 (declare (type (or rational complex
) z
))
1100 ;; atan z = -i * atanh (i*z)
1101 (let* ((iz (complex (- (imagpart z
)) (realpart z
)))
1102 (result (complex-atanh iz
)))
1103 (complex (imagpart result
)
1104 (- (realpart result
)))))
1106 ;;; Compute tan z = -i * tanh(i * z)
1108 ;;; Z may be any number, but the result is always a complex.
1109 (defun complex-tan (z)
1110 (declare (type (or rational complex
) z
))
1111 ;; tan z = -i * tanh(i*z)
1112 (let* ((iz (complex (- (imagpart z
)) (realpart z
)))
1113 (result (complex-tanh iz
)))
1114 (complex (imagpart result
)
1115 (- (realpart result
)))))