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