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