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