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