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