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