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