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