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