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