Don't ad-hoc reimplement DEFCONSTANT-EQX for LAMBDA-LIST-KEYWORDS.
[sbcl.git] / src / code / irrat.lisp
blob02aed7831c77d9f9610bc7fd79838fed16d7e9a7
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 arm64) ;; 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 arm64) (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 (declare (explicit-check))
104 (number-dispatch ((number number))
105 (handle-reals %exp number)
106 ((complex)
107 (* (exp (realpart number))
108 (cis (imagpart number))))))
110 ;;; INTEXP -- Handle the rational base, integer power case.
112 (declaim (type (or integer null) *intexp-maximum-exponent*))
113 (defparameter *intexp-maximum-exponent* nil)
115 ;;; This function precisely calculates base raised to an integral
116 ;;; power. It separates the cases by the sign of power, for efficiency
117 ;;; reasons, as powers can be calculated more efficiently if power is
118 ;;; a positive integer. Values of power are calculated as positive
119 ;;; integers, and inverted if negative.
120 (defun intexp (base power)
121 (when (and *intexp-maximum-exponent*
122 (> (abs power) *intexp-maximum-exponent*))
123 (error "The absolute value of ~S exceeds ~S."
124 power '*intexp-maximum-exponent*))
125 (cond ((minusp power)
126 (/ (intexp base (- power))))
127 ((eql base 2)
128 (ash 1 power))
130 (do ((nextn (ash power -1) (ash power -1))
131 (total (if (oddp power) base 1)
132 (if (oddp power) (* base total) total)))
133 ((zerop nextn) total)
134 (setq base (* base base))
135 (setq power nextn)))))
137 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
138 ;;; floating point stuff. If both args are real, we try %POW right
139 ;;; off, assuming it will return 0 if the result may be complex. If
140 ;;; so, we call COMPLEX-POW which directly computes the complex
141 ;;; result. We also separate the complex-real and real-complex cases
142 ;;; from the general complex case.
143 (defun expt (base power)
144 #!+sb-doc
145 "Return BASE raised to the POWER."
146 (declare (explicit-check))
147 (if (zerop power)
148 (if (and (zerop base) (floatp power))
149 (error 'arguments-out-of-domain-error
150 :operands (list base power)
151 :operation 'expt
152 :references (list '(:ansi-cl :function expt)))
153 (let ((result (1+ (* base power))))
154 (if (and (floatp result) (float-nan-p result))
155 (float 1 result)
156 result)))
157 (labels (;; determine if the double float is an integer.
158 ;; 0 - not an integer
159 ;; 1 - an odd int
160 ;; 2 - an even int
161 (isint (ihi lo)
162 (declare (type (unsigned-byte 31) ihi)
163 (type (unsigned-byte 32) lo)
164 (optimize (speed 3) (safety 0)))
165 (let ((isint 0))
166 (declare (type fixnum isint))
167 (cond ((>= ihi #x43400000) ; exponent >= 53
168 (setq isint 2))
169 ((>= ihi #x3ff00000)
170 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
171 (declare (type (mod 53) k))
172 (cond ((> k 20)
173 (let* ((shift (- 52 k))
174 (j (logand (ash lo (- shift))))
175 (j2 (ash j shift)))
176 (declare (type (mod 32) shift)
177 (type (unsigned-byte 32) j j2))
178 (when (= j2 lo)
179 (setq isint (- 2 (logand j 1))))))
180 ((= lo 0)
181 (let* ((shift (- 20 k))
182 (j (ash ihi (- shift)))
183 (j2 (ash j shift)))
184 (declare (type (mod 32) shift)
185 (type (unsigned-byte 31) j j2))
186 (when (= j2 ihi)
187 (setq isint (- 2 (logand j 1))))))))))
188 isint))
189 (real-expt (x y rtype)
190 (let ((x (coerce x 'double-float))
191 (y (coerce y 'double-float)))
192 (declare (double-float x y))
193 (let* ((x-hi (double-float-high-bits x))
194 (x-lo (double-float-low-bits x))
195 (x-ihi (logand x-hi #x7fffffff))
196 (y-hi (double-float-high-bits y))
197 (y-lo (double-float-low-bits y))
198 (y-ihi (logand y-hi #x7fffffff)))
199 (declare (type (signed-byte 32) x-hi y-hi)
200 (type (unsigned-byte 31) x-ihi y-ihi)
201 (type (unsigned-byte 32) x-lo y-lo))
202 ;; y==zero: x**0 = 1
203 (when (zerop (logior y-ihi y-lo))
204 (return-from real-expt (coerce 1d0 rtype)))
205 ;; +-NaN return x+y
206 ;; FIXME: Hardcoded qNaN/sNaN values are not portable.
207 (when (or (> x-ihi #x7ff00000)
208 (and (= x-ihi #x7ff00000) (/= x-lo 0))
209 (> y-ihi #x7ff00000)
210 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
211 (return-from real-expt (coerce (+ x y) rtype)))
212 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
213 (declare (type fixnum yisint))
214 ;; special value of y
215 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
216 ;; y is +-inf
217 (return-from real-expt
218 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
219 ;; +-1**inf is NaN
220 (coerce (- y y) rtype))
221 ((>= x-ihi #x3ff00000)
222 ;; (|x|>1)**+-inf = inf,0
223 (if (>= y-hi 0)
224 (coerce y rtype)
225 (coerce 0 rtype)))
227 ;; (|x|<1)**-,+inf = inf,0
228 (if (< y-hi 0)
229 (coerce (- y) rtype)
230 (coerce 0 rtype))))))
232 (let ((abs-x (abs x)))
233 (declare (double-float abs-x))
234 ;; special value of x
235 (when (and (zerop x-lo)
236 (or (= x-ihi #x7ff00000) (zerop x-ihi)
237 (= x-ihi #x3ff00000)))
238 ;; x is +-0,+-inf,+-1
239 (let ((z (if (< y-hi 0)
240 (/ 1 abs-x) ; z = (1/|x|)
241 abs-x)))
242 (declare (double-float z))
243 (when (< x-hi 0)
244 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
245 ;; (-1)**non-int
246 (let ((y*pi (* y pi)))
247 (declare (double-float y*pi))
248 (return-from real-expt
249 (complex
250 (coerce (%cos y*pi) rtype)
251 (coerce (%sin y*pi) rtype)))))
252 ((= yisint 1)
253 ;; (x<0)**odd = -(|x|**odd)
254 (setq z (- z)))))
255 (return-from real-expt (coerce z rtype))))
257 (if (>= x-hi 0)
258 ;; x>0
259 (coerce (%pow x y) rtype)
260 ;; x<0
261 (let ((pow (%pow abs-x y)))
262 (declare (double-float pow))
263 (case yisint
264 (1 ; odd
265 (coerce (* -1d0 pow) rtype))
266 (2 ; even
267 (coerce pow rtype))
268 (t ; non-integer
269 (let ((y*pi (* y pi)))
270 (declare (double-float y*pi))
271 (complex
272 (coerce (* pow (%cos y*pi))
273 rtype)
274 (coerce (* pow (%sin y*pi))
275 rtype))))))))))))
276 (complex-expt (base power)
277 (if (and (zerop base) (plusp (realpart power)))
278 (* base power)
279 (exp (* power (log base))))))
280 (declare (inline real-expt complex-expt))
281 (number-dispatch ((base number) (power number))
282 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
283 (intexp base power))
284 (((foreach single-float double-float) rational)
285 (real-expt base power '(dispatch-type base)))
286 (((foreach fixnum (or bignum ratio) single-float)
287 (foreach ratio single-float))
288 (real-expt base power 'single-float))
289 (((foreach fixnum (or bignum ratio) single-float double-float)
290 double-float)
291 (real-expt base power 'double-float))
292 ((double-float single-float)
293 (real-expt base power 'double-float))
294 ;; Handle (expt <complex> <rational>), except the case dealt with
295 ;; in the first clause above, (expt <(complex rational)> <integer>).
296 (((foreach (complex rational) (complex single-float)
297 (complex double-float))
298 rational)
299 (* (expt (abs base) power)
300 (cis (* power (phase base)))))
301 ;; The next three clauses handle (expt <real> <complex>).
302 (((foreach fixnum (or bignum ratio) single-float)
303 (foreach (complex single-float) (complex rational)))
304 (complex-expt base power))
305 (((foreach fixnum (or bignum ratio) single-float)
306 (complex double-float))
307 (complex-expt (coerce base 'double-float) power))
308 ((double-float complex)
309 (complex-expt base power))
310 ;; The next three clauses handle (expt <complex> <float>) and
311 ;; (expt <complex> <complex>).
312 (((foreach (complex single-float) (complex rational))
313 (foreach (complex single-float) (complex rational) single-float))
314 (complex-expt base power))
315 (((foreach (complex single-float) (complex rational))
316 (foreach (complex double-float) double-float))
317 (complex-expt (coerce base '(complex double-float)) power))
318 (((complex double-float)
319 (foreach complex double-float single-float))
320 (complex-expt base power))))))
322 ;;; FIXME: Maybe rename this so that it's clearer that it only works
323 ;;; on integers?
324 (defun log2 (x)
325 (declare (type integer x))
326 ;; CMUCL comment:
328 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n +
329 ;; log2(f). So we grab the top few bits of x and scale that
330 ;; appropriately, take the log of it and add it to n.
332 ;; Motivated by an attempt to get LOG to work better on bignums.
333 (let ((n (integer-length x)))
334 (if (< n sb!vm:double-float-digits)
335 (log (coerce x 'double-float) 2.0d0)
336 (let ((f (ldb (byte sb!vm:double-float-digits
337 (- n sb!vm:double-float-digits))
338 x)))
339 (+ n (log (scale-float (coerce f 'double-float)
340 (- sb!vm:double-float-digits))
341 2.0d0))))))
343 (defun log (number &optional (base nil base-p))
344 #!+sb-doc
345 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
346 (declare (explicit-check))
347 (if base-p
348 (cond
349 ((zerop base)
350 (if (or (typep number 'double-float) (typep base 'double-float))
351 0.0d0
352 0.0f0))
353 ((and (typep number '(integer (0) *))
354 (typep base '(integer (0) *)))
355 (coerce (/ (log2 number) (log2 base)) 'single-float))
356 ((and (typep number 'integer) (typep base 'double-float))
357 ;; No single float intermediate result
358 (/ (log2 number) (log base 2.0d0)))
359 ((and (typep number 'double-float) (typep base 'integer))
360 (/ (log number 2.0d0) (log2 base)))
362 (/ (log number) (log base))))
363 (number-dispatch ((number number))
364 (((foreach fixnum bignum))
365 (if (minusp number)
366 (complex (log (- number)) (coerce pi 'single-float))
367 (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
368 ((ratio)
369 (if (minusp number)
370 (complex (log (- number)) (coerce pi 'single-float))
371 (let ((numerator (numerator number))
372 (denominator (denominator number)))
373 (if (= (integer-length numerator)
374 (integer-length denominator))
375 (coerce (%log1p (coerce (- number 1) 'double-float))
376 'single-float)
377 (coerce (/ (- (log2 numerator) (log2 denominator))
378 (log (exp 1.0d0) 2.0d0))
379 'single-float)))))
380 (((foreach single-float double-float))
381 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
382 ;; Since this doesn't seem to be an implementation issue
383 ;; I (pw) take the Kahan result.
384 (if (< (float-sign number)
385 (coerce 0 '(dispatch-type number)))
386 (complex (log (- number)) (coerce pi '(dispatch-type number)))
387 (coerce (%log (coerce number 'double-float))
388 '(dispatch-type number))))
389 ((complex)
390 (complex-log number)))))
392 (defun sqrt (number)
393 #!+sb-doc
394 "Return the square root of NUMBER."
395 (declare (explicit-check))
396 (number-dispatch ((number number))
397 (((foreach fixnum bignum ratio))
398 (if (minusp number)
399 (complex-sqrt number)
400 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
401 (((foreach single-float double-float))
402 (if (minusp number)
403 (complex-sqrt (complex number))
404 (coerce (%sqrt (coerce number 'double-float))
405 '(dispatch-type number))))
406 ((complex)
407 (complex-sqrt number))))
409 ;;;; trigonometic and related functions
411 (defun abs (number)
412 #!+sb-doc
413 "Return the absolute value of the number."
414 (declare (explicit-check))
415 (number-dispatch ((number number))
416 (((foreach single-float double-float fixnum rational))
417 (abs number))
418 ((complex)
419 (let ((rx (realpart number))
420 (ix (imagpart number)))
421 (etypecase rx
422 (rational
423 (sqrt (+ (* rx rx) (* ix ix))))
424 (single-float
425 (coerce (%hypot (coerce rx 'double-float)
426 (coerce (truly-the single-float ix) 'double-float))
427 'single-float))
428 (double-float
429 (%hypot rx (truly-the double-float ix))))))))
431 (defun phase (number)
432 #!+sb-doc
433 "Return the angle part of the polar representation of a complex number.
434 For complex numbers, this is (atan (imagpart number) (realpart number)).
435 For non-complex positive numbers, this is 0. For non-complex negative
436 numbers this is PI."
437 (declare (explicit-check))
438 (etypecase number
439 (rational
440 (if (minusp number)
441 (coerce pi 'single-float)
442 0.0f0))
443 (single-float
444 (if (minusp (float-sign number))
445 (coerce pi 'single-float)
446 0.0f0))
447 (double-float
448 (if (minusp (float-sign number))
449 (coerce pi 'double-float)
450 0.0d0))
451 (complex
452 (atan (imagpart number) (realpart number)))))
454 (defun sin (number)
455 #!+sb-doc
456 "Return the sine of NUMBER."
457 (declare (explicit-check))
458 (number-dispatch ((number number))
459 (handle-reals %sin number)
460 ((complex)
461 (let ((x (realpart number))
462 (y (imagpart number)))
463 (complex (* (sin x) (cosh y))
464 (* (cos x) (sinh y)))))))
466 (defun cos (number)
467 #!+sb-doc
468 "Return the cosine of NUMBER."
469 (declare (explicit-check))
470 (number-dispatch ((number number))
471 (handle-reals %cos number)
472 ((complex)
473 (let ((x (realpart number))
474 (y (imagpart number)))
475 (complex (* (cos x) (cosh y))
476 (- (* (sin x) (sinh y))))))))
478 (defun tan (number)
479 #!+sb-doc
480 "Return the tangent of NUMBER."
481 (declare (explicit-check))
482 (number-dispatch ((number number))
483 (handle-reals %tan number)
484 ((complex)
485 (complex-tan number))))
487 (defun cis (theta)
488 #!+sb-doc
489 "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
490 (declare (type real theta) (explicit-check))
491 (complex (cos theta) (sin theta)))
493 (defun asin (number)
494 #!+sb-doc
495 "Return the arc sine of NUMBER."
496 (declare (explicit-check))
497 (number-dispatch ((number number))
498 ((rational)
499 (if (or (> number 1) (< number -1))
500 (complex-asin number)
501 (coerce (%asin (coerce number 'double-float)) 'single-float)))
502 (((foreach single-float double-float))
503 (if (or (> number (coerce 1 '(dispatch-type number)))
504 (< number (coerce -1 '(dispatch-type number))))
505 (complex-asin (complex number))
506 (coerce (%asin (coerce number 'double-float))
507 '(dispatch-type number))))
508 ((complex)
509 (complex-asin number))))
511 (defun acos (number)
512 #!+sb-doc
513 "Return the arc cosine of NUMBER."
514 (declare (explicit-check))
515 (number-dispatch ((number number))
516 ((rational)
517 (if (or (> number 1) (< number -1))
518 (complex-acos number)
519 (coerce (%acos (coerce number 'double-float)) 'single-float)))
520 (((foreach single-float double-float))
521 (if (or (> number (coerce 1 '(dispatch-type number)))
522 (< number (coerce -1 '(dispatch-type number))))
523 (complex-acos (complex number))
524 (coerce (%acos (coerce number 'double-float))
525 '(dispatch-type number))))
526 ((complex)
527 (complex-acos number))))
529 (defun atan (y &optional (x nil xp))
530 #!+sb-doc
531 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
532 (declare (explicit-check))
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 (declare (explicit-check))
570 (number-dispatch ((number number))
571 (handle-reals %sinh number)
572 ((complex)
573 (let ((x (realpart number))
574 (y (imagpart number)))
575 (complex (* (sinh x) (cos y))
576 (* (cosh x) (sin y)))))))
578 (defun cosh (number)
579 #!+sb-doc
580 "Return the hyperbolic cosine of NUMBER."
581 (declare (explicit-check))
582 (number-dispatch ((number number))
583 (handle-reals %cosh number)
584 ((complex)
585 (let ((x (realpart number))
586 (y (imagpart number)))
587 (complex (* (cosh x) (cos y))
588 (* (sinh x) (sin y)))))))
590 (defun tanh (number)
591 #!+sb-doc
592 "Return the hyperbolic tangent of NUMBER."
593 (declare (explicit-check))
594 (number-dispatch ((number number))
595 (handle-reals %tanh number)
596 ((complex)
597 (complex-tanh number))))
599 (defun asinh (number)
600 #!+sb-doc
601 "Return the hyperbolic arc sine of NUMBER."
602 (declare (explicit-check))
603 (number-dispatch ((number number))
604 (handle-reals %asinh number)
605 ((complex)
606 (complex-asinh number))))
608 (defun acosh (number)
609 #!+sb-doc
610 "Return the hyperbolic arc cosine of NUMBER."
611 (declare (explicit-check))
612 (number-dispatch ((number number))
613 ((rational)
614 ;; acosh is complex if number < 1
615 (if (< number 1)
616 (complex-acosh number)
617 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
618 (((foreach single-float double-float))
619 (if (< number (coerce 1 '(dispatch-type number)))
620 (complex-acosh (complex number))
621 (coerce (%acosh (coerce number 'double-float))
622 '(dispatch-type number))))
623 ((complex)
624 (complex-acosh number))))
626 (defun atanh (number)
627 #!+sb-doc
628 "Return the hyperbolic arc tangent of NUMBER."
629 (declare (explicit-check))
630 (number-dispatch ((number number))
631 ((rational)
632 ;; atanh is complex if |number| > 1
633 (if (or (> number 1) (< number -1))
634 (complex-atanh number)
635 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
636 (((foreach single-float double-float))
637 (if (or (> number (coerce 1 '(dispatch-type number)))
638 (< number (coerce -1 '(dispatch-type number))))
639 (complex-atanh (complex number))
640 (coerce (%atanh (coerce number 'double-float))
641 '(dispatch-type number))))
642 ((complex)
643 (complex-atanh number))))
646 ;;;; not-OLD-SPECFUN stuff
647 ;;;;
648 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
649 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
650 ;;;; the standard special function system.)
651 ;;;;
652 ;;;; This is a set of routines that implement many elementary
653 ;;;; transcendental functions as specified by ANSI Common Lisp. The
654 ;;;; implementation is based on Kahan's paper.
655 ;;;;
656 ;;;; I believe I have accurately implemented the routines and are
657 ;;;; correct, but you may want to check for your self.
658 ;;;;
659 ;;;; These functions are written for CMU Lisp and take advantage of
660 ;;;; some of the features available there. It may be possible,
661 ;;;; however, to port this to other Lisps.
662 ;;;;
663 ;;;; Some functions are significantly more accurate than the original
664 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
665 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
666 ;;;; answer is pi + i*log(2-sqrt(3)).
667 ;;;;
668 ;;;; All of the implemented functions will take any number for an
669 ;;;; input, but the result will always be a either a complex
670 ;;;; single-float or a complex double-float.
671 ;;;;
672 ;;;; general functions:
673 ;;;; complex-sqrt
674 ;;;; complex-log
675 ;;;; complex-atanh
676 ;;;; complex-tanh
677 ;;;; complex-acos
678 ;;;; complex-acosh
679 ;;;; complex-asin
680 ;;;; complex-asinh
681 ;;;; complex-atan
682 ;;;; complex-tan
683 ;;;;
684 ;;;; utility functions:
685 ;;;; logb
686 ;;;;
687 ;;;; internal functions:
688 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
689 ;;;;
690 ;;;; references:
691 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
692 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
693 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
694 ;;;; Press, 1987
695 ;;;;
696 ;;;; The original CMU CL code requested:
697 ;;;; Please send any bug reports, comments, or improvements to
698 ;;;; Raymond Toy at <email address deleted during 2002 spam avalanche>.
700 ;;; FIXME: In SBCL, the floating point infinity constants like
701 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
702 ;;; constants at cross-compile time, because the cross-compilation
703 ;;; host might not have support for floating point infinities. Thus,
704 ;;; they're effectively implemented as special variable references,
705 ;;; and the code below which uses them might be unnecessarily
706 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
707 ;;; should be used instead? (KLUDGED 2004-03-08 CSR, by replacing the
708 ;;; special variable references with (probably equally slow)
709 ;;; constructors)
711 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
712 ;;; differ in their interpretations of the real line, IMAGPART was
713 ;;; patch, which without a certain amount of effort would have altered
714 ;;; all the branch cut treatment. Clients of these COMPLEX- routines
715 ;;; were patched to use explicit COMPLEX, rather than implicitly
716 ;;; passing in real numbers for treatment with IMAGPART, and these
717 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
718 ;;; however, someone needs to go back to Kahan for the definitive
719 ;;; answer for treatment of negative real floating point numbers and
720 ;;; branch cuts. If adjustment is needed, it is probably the removal
721 ;;; of explicit calls to COMPLEX in the clients of irrational
722 ;;; functions. -- a slightly bitter CSR, 2004-05-16
724 (declaim (inline square))
725 (defun square (x)
726 (declare (double-float x))
727 (* x x))
729 ;;; original CMU CL comment, apparently re. LOGB and
730 ;;; perhaps CSSQS:
731 ;;; If you have these functions in libm, perhaps they should be used
732 ;;; instead of these Lisp versions. These versions are probably good
733 ;;; enough, especially since they are portable.
735 ;;; This is like LOGB, but X is not infinity and non-zero and not a
736 ;;; NaN, so we can always return an integer.
737 (declaim (inline logb-finite))
738 (defun logb-finite (x)
739 (declare (type double-float x))
740 (multiple-value-bind (signif exponent sign)
741 (decode-float x)
742 (declare (ignore signif sign))
743 ;; DECODE-FLOAT is almost right, except that the exponent is off
744 ;; by one.
745 (1- exponent)))
747 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
748 ;;; For the special cases, the following values are used:
749 ;;; x logb
750 ;;; NaN NaN
751 ;;; +/- infinity +infinity
752 ;;; 0 -infinity
753 (defun logb (x)
754 (declare (type double-float x))
755 (cond ((float-nan-p x)
757 ((float-infinity-p x)
758 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
759 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
760 ((zerop x)
761 ;; The answer is negative infinity, but we are supposed to
762 ;; signal divide-by-zero, so do the actual division
763 (/ -1.0d0 x)
766 (logb-finite x))))
768 ;;; This function is used to create a complex number of the
769 ;;; appropriate type:
770 ;;; Create complex number with real part X and imaginary part Y
771 ;;; such that has the same type as Z. If Z has type (complex
772 ;;; rational), the X and Y are coerced to single-float.
773 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
774 (error "needs work for long float support"))
775 (declaim (inline coerce-to-complex-type))
776 (defun coerce-to-complex-type (x y z)
777 (declare (double-float x y)
778 (number z))
779 (if (typep (realpart z) 'double-float)
780 (complex x y)
781 ;; Convert anything that's not already a DOUBLE-FLOAT (because
782 ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
783 ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
784 (complex (float x 1f0)
785 (float y 1f0))))
787 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
788 ;;; result is r + i*k, where k is an integer.
789 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
790 (error "needs work for long float support"))
791 (defun cssqs (z)
792 (let ((x (float (realpart z) 1d0))
793 (y (float (imagpart z) 1d0)))
794 ;; Would this be better handled using an exception handler to
795 ;; catch the overflow or underflow signal? For now, we turn all
796 ;; traps off and look at the accrued exceptions to see if any
797 ;; signal would have been raised.
798 (with-float-traps-masked (:underflow :overflow)
799 (let ((rho (+ (square x) (square y))))
800 (declare (optimize (speed 3) (space 0)))
801 (cond ((and (or (float-nan-p rho)
802 (float-infinity-p rho))
803 (or (float-infinity-p (abs x))
804 (float-infinity-p (abs y))))
805 ;; DOUBLE-FLOAT-POSITIVE-INFINITY
806 (values
807 (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
809 ((let ((threshold
810 ;; (/ least-positive-double-float double-float-epsilon)
811 (load-time-value
812 #!-long-float
813 (make-double-float #x1fffff #xfffffffe)
814 #!+long-float
815 (error "(/ least-positive-long-float long-float-epsilon)")))
816 (traps (ldb sb!vm::float-sticky-bits
817 (sb!vm:floating-point-modes))))
818 ;; Overflow raised or (underflow raised and rho <
819 ;; lambda/eps)
820 (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
821 (and (not (zerop (logand sb!vm:float-underflow-trap-bit
822 traps)))
823 (< rho threshold))))
824 ;; If we're here, neither x nor y are infinity and at
825 ;; least one is non-zero.. Thus logb returns a nice
826 ;; integer.
827 (let ((k (- (logb-finite (max (abs x) (abs y))))))
828 (values (+ (square (scale-float x k))
829 (square (scale-float y k)))
830 (- k))))
832 (values rho 0)))))))
834 ;;; principal square root of Z
836 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
837 (defun complex-sqrt (z)
838 ;; KLUDGE: Here and below, we can't just declare Z to be of type
839 ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
840 ;; Since there isn't a rational negative zero, this is OK from the
841 ;; point of view of getting the right answer in the face of branch
842 ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
843 ;; still ugly. -- CSR, 2004-05-16
844 (declare (type (or complex rational) z))
845 (multiple-value-bind (rho k)
846 (cssqs z)
847 (declare (type (or (member 0d0) (double-float 0d0)) rho)
848 (type fixnum k))
849 (let ((x (float (realpart z) 1.0d0))
850 (y (float (imagpart z) 1.0d0))
851 (eta 0d0)
852 (nu 0d0))
853 (declare (double-float x y eta nu)
854 ;; get maybe-inline functions inlined.
855 (optimize (space 0)))
856 (if (not (float-nan-p x))
857 (setf rho (+ (scale-float (abs x) (- k)) (sqrt rho))))
859 (cond ((oddp k)
860 (setf k (ash k -1)))
862 (setf k (1- (ash k -1)))
863 (setf rho (+ rho rho))))
865 (setf rho (scale-float (sqrt rho) k))
867 (setf eta rho)
868 (setf nu y)
870 (when (/= rho 0d0)
871 (when (not (float-infinity-p (abs nu)))
872 (setf nu (/ (/ nu rho) 2d0)))
873 (when (< x 0d0)
874 (setf eta (abs nu))
875 (setf nu (float-sign y rho))))
876 (coerce-to-complex-type eta nu z))))
878 ;;; Compute log(2^j*z).
880 ;;; This is for use with J /= 0 only when |z| is huge.
881 (defun complex-log-scaled (z j)
882 (declare (type (or rational complex) z)
883 (fixnum j))
884 ;; The constants t0, t1, t2 should be evaluated to machine
885 ;; precision. In addition, Kahan says the accuracy of log1p
886 ;; influences the choices of these constants but doesn't say how to
887 ;; choose them. We'll just assume his choices matches our
888 ;; implementation of log1p.
889 (let ((t0 (load-time-value
890 #!-long-float
891 (make-double-float #x3fe6a09e #x667f3bcd)
892 #!+long-float
893 (error "(/ (sqrt 2l0))")))
894 ;; KLUDGE: if repeatable fasls start failing under some weird
895 ;; xc host, this 1.2d0 might be a good place to examine: while
896 ;; it _should_ be the same in all vaguely-IEEE754 hosts, 1.2
897 ;; is not exactly representable, so something could go wrong.
898 (t1 1.2d0)
899 (t2 3d0)
900 (ln2 (load-time-value
901 #!-long-float
902 (make-double-float #x3fe62e42 #xfefa39ef)
903 #!+long-float
904 (error "(log 2l0)")))
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 (load-time-value
1003 #!-long-float
1004 (make-double-float #x406633ce #x8fb9f87e)
1005 #!+long-float
1006 (error "(/ (+ (log 2l0) (log most-positive-long-float)) 4l0)")))
1007 (coerce-to-complex-type (float-sign x)
1008 (float-sign y) z))
1010 (let* ((tv (%tan y))
1011 (beta (+ 1.0d0 (* tv tv)))
1012 (s (sinh x))
1013 (rho (sqrt (+ 1.0d0 (* s s)))))
1014 (if (float-infinity-p (abs tv))
1015 (coerce-to-complex-type (/ rho s)
1016 (/ tv)
1018 (let ((den (+ 1.0d0 (* beta s s))))
1019 (coerce-to-complex-type (/ (* beta rho s)
1020 den)
1021 (/ tv den)
1022 z)))))))))
1024 ;;; Compute acos z = pi/2 - asin z.
1026 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1027 (defun complex-acos (z)
1028 ;; Kahan says we should only compute the parts needed. Thus, the
1029 ;; REALPART's below should only compute the real part, not the whole
1030 ;; complex expression. Doing this can be important because we may get
1031 ;; spurious signals that occur in the part that we are not using.
1033 ;; However, we take a pragmatic approach and just use the whole
1034 ;; expression.
1036 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1037 ;; it's the conjugate of the square root or the square root of the
1038 ;; conjugate. This needs to be checked.
1040 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1041 ;; same as (sqrt (conjugate z)) for all z. This follows because
1043 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1045 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1047 ;; and these two expressions are equal if and only if arg conj z =
1048 ;; -arg z, which is clearly true for all z.
1049 (declare (type (or rational complex) z))
1050 (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
1051 (sqrt-1-z (complex-sqrt (- 1 z))))
1052 (with-float-traps-masked (:divide-by-zero)
1053 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1054 (realpart sqrt-1+z))))
1055 (asinh (imagpart (* (conjugate sqrt-1+z)
1056 sqrt-1-z)))))))
1058 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1060 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1061 (defun complex-acosh (z)
1062 (declare (type (or rational complex) z))
1063 (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1064 (sqrt-z+1 (complex-sqrt (+ z 1))))
1065 (with-float-traps-masked (:divide-by-zero)
1066 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1067 sqrt-z+1)))
1068 (* 2 (atan (/ (imagpart sqrt-z-1)
1069 (realpart sqrt-z+1))))))))
1071 ;;; Compute asin z = asinh(i*z)/i.
1073 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1074 (defun complex-asin (z)
1075 (declare (type (or rational complex) z))
1076 (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1077 (sqrt-1+z (complex-sqrt (+ 1 z))))
1078 (with-float-traps-masked (:divide-by-zero)
1079 (complex (atan (/ (realpart z)
1080 (realpart (* sqrt-1-z sqrt-1+z))))
1081 (asinh (imagpart (* (conjugate sqrt-1-z)
1082 sqrt-1+z)))))))
1084 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1086 ;;; Z may be any number, but the result is always a complex.
1087 (defun complex-asinh (z)
1088 (declare (type (or rational complex) z))
1089 ;; asinh z = -i * asin (i*z)
1090 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1091 (result (complex-asin iz)))
1092 (complex (imagpart result)
1093 (- (realpart result)))))
1095 ;;; Compute atan z = atanh (i*z) / i.
1097 ;;; Z may be any number, but the result is always a complex.
1098 (defun complex-atan (z)
1099 (declare (type (or rational complex) z))
1100 ;; atan z = -i * atanh (i*z)
1101 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1102 (result (complex-atanh iz)))
1103 (complex (imagpart result)
1104 (- (realpart result)))))
1106 ;;; Compute tan z = -i * tanh(i * z)
1108 ;;; Z may be any number, but the result is always a complex.
1109 (defun complex-tan (z)
1110 (declare (type (or rational complex) z))
1111 ;; tan z = -i * tanh(i*z)
1112 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1113 (result (complex-tanh iz)))
1114 (complex (imagpart result)
1115 (- (realpart result)))))