0.8.10.27:
[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 (complex 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 (complex 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 (complex 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 (complex 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 (complex 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 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
645 ;;; differ in their interpretations of the real line, IMAGPART was
646 ;;; patch, which without a certain amount of effort would have altered
647 ;;; all the branch cut treatment.  Clients of these COMPLEX- routines
648 ;;; were patched to use explicit COMPLEX, rather than implicitly
649 ;;; passing in real numbers for treatment with IMAGPART, and these
650 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
651 ;;; however, someone needs to go back to Kahan for the definitive
652 ;;; answer for treatment of negative real floating point numbers and
653 ;;; branch cuts.  If adjustment is needed, it is probably the removal
654 ;;; of explicit calls to COMPLEX in the clients of irrational
655 ;;; functions.  -- a slightly bitter CSR, 2004-05-16
656
657 (declaim (inline square))
658 (defun square (x)
659   (declare (double-float x))
660   (* x x))
661
662 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
663 ;;; perhaps CSSQS:
664 ;;;   If you have these functions in libm, perhaps they should be used
665 ;;;   instead of these Lisp versions. These versions are probably good
666 ;;;   enough, especially since they are portable.
667
668 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
669 ;;; the underlying floating-point format.)
670 (declaim (inline scalb))
671 (defun scalb (x n)
672   (declare (type double-float x)
673            (type double-float-exponent n))
674   (scale-float x n))
675
676 ;;; This is like LOGB, but X is not infinity and non-zero and not a
677 ;;; NaN, so we can always return an integer.
678 (declaim (inline logb-finite))
679 (defun logb-finite (x)
680   (declare (type double-float x))
681   (multiple-value-bind (signif exponent sign)
682       (decode-float x)
683     (declare (ignore signif sign))
684     ;; DECODE-FLOAT is almost right, except that the exponent is off
685     ;; by one.
686     (1- exponent)))
687
688 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
689 ;;; For the special cases, the following values are used:
690 ;;;    x             logb
691 ;;;   NaN            NaN
692 ;;;   +/- infinity   +infinity
693 ;;;   0              -infinity
694 (defun logb (x)
695   (declare (type double-float x))
696   (cond ((float-nan-p x)
697          x)
698         ((float-infinity-p x)
699          ;; DOUBLE-FLOAT-POSITIVE-INFINITY
700          (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
701         ((zerop x)
702          ;; The answer is negative infinity, but we are supposed to
703           ;; signal divide-by-zero, so do the actual division
704          (/ -1.0d0 x)
705          )
706         (t
707           (logb-finite x))))
708
709 ;;; This function is used to create a complex number of the
710 ;;; appropriate type:
711 ;;;   Create complex number with real part X and imaginary part Y
712 ;;;   such that has the same type as Z.  If Z has type (complex
713 ;;;   rational), the X and Y are coerced to single-float.
714 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
715                 (error "needs work for long float support"))
716 (declaim (inline coerce-to-complex-type))
717 (defun coerce-to-complex-type (x y z)
718   (declare (double-float x y)
719            (number z))
720   (if (typep (realpart z) 'double-float)
721       (complex x y)
722       ;; Convert anything that's not already a DOUBLE-FLOAT (because
723       ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
724       ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
725       (complex (float x 1f0)
726                (float y 1f0))))
727
728 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
729 ;;; result is r + i*k, where k is an integer.
730 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
731                 (error "needs work for long float support"))
732 (defun cssqs (z)
733   (let ((x (float (realpart z) 1d0))
734         (y (float (imagpart z) 1d0)))
735     ;; Would this be better handled using an exception handler to
736     ;; catch the overflow or underflow signal?  For now, we turn all
737     ;; traps off and look at the accrued exceptions to see if any
738     ;; signal would have been raised.
739     (with-float-traps-masked (:underflow :overflow)
740       (let ((rho (+ (square x) (square y))))
741        (declare (optimize (speed 3) (space 0)))
742       (cond ((and (or (float-nan-p rho)
743                       (float-infinity-p rho))
744                   (or (float-infinity-p (abs x))
745                       (float-infinity-p (abs y))))
746              ;; DOUBLE-FLOAT-POSITIVE-INFINITY
747              (values
748               (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
749               0))
750             ((let ((threshold #.(/ least-positive-double-float
751                                    double-float-epsilon))
752                    (traps (ldb sb!vm::float-sticky-bits
753                                (sb!vm:floating-point-modes))))
754                 ;; Overflow raised or (underflow raised and rho <
755                 ;; lambda/eps)
756                (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
757                    (and (not (zerop (logand sb!vm:float-underflow-trap-bit
758                                             traps)))
759                         (< rho threshold))))
760               ;; If we're here, neither x nor y are infinity and at
761               ;; least one is non-zero.. Thus logb returns a nice
762               ;; integer.
763               (let ((k (- (logb-finite (max (abs x) (abs y))))))
764                 (values (+ (square (scalb x k))
765                            (square (scalb y k)))
766                         (- k))))
767              (t
768               (values rho 0)))))))
769
770 ;;; principal square root of Z
771 ;;;
772 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
773 (defun complex-sqrt (z)
774   ;; KLUDGE: Here and below, we can't just declare Z to be of type
775   ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
776   ;; Since there isn't a rational negative zero, this is OK from the
777   ;; point of view of getting the right answer in the face of branch
778   ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
779   ;; still ugly.  -- CSR, 2004-05-16
780   (declare (type (or complex rational) z))
781   (multiple-value-bind (rho k)
782       (cssqs z)
783     (declare (type (or (member 0d0) (double-float 0d0)) rho)
784              (type fixnum k))
785     (let ((x (float (realpart z) 1.0d0))
786           (y (float (imagpart z) 1.0d0))
787           (eta 0d0)
788           (nu 0d0))
789       (declare (double-float x y eta nu))
790
791       (locally
792          ;; space 0 to get maybe-inline functions inlined.
793          (declare (optimize (speed 3) (space 0)))
794
795       (if (not (float-nan-p x))
796           (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
797
798       (cond ((oddp k)
799              (setf k (ash k -1)))
800             (t
801              (setf k (1- (ash k -1)))
802              (setf rho (+ rho rho))))
803
804       (setf rho (scalb (sqrt rho) k))
805
806       (setf eta rho)
807       (setf nu y)
808
809       (when (/= rho 0d0)
810             (when (not (float-infinity-p (abs nu)))
811                   (setf nu (/ (/ nu rho) 2d0)))
812             (when (< x 0d0)
813                   (setf eta (abs nu))
814                   (setf nu (float-sign y rho))))
815        (coerce-to-complex-type eta nu z)))))
816     
817 ;;; Compute log(2^j*z).
818 ;;;
819 ;;; This is for use with J /= 0 only when |z| is huge.
820 (defun complex-log-scaled (z j)
821   (declare (type (or rational complex) z)
822            (fixnum j))
823   ;; The constants t0, t1, t2 should be evaluated to machine
824   ;; precision.  In addition, Kahan says the accuracy of log1p
825   ;; influences the choices of these constants but doesn't say how to
826   ;; choose them.  We'll just assume his choices matches our
827   ;; implementation of log1p.
828   (let ((t0 #.(/ 1 (sqrt 2.0d0)))
829         (t1 1.2d0)
830         (t2 3d0)
831         (ln2 #.(log 2d0))
832         (x (float (realpart z) 1.0d0))
833         (y (float (imagpart z) 1.0d0)))
834     (multiple-value-bind (rho k)
835         (cssqs z)
836       (declare (optimize (speed 3)))
837       (let ((beta (max (abs x) (abs y)))
838             (theta (min (abs x) (abs y))))
839         (coerce-to-complex-type (if (and (zerop k)
840                  (< t0 beta)
841                  (or (<= beta t1)
842                      (< rho t2)))
843                                   (/ (%log1p (+ (* (- beta 1.0d0)
844                                        (+ beta 1.0d0))
845                                     (* theta theta)))
846                                      2d0)
847                                   (+ (/ (log rho) 2d0)
848                                      (* (+ k j) ln2)))
849                                 (atan y x)
850                                 z)))))
851
852 ;;; log of Z = log |Z| + i * arg Z
853 ;;;
854 ;;; Z may be any number, but the result is always a complex.
855 (defun complex-log (z)
856   (declare (type (or rational complex) z))
857   (complex-log-scaled z 0))
858                
859 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
860 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
861 ;;; The reason for the imaginary part is caused by the fact that arg
862 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
863 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
864 (defun complex-atanh (z)
865   (declare (type (or rational complex) z))
866   (let* (;; constants
867          (theta (/ (sqrt most-positive-double-float) 4.0d0))
868          (rho (/ 4.0d0 (sqrt most-positive-double-float)))
869          (half-pi (/ pi 2.0d0))
870          (rp (float (realpart z) 1.0d0))
871          (beta (float-sign rp 1.0d0))
872          (x (* beta rp))
873          (y (* beta (- (float (imagpart z) 1.0d0))))
874          (eta 0.0d0)
875          (nu 0.0d0))
876     ;; Shouldn't need this declare.
877     (declare (double-float x y))
878     (locally
879        (declare (optimize (speed 3)))
880     (cond ((or (> x theta)
881                (> (abs y) theta))
882             ;; To avoid overflow...
883            (setf eta (float-sign y half-pi))
884            ;; nu is real part of 1/(x + iy).  This is x/(x^2+y^2),
885            ;; which can cause overflow.  Arrange this computation so
886            ;; that it won't overflow.
887            (setf nu (let* ((x-bigger (> x (abs y)))
888                            (r (if x-bigger (/ y x) (/ x y)))
889                            (d (+ 1.0d0 (* r r))))
890                       (if x-bigger
891                           (/ (/ x) d)
892                           (/ (/ r y) d)))))
893           ((= x 1.0d0)
894            ;; Should this be changed so that if y is zero, eta is set
895            ;; to +infinity instead of approx 176?  In any case
896            ;; tanh(176) is 1.0d0 within working precision.
897            (let ((t1 (+ 4d0 (square y)))
898                  (t2 (+ (abs y) rho)))
899              (setf eta (log (/ (sqrt (sqrt t1)))
900                             (sqrt t2)))
901              (setf nu (* 0.5d0
902                          (float-sign y
903                                      (+ half-pi (atan (* 0.5d0 t2))))))))
904           (t
905            (let ((t1 (+ (abs y) rho)))
906               ;; Normal case using log1p(x) = log(1 + x)
907              (setf eta (* 0.25d0
908                           (%log1p (/ (* 4.0d0 x)
909                                      (+ (square (- 1.0d0 x))
910                                         (square t1))))))
911              (setf nu (* 0.5d0
912                          (atan (* 2.0d0 y)
913                                (- (* (- 1.0d0 x)
914                                      (+ 1.0d0 x))
915                                   (square t1))))))))
916     (coerce-to-complex-type (* beta eta)
917                             (- (* beta nu))
918                              z))))
919
920 ;;; Compute tanh z = sinh z / cosh z.
921 (defun complex-tanh (z)
922   (declare (type (or rational complex) z))
923   (let ((x (float (realpart z) 1.0d0))
924         (y (float (imagpart z) 1.0d0)))
925     (locally
926       ;; space 0 to get maybe-inline functions inlined
927       (declare (optimize (speed 3) (space 0)))
928     (cond ((> (abs x)
929               ;; FIXME: this form is hideously broken wrt
930               ;; cross-compilation portability.  Much else in this
931               ;; file is too, of course, sometimes hidden by
932               ;; constant-folding, but this one in particular clearly
933               ;; depends on host and target
934               ;; MOST-POSITIVE-DOUBLE-FLOATs being equal.  -- CSR,
935               ;; 2003-04-20
936               #.(/ (+ (log 2.0d0)
937                       (log most-positive-double-float))
938                    4d0))
939            (coerce-to-complex-type (float-sign x)
940                                    (float-sign y) z))
941           (t
942            (let* ((tv (%tan y))
943                   (beta (+ 1.0d0 (* tv tv)))
944                   (s (sinh x))
945                   (rho (sqrt (+ 1.0d0 (* s s)))))
946              (if (float-infinity-p (abs tv))
947                  (coerce-to-complex-type (/ rho s)
948                                          (/ tv)
949                                          z)
950                  (let ((den (+ 1.0d0 (* beta s s))))
951                    (coerce-to-complex-type (/ (* beta rho s)
952                                               den)
953                                            (/ tv den)
954                                             z)))))))))
955
956 ;;; Compute acos z = pi/2 - asin z.
957 ;;;
958 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
959 (defun complex-acos (z)
960   ;; Kahan says we should only compute the parts needed.  Thus, the
961   ;; REALPART's below should only compute the real part, not the whole
962   ;; complex expression.  Doing this can be important because we may get
963   ;; spurious signals that occur in the part that we are not using.
964   ;;
965   ;; However, we take a pragmatic approach and just use the whole
966   ;; expression.
967   ;;
968   ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
969   ;; it's the conjugate of the square root or the square root of the
970   ;; conjugate.  This needs to be checked.
971   ;;
972   ;; I checked.  It doesn't matter because (conjugate (sqrt z)) is the
973   ;; same as (sqrt (conjugate z)) for all z.  This follows because
974   ;;
975   ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
976   ;;
977   ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
978   ;;
979   ;; and these two expressions are equal if and only if arg conj z =
980   ;; -arg z, which is clearly true for all z.
981   (declare (type (or rational complex) z))
982   (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
983         (sqrt-1-z (complex-sqrt (- 1 z))))
984     (with-float-traps-masked (:divide-by-zero)
985       (complex (* 2 (atan (/ (realpart sqrt-1-z)
986                              (realpart sqrt-1+z))))
987                (asinh (imagpart (* (conjugate sqrt-1+z)
988                                    sqrt-1-z)))))))
989
990 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
991 ;;;
992 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
993 (defun complex-acosh (z)
994   (declare (type (or rational complex) z))
995   (let ((sqrt-z-1 (complex-sqrt (- z 1)))
996         (sqrt-z+1 (complex-sqrt (+ z 1))))
997     (with-float-traps-masked (:divide-by-zero)
998       (complex (asinh (realpart (* (conjugate sqrt-z-1)
999                                    sqrt-z+1)))
1000                (* 2 (atan (/ (imagpart sqrt-z-1)
1001                              (realpart sqrt-z+1))))))))
1002
1003 ;;; Compute asin z = asinh(i*z)/i.
1004 ;;;
1005 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1006 (defun complex-asin (z)
1007   (declare (type (or rational complex) z))
1008   (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1009         (sqrt-1+z (complex-sqrt (+ 1 z))))
1010     (with-float-traps-masked (:divide-by-zero)
1011       (complex (atan (/ (realpart z)
1012                         (realpart (* sqrt-1-z sqrt-1+z))))
1013                (asinh (imagpart (* (conjugate sqrt-1-z)
1014                                    sqrt-1+z)))))))
1015
1016 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1017 ;;;
1018 ;;; Z may be any number, but the result is always a complex.
1019 (defun complex-asinh (z)
1020   (declare (type (or rational complex) z))
1021   ;; asinh z = -i * asin (i*z)
1022   (let* ((iz (complex (- (imagpart z)) (realpart z)))
1023          (result (complex-asin iz)))
1024     (complex (imagpart result)
1025              (- (realpart result)))))
1026          
1027 ;;; Compute atan z = atanh (i*z) / i.
1028 ;;;
1029 ;;; Z may be any number, but the result is always a complex.
1030 (defun complex-atan (z)
1031   (declare (type (or rational complex) z))
1032   ;; atan z = -i * atanh (i*z)
1033   (let* ((iz (complex (- (imagpart z)) (realpart z)))
1034          (result (complex-atanh iz)))
1035     (complex (imagpart result)
1036              (- (realpart result)))))
1037
1038 ;;; Compute tan z = -i * tanh(i * z)
1039 ;;;
1040 ;;; Z may be any number, but the result is always a complex.
1041 (defun complex-tan (z)
1042   (declare (type (or rational complex) z))
1043   ;; tan z = -i * tanh(i*z)
1044   (let* ((iz (complex (- (imagpart z)) (realpart z)))
1045          (result (complex-tanh iz)))
1046     (complex (imagpart result)
1047              (- (realpart result)))))