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