1.0.21.1: address TYPE-WARNING in CLOS allocator for funcallable structures
[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         ((and (typep number 'integer) (typep base 'double-float))
346          ;; No single float intermediate result
347          (/ (log2 number) (log base 2.0d0)))
348         ((and (typep number 'double-float) (typep base 'integer))
349          (/ (log number 2.0d0) (log2 base)))
350         (t
351          (/ (log number) (log base))))
352       (number-dispatch ((number number))
353         (((foreach fixnum bignum))
354          (if (minusp number)
355              (complex (log (- number)) (coerce pi 'single-float))
356              (coerce (/ (log2 number) (log (exp 1.0d0) 2.0d0)) 'single-float)))
357         ((ratio)
358          (if (minusp number)
359              (complex (log (- number)) (coerce pi 'single-float))
360              (let ((numerator (numerator number))
361                    (denominator (denominator number)))
362                (if (= (integer-length numerator)
363                       (integer-length denominator))
364                    (coerce (%log1p (coerce (- number 1) 'double-float))
365                            'single-float)
366                    (coerce (/ (- (log2 numerator) (log2 denominator))
367                               (log (exp 1.0d0) 2.0d0))
368                            'single-float)))))
369         (((foreach single-float double-float))
370          ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
371          ;; Since this doesn't seem to be an implementation issue
372          ;; I (pw) take the Kahan result.
373          (if (< (float-sign number)
374                 (coerce 0 '(dispatch-type number)))
375              (complex (log (- number)) (coerce pi '(dispatch-type number)))
376              (coerce (%log (coerce number 'double-float))
377                      '(dispatch-type number))))
378         ((complex)
379          (complex-log number)))))
380
381 (defun sqrt (number)
382   #!+sb-doc
383   "Return the square root of NUMBER."
384   (number-dispatch ((number number))
385     (((foreach fixnum bignum ratio))
386      (if (minusp number)
387          (complex-sqrt number)
388          (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
389     (((foreach single-float double-float))
390      (if (minusp number)
391          (complex-sqrt (complex number))
392          (coerce (%sqrt (coerce number 'double-float))
393                  '(dispatch-type number))))
394      ((complex)
395       (complex-sqrt number))))
396 \f
397 ;;;; trigonometic and related functions
398
399 (defun abs (number)
400   #!+sb-doc
401   "Return the absolute value of the number."
402   (number-dispatch ((number number))
403     (((foreach single-float double-float fixnum rational))
404      (abs number))
405     ((complex)
406      (let ((rx (realpart number))
407            (ix (imagpart number)))
408        (etypecase rx
409          (rational
410           (sqrt (+ (* rx rx) (* ix ix))))
411          (single-float
412           (coerce (%hypot (coerce rx 'double-float)
413                           (coerce ix 'double-float))
414                   'single-float))
415          (double-float
416           (%hypot rx ix)))))))
417
418 (defun phase (number)
419   #!+sb-doc
420   "Return the angle part of the polar representation of a complex number.
421   For complex numbers, this is (atan (imagpart number) (realpart number)).
422   For non-complex positive numbers, this is 0. For non-complex negative
423   numbers this is PI."
424   (etypecase number
425     (rational
426      (if (minusp number)
427          (coerce pi 'single-float)
428          0.0f0))
429     (single-float
430      (if (minusp (float-sign number))
431          (coerce pi 'single-float)
432          0.0f0))
433     (double-float
434      (if (minusp (float-sign number))
435          (coerce pi 'double-float)
436          0.0d0))
437     (complex
438      (atan (imagpart number) (realpart number)))))
439
440 (defun sin (number)
441   #!+sb-doc
442   "Return the sine of NUMBER."
443   (number-dispatch ((number number))
444     (handle-reals %sin number)
445     ((complex)
446      (let ((x (realpart number))
447            (y (imagpart number)))
448        (complex (* (sin x) (cosh y))
449                 (* (cos x) (sinh y)))))))
450
451 (defun cos (number)
452   #!+sb-doc
453   "Return the cosine of NUMBER."
454   (number-dispatch ((number number))
455     (handle-reals %cos number)
456     ((complex)
457      (let ((x (realpart number))
458            (y (imagpart number)))
459        (complex (* (cos x) (cosh y))
460                 (- (* (sin x) (sinh y))))))))
461
462 (defun tan (number)
463   #!+sb-doc
464   "Return the tangent of NUMBER."
465   (number-dispatch ((number number))
466     (handle-reals %tan number)
467     ((complex)
468      (complex-tan number))))
469
470 (defun cis (theta)
471   #!+sb-doc
472   "Return cos(Theta) + i sin(Theta), i.e. exp(i Theta)."
473   (declare (type real theta))
474   (complex (cos theta) (sin theta)))
475
476 (defun asin (number)
477   #!+sb-doc
478   "Return the arc sine of NUMBER."
479   (number-dispatch ((number number))
480     ((rational)
481      (if (or (> number 1) (< number -1))
482          (complex-asin number)
483          (coerce (%asin (coerce number 'double-float)) 'single-float)))
484     (((foreach single-float double-float))
485      (if (or (> number (coerce 1 '(dispatch-type number)))
486              (< number (coerce -1 '(dispatch-type number))))
487          (complex-asin (complex number))
488          (coerce (%asin (coerce number 'double-float))
489                  '(dispatch-type number))))
490     ((complex)
491      (complex-asin number))))
492
493 (defun acos (number)
494   #!+sb-doc
495   "Return the arc cosine of NUMBER."
496   (number-dispatch ((number number))
497     ((rational)
498      (if (or (> number 1) (< number -1))
499          (complex-acos number)
500          (coerce (%acos (coerce number 'double-float)) 'single-float)))
501     (((foreach single-float double-float))
502      (if (or (> number (coerce 1 '(dispatch-type number)))
503              (< number (coerce -1 '(dispatch-type number))))
504          (complex-acos (complex number))
505          (coerce (%acos (coerce number 'double-float))
506                  '(dispatch-type number))))
507     ((complex)
508      (complex-acos number))))
509
510 (defun atan (y &optional (x nil xp))
511   #!+sb-doc
512   "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
513   (if xp
514       (flet ((atan2 (y x)
515                (declare (type double-float y x)
516                         (values double-float))
517                (if (zerop x)
518                    (if (zerop y)
519                        (if (plusp (float-sign x))
520                            y
521                            (float-sign y pi))
522                        (float-sign y (/ pi 2)))
523                    (%atan2 y x))))
524         (number-dispatch ((y real) (x real))
525           ((double-float
526             (foreach double-float single-float fixnum bignum ratio))
527            (atan2 y (coerce x 'double-float)))
528           (((foreach single-float fixnum bignum ratio)
529             double-float)
530            (atan2 (coerce y 'double-float) x))
531           (((foreach single-float fixnum bignum ratio)
532             (foreach single-float fixnum bignum ratio))
533            (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
534                    'single-float))))
535       (number-dispatch ((y number))
536         (handle-reals %atan y)
537         ((complex)
538          (complex-atan y)))))
539
540 ;;; It seems that every target system has a C version of sinh, cosh,
541 ;;; and tanh. Let's use these for reals because the original
542 ;;; implementations based on the definitions lose big in round-off
543 ;;; error. These bad definitions also mean that sin and cos for
544 ;;; complex numbers can also lose big.
545
546 (defun sinh (number)
547   #!+sb-doc
548   "Return the hyperbolic sine of NUMBER."
549   (number-dispatch ((number number))
550     (handle-reals %sinh number)
551     ((complex)
552      (let ((x (realpart number))
553            (y (imagpart number)))
554        (complex (* (sinh x) (cos y))
555                 (* (cosh x) (sin y)))))))
556
557 (defun cosh (number)
558   #!+sb-doc
559   "Return the hyperbolic cosine of NUMBER."
560   (number-dispatch ((number number))
561     (handle-reals %cosh number)
562     ((complex)
563      (let ((x (realpart number))
564            (y (imagpart number)))
565        (complex (* (cosh x) (cos y))
566                 (* (sinh x) (sin y)))))))
567
568 (defun tanh (number)
569   #!+sb-doc
570   "Return the hyperbolic tangent of NUMBER."
571   (number-dispatch ((number number))
572     (handle-reals %tanh number)
573     ((complex)
574      (complex-tanh number))))
575
576 (defun asinh (number)
577   #!+sb-doc
578   "Return the hyperbolic arc sine of NUMBER."
579   (number-dispatch ((number number))
580     (handle-reals %asinh number)
581     ((complex)
582      (complex-asinh number))))
583
584 (defun acosh (number)
585   #!+sb-doc
586   "Return the hyperbolic arc cosine of NUMBER."
587   (number-dispatch ((number number))
588     ((rational)
589      ;; acosh is complex if number < 1
590      (if (< number 1)
591          (complex-acosh number)
592          (coerce (%acosh (coerce number 'double-float)) 'single-float)))
593     (((foreach single-float double-float))
594      (if (< number (coerce 1 '(dispatch-type number)))
595          (complex-acosh (complex number))
596          (coerce (%acosh (coerce number 'double-float))
597                  '(dispatch-type number))))
598     ((complex)
599      (complex-acosh number))))
600
601 (defun atanh (number)
602   #!+sb-doc
603   "Return the hyperbolic arc tangent of NUMBER."
604   (number-dispatch ((number number))
605     ((rational)
606      ;; atanh is complex if |number| > 1
607      (if (or (> number 1) (< number -1))
608          (complex-atanh number)
609          (coerce (%atanh (coerce number 'double-float)) 'single-float)))
610     (((foreach single-float double-float))
611      (if (or (> number (coerce 1 '(dispatch-type number)))
612              (< number (coerce -1 '(dispatch-type number))))
613          (complex-atanh (complex number))
614          (coerce (%atanh (coerce number 'double-float))
615                  '(dispatch-type number))))
616     ((complex)
617      (complex-atanh number))))
618
619 ;;; HP-UX does not supply a C version of log1p, so use the definition.
620 ;;;
621 ;;; FIXME: This is really not a good definition. As per Raymond Toy
622 ;;; working on CMU CL, "The definition really loses big-time in
623 ;;; roundoff as x gets small."
624 #!+hpux
625 #!-sb-fluid (declaim (inline %log1p))
626 #!+hpux
627 (defun %log1p (number)
628   (declare (double-float number)
629            (optimize (speed 3) (safety 0)))
630   (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
631 \f
632 ;;;; not-OLD-SPECFUN stuff
633 ;;;;
634 ;;;; (This was conditional on #-OLD-SPECFUN in the CMU CL sources,
635 ;;;; but OLD-SPECFUN was mentioned nowhere else, so it seems to be
636 ;;;; the standard special function system.)
637 ;;;;
638 ;;;; This is a set of routines that implement many elementary
639 ;;;; transcendental functions as specified by ANSI Common Lisp.  The
640 ;;;; implementation is based on Kahan's paper.
641 ;;;;
642 ;;;; I believe I have accurately implemented the routines and are
643 ;;;; correct, but you may want to check for your self.
644 ;;;;
645 ;;;; These functions are written for CMU Lisp and take advantage of
646 ;;;; some of the features available there.  It may be possible,
647 ;;;; however, to port this to other Lisps.
648 ;;;;
649 ;;;; Some functions are significantly more accurate than the original
650 ;;;; definitions in CMU Lisp.  In fact, some functions in CMU Lisp
651 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
652 ;;;; answer is pi + i*log(2-sqrt(3)).
653 ;;;;
654 ;;;; All of the implemented functions will take any number for an
655 ;;;; input, but the result will always be a either a complex
656 ;;;; single-float or a complex double-float.
657 ;;;;
658 ;;;; general functions:
659 ;;;;   complex-sqrt
660 ;;;;   complex-log
661 ;;;;   complex-atanh
662 ;;;;   complex-tanh
663 ;;;;   complex-acos
664 ;;;;   complex-acosh
665 ;;;;   complex-asin
666 ;;;;   complex-asinh
667 ;;;;   complex-atan
668 ;;;;   complex-tan
669 ;;;;
670 ;;;; utility functions:
671 ;;;;   scalb logb
672 ;;;;
673 ;;;; internal functions:
674 ;;;;    square coerce-to-complex-type cssqs complex-log-scaled
675 ;;;;
676 ;;;; references:
677 ;;;;   Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
678 ;;;;   Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
679 ;;;;   State of the Art in Numerical Analysis", pp. 165-211, Clarendon
680 ;;;;   Press, 1987
681 ;;;;
682 ;;;; The original CMU CL code requested:
683 ;;;;   Please send any bug reports, comments, or improvements to
684 ;;;;   Raymond Toy at <email address deleted during 2002 spam avalanche>.
685
686 ;;; FIXME: In SBCL, the floating point infinity constants like
687 ;;; SB!EXT:DOUBLE-FLOAT-POSITIVE-INFINITY aren't available as
688 ;;; constants at cross-compile time, because the cross-compilation
689 ;;; host might not have support for floating point infinities. Thus,
690 ;;; they're effectively implemented as special variable references,
691 ;;; and the code below which uses them might be unnecessarily
692 ;;; inefficient. Perhaps some sort of MAKE-LOAD-TIME-VALUE hackery
693 ;;; should be used instead?  (KLUDGED 2004-03-08 CSR, by replacing the
694 ;;; special variable references with (probably equally slow)
695 ;;; constructors)
696 ;;;
697 ;;; FIXME: As of 2004-05, when PFD noted that IMAGPART and COMPLEX
698 ;;; differ in their interpretations of the real line, IMAGPART was
699 ;;; patch, which without a certain amount of effort would have altered
700 ;;; all the branch cut treatment.  Clients of these COMPLEX- routines
701 ;;; were patched to use explicit COMPLEX, rather than implicitly
702 ;;; passing in real numbers for treatment with IMAGPART, and these
703 ;;; COMPLEX- functions altered to require arguments of type COMPLEX;
704 ;;; however, someone needs to go back to Kahan for the definitive
705 ;;; answer for treatment of negative real floating point numbers and
706 ;;; branch cuts.  If adjustment is needed, it is probably the removal
707 ;;; of explicit calls to COMPLEX in the clients of irrational
708 ;;; functions.  -- a slightly bitter CSR, 2004-05-16
709
710 (declaim (inline square))
711 (defun square (x)
712   (declare (double-float x))
713   (* x x))
714
715 ;;; original CMU CL comment, apparently re. SCALB and LOGB and
716 ;;; perhaps CSSQS:
717 ;;;   If you have these functions in libm, perhaps they should be used
718 ;;;   instead of these Lisp versions. These versions are probably good
719 ;;;   enough, especially since they are portable.
720
721 ;;; Compute 2^N * X without computing 2^N first. (Use properties of
722 ;;; the underlying floating-point format.)
723 (declaim (inline scalb))
724 (defun scalb (x n)
725   (declare (type double-float x)
726            (type double-float-exponent n))
727   (scale-float x n))
728
729 ;;; This is like LOGB, but X is not infinity and non-zero and not a
730 ;;; NaN, so we can always return an integer.
731 (declaim (inline logb-finite))
732 (defun logb-finite (x)
733   (declare (type double-float x))
734   (multiple-value-bind (signif exponent sign)
735       (decode-float x)
736     (declare (ignore signif sign))
737     ;; DECODE-FLOAT is almost right, except that the exponent is off
738     ;; by one.
739     (1- exponent)))
740
741 ;;; Compute an integer N such that 1 <= |2^N * x| < 2.
742 ;;; For the special cases, the following values are used:
743 ;;;    x             logb
744 ;;;   NaN            NaN
745 ;;;   +/- infinity   +infinity
746 ;;;   0              -infinity
747 (defun logb (x)
748   (declare (type double-float x))
749   (cond ((float-nan-p x)
750          x)
751         ((float-infinity-p x)
752          ;; DOUBLE-FLOAT-POSITIVE-INFINITY
753          (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0))
754         ((zerop x)
755          ;; The answer is negative infinity, but we are supposed to
756           ;; signal divide-by-zero, so do the actual division
757          (/ -1.0d0 x)
758          )
759         (t
760           (logb-finite x))))
761
762 ;;; This function is used to create a complex number of the
763 ;;; appropriate type:
764 ;;;   Create complex number with real part X and imaginary part Y
765 ;;;   such that has the same type as Z.  If Z has type (complex
766 ;;;   rational), the X and Y are coerced to single-float.
767 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
768                 (error "needs work for long float support"))
769 (declaim (inline coerce-to-complex-type))
770 (defun coerce-to-complex-type (x y z)
771   (declare (double-float x y)
772            (number z))
773   (if (typep (realpart z) 'double-float)
774       (complex x y)
775       ;; Convert anything that's not already a DOUBLE-FLOAT (because
776       ;; the initial argument was a (COMPLEX DOUBLE-FLOAT) and we
777       ;; haven't done anything to lose precision) to a SINGLE-FLOAT.
778       (complex (float x 1f0)
779                (float y 1f0))))
780
781 ;;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
782 ;;; result is r + i*k, where k is an integer.
783 #!+long-float (eval-when (:compile-toplevel :load-toplevel :execute)
784                 (error "needs work for long float support"))
785 (defun cssqs (z)
786   (let ((x (float (realpart z) 1d0))
787         (y (float (imagpart z) 1d0)))
788     ;; Would this be better handled using an exception handler to
789     ;; catch the overflow or underflow signal?  For now, we turn all
790     ;; traps off and look at the accrued exceptions to see if any
791     ;; signal would have been raised.
792     (with-float-traps-masked (:underflow :overflow)
793       (let ((rho (+ (square x) (square y))))
794        (declare (optimize (speed 3) (space 0)))
795       (cond ((and (or (float-nan-p rho)
796                       (float-infinity-p rho))
797                   (or (float-infinity-p (abs x))
798                       (float-infinity-p (abs y))))
799              ;; DOUBLE-FLOAT-POSITIVE-INFINITY
800              (values
801               (double-from-bits 0 (1+ sb!vm:double-float-normal-exponent-max) 0)
802               0))
803             ((let ((threshold #.(/ least-positive-double-float
804                                    double-float-epsilon))
805                    (traps (ldb sb!vm::float-sticky-bits
806                                (sb!vm:floating-point-modes))))
807                 ;; Overflow raised or (underflow raised and rho <
808                 ;; lambda/eps)
809                (or (not (zerop (logand sb!vm:float-overflow-trap-bit traps)))
810                    (and (not (zerop (logand sb!vm:float-underflow-trap-bit
811                                             traps)))
812                         (< rho threshold))))
813               ;; If we're here, neither x nor y are infinity and at
814               ;; least one is non-zero.. Thus logb returns a nice
815               ;; integer.
816               (let ((k (- (logb-finite (max (abs x) (abs y))))))
817                 (values (+ (square (scalb x k))
818                            (square (scalb y k)))
819                         (- k))))
820              (t
821               (values rho 0)))))))
822
823 ;;; principal square root of Z
824 ;;;
825 ;;; Z may be RATIONAL or COMPLEX; the result is always a COMPLEX.
826 (defun complex-sqrt (z)
827   ;; KLUDGE: Here and below, we can't just declare Z to be of type
828   ;; COMPLEX, because one-arg COMPLEX on rationals returns a rational.
829   ;; Since there isn't a rational negative zero, this is OK from the
830   ;; point of view of getting the right answer in the face of branch
831   ;; cuts, but declarations of the form (OR RATIONAL COMPLEX) are
832   ;; still ugly.  -- CSR, 2004-05-16
833   (declare (type (or complex rational) z))
834   (multiple-value-bind (rho k)
835       (cssqs z)
836     (declare (type (or (member 0d0) (double-float 0d0)) rho)
837              (type fixnum k))
838     (let ((x (float (realpart z) 1.0d0))
839           (y (float (imagpart z) 1.0d0))
840           (eta 0d0)
841           (nu 0d0))
842       (declare (double-float x y eta nu))
843
844       (locally
845          ;; space 0 to get maybe-inline functions inlined.
846          (declare (optimize (speed 3) (space 0)))
847
848       (if (not (float-nan-p x))
849           (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
850
851       (cond ((oddp k)
852              (setf k (ash k -1)))
853             (t
854              (setf k (1- (ash k -1)))
855              (setf rho (+ rho rho))))
856
857       (setf rho (scalb (sqrt rho) k))
858
859       (setf eta rho)
860       (setf nu y)
861
862       (when (/= rho 0d0)
863             (when (not (float-infinity-p (abs nu)))
864                   (setf nu (/ (/ nu rho) 2d0)))
865             (when (< x 0d0)
866                   (setf eta (abs nu))
867                   (setf nu (float-sign y rho))))
868        (coerce-to-complex-type eta nu z)))))
869
870 ;;; Compute log(2^j*z).
871 ;;;
872 ;;; This is for use with J /= 0 only when |z| is huge.
873 (defun complex-log-scaled (z j)
874   (declare (type (or rational complex) z)
875            (fixnum j))
876   ;; The constants t0, t1, t2 should be evaluated to machine
877   ;; precision.  In addition, Kahan says the accuracy of log1p
878   ;; influences the choices of these constants but doesn't say how to
879   ;; choose them.  We'll just assume his choices matches our
880   ;; implementation of log1p.
881   (let ((t0 #.(/ 1 (sqrt 2.0d0)))
882         (t1 1.2d0)
883         (t2 3d0)
884         (ln2 #.(log 2d0))
885         (x (float (realpart z) 1.0d0))
886         (y (float (imagpart z) 1.0d0)))
887     (multiple-value-bind (rho k)
888         (cssqs z)
889       (declare (optimize (speed 3)))
890       (let ((beta (max (abs x) (abs y)))
891             (theta (min (abs x) (abs y))))
892         (coerce-to-complex-type (if (and (zerop k)
893                  (< t0 beta)
894                  (or (<= beta t1)
895                      (< rho t2)))
896                                   (/ (%log1p (+ (* (- beta 1.0d0)
897                                        (+ beta 1.0d0))
898                                     (* theta theta)))
899                                      2d0)
900                                   (+ (/ (log rho) 2d0)
901                                      (* (+ k j) ln2)))
902                                 (atan y x)
903                                 z)))))
904
905 ;;; log of Z = log |Z| + i * arg Z
906 ;;;
907 ;;; Z may be any number, but the result is always a complex.
908 (defun complex-log (z)
909   (declare (type (or rational complex) z))
910   (complex-log-scaled z 0))
911
912 ;;; KLUDGE: Let us note the following "strange" behavior. atanh 1.0d0
913 ;;; is +infinity, but the following code returns approx 176 + i*pi/4.
914 ;;; The reason for the imaginary part is caused by the fact that arg
915 ;;; i*y is never 0 since we have positive and negative zeroes. -- rtoy
916 ;;; Compute atanh z = (log(1+z) - log(1-z))/2.
917 (defun complex-atanh (z)
918   (declare (type (or rational complex) z))
919   (let* (;; constants
920          (theta (/ (sqrt most-positive-double-float) 4.0d0))
921          (rho (/ 4.0d0 (sqrt most-positive-double-float)))
922          (half-pi (/ pi 2.0d0))
923          (rp (float (realpart z) 1.0d0))
924          (beta (float-sign rp 1.0d0))
925          (x (* beta rp))
926          (y (* beta (- (float (imagpart z) 1.0d0))))
927          (eta 0.0d0)
928          (nu 0.0d0))
929     ;; Shouldn't need this declare.
930     (declare (double-float x y))
931     (locally
932        (declare (optimize (speed 3)))
933     (cond ((or (> x theta)
934                (> (abs y) theta))
935            ;; To avoid overflow...
936            (setf nu (float-sign y half-pi))
937            ;; ETA is real part of 1/(x + iy).  This is x/(x^2+y^2),
938            ;; which can cause overflow.  Arrange this computation so
939            ;; that it won't overflow.
940            (setf eta (let* ((x-bigger (> x (abs y)))
941                             (r (if x-bigger (/ y x) (/ x y)))
942                             (d (+ 1.0d0 (* r r))))
943                        (if x-bigger
944                            (/ (/ x) d)
945                            (/ (/ r y) d)))))
946           ((= x 1.0d0)
947            ;; Should this be changed so that if y is zero, eta is set
948            ;; to +infinity instead of approx 176?  In any case
949            ;; tanh(176) is 1.0d0 within working precision.
950            (let ((t1 (+ 4d0 (square y)))
951                  (t2 (+ (abs y) rho)))
952              (setf eta (log (/ (sqrt (sqrt t1))
953                                (sqrt t2))))
954              (setf nu (* 0.5d0
955                          (float-sign y
956                                      (+ half-pi (atan (* 0.5d0 t2))))))))
957           (t
958            (let ((t1 (+ (abs y) rho)))
959               ;; Normal case using log1p(x) = log(1 + x)
960              (setf eta (* 0.25d0
961                           (%log1p (/ (* 4.0d0 x)
962                                      (+ (square (- 1.0d0 x))
963                                         (square t1))))))
964              (setf nu (* 0.5d0
965                          (atan (* 2.0d0 y)
966                                (- (* (- 1.0d0 x)
967                                      (+ 1.0d0 x))
968                                   (square t1))))))))
969     (coerce-to-complex-type (* beta eta)
970                             (- (* beta nu))
971                              z))))
972
973 ;;; Compute tanh z = sinh z / cosh z.
974 (defun complex-tanh (z)
975   (declare (type (or rational complex) z))
976   (let ((x (float (realpart z) 1.0d0))
977         (y (float (imagpart z) 1.0d0)))
978     (locally
979       ;; space 0 to get maybe-inline functions inlined
980       (declare (optimize (speed 3) (space 0)))
981     (cond ((> (abs x)
982               ;; FIXME: this form is hideously broken wrt
983               ;; cross-compilation portability.  Much else in this
984               ;; file is too, of course, sometimes hidden by
985               ;; constant-folding, but this one in particular clearly
986               ;; depends on host and target
987               ;; MOST-POSITIVE-DOUBLE-FLOATs being equal.  -- CSR,
988               ;; 2003-04-20
989               #.(/ (+ (log 2.0d0)
990                       (log most-positive-double-float))
991                    4d0))
992            (coerce-to-complex-type (float-sign x)
993                                    (float-sign y) z))
994           (t
995            (let* ((tv (%tan y))
996                   (beta (+ 1.0d0 (* tv tv)))
997                   (s (sinh x))
998                   (rho (sqrt (+ 1.0d0 (* s s)))))
999              (if (float-infinity-p (abs tv))
1000                  (coerce-to-complex-type (/ rho s)
1001                                          (/ tv)
1002                                          z)
1003                  (let ((den (+ 1.0d0 (* beta s s))))
1004                    (coerce-to-complex-type (/ (* beta rho s)
1005                                               den)
1006                                            (/ tv den)
1007                                             z)))))))))
1008
1009 ;;; Compute acos z = pi/2 - asin z.
1010 ;;;
1011 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1012 (defun complex-acos (z)
1013   ;; Kahan says we should only compute the parts needed.  Thus, the
1014   ;; REALPART's below should only compute the real part, not the whole
1015   ;; complex expression.  Doing this can be important because we may get
1016   ;; spurious signals that occur in the part that we are not using.
1017   ;;
1018   ;; However, we take a pragmatic approach and just use the whole
1019   ;; expression.
1020   ;;
1021   ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1022   ;; it's the conjugate of the square root or the square root of the
1023   ;; conjugate.  This needs to be checked.
1024   ;;
1025   ;; I checked.  It doesn't matter because (conjugate (sqrt z)) is the
1026   ;; same as (sqrt (conjugate z)) for all z.  This follows because
1027   ;;
1028   ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1029   ;;
1030   ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1031   ;;
1032   ;; and these two expressions are equal if and only if arg conj z =
1033   ;; -arg z, which is clearly true for all z.
1034   (declare (type (or rational complex) z))
1035   (let ((sqrt-1+z (complex-sqrt (+ 1 z)))
1036         (sqrt-1-z (complex-sqrt (- 1 z))))
1037     (with-float-traps-masked (:divide-by-zero)
1038       (complex (* 2 (atan (/ (realpart sqrt-1-z)
1039                              (realpart sqrt-1+z))))
1040                (asinh (imagpart (* (conjugate sqrt-1+z)
1041                                    sqrt-1-z)))))))
1042
1043 ;;; Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1044 ;;;
1045 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1046 (defun complex-acosh (z)
1047   (declare (type (or rational complex) z))
1048   (let ((sqrt-z-1 (complex-sqrt (- z 1)))
1049         (sqrt-z+1 (complex-sqrt (+ z 1))))
1050     (with-float-traps-masked (:divide-by-zero)
1051       (complex (asinh (realpart (* (conjugate sqrt-z-1)
1052                                    sqrt-z+1)))
1053                (* 2 (atan (/ (imagpart sqrt-z-1)
1054                              (realpart sqrt-z+1))))))))
1055
1056 ;;; Compute asin z = asinh(i*z)/i.
1057 ;;;
1058 ;;; Z may be any NUMBER, but the result is always a COMPLEX.
1059 (defun complex-asin (z)
1060   (declare (type (or rational complex) z))
1061   (let ((sqrt-1-z (complex-sqrt (- 1 z)))
1062         (sqrt-1+z (complex-sqrt (+ 1 z))))
1063     (with-float-traps-masked (:divide-by-zero)
1064       (complex (atan (/ (realpart z)
1065                         (realpart (* sqrt-1-z sqrt-1+z))))
1066                (asinh (imagpart (* (conjugate sqrt-1-z)
1067                                    sqrt-1+z)))))))
1068
1069 ;;; Compute asinh z = log(z + sqrt(1 + z*z)).
1070 ;;;
1071 ;;; Z may be any number, but the result is always a complex.
1072 (defun complex-asinh (z)
1073   (declare (type (or rational complex) z))
1074   ;; asinh z = -i * asin (i*z)
1075   (let* ((iz (complex (- (imagpart z)) (realpart z)))
1076          (result (complex-asin iz)))
1077     (complex (imagpart result)
1078              (- (realpart result)))))
1079
1080 ;;; Compute atan z = atanh (i*z) / i.
1081 ;;;
1082 ;;; Z may be any number, but the result is always a complex.
1083 (defun complex-atan (z)
1084   (declare (type (or rational complex) z))
1085   ;; atan z = -i * atanh (i*z)
1086   (let* ((iz (complex (- (imagpart z)) (realpart z)))
1087          (result (complex-atanh iz)))
1088     (complex (imagpart result)
1089              (- (realpart result)))))
1090
1091 ;;; Compute tan z = -i * tanh(i * z)
1092 ;;;
1093 ;;; Z may be any number, but the result is always a complex.
1094 (defun complex-tan (z)
1095   (declare (type (or rational complex) z))
1096   ;; tan z = -i * tanh(i*z)
1097   (let* ((iz (complex (- (imagpart z)) (realpart z)))
1098          (result (complex-tanh iz)))
1099     (complex (imagpart result)
1100              (- (realpart result)))))