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