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