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