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