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