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