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