1.0.18.17: Alter some STYLE-WARNING names introduced in 1.0.18.16.
[sbcl/pkhuong.git] / src / code / irrat.lisp
blob65c96f152a6ebb8277b7ac799f0747791eb0e60d
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
5 ;;;; more information.
6 ;;;;
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
17 (defconstant pi
18 #!+long-float 3.14159265358979323846264338327950288419716939937511l0
19 #!-long-float 3.14159265358979323846264338327950288419716939937511d0)
21 ;;; Make these INLINE, since the call to C is at least as compact as a
22 ;;; Lisp call, and saves number consing to boot.
23 (eval-when (:compile-toplevel :execute)
25 (sb!xc:defmacro def-math-rtn (name num-args)
26 (let ((function (symbolicate "%" (string-upcase name))))
27 `(progn
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))
33 'double-float)
34 results)))))))
36 (defun handle-reals (function var)
37 `((((foreach fixnum single-float bignum ratio))
38 (coerce (,function (coerce ,var 'double-float)) 'single-float))
39 ((double-float)
40 (,function ,var))))
42 ) ; EVAL-WHEN
44 #!+x86 ;; for constant folding
45 (macrolet ((def (name ll)
46 `(defun ,name ,ll (,name ,@ll))))
47 (def %atan2 (x y))
48 (def %atan (x))
49 (def %tan (x))
50 (def %tan-quick (x))
51 (def %cos (x))
52 (def %cos-quick (x))
53 (def %sin (x))
54 (def %sin-quick (x))
55 (def %sqrt (x))
56 (def %log (x))
57 (def %exp (x)))
59 #!+x86-64 ;; for constant folding
60 (macrolet ((def (name ll)
61 `(defun ,name ,ll (,name ,@ll))))
62 (def %sqrt (x)))
64 ;;;; stubs for the Unix math library
65 ;;;;
66 ;;;; Many of these are unnecessary on the X86 because they're built
67 ;;;; into the FPU.
69 ;;; trigonometric
70 #!-x86 (def-math-rtn "sin" 1)
71 #!-x86 (def-math-rtn "cos" 1)
72 #!-x86 (def-math-rtn "tan" 1)
73 (def-math-rtn "asin" 1)
74 (def-math-rtn "acos" 1)
75 #!-x86 (def-math-rtn "atan" 1)
76 #!-x86 (def-math-rtn "atan2" 2)
77 (def-math-rtn "sinh" 1)
78 (def-math-rtn "cosh" 1)
79 #!-win32
80 (progn
81 (def-math-rtn "tanh" 1)
82 (def-math-rtn "asinh" 1)
83 (def-math-rtn "acosh" 1)
84 (def-math-rtn "atanh" 1))
85 #!+win32
86 (progn
87 (declaim (inline %tanh))
88 (defun %tanh (number)
89 (/ (%sinh number) (%cosh number)))
90 (declaim (inline %asinh))
91 (defun %asinh (number)
92 (log (+ number (sqrt (+ (* number number) 1.0d0))) #.(exp 1.0d0)))
93 (declaim (inline %acosh))
94 (defun %acosh (number)
95 (log (+ number (sqrt (- (* number number) 1.0d0))) #.(exp 1.0d0)))
96 (declaim (inline %atanh))
97 (defun %atanh (number)
98 (let ((ratio (/ (+ 1 number) (- 1 number))))
99 ;; Were we effectively zero?
100 (if (= ratio -1.0d0)
101 0.0d0
102 (/ (log ratio #.(exp 1.0d0)) 2.0d0)))))
104 ;;; exponential and logarithmic
105 #!-x86 (def-math-rtn "exp" 1)
106 #!-x86 (def-math-rtn "log" 1)
107 #!-x86 (def-math-rtn "log10" 1)
108 #!-win32(def-math-rtn "pow" 2)
109 #!-(or x86 x86-64) (def-math-rtn "sqrt" 1)
110 (def-math-rtn "hypot" 2)
111 #!-(or hpux x86) (def-math-rtn "log1p" 1)
113 ;;;; power functions
115 (defun exp (number)
116 #!+sb-doc
117 "Return e raised to the power NUMBER."
118 (number-dispatch ((number number))
119 (handle-reals %exp number)
120 ((complex)
121 (* (exp (realpart number))
122 (cis (imagpart number))))))
124 ;;; INTEXP -- Handle the rational base, integer power case.
126 (declaim (type (or integer null) *intexp-maximum-exponent*))
127 (defparameter *intexp-maximum-exponent* nil)
129 ;;; This function precisely calculates base raised to an integral
130 ;;; power. It separates the cases by the sign of power, for efficiency
131 ;;; reasons, as powers can be calculated more efficiently if power is
132 ;;; a positive integer. Values of power are calculated as positive
133 ;;; integers, and inverted if negative.
134 (defun intexp (base power)
135 (when (and *intexp-maximum-exponent*
136 (> (abs power) *intexp-maximum-exponent*))
137 (error "The absolute value of ~S exceeds ~S."
138 power '*intexp-maximum-exponent*))
139 (cond ((minusp power)
140 (/ (intexp base (- power))))
141 ((eql base 2)
142 (ash 1 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 #!+sb-doc
159 "Return BASE raised to the POWER."
160 (if (zerop power)
161 (let ((result (1+ (* base power))))
162 (if (and (floatp result) (float-nan-p result))
163 (float 1 result)
164 result))
165 (labels (;; determine if the double float is an integer.
166 ;; 0 - not an integer
167 ;; 1 - an odd int
168 ;; 2 - an even int
169 (isint (ihi lo)
170 (declare (type (unsigned-byte 31) ihi)
171 (type (unsigned-byte 32) lo)
172 (optimize (speed 3) (safety 0)))
173 (let ((isint 0))
174 (declare (type fixnum isint))
175 (cond ((>= ihi #x43400000) ; exponent >= 53
176 (setq isint 2))
177 ((>= ihi #x3ff00000)
178 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
179 (declare (type (mod 53) k))
180 (cond ((> k 20)
181 (let* ((shift (- 52 k))
182 (j (logand (ash lo (- shift))))
183 (j2 (ash j shift)))
184 (declare (type (mod 32) shift)
185 (type (unsigned-byte 32) j j2))
186 (when (= j2 lo)
187 (setq isint (- 2 (logand j 1))))))
188 ((= lo 0)
189 (let* ((shift (- 20 k))
190 (j (ash ihi (- shift)))
191 (j2 (ash j shift)))
192 (declare (type (mod 32) shift)
193 (type (unsigned-byte 31) j j2))
194 (when (= j2 ihi)
195 (setq isint (- 2 (logand j 1))))))))))
196 isint))
197 (real-expt (x y rtype)
198 (let ((x (coerce x 'double-float))
199 (y (coerce y 'double-float)))
200 (declare (double-float x y))
201 (let* ((x-hi (sb!kernel:double-float-high-bits x))
202 (x-lo (sb!kernel:double-float-low-bits x))
203 (x-ihi (logand x-hi #x7fffffff))
204 (y-hi (sb!kernel:double-float-high-bits y))
205 (y-lo (sb!kernel:double-float-low-bits y))
206 (y-ihi (logand y-hi #x7fffffff)))
207 (declare (type (signed-byte 32) x-hi y-hi)
208 (type (unsigned-byte 31) x-ihi y-ihi)
209 (type (unsigned-byte 32) x-lo y-lo))
210 ;; y==zero: x**0 = 1
211 (when (zerop (logior y-ihi y-lo))
212 (return-from real-expt (coerce 1d0 rtype)))
213 ;; +-NaN return x+y
214 ;; FIXME: Hardcoded qNaN/sNaN values are not portable.
215 (when (or (> x-ihi #x7ff00000)
216 (and (= x-ihi #x7ff00000) (/= x-lo 0))
217 (> y-ihi #x7ff00000)
218 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
219 (return-from real-expt (coerce (+ x y) rtype)))
220 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
221 (declare (type fixnum yisint))
222 ;; special value of y
223 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
224 ;; y is +-inf
225 (return-from real-expt
226 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
227 ;; +-1**inf is NaN
228 (coerce (- y y) rtype))
229 ((>= x-ihi #x3ff00000)
230 ;; (|x|>1)**+-inf = inf,0
231 (if (>= y-hi 0)
232 (coerce y rtype)
233 (coerce 0 rtype)))
235 ;; (|x|<1)**-,+inf = inf,0
236 (if (< y-hi 0)
237 (coerce (- y) rtype)
238 (coerce 0 rtype))))))
240 (let ((abs-x (abs x)))
241 (declare (double-float abs-x))
242 ;; special value of x
243 (when (and (zerop x-lo)
244 (or (= x-ihi #x7ff00000) (zerop x-ihi)
245 (= x-ihi #x3ff00000)))
246 ;; x is +-0,+-inf,+-1
247 (let ((z (if (< y-hi 0)
248 (/ 1 abs-x) ; z = (1/|x|)
249 abs-x)))
250 (declare (double-float z))
251 (when (< x-hi 0)
252 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
253 ;; (-1)**non-int
254 (let ((y*pi (* y pi)))
255 (declare (double-float y*pi))
256 (return-from real-expt
257 (complex
258 (coerce (%cos y*pi) rtype)
259 (coerce (%sin y*pi) rtype)))))
260 ((= yisint 1)
261 ;; (x<0)**odd = -(|x|**odd)
262 (setq z (- z)))))
263 (return-from real-expt (coerce z rtype))))
265 (if (>= x-hi 0)
266 ;; x>0
267 (coerce (sb!kernel::%pow x y) rtype)
268 ;; x<0
269 (let ((pow (sb!kernel::%pow abs-x y)))
270 (declare (double-float pow))
271 (case yisint
272 (1 ; odd
273 (coerce (* -1d0 pow) rtype))
274 (2 ; even
275 (coerce pow rtype))
276 (t ; non-integer
277 (let ((y*pi (* y pi)))
278 (declare (double-float y*pi))
279 (complex
280 (coerce (* pow (%cos y*pi))
281 rtype)
282 (coerce (* pow (%sin y*pi))
283 rtype)))))))))))))
284 (declare (inline real-expt))
285 (number-dispatch ((base number) (power number))
286 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
287 (intexp base power))
288 (((foreach single-float double-float) rational)
289 (real-expt base power '(dispatch-type base)))
290 (((foreach fixnum (or bignum ratio) single-float)
291 (foreach ratio single-float))
292 (real-expt base power 'single-float))
293 (((foreach fixnum (or bignum ratio) single-float double-float)
294 double-float)
295 (real-expt base power 'double-float))
296 ((double-float single-float)
297 (real-expt base power 'double-float))
298 (((foreach (complex rational) (complex float)) rational)
299 (* (expt (abs base) power)
300 (cis (* power (phase base)))))
301 (((foreach fixnum (or bignum ratio) single-float double-float)
302 complex)
303 (if (and (zerop base) (plusp (realpart power)))
304 (* base power)
305 (exp (* power (log base)))))
306 (((foreach (complex float) (complex rational))
307 (foreach complex double-float single-float))
308 (if (and (zerop base) (plusp (realpart power)))
309 (* base power)
310 (exp (* power (log base)))))))))
312 ;;; FIXME: Maybe rename this so that it's clearer that it only works
313 ;;; on integers?
314 (defun log2 (x)
315 (declare (type integer x))
316 ;; CMUCL comment:
318 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
319 ;; log2(f). So we grab the top few bits of x and scale that
320 ;; appropriately, take the log of it and add it to n.
322 ;; Motivated by an attempt to get LOG to work better on bignums.
323 (let ((n (integer-length x)))
324 (if (< n sb!vm:double-float-digits)
325 (log (coerce x 'double-float) 2.0d0)
326 (let ((f (ldb (byte sb!vm:double-float-digits
327 (- n sb!vm:double-float-digits))
328 x)))
329 (+ n (log (scale-float (coerce f 'double-float)
330 (- sb!vm:double-float-digits))
331 2.0d0))))))
333 (defun log (number &optional (base nil base-p))
334 #!+sb-doc
335 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
336 (if base-p
337 (cond
338 ((zerop base) 0f0) ; FIXME: type
339 ((and (typep number '(integer (0) *))
340 (typep base '(integer (0) *)))
341 (coerce (/ (log2 number) (log2 base)) 'single-float))
342 (t (/ (log number) (log base))))
343 (number-dispatch ((number number))
344 (((foreach fixnum bignum))
345 (if (minusp number)
346 (complex (log (- number)) (coerce pi 'single-float))
347 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
348 ((ratio)
349 (if (minusp number)
350 (complex (log (- number)) (coerce pi 'single-float))
351 (let ((numerator (numerator number))
352 (denominator (denominator number)))
353 (if (= (integer-length numerator)
354 (integer-length denominator))
355 (coerce (%log1p (coerce (- number 1) 'double-float))
356 'single-float)
357 (coerce (/ (- (log2 numerator) (log2 denominator))
358 (log (exp 1.0d0) 2.0d0))
359 'single-float)))))
360 (((foreach single-float double-float))
361 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
362 ;; Since this doesn't seem to be an implementation issue
363 ;; I (pw) take the Kahan result.
364 (if (< (float-sign number)
365 (coerce 0 '(dispatch-type number)))
366 (complex (log (- number)) (coerce pi '(dispatch-type number)))
367 (coerce (%log (coerce number 'double-float))
368 '(dispatch-type number))))
369 ((complex)
370 (complex-log number)))))
372 (defun sqrt (number)
373 #!+sb-doc
374 "Return the square root of NUMBER."
375 (number-dispatch ((number number))
376 (((foreach fixnum bignum ratio))
377 (if (minusp number)
378 (complex-sqrt number)
379 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
380 (((foreach single-float double-float))
381 (if (minusp number)
382 (complex-sqrt (complex number))
383 (coerce (%sqrt (coerce number 'double-float))
384 '(dispatch-type number))))
385 ((complex)
386 (complex-sqrt number))))
388 ;;;; trigonometic and related functions
390 (defun abs (number)
391 #!+sb-doc
392 "Return the absolute value of the number."
393 (number-dispatch ((number number))
394 (((foreach single-float double-float fixnum rational))
395 (abs number))
396 ((complex)
397 (let ((rx (realpart number))
398 (ix (imagpart number)))
399 (etypecase rx
400 (rational
401 (sqrt (+ (* rx rx) (* ix ix))))
402 (single-float
403 (coerce (%hypot (coerce rx 'double-float)
404 (coerce ix 'double-float))
405 'single-float))
406 (double-float
407 (%hypot rx ix)))))))
409 (defun phase (number)
410 #!+sb-doc
411 "Return the angle part of the polar representation of a complex number.
412 For complex numbers, this is (atan (imagpart number) (realpart number)).
413 For non-complex positive numbers, this is 0. For non-complex negative
414 numbers this is PI."
415 (etypecase number
416 (rational
417 (if (minusp number)
418 (coerce pi 'single-float)
419 0.0f0))
420 (single-float
421 (if (minusp (float-sign number))
422 (coerce pi 'single-float)
423 0.0f0))
424 (double-float
425 (if (minusp (float-sign number))
426 (coerce pi 'double-float)
427 0.0d0))
428 (complex
429 (atan (imagpart number) (realpart number)))))
431 (defun sin (number)
432 #!+sb-doc
433 "Return the sine of NUMBER."
434 (number-dispatch ((number number))
435 (handle-reals %sin number)
436 ((complex)
437 (let ((x (realpart number))
438 (y (imagpart number)))
439 (complex (* (sin x) (cosh y))
440 (* (cos x) (sinh y)))))))
442 (defun cos (number)
443 #!+sb-doc
444 "Return the cosine of NUMBER."
445 (number-dispatch ((number number))
446 (handle-reals %cos number)
447 ((complex)
448 (let ((x (realpart number))
449 (y (imagpart number)))
450 (complex (* (cos x) (cosh y))
451 (- (* (sin x) (sinh y))))))))
453 (defun tan (number)
454 #!+sb-doc
455 "Return the tangent of NUMBER."
456 (number-dispatch ((number number))
457 (handle-reals %tan number)
458 ((complex)
459 (complex-tan number))))
461 (defun cis (theta)
462 #!+sb-doc
463 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
464 (declare (type real theta))
465 (complex (cos theta) (sin theta)))
467 (defun asin (number)
468 #!+sb-doc
469 "Return the arc sine of NUMBER."
470 (number-dispatch ((number number))
471 ((rational)
472 (if (or (> number 1) (< number -1))
473 (complex-asin number)
474 (coerce (%asin (coerce number 'double-float)) 'single-float)))
475 (((foreach single-float double-float))
476 (if (or (> number (coerce 1 '(dispatch-type number)))
477 (< number (coerce -1 '(dispatch-type number))))
478 (complex-asin (complex number))
479 (coerce (%asin (coerce number 'double-float))
480 '(dispatch-type number))))
481 ((complex)
482 (complex-asin number))))
484 (defun acos (number)
485 #!+sb-doc
486 "Return the arc cosine of NUMBER."
487 (number-dispatch ((number number))
488 ((rational)
489 (if (or (> number 1) (< number -1))
490 (complex-acos number)
491 (coerce (%acos (coerce number 'double-float)) 'single-float)))
492 (((foreach single-float double-float))
493 (if (or (> number (coerce 1 '(dispatch-type number)))
494 (< number (coerce -1 '(dispatch-type number))))
495 (complex-acos (complex number))
496 (coerce (%acos (coerce number 'double-float))
497 '(dispatch-type number))))
498 ((complex)
499 (complex-acos number))))
501 (defun atan (y &optional (x nil xp))
502 #!+sb-doc
503 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
504 (if xp
505 (flet ((atan2 (y x)
506 (declare (type double-float y x)
507 (values double-float))
508 (if (zerop x)
509 (if (zerop y)
510 (if (plusp (float-sign x))
512 (float-sign y pi))
513 (float-sign y (/ pi 2)))
514 (%atan2 y x))))
515 (number-dispatch ((y real) (x real))
516 ((double-float
517 (foreach double-float single-float fixnum bignum ratio))
518 (atan2 y (coerce x 'double-float)))
519 (((foreach single-float fixnum bignum ratio)
520 double-float)
521 (atan2 (coerce y 'double-float) x))
522 (((foreach single-float fixnum bignum ratio)
523 (foreach single-float fixnum bignum ratio))
524 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
525 'single-float))))
526 (number-dispatch ((y number))
527 (handle-reals %atan y)
528 ((complex)
529 (complex-atan y)))))
531 ;;; It seems that every target system has a C version of sinh, cosh,
532 ;;; and tanh. Let's use these for reals because the original
533 ;;; implementations based on the definitions lose big in round-off
534 ;;; error. These bad definitions also mean that sin and cos for
535 ;;; complex numbers can also lose big.
537 (defun sinh (number)
538 #!+sb-doc
539 "Return the hyperbolic sine of NUMBER."
540 (number-dispatch ((number number))
541 (handle-reals %sinh number)
542 ((complex)
543 (let ((x (realpart number))
544 (y (imagpart number)))
545 (complex (* (sinh x) (cos y))
546 (* (cosh x) (sin y)))))))
548 (defun cosh (number)
549 #!+sb-doc
550 "Return the hyperbolic cosine of NUMBER."
551 (number-dispatch ((number number))
552 (handle-reals %cosh number)
553 ((complex)
554 (let ((x (realpart number))
555 (y (imagpart number)))
556 (complex (* (cosh x) (cos y))
557 (* (sinh x) (sin y)))))))
559 (defun tanh (number)
560 #!+sb-doc
561 "Return the hyperbolic tangent of NUMBER."
562 (number-dispatch ((number number))
563 (handle-reals %tanh number)
564 ((complex)
565 (complex-tanh number))))
567 (defun asinh (number)
568 #!+sb-doc
569 "Return the hyperbolic arc sine of NUMBER."
570 (number-dispatch ((number number))
571 (handle-reals %asinh number)
572 ((complex)
573 (complex-asinh number))))
575 (defun acosh (number)
576 #!+sb-doc
577 "Return the hyperbolic arc cosine of NUMBER."
578 (number-dispatch ((number number))
579 ((rational)
580 ;; acosh is complex if number < 1
581 (if (< number 1)
582 (complex-acosh number)
583 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
584 (((foreach single-float double-float))
585 (if (< number (coerce 1 '(dispatch-type number)))
586 (complex-acosh (complex number))
587 (coerce (%acosh (coerce number 'double-float))
588 '(dispatch-type number))))
589 ((complex)
590 (complex-acosh number))))
592 (defun atanh (number)
593 #!+sb-doc
594 "Return the hyperbolic arc tangent of NUMBER."
595 (number-dispatch ((number number))
596 ((rational)
597 ;; atanh is complex if |number| > 1
598 (if (or (> number 1) (< number -1))
599 (complex-atanh number)
600 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
601 (((foreach single-float double-float))
602 (if (or (> number (coerce 1 '(dispatch-type number)))
603 (< number (coerce -1 '(dispatch-type number))))
604 (complex-atanh (complex number))
605 (coerce (%atanh (coerce number 'double-float))
606 '(dispatch-type number))))
607 ((complex)
608 (complex-atanh number))))
610 ;;; HP-UX does not supply a C version of log1p, so use the definition.
612 ;;; FIXME: This is really not a good definition. As per Raymond Toy
613 ;;; working on CMU CL, "The definition really loses big-time in
614 ;;; roundoff as x gets small."
615 #!+hpux
616 #!-sb-fluid (declaim (inline %log1p))
617 #!+hpux
618 (defun %log1p (number)
619 (declare (double-float number)
620 (optimize (speed 3) (safety 0)))
621 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
623 ;;;; not-OLD-SPECFUN stuff
624 ;;;;
625 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
626 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
627 ;;;; the standard special function system.)
628 ;;;;
629 ;;;; This is a set of routines that implement many elementary
630 ;;;; transcendental functions as specified by ANSI Common Lisp. The
631 ;;;; implementation is based on Kahan's paper.
632 ;;;;
633 ;;;; I believe I have accurately implemented the routines and are
634 ;;;; correct, but you may want to check for your self.
635 ;;;;
636 ;;;; These functions are written for CMU Lisp and take advantage of
637 ;;;; some of the features available there. It may be possible,
638 ;;;; however, to port this to other Lisps.
639 ;;;;
640 ;;;; Some functions are significantly more accurate than the original
641 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
642 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
643 ;;;; answer is pi + i*log(2-sqrt(3)).
644 ;;;;
645 ;;;; All of the implemented functions will take any number for an
646 ;;;; input, but the result will always be a either a complex
647 ;;;; single-float or a complex double-float.
648 ;;;;
649 ;;;; general functions:
650 ;;;; complex-sqrt
651 ;;;; complex-log
652 ;;;; complex-atanh
653 ;;;; complex-tanh
654 ;;;; complex-acos
655 ;;;; complex-acosh
656 ;;;; complex-asin
657 ;;;; complex-asinh
658 ;;;; complex-atan
659 ;;;; complex-tan
660 ;;;;
661 ;;;; utility functions:
662 ;;;; scalb logb
663 ;;;;
664 ;;;; internal functions:
665 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
666 ;;;;
667 ;;;; references:
668 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
669 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
670 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
671 ;;;; Press, 1987
672 ;;;;
673 ;;;; The original CMU CL code requested:
674 ;;;; Please send any bug reports, comments, or improvements to
675 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
677 ;;; FIXME: In SBCL, the floating point infinity constants like
678 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
679 ;;; constants at cross-compile time, because the cross-compilation
680 ;;; host might not have support for floating point infinities. Thus,
681 ;;; they're effectively implemented as special variable references,
682 ;;; and the code below which uses them might be unnecessarily
683 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
684 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
685 ;;; special variable references with (probably equally slow)
686 ;;; constructors)
688 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
689 ;;; differ in their interpretations of the real line, IMAGPART was
690 ;;; patch, which without a certain amount of effort would have altered
691 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
692 ;;; were patched to use explicit COMPLEX, rather than implicitly
693 ;;; passing in real numbers for treatment with IMAGPART, and these
694 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
695 ;;; however, someone needs to go back to Kahan for the definitive
696 ;;; answer for treatment of negative real floating point numbers and
697 ;;; branch cuts. If adjustment is needed, it is probably the removal
698 ;;; of explicit calls to COMPLEX in the clients of irrational
699 ;;; functions. -- a slightly bitter CSR, 2004-05-16
701 (declaim (inline square))
702 (defun square (x)
703 (declare (double-float x))
704 (* x x))
706 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
707 ;;; perhaps CSSQS:
708 ;;; If you have these functions in libm, perhaps they should be used
709 ;;; instead of these Lisp versions. These versions are probably good
710 ;;; enough, especially since they are portable.
712 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
713 ;;; the underlying floating-point format.)
714 (declaim (inline scalb))
715 (defun scalb (x n)
716 (declare (type double-float x)
717 (type double-float-exponent n))
718 (scale-float x n))
720 ;;; This is like LOGB, but X is not infinity and non-zero and not a
721 ;;; NaN, so we can always return an integer.
722 (declaim (inline logb-finite))
723 (defun logb-finite (x)
724 (declare (type double-float x))
725 (multiple-value-bind (signif exponent sign)
726 (decode-float x)
727 (declare (ignore signif sign))
728 ;; DECODE-FLOAT is almost right, except that the exponent is off
729 ;; by one.
730 (1- exponent)))
732 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
733 ;;; For the special cases, the following values are used:
734 ;;; x logb
735 ;;; NaN NaN
736 ;;; +/- infinity +infinity
737 ;;; 0 -infinity
738 (defun logb (x)
739 (declare (type double-float x))
740 (cond ((float-nan-p x)
742 ((float-infinity-p x)
743 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
744 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
745 ((zerop x)
746 ;; The answer is negative infinity, but we are supposed to
747 ;; signal divide-by-zero, so do the actual division
748 (/ -1.0d0 x)
751 (logb-finite x))))
753 ;;; This function is used to create a complex number of the
754 ;;; appropriate type:
755 ;;; Create complex number with real part X and imaginary part Y
756 ;;; such that has the same type as Z. If Z has type (complex
757 ;;; rational), the X and Y are coerced to single-float.
758 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
759 (error "needs work for long float support"))
760 (declaim (inline coerce-to-complex-type))
761 (defun coerce-to-complex-type (x y z)
762 (declare (double-float x y)
763 (number z))
764 (if (typep (realpart z) 'double-float)
765 (complex x y)
766 ;; Convert anything that's not already a DOUBLE-FLOAT (because
767 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
768 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
769 (complex (float x 1f0)
770 (float y 1f0))))
772 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
773 ;;; result is r + i*k, where k is an integer.
774 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
775 (error "needs work for long float support"))
776 (defun cssqs (z)
777 (let ((x (float (realpart z) 1d0))
778 (y (float (imagpart z) 1d0)))
779 ;; Would this be better handled using an exception handler to
780 ;; catch the overflow or underflow signal? For now, we turn all
781 ;; traps off and look at the accrued exceptions to see if any
782 ;; signal would have been raised.
783 (with-float-traps-masked (:underflow :overflow)
784 (let ((rho (+ (square x) (square y))))
785 (declare (optimize (speed 3) (space 0)))
786 (cond ((and (or (float-nan-p rho)
787 (float-infinity-p rho))
788 (or (float-infinity-p (abs x))
789 (float-infinity-p (abs y))))
790 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
791 (values
792 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
794 ((let ((threshold #.(/ least-positive-double-float
795 double-float-epsilon))
796 (traps (ldb sb!vm::float-sticky-bits
797 (sb!vm:floating-point-modes))))
798 ;; Overflow raised or (underflow raised and rho <
799 ;; lambda/eps)
800 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
801 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
802 traps)))
803 (< rho threshold))))
804 ;; If we're here, neither x nor y are infinity and at
805 ;; least one is non-zero.. Thus logb returns a nice
806 ;; integer.
807 (let ((k (- (logb-finite (max (abs x) (abs y))))))
808 (values (+ (square (scalb x k))
809 (square (scalb y k)))
810 (- k))))
812 (values rho 0)))))))
814 ;;; principal square root of Z
816 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
817 (defun complex-sqrt (z)
818 ;; KLUDGE: Here and below, we can't just declare Z to be of type
819 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
820 ;; Since there isn't a rational negative zero, this is OK from the
821 ;; point of view of getting the right answer in the face of branch
822 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
823 ;; still ugly. -- CSR, 2004-05-16
824 (declare (type (or complex rational) z))
825 (multiple-value-bind (rho k)
826 (cssqs z)
827 (declare (type (or (member 0d0) (double-float 0d0)) rho)
828 (type fixnum k))
829 (let ((x (float (realpart z) 1.0d0))
830 (y (float (imagpart z) 1.0d0))
831 (eta 0d0)
832 (nu 0d0))
833 (declare (double-float x y eta nu))
835 (locally
836 ;; space 0 to get maybe-inline functions inlined.
837 (declare (optimize (speed 3) (space 0)))
839 (if (not (float-nan-p x))
840 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
842 (cond ((oddp k)
843 (setf k (ash k -1)))
845 (setf k (1- (ash k -1)))
846 (setf rho (+ rho rho))))
848 (setf rho (scalb (sqrt rho) k))
850 (setf eta rho)
851 (setf nu y)
853 (when (/= rho 0d0)
854 (when (not (float-infinity-p (abs nu)))
855 (setf nu (/ (/ nu rho) 2d0)))
856 (when (< x 0d0)
857 (setf eta (abs nu))
858 (setf nu (float-sign y rho))))
859 (coerce-to-complex-type eta nu z)))))
861 ;;; Compute log(2^j*z).
863 ;;; This is for use with J /= 0 only when |z| is huge.
864 (defun complex-log-scaled (z j)
865 (declare (type (or rational complex) z)
866 (fixnum j))
867 ;; The constants t0, t1, t2 should be evaluated to machine
868 ;; precision. In addition, Kahan says the accuracy of log1p
869 ;; influences the choices of these constants but doesn't say how to
870 ;; choose them. We'll just assume his choices matches our
871 ;; implementation of log1p.
872 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
873 (t1 1.2d0)
874 (t2 3d0)
875 (ln2 #.(log 2d0))
876 (x (float (realpart z) 1.0d0))
877 (y (float (imagpart z) 1.0d0)))
878 (multiple-value-bind (rho k)
879 (cssqs z)
880 (declare (optimize (speed 3)))
881 (let ((beta (max (abs x) (abs y)))
882 (theta (min (abs x) (abs y))))
883 (coerce-to-complex-type (if (and (zerop k)
884 (< t0 beta)
885 (or (<= beta t1)
886 (< rho t2)))
887 (/ (%log1p (+ (* (- beta 1.0d0)
888 (+ beta 1.0d0))
889 (* theta theta)))
890 2d0)
891 (+ (/ (log rho) 2d0)
892 (* (+ k j) ln2)))
893 (atan y x)
894 z)))))
896 ;;; log of Z = log |Z| + i * arg Z
898 ;;; Z may be any number, but the result is always a complex.
899 (defun complex-log (z)
900 (declare (type (or rational complex) z))
901 (complex-log-scaled z 0))
903 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
904 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
905 ;;; The reason for the imaginary part is caused by the fact that arg
906 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
907 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
908 (defun complex-atanh (z)
909 (declare (type (or rational complex) z))
910 (let* (;; constants
911 (theta (/ (sqrt most-positive-double-float) 4.0d0))
912 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
913 (half-pi (/ pi 2.0d0))
914 (rp (float (realpart z) 1.0d0))
915 (beta (float-sign rp 1.0d0))
916 (x (* beta rp))
917 (y (* beta (- (float (imagpart z) 1.0d0))))
918 (eta 0.0d0)
919 (nu 0.0d0))
920 ;; Shouldn't need this declare.
921 (declare (double-float x y))
922 (locally
923 (declare (optimize (speed 3)))
924 (cond ((or (> x theta)
925 (> (abs y) theta))
926 ;; To avoid overflow...
927 (setf nu (float-sign y half-pi))
928 ;; ETA is real part of 1/(x + iy). This is x/(x^2+y^2),
929 ;; which can cause overflow. Arrange this computation so
930 ;; that it won't overflow.
931 (setf eta (let* ((x-bigger (> x (abs y)))
932 (r (if x-bigger (/ y x) (/ x y)))
933 (d (+ 1.0d0 (* r r))))
934 (if x-bigger
935 (/ (/ x) d)
936 (/ (/ r y) d)))))
937 ((= x 1.0d0)
938 ;; Should this be changed so that if y is zero, eta is set
939 ;; to +infinity instead of approx 176? In any case
940 ;; tanh(176) is 1.0d0 within working precision.
941 (let ((t1 (+ 4d0 (square y)))
942 (t2 (+ (abs y) rho)))
943 (setf eta (log (/ (sqrt (sqrt t1))
944 (sqrt t2))))
945 (setf nu (* 0.5d0
946 (float-sign y
947 (+ half-pi (atan (* 0.5d0 t2))))))))
949 (let ((t1 (+ (abs y) rho)))
950 ;; Normal case using log1p(x) = log(1 + x)
951 (setf eta (* 0.25d0
952 (%log1p (/ (* 4.0d0 x)
953 (+ (square (- 1.0d0 x))
954 (square t1))))))
955 (setf nu (* 0.5d0
956 (atan (* 2.0d0 y)
957 (- (* (- 1.0d0 x)
958 (+ 1.0d0 x))
959 (square t1))))))))
960 (coerce-to-complex-type (* beta eta)
961 (- (* beta nu))
962 z))))
964 ;;; Compute tanh z = sinh z / cosh z.
965 (defun complex-tanh (z)
966 (declare (type (or rational complex) z))
967 (let ((x (float (realpart z) 1.0d0))
968 (y (float (imagpart z) 1.0d0)))
969 (locally
970 ;; space 0 to get maybe-inline functions inlined
971 (declare (optimize (speed 3) (space 0)))
972 (cond ((> (abs x)
973 ;; FIXME: this form is hideously broken wrt
974 ;; cross-compilation portability. Much else in this
975 ;; file is too, of course, sometimes hidden by
976 ;; constant-folding, but this one in particular clearly
977 ;; depends on host and target
978 ;; MOST-POSITIVE-DOUBLE-FLOATs being equal. -- CSR,
979 ;; 2003-04-20
980 #.(/ (+ (log 2.0d0)
981 (log most-positive-double-float))
982 4d0))
983 (coerce-to-complex-type (float-sign x)
984 (float-sign y) z))
986 (let* ((tv (%tan y))
987 (beta (+ 1.0d0 (* tv tv)))
988 (s (sinh x))
989 (rho (sqrt (+ 1.0d0 (* s s)))))
990 (if (float-infinity-p (abs tv))
991 (coerce-to-complex-type (/ rho s)
992 (/ tv)
994 (let ((den (+ 1.0d0 (* beta s s))))
995 (coerce-to-complex-type (/ (* beta rho s)
996 den)
997 (/ tv den)
998 z)))))))))
1000 ;;; Compute acos z = pi/2 - asin z.
1002 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1003 (defun complex-acos (z)
1004 ;; Kahan says we should only compute the parts needed. Thus, the
1005 ;; REALPART's below should only compute the real part, not the whole
1006 ;; complex expression. Doing this can be important because we may get
1007 ;; spurious signals that occur in the part that we are not using.
1009 ;; However, we take a pragmatic approach and just use the whole
1010 ;; expression.
1012 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1013 ;; it's the conjugate of the square root or the square root of the
1014 ;; conjugate. This needs to be checked.
1016 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1017 ;; same as (sqrt (conjugate z)) for all z. This follows because
1019 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1021 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1023 ;; and these two expressions are equal if and only if arg conj z =
1024 ;; -arg z, which is clearly true for all z.
1025 (declare (type (or rational complex) z))
1026 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
1027 (sqrt-1-z (complex-sqrt (- 1 z))))
1028 (with-float-traps-masked (:divide-by-zero)
1029 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1030 (realpart sqrt-1+z))))
1031 (asinh (imagpart (* (conjugate sqrt-1+z)
1032 sqrt-1-z)))))))
1034 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1036 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1037 (defun complex-acosh (z)
1038 (declare (type (or rational complex) z))
1039 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1040 (sqrt-z+1 (complex-sqrt (+ z 1))))
1041 (with-float-traps-masked (:divide-by-zero)
1042 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1043 sqrt-z+1)))
1044 (* 2 (atan (/ (imagpart sqrt-z-1)
1045 (realpart sqrt-z+1))))))))
1047 ;;; Compute asin z = asinh(i*z)/i.
1049 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1050 (defun complex-asin (z)
1051 (declare (type (or rational complex) z))
1052 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1053 (sqrt-1+z (complex-sqrt (+ 1 z))))
1054 (with-float-traps-masked (:divide-by-zero)
1055 (complex (atan (/ (realpart z)
1056 (realpart (* sqrt-1-z sqrt-1+z))))
1057 (asinh (imagpart (* (conjugate sqrt-1-z)
1058 sqrt-1+z)))))))
1060 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1062 ;;; Z may be any number, but the result is always a complex.
1063 (defun complex-asinh (z)
1064 (declare (type (or rational complex) z))
1065 ;; asinh z = -i * asin (i*z)
1066 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1067 (result (complex-asin iz)))
1068 (complex (imagpart result)
1069 (- (realpart result)))))
1071 ;;; Compute atan z = atanh (i*z) / i.
1073 ;;; Z may be any number, but the result is always a complex.
1074 (defun complex-atan (z)
1075 (declare (type (or rational complex) z))
1076 ;; atan z = -i * atanh (i*z)
1077 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1078 (result (complex-atanh iz)))
1079 (complex (imagpart result)
1080 (- (realpart result)))))
1082 ;;; Compute tan z = -i * tanh(i * z)
1084 ;;; Z may be any number, but the result is always a complex.
1085 (defun complex-tan (z)
1086 (declare (type (or rational complex) z))
1087 ;; tan z = -i * tanh(i*z)
1088 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1089 (result (complex-tanh iz)))
1090 (complex (imagpart result)
1091 (- (realpart result)))))