/[cmucl]/src/code/irrat.lisp
ViewVC logotype

Contents of /src/code/irrat.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.55 - (show annotations)
Thu Jan 31 19:12:40 2008 UTC (6 years, 2 months ago) by rtoy
Branch: MAIN
CVS Tags: snapshot-2008-08, snapshot-2008-09, snapshot-2008-05, snapshot-2008-06, snapshot-2008-07, snapshot-2008-02, snapshot-2008-03, sse2-base, release-19e, unicode-utf16-sync-2008-07, unicode-utf16-sync-2008-09, snapshot-2008-04, unicode-utf16-extfmts-pre-sync-2008-11, snapshot-2008-10, release-19e-pre1, release-19e-pre2, unicode-utf16-string-support, release-19e-base, unicode-utf16-base
Branch point for: unicode-utf16-branch, release-19e-branch, sse2-branch, unicode-utf16-extfmt-branch
Changes since 1.54: +10 -9 lines
Correct some comments.
1 ;;; -*- Mode: Lisp; Package: KERNEL; Log: code.log -*-
2 ;;;
3 ;;; **********************************************************************
4 ;;; This code was written as part of the CMU Common Lisp project at
5 ;;; Carnegie Mellon University, and has been placed in the public domain.
6 ;;;
7 (ext:file-comment
8 "$Header: /tiger/var/lib/cvsroots/cmucl/src/code/irrat.lisp,v 1.55 2008/01/31 19:12:40 rtoy Exp $")
9 ;;;
10 ;;; **********************************************************************
11 ;;;
12 ;;; This file contains all the irrational functions. Actually, most of the
13 ;;; work is done by calling out to C...
14 ;;;
15 ;;; Author: William Lott.
16 ;;;
17
18 (in-package "KERNEL")
19
20
21 ;;;; Random constants, utility functions, and macros.
22
23 (defconstant pi 3.14159265358979323846264338327950288419716939937511L0)
24 ;(defconstant e 2.71828182845904523536028747135266249775724709369996L0)
25
26 ;;; Make these INLINE, since the call to C is at least as compact as a Lisp
27 ;;; call, and saves number consing to boot.
28 ;;;
29 (defmacro def-math-rtn (name num-args)
30 (let ((function (intern (concatenate 'simple-string
31 "%"
32 (string-upcase name)))))
33 `(progn
34 (declaim (inline ,function))
35 (export ',function)
36 (alien:def-alien-routine (,name ,function) double-float
37 ,@(let ((results nil))
38 (dotimes (i num-args (nreverse results))
39 (push (list (intern (format nil "ARG-~D" i))
40 'double-float)
41 results)))))))
42
43 (eval-when (compile load eval)
44
45 (defun handle-reals (function var)
46 `((((foreach fixnum single-float bignum ratio))
47 (coerce (,function (coerce ,var 'double-float)) 'single-float))
48 ((double-float)
49 (,function ,var))
50 #+double-double
51 ((double-double-float)
52 (,(symbolicate "DD-" function) ,var))))
53
54 ); eval-when (compile load eval)
55
56
57 ;;;; Stubs for the Unix math library.
58
59 ;;; Please refer to the Unix man pages for details about these routines.
60
61 ;;; Trigonometric.
62 #-x86 (def-math-rtn "sin" 1)
63 #-x86 (def-math-rtn "cos" 1)
64 #-x86 (def-math-rtn "tan" 1)
65 (def-math-rtn "asin" 1)
66 (def-math-rtn "acos" 1)
67 #-x86 (def-math-rtn "atan" 1)
68 #-x86 (def-math-rtn "atan2" 2)
69 (def-math-rtn "sinh" 1)
70 (def-math-rtn "cosh" 1)
71 (def-math-rtn "tanh" 1)
72 (def-math-rtn "asinh" 1)
73 (def-math-rtn "acosh" 1)
74 (def-math-rtn "atanh" 1)
75
76 ;;; Exponential and Logarithmic.
77 #-x86 (def-math-rtn "exp" 1)
78 #-x86 (def-math-rtn "log" 1)
79 #-x86 (def-math-rtn "log10" 1)
80 (def-math-rtn "pow" 2)
81 #-(or x86 sparc-v7 sparc-v8 sparc-v9) (def-math-rtn "sqrt" 1)
82 (def-math-rtn "hypot" 2)
83 #-(or hpux x86) (def-math-rtn "log1p" 1)
84
85 #+x86 ;; These are needed for use by byte-compiled files.
86 (progn
87 #+nil
88 (defun %sin (x)
89 (declare (double-float x)
90 (values double-float))
91 (%sin x))
92 (defun %sin-quick (x)
93 (declare (double-float x)
94 (values double-float))
95 (%sin-quick x))
96 #+nil
97 (defun %cos (x)
98 (declare (double-float x)
99 (values double-float))
100 (%cos x))
101 (defun %cos-quick (x)
102 (declare (double-float x)
103 (values double-float))
104 (%cos-quick x))
105 #+nil
106 (defun %tan (x)
107 (declare (double-float x)
108 (values double-float))
109 (%tan x))
110 (defun %tan-quick (x)
111 (declare (double-float x)
112 (values double-float))
113 (%tan-quick x))
114 (defun %atan (x)
115 (declare (double-float x)
116 (values double-float))
117 (%atan x))
118 (defun %atan2 (x y)
119 (declare (double-float x y)
120 (values double-float))
121 (%atan2 x y))
122 (defun %exp (x)
123 (declare (double-float x)
124 (values double-float))
125 (%exp x))
126 (defun %log (x)
127 (declare (double-float x)
128 (values double-float))
129 (%log x))
130 (defun %log10 (x)
131 (declare (double-float x)
132 (values double-float))
133 (%log10 x))
134 #+nil ;; notyet
135 (defun %pow (x y)
136 (declare (type (double-float 0d0) x)
137 (double-float y)
138 (values (double-float 0d0)))
139 (%pow x y))
140 (defun %sqrt (x)
141 (declare (double-float x)
142 (values double-float))
143 (%sqrt x))
144 (defun %scalbn (f ex)
145 (declare (double-float f)
146 (type (signed-byte 32) ex)
147 (values double-float))
148 (%scalbn f ex))
149 (defun %scalb (f ex)
150 (declare (double-float f ex)
151 (values double-float))
152 (%scalb f ex))
153 (defun %logb (x)
154 (declare (double-float x)
155 (values double-float))
156 (%logb x))
157 (defun %log1p (x)
158 (declare (double-float x)
159 (values double-float))
160 (%log1p x))
161 ) ; progn
162
163
164 ;; As above for x86. It also seems to be needed to handle
165 ;; constant-folding in the compiler.
166 #+sparc
167 (progn
168 (defun %sqrt (x)
169 (declare (double-float x)
170 (values double-float))
171 (%sqrt x))
172 )
173
174 ;;; The standard libm routines for sin, cos, and tan on x86 (Linux)
175 ;;; and ppc are not very accurate for large arguments when compared to
176 ;;; sparc (and maxima). This is basically caused by the fact that
177 ;;; those libraries do not do an accurate argument reduction. The
178 ;;; following functions use some routines Sun's free fdlibm library to
179 ;;; do accurate reduction. Then we call the standard C functions (or
180 ;;; vops for x86) on the reduced argument. This produces much more
181 ;;; accurate values.
182
183 #+(or ppc x86)
184 (progn
185 (declaim (inline %%ieee754-rem-pi/2))
186 ;; Basic argument reduction routine. It returns two values: n and y
187 ;; such that (n + 8*k)*pi/2+y = x where |y|<pi/4 and n indicates in
188 ;; which octant the arg lies. Y is actually computed in two parts,
189 ;; y[0] and y[1] such that the sum is y, for accuracy.
190
191 (alien:def-alien-routine ("__ieee754_rem_pio2" %%ieee754-rem-pi/2) c-call:int
192 (x double-float)
193 (y (* double-float)))
194
195 ;; Same as above, but instead of needing to pass an array in, the
196 ;; output array is broken up into two output values instead. This is
197 ;; easier for the user, and we don't have to wrap calls with
198 ;; without-gcing.
199 (declaim (inline %ieee754-rem-pi/2))
200 (alien:def-alien-routine ("ieee754_rem_pio2" %ieee754-rem-pi/2) c-call:int
201 (x double-float)
202 (y0 double-float :out)
203 (y1 double-float :out))
204
205 )
206
207 #+ppc
208 (progn
209 (declaim (inline %%sin %%cos %%tan))
210 (macrolet ((frob (alien-name lisp-name)
211 `(alien:def-alien-routine (,alien-name ,lisp-name) double-float
212 (x double-float))))
213 (frob "sin" %%sin)
214 (frob "cos" %%cos)
215 (frob "tan" %%tan))
216 )
217
218 #+(or ppc x86)
219 (macrolet
220 ((frob (sin cos tan)
221 `(progn
222 ;; In all of the routines below, we just compute the sum of
223 ;; y0 and y1 and use that as the (reduced) argument for the
224 ;; trig functions. This is slightly less accurate than what
225 ;; fdlibm does, which calls special functions using y0 and
226 ;; y1 separately, for greater accuracy. This isn't
227 ;; implemented, and some spot checks indicate that what we
228 ;; have here is accurate.
229 ;;
230 ;; For x86 with an fsin/fcos/fptan instruction, the pi/4 is
231 ;; probably too restrictive.
232 (defun %sin (x)
233 (declare (double-float x))
234 (if (< (abs x) (/ pi 4))
235 (,sin x)
236 ;; Argument reduction needed
237 (multiple-value-bind (n y0 y1)
238 (%ieee754-rem-pi/2 x)
239 (let ((reduced (+ y0 y1)))
240 (case (logand n 3)
241 (0 (,sin reduced))
242 (1 (,cos reduced))
243 (2 (- (,sin reduced)))
244 (3 (- (,cos reduced))))))))
245 (defun %cos (x)
246 (declare (double-float x))
247 (if (< (abs x) (/ pi 4))
248 (,cos x)
249 ;; Argument reduction needed
250 (multiple-value-bind (n y0 y1)
251 (%ieee754-rem-pi/2 x)
252 (let ((reduced (+ y0 y1)))
253 (case (logand n 3)
254 (0 (,cos reduced))
255 (1 (- (,sin reduced)))
256 (2 (- (,cos reduced)))
257 (3 (,sin reduced)))))))
258 (defun %tan (x)
259 (declare (double-float x))
260 (if (< (abs x) (/ pi 4))
261 (,tan x)
262 ;; Argument reduction needed
263 (multiple-value-bind (n y0 y1)
264 (%ieee754-rem-pi/2 x)
265 (let ((reduced (+ y0 y1)))
266 (if (evenp n)
267 (,tan reduced)
268 (- (/ (,tan reduced)))))))))))
269 #+x86
270 (frob %sin-quick %cos-quick %tan-quick)
271 #+ppc
272 (frob %%sin %%cos %%tan))
273
274
275
276 ;;;; Power functions.
277
278 (defun exp (number)
279 "Return e raised to the power NUMBER."
280 (number-dispatch ((number number))
281 (handle-reals %exp number)
282 ((complex)
283 (* (exp (realpart number))
284 (cis (imagpart number))))))
285
286 ;;; INTEXP -- Handle the rational base, integer power case.
287
288 (defparameter *intexp-maximum-exponent* 10000)
289
290 ;;; This function precisely calculates base raised to an integral power. It
291 ;;; separates the cases by the sign of power, for efficiency reasons, as powers
292 ;;; can be calculated more efficiently if power is a positive integer. Values
293 ;;; of power are calculated as positive integers, and inverted if negative.
294 ;;;
295 (defun intexp (base power)
296 ;; Handle the special case of 1^power. Maxima sometimes does this,
297 ;; and there's no need to cause a continuable error in this case.
298 ;; Should we also handle (-1)^power?
299 (when (eql base 1)
300 (return-from intexp base))
301
302 (when (> (abs power) *intexp-maximum-exponent*)
303 (cerror "Continue with calculation."
304 "The absolute value of ~S exceeds ~S."
305 power '*intexp-maximum-exponent* base power))
306 (cond ((minusp power)
307 (/ (intexp base (- power))))
308 ((eql base 2)
309 (ash 1 power))
310 (t
311 (do ((nextn (ash power -1) (ash power -1))
312 (total (if (oddp power) base 1)
313 (if (oddp power) (* base total) total)))
314 ((zerop nextn) total)
315 (setq base (* base base))
316 (setq power nextn)))))
317
318
319 ;;; EXPT -- Public
320 ;;;
321 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
322 ;;; floating point stuff. If both args are real, we try %POW right off,
323 ;;; assuming it will return 0 if the result may be complex. If so, we call
324 ;;; COMPLEX-POW which directly computes the complex result. We also separate
325 ;;; the complex-real and real-complex cases from the general complex case.
326 ;;;
327 (defun expt (base power)
328 "Returns BASE raised to the POWER."
329 (if (zerop power)
330 ;; CLHS says that if the power is 0, the result is 1, subject to
331 ;; numeric contagion. But what happens if base is infinity or
332 ;; NaN? Do we silently return 1? For now, I think we should
333 ;; signal an error if the FP modes say so.
334 (let ((result (1+ (* base power))))
335 ;; If we get an NaN here, that means base*power above didn't
336 ;; produce 0 and FP traps were disabled, so we handle that
337 ;; here. Should this be a continuable restart?
338 (if (and (floatp result) (float-nan-p result))
339 (float 1 result)
340 result))
341 (labels (;; determine if the double float is an integer.
342 ;; 0 - not an integer
343 ;; 1 - an odd int
344 ;; 2 - an even int
345 (isint (ihi lo)
346 (declare (type (unsigned-byte 31) ihi)
347 (type (unsigned-byte 32) lo)
348 (optimize (speed 3) (safety 0)))
349 (let ((isint 0))
350 (declare (type fixnum isint))
351 (cond ((>= ihi #x43400000) ; exponent >= 53
352 (setq isint 2))
353 ((>= ihi #x3ff00000)
354 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
355 (declare (type (mod 53) k))
356 (cond ((> k 20)
357 (let* ((shift (- 52 k))
358 (j (logand (ash lo (- shift))))
359 (j2 (ash j shift)))
360 (declare (type (mod 32) shift)
361 (type (unsigned-byte 32) j j2))
362 (when (= j2 lo)
363 (setq isint (- 2 (logand j 1))))))
364 ((= lo 0)
365 (let* ((shift (- 20 k))
366 (j (ash ihi (- shift)))
367 (j2 (ash j shift)))
368 (declare (type (mod 32) shift)
369 (type (unsigned-byte 31) j j2))
370 (when (= j2 ihi)
371 (setq isint (- 2 (logand j 1))))))))))
372 isint))
373 (real-expt (x y rtype)
374 (let ((x (coerce x 'double-float))
375 (y (coerce y 'double-float)))
376 (declare (double-float x y))
377 (let* ((x-hi (kernel:double-float-high-bits x))
378 (x-lo (kernel:double-float-low-bits x))
379 (x-ihi (logand x-hi #x7fffffff))
380 (y-hi (kernel:double-float-high-bits y))
381 (y-lo (kernel:double-float-low-bits y))
382 (y-ihi (logand y-hi #x7fffffff)))
383 (declare (type (signed-byte 32) x-hi y-hi)
384 (type (unsigned-byte 31) x-ihi y-ihi)
385 (type (unsigned-byte 32) x-lo y-lo))
386 ;; y==zero: x**0 = 1
387 (when (zerop (logior y-ihi y-lo))
388 (return-from real-expt (coerce 1d0 rtype)))
389 ;; +-NaN return x+y
390 (when (or (> x-ihi #x7ff00000)
391 (and (= x-ihi #x7ff00000) (/= x-lo 0))
392 (> y-ihi #x7ff00000)
393 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
394 (return-from real-expt (coerce (+ x y) rtype)))
395 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
396 (declare (type fixnum yisint))
397 ;; special value of y
398 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
399 ;; y is +-inf
400 (return-from real-expt
401 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
402 ;; +-1**inf is NaN
403 (coerce (- y y) rtype))
404 ((>= x-ihi #x3ff00000)
405 ;; (|x|>1)**+-inf = inf,0
406 (if (>= y-hi 0)
407 (coerce y rtype)
408 (coerce 0 rtype)))
409 (t
410 ;; (|x|<1)**-,+inf = inf,0
411 (if (< y-hi 0)
412 (coerce (- y) rtype)
413 (coerce 0 rtype))))))
414
415 (let ((abs-x (abs x)))
416 (declare (double-float abs-x))
417 ;; special value of x
418 (when (and (zerop x-lo)
419 (or (= x-ihi #x7ff00000) (zerop x-ihi)
420 (= x-ihi #x3ff00000)))
421 ;; x is +-0,+-inf,+-1
422 (let ((z (if (< y-hi 0)
423 (/ 1 abs-x) ; z = (1/|x|)
424 abs-x)))
425 (declare (double-float z))
426 (when (< x-hi 0)
427 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
428 ;; (-1)**non-int
429 (let ((y*pi (* y pi)))
430 (declare (double-float y*pi))
431 (return-from real-expt
432 (complex
433 (coerce (%cos y*pi) rtype)
434 (coerce (%sin y*pi) rtype)))))
435 ((= yisint 1)
436 ;; (x<0)**odd = -(|x|**odd)
437 (setq z (- z)))))
438 (return-from real-expt (coerce z rtype))))
439
440 (if (>= x-hi 0)
441 ;; x>0
442 (coerce (kernel::%pow x y) rtype)
443 ;; x<0
444 (let ((pow (kernel::%pow abs-x y)))
445 (declare (double-float pow))
446 (case yisint
447 (1 ; Odd
448 (coerce (* -1d0 pow) rtype))
449 (2 ; Even
450 (coerce pow rtype))
451 (t ; Non-integer
452 (let ((y*pi (* y pi)))
453 (declare (double-float y*pi))
454 (complex
455 (coerce (* pow (%cos y*pi)) rtype)
456 (coerce (* pow (%sin y*pi)) rtype)))))))))))))
457 (declare (inline real-expt))
458 (number-dispatch ((base number) (power number))
459 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
460 (intexp base power))
461 (((foreach single-float double-float) rational)
462 (real-expt base power '(dispatch-type base)))
463 (((foreach fixnum (or bignum ratio) single-float)
464 (foreach ratio single-float))
465 (real-expt base power 'single-float))
466 (((foreach fixnum (or bignum ratio) single-float double-float)
467 double-float)
468 (real-expt base power 'double-float))
469 ((double-float single-float)
470 (real-expt base power 'double-float))
471 #+double-double
472 (((foreach fixnum (or bignum ratio) single-float double-float double-double-float)
473 double-double-float)
474 (dd-%pow (coerce base 'double-double-float) power))
475 #+double-double
476 ((double-double-float
477 (foreach fixnum (or bignum ratio) single-float double-float))
478 (dd-%pow base (coerce power 'double-double-float)))
479 (((foreach (complex rational) (complex float)) rational)
480 (* (expt (abs base) power)
481 (cis (* power (phase base)))))
482 (((foreach fixnum (or bignum ratio) single-float double-float
483 #+double-double double-double-float)
484 complex)
485 (if (and (zerop base) (plusp (realpart power)))
486 (* base power)
487 (exp (* power (log base)))))
488 (((foreach (complex float) (complex rational))
489 (foreach complex double-float single-float #+double-double double-double-float))
490 (if (and (zerop base) (plusp (realpart power)))
491 (* base power)
492 (exp (* power (log base)))))))))
493
494 ;; Log base 2 of a real number. The result is a either a double-float
495 ;; or double-double-float number (real or complex, as appropriate),
496 ;; depending on the type of FLOAT-TYPE.
497 (defun log2 (x &optional (float-type 1d0))
498 (labels ((log-of-2 (f)
499 ;; log(2), with the precision specified by the type of F
500 (number-dispatch ((f real))
501 ((double-float)
502 #.(log 2d0))
503 #+double-double
504 ((double-double-float)
505 #.(log 2w0))))
506 (log-2-pi (f)
507 ;; log(pi), with the precision specified by the type of F
508 (number-dispatch ((f real))
509 ((double-float)
510 #.(/ pi (log 2d0)))
511 #+double-double
512 ((double-double-float)
513 #.(/ dd-pi (log 2w0)))))
514 (log1p (x)
515 ;; log(1+x), with the precision specified by the type of
516 ;; X
517 (number-dispatch ((x real))
518 (((foreach single-float double-float))
519 (%log1p (float x 1d0)))
520 #+double-double
521 ((double-double-float)
522 (dd-%log1p x))))
523 (log2-bignum (bignum)
524 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n
525 ;; + log2(f).
526 ;;
527 ;; So we grab the top few bits of x and scale that
528 ;; appropriately, take the log of it and add it to n.
529 ;;
530 ;; Return n and log2(f) separately.
531 (if (minusp bignum)
532 (multiple-value-bind (n frac)
533 (log2-bignum (abs bignum))
534 (values n (complex frac (log-2-pi float-type))))
535 (let ((n (integer-length bignum))
536 (float-bits (float-digits float-type)))
537 (if (< n float-bits)
538 (values 0 (log (float bignum float-type)
539 (float 2 float-type)))
540 (let ((exp (min float-bits n))
541 (f (ldb (byte float-bits
542 (max 0 (- n float-bits)))
543 bignum)))
544 (values n (log (scale-float (float f float-type) (- exp))
545 (float 2 float-type)))))))))
546 (etypecase x
547 (float
548 (/ (log (float x float-type)) (log-of-2 float-type)))
549 (ratio
550 (let ((top (numerator x))
551 (bot (denominator x)))
552 ;; If the number of bits in the numerator and
553 ;; denominator are different, just use the fact
554 ;; log(x/y) = log(x) - log(y). But to preserve
555 ;; accuracy, we actually do
556 ;; (log2(x)-log2(y))/log2(e)).
557 ;;
558 ;; However, if the numerator and denominator have the
559 ;; same number of bits, implying the quotient is near
560 ;; one, we use log1p(x) = log(1+x). Since the number is
561 ;; rational, we don't lose precision subtracting 1 from
562 ;; it, and converting it to double-float is accurate.
563 (if (= (integer-length top)
564 (integer-length bot))
565 (/ (log1p (float (- x 1) float-type))
566 (log-of-2 float-type))
567 (multiple-value-bind (top-n top-frac)
568 (log2-bignum top)
569 (multiple-value-bind (bot-n bot-frac)
570 (log2-bignum bot)
571 (+ (- top-n bot-n)
572 (- top-frac bot-frac)))))))
573 (integer
574 (multiple-value-bind (n frac)
575 (log2-bignum x)
576 (+ n frac))))))
577
578 (defun log (number &optional (base nil base-p))
579 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
580 (if base-p
581 (cond ((zerop base)
582 ;; ANSI spec
583 base)
584 ((and (realp number) (realp base))
585 ;; CLHS 12.1.4.1 says
586 ;;
587 ;; When rationals and floats are combined by a
588 ;; numerical function, the rational is first converted
589 ;; to a float of the same format.
590 ;;
591 ;; So assume this applies to floats as well convert all
592 ;; numbers to the largest float format before computing
593 ;; the log.
594 ;;
595 ;; This makes (log 17 10.0) = (log 17.0 10) and so on.
596 (number-dispatch ((number real) (base real))
597 ((double-float
598 (foreach double-float single-float))
599 (/ (log2 number) (log2 base)))
600 (((foreach fixnum bignum ratio)
601 (foreach fixnum bignum ratio single-float))
602 (let* ((result (/ (log2 number) (log2 base))))
603 ;; Figure out the right result type
604 (if (realp result)
605 (coerce result 'single-float)
606 (coerce result '(complex single-float)))))
607 (((foreach fixnum bignum ratio)
608 double-float)
609 (/ (log2 number) (log2 base)))
610 ((single-float
611 (foreach fixnum bignum ratio))
612 (let* ((result (/ (log2 number) (log2 base))))
613 ;; Figure out the right result type
614 (if (realp result)
615 (coerce result 'single-float)
616 (coerce result '(complex single-float)))))
617 ((double-float
618 (foreach fixnum bignum ratio))
619 (/ (log2 number) (log2 base)))
620 ((single-float double-float)
621 (/ (log (coerce number 'double-float)) (log base)))
622 #+double-double
623 ((double-double-float
624 (foreach fixnum bignum ratio))
625 (/ (log2 number 1w0) (log2 base 1w0)))
626 #+double-double
627 ((double-double-float
628 (foreach double-double-float double-float single-float))
629 (/ (log number) (log (coerce base 'double-double-float))))
630 #+double-double
631 (((foreach fixnum bignum ratio)
632 double-double-float)
633 (/ (log2 number 1w0) (log2 base 1w0)))
634 #+double-double
635 (((foreach double-float single-float)
636 double-double-float)
637 (/ (log (coerce number 'double-double-float)) (log base)))
638 (((foreach single-float)
639 (foreach single-float))
640 ;; Converting everything to double-float helps the
641 ;; cases like (log 17 10) = (/ (log 17) (log 10)).
642 ;; This is usually handled above, but if we compute (/
643 ;; (log 17) (log 10)), we get a slightly different
644 ;; answer due to roundoff. This makes it a bit more
645 ;; consistent.
646 ;;
647 ;; FIXME: This probably needs more work.
648 (let ((result (/ (log (float number 1d0))
649 (log (float base 1d0)))))
650 (if (realp result)
651 (coerce result 'single-float)
652 (coerce result '(complex single-float)))))))
653 (t
654 ;; FIXME: This probably needs some work as well.
655 (/ (log number) (log base))))
656 (number-dispatch ((number number))
657 (((foreach fixnum bignum))
658 (if (minusp number)
659 (complex (coerce (log (- number)) 'single-float)
660 (coerce pi 'single-float))
661 (coerce (/ (log2 number) #.(log (exp 1d0) 2d0)) 'single-float)))
662 ((ratio)
663 (if (minusp number)
664 (complex (coerce (log (- number)) 'single-float)
665 (coerce pi 'single-float))
666 ;; What happens when the ratio is close to 1? We need to
667 ;; be careful to preserve accuracy.
668 (let ((top (numerator number))
669 (bot (denominator number)))
670 ;; If the number of bits in the numerator and
671 ;; denominator are different, just use the fact
672 ;; log(x/y) = log(x) - log(y). But to preserve
673 ;; accuracy, we actually do
674 ;; (log2(x)-log2(y))/log2(e)).
675 ;;
676 ;; However, if the numerator and denominator have the
677 ;; same number of bits, implying the quotient is near
678 ;; one, we use log1p(x) = log(1+x). Since the number is
679 ;; rational, we don't lose precision subtracting 1 from
680 ;; it, and converting it to double-float is accurate.
681 (if (= (integer-length top)
682 (integer-length bot))
683 (coerce (%log1p (coerce (- number 1) 'double-float))
684 'single-float)
685 (coerce (/ (- (log2 top) (log2 bot))
686 #.(log (exp 1d0) 2d0))
687 'single-float)))))
688 (((foreach single-float double-float))
689 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
690 ;; Since this doesn't seem to be an implementation issue
691 ;; I (pw) take the Kahan result.
692 (if (< (float-sign number)
693 (coerce 0 '(dispatch-type number)))
694 (complex (log (- number)) (coerce pi '(dispatch-type number)))
695 (coerce (%log (coerce number 'double-float))
696 '(dispatch-type number))))
697 #+double-double
698 ((double-double-float)
699 (let ((hi (kernel:double-double-hi number)))
700 (if (< (float-sign hi) 0d0)
701 (complex (dd-%log (- number)) dd-pi)
702 (dd-%log number))))
703 ((complex)
704 (complex-log number)))))
705
706 (defun sqrt (number)
707 "Return the square root of NUMBER."
708 (number-dispatch ((number number))
709 (((foreach fixnum bignum ratio))
710 (if (minusp number)
711 (complex-sqrt number)
712 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
713 (((foreach single-float double-float))
714 (if (minusp number)
715 (complex-sqrt number)
716 (coerce (%sqrt (coerce number 'double-float))
717 '(dispatch-type number))))
718 #+double-double
719 ((double-double-float)
720 (if (minusp number)
721 (dd-complex-sqrt number)
722 (multiple-value-bind (hi lo)
723 (c::sqrt-dd (kernel:double-double-hi number) (kernel:double-double-lo number))
724 (kernel:%make-double-double-float hi lo))))
725 ((complex)
726 (complex-sqrt number))))
727
728
729 ;;;; Trigonometic and Related Functions
730
731 (defun abs (number)
732 "Returns the absolute value of the number."
733 (number-dispatch ((number number))
734 (((foreach single-float double-float fixnum rational
735 #+double-double double-double-float))
736 (abs number))
737 ((complex)
738 (let ((rx (realpart number))
739 (ix (imagpart number)))
740 (etypecase rx
741 (rational
742 (sqrt (+ (* rx rx) (* ix ix))))
743 (single-float
744 (coerce (%hypot (coerce rx 'double-float)
745 (coerce ix 'double-float))
746 'single-float))
747 (double-float
748 (%hypot rx ix))
749 #+double-double
750 (double-double-float
751 (multiple-value-bind (abs^2 scale)
752 (dd-cssqs number)
753 (scale-float (sqrt abs^2) scale))))))))
754
755 (defun phase (number)
756 "Returns the angle part of the polar representation of a complex number.
757 For complex numbers, this is (atan (imagpart number) (realpart number)).
758 For non-complex positive numbers, this is 0. For non-complex negative
759 numbers this is PI."
760 (etypecase number
761 (rational
762 (if (minusp number)
763 (coerce pi 'single-float)
764 0.0f0))
765 (single-float
766 (if (minusp (float-sign number))
767 (coerce pi 'single-float)
768 0.0f0))
769 (double-float
770 (if (minusp (float-sign number))
771 (coerce pi 'double-float)
772 0.0d0))
773 #+double-double
774 (double-double-float
775 (if (minusp (float-sign number))
776 dd-pi
777 0w0))
778 (complex
779 (atan (imagpart number) (realpart number)))))
780
781
782 (defun sin (number)
783 "Return the sine of NUMBER."
784 (number-dispatch ((number number))
785 (handle-reals %sin number)
786 ((complex)
787 (let ((x (realpart number))
788 (y (imagpart number)))
789 (complex (* (sin x) (cosh y))
790 (* (cos x) (sinh y)))))))
791
792 (defun cos (number)
793 "Return the cosine of NUMBER."
794 (number-dispatch ((number number))
795 (handle-reals %cos number)
796 ((complex)
797 (let ((x (realpart number))
798 (y (imagpart number)))
799 (complex (* (cos x) (cosh y))
800 (- (* (sin x) (sinh y))))))))
801
802 (defun tan (number)
803 "Return the tangent of NUMBER."
804 (number-dispatch ((number number))
805 (handle-reals %tan number)
806 ((complex)
807 (complex-tan number))))
808
809 (defun cis (theta)
810 "Return cos(Theta) + i sin(Theta), AKA exp(i Theta)."
811 (if (complexp theta)
812 (error "Argument to CIS is complex: ~S" theta)
813 (complex (cos theta) (sin theta))))
814
815 (defun asin (number)
816 "Return the arc sine of NUMBER."
817 (number-dispatch ((number number))
818 ((rational)
819 (if (or (> number 1) (< number -1))
820 (complex-asin number)
821 (coerce (%asin (coerce number 'double-float)) 'single-float)))
822 (((foreach single-float double-float))
823 (if (or (float-nan-p number)
824 (and (<= number (coerce 1 '(dispatch-type number)))
825 (>= number (coerce -1 '(dispatch-type number)))))
826 (coerce (%asin (coerce number 'double-float))
827 '(dispatch-type number))
828 (complex-asin number)))
829 #+double-double
830 ((double-double-float)
831 (if (or (float-nan-p number)
832 (and (<= number 1w0)
833 (>= number -1w0)))
834 (dd-%asin number)
835 (dd-complex-asin number)))
836 ((complex)
837 (complex-asin number))))
838
839 (defun acos (number)
840 "Return the arc cosine of NUMBER."
841 (number-dispatch ((number number))
842 ((rational)
843 (if (or (> number 1) (< number -1))
844 (complex-acos number)
845 (coerce (%acos (coerce number 'double-float)) 'single-float)))
846 (((foreach single-float double-float))
847 (if (or (float-nan-p number)
848 (and (<= number (coerce 1 '(dispatch-type number)))
849 (>= number (coerce -1 '(dispatch-type number)))))
850 (coerce (%acos (coerce number 'double-float))
851 '(dispatch-type number))
852 (complex-acos number)))
853 #+double-double
854 ((double-double-float)
855 (if (or (float-nan-p number)
856 (and (<= number 1w0)
857 (>= number -1w0)))
858 (dd-%acos number)
859 (complex-acos number)))
860 ((complex)
861 (complex-acos number))))
862
863
864 (defun atan (y &optional (x nil xp))
865 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
866 (if xp
867 (flet ((atan2 (y x)
868 (declare (type double-float y x)
869 (values double-float))
870 (if (zerop x)
871 (if (zerop y)
872 (if (plusp (float-sign x))
873 y
874 (float-sign y pi))
875 (float-sign y (/ pi 2)))
876 (%atan2 y x))))
877 ;; If X is given, both X and Y must be real numbers.
878 (number-dispatch ((y real) (x real))
879 ((double-float
880 (foreach double-float single-float fixnum bignum ratio))
881 (atan2 y (coerce x 'double-float)))
882 (((foreach single-float fixnum bignum ratio)
883 double-float)
884 (atan2 (coerce y 'double-float) x))
885 (((foreach single-float fixnum bignum ratio)
886 (foreach single-float fixnum bignum ratio))
887 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
888 'single-float))
889 #+double-double
890 ((double-double-float
891 (foreach double-double-float double-float single-float fixnum bignum ratio))
892 (dd-%atan2 y (coerce x 'double-double-float)))
893 #+double-double
894 (((foreach double-float single-float fixnum bignum ratio)
895 double-double-float)
896 (dd-%atan2 (coerce y 'double-double-float) x))))
897 (number-dispatch ((y number))
898 (handle-reals %atan y)
899 ((complex)
900 (complex-atan y)))))
901
902 (defun sinh (number)
903 "Return the hyperbolic sine of NUMBER."
904 (number-dispatch ((number number))
905 (handle-reals %sinh number)
906 ((complex)
907 (let ((x (realpart number))
908 (y (imagpart number)))
909 (complex (* (sinh x) (cos y))
910 (* (cosh x) (sin y)))))))
911
912 (defun cosh (number)
913 "Return the hyperbolic cosine of NUMBER."
914 (number-dispatch ((number number))
915 (handle-reals %cosh number)
916 ((complex)
917 (let ((x (realpart number))
918 (y (imagpart number)))
919 (complex (* (cosh x) (cos y))
920 (* (sinh x) (sin y)))))))
921
922 (defun tanh (number)
923 "Return the hyperbolic tangent of NUMBER."
924 (number-dispatch ((number number))
925 (handle-reals %tanh number)
926 ((complex)
927 (complex-tanh number))))
928
929 (defun asinh (number)
930 "Return the hyperbolic arc sine of NUMBER."
931 (number-dispatch ((number number))
932 (handle-reals %asinh number)
933 ((complex)
934 (complex-asinh number))))
935
936 (defun acosh (number)
937 "Return the hyperbolic arc cosine of NUMBER."
938 (number-dispatch ((number number))
939 ((rational)
940 ;; acosh is complex if number < 1
941 (if (< number 1)
942 (complex-acosh number)
943 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
944 (((foreach single-float double-float))
945 (if (< number (coerce 1 '(dispatch-type number)))
946 (complex-acosh number)
947 (coerce (%acosh (coerce number 'double-float))
948 '(dispatch-type number))))
949 #+double-double
950 ((double-double-float)
951 (if (< number 1w0)
952 (complex-acosh number)
953 (dd-%acosh number)))
954 ((complex)
955 (complex-acosh number))))
956
957 (defun atanh (number)
958 "Return the hyperbolic arc tangent of NUMBER."
959 (number-dispatch ((number number))
960 ((rational)
961 ;; atanh is complex if |number| > 1
962 (if (or (> number 1) (< number -1))
963 (complex-atanh number)
964 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
965 (((foreach single-float double-float))
966 (if (or (> number (coerce 1 '(dispatch-type number)))
967 (< number (coerce -1 '(dispatch-type number))))
968 (complex-atanh number)
969 (coerce (%atanh (coerce number 'double-float))
970 '(dispatch-type number))))
971 #+double-double
972 ((double-double-float)
973 (if (or (> number 1w0)
974 (< number -1w0))
975 (complex-atanh number)
976 (dd-%atanh (coerce number 'double-double-float))))
977 ((complex)
978 (complex-atanh number))))
979
980 ;;; HP-UX does not supply a C version of log1p, so use the definition.
981 ;;; We really need to fix this. The definition really loses big-time
982 ;;; in roundoff as x gets small.
983
984 #+hpux
985 (declaim (inline %log1p))
986 #+hpux
987 (defun %log1p (number)
988 (declare (double-float number)
989 (optimize (speed 3) (safety 0)))
990 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
991
992
993 ;;;;
994 ;;;; This is a set of routines that implement many elementary
995 ;;;; transcendental functions as specified by ANSI Common Lisp. The
996 ;;;; implementation is based on Kahan's paper.
997 ;;;;
998 ;;;; I believe I have accurately implemented the routines and are
999 ;;;; correct, but you may want to check for your self.
1000 ;;;;
1001 ;;;; These functions are written for CMU Lisp and take advantage of
1002 ;;;; some of the features available there. It may be possible,
1003 ;;;; however, to port this to other Lisps.
1004 ;;;;
1005 ;;;; Some functions are significantly more accurate than the original
1006 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
1007 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
1008 ;;;; answer is pi + i*log(2-sqrt(3)).
1009 ;;;;
1010 ;;;; All of the implemented functions will take any number for an
1011 ;;;; input, but the result will always be a either a complex
1012 ;;;; single-float or a complex double-float.
1013 ;;;;
1014 ;;;; General functions
1015 ;;;; complex-sqrt
1016 ;;;; complex-log
1017 ;;;; complex-atanh
1018 ;;;; complex-tanh
1019 ;;;; complex-acos
1020 ;;;; complex-acosh
1021 ;;;; complex-asin
1022 ;;;; complex-asinh
1023 ;;;; complex-atan
1024 ;;;; complex-tan
1025 ;;;;
1026 ;;;; Utility functions:
1027 ;;;; scalb logb
1028 ;;;;
1029 ;;;; Internal functions:
1030 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
1031 ;;;;
1032 ;;;;
1033 ;;;; Please send any bug reports, comments, or improvements to Raymond
1034 ;;;; Toy at toy@rtp.ericsson.se.
1035 ;;;;
1036 ;;;; References
1037 ;;;;
1038 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
1039 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
1040 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
1041 ;;;; Press, 1987
1042 ;;;;
1043
1044 (declaim (inline square))
1045 (defun square (x)
1046 (declare (float x))
1047 (* x x))
1048
1049 ;; If you have these functions in libm, perhaps they should be used
1050 ;; instead of these Lisp versions. These versions are probably good
1051 ;; enough, especially since they are portable.
1052
1053 (declaim (inline scalb))
1054 (defun scalb (x n)
1055 "Compute 2^N * X without compute 2^N first (use properties of the
1056 underlying floating-point format"
1057 (declare (type float x)
1058 (type double-float-exponent n))
1059 (scale-float x n))
1060
1061 (declaim (inline logb-finite))
1062 (defun logb-finite (x)
1063 "Same as logb but X is not infinity and non-zero and not a NaN, so
1064 that we can always return an integer"
1065 (declare (type float x))
1066 (multiple-value-bind (signif expon sign)
1067 (decode-float x)
1068 (declare (ignore signif sign))
1069 ;; decode-float is almost right, except that the exponent
1070 ;; is off by one
1071 (1- expon)))
1072
1073 (defun logb (x)
1074 "Compute an integer N such that 1 <= |2^(-N) * x| < 2.
1075 For the special cases, the following values are used:
1076
1077 x logb
1078 NaN NaN
1079 +/- infinity +infinity
1080 0 -infinity
1081 "
1082 (declare (type float x))
1083 (cond ((float-nan-p x)
1084 x)
1085 ((float-infinity-p x)
1086 #.ext:double-float-positive-infinity)
1087 ((zerop x)
1088 ;; The answer is negative infinity, but we are supposed to
1089 ;; signal divide-by-zero, so do the actual division
1090 (/ -1 x)
1091 )
1092 (t
1093 (logb-finite x))))
1094
1095
1096
1097 ;; This function is used to create a complex number of the appropriate
1098 ;; type.
1099
1100 (declaim (inline coerce-to-complex-type))
1101 (defun coerce-to-complex-type (x y z)
1102 "Create complex number with real part X and imaginary part Y such that
1103 it has the same type as Z. If Z has type (complex rational), the X
1104 and Y are coerced to single-float."
1105 (declare (double-float x y)
1106 (number z)
1107 (optimize (extensions:inhibit-warnings 3)))
1108 (if (typep (realpart z) 'double-float)
1109 (complex x y)
1110 ;; Convert anything that's not a double-float to a single-float.
1111 (complex (float x 1f0)
1112 (float y 1f0))))
1113
1114 (defun cssqs (z)
1115 ;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
1116 ;; result is r + i*k, where k is an integer.
1117
1118 ;; Save all FP flags
1119 (let ((x (float (realpart z) 1d0))
1120 (y (float (imagpart z) 1d0)))
1121 ;; Would this be better handled using an exception handler to
1122 ;; catch the overflow or underflow signal? For now, we turn all
1123 ;; traps off and look at the accrued exceptions to see if any
1124 ;; signal would have been raised.
1125 (with-float-traps-masked (:underflow :overflow)
1126 (let ((rho (+ (square x) (square y))))
1127 (declare (optimize (speed 3) (space 0)))
1128 (cond ((and (or (float-nan-p rho)
1129 (float-infinity-p rho))
1130 (or (float-infinity-p (abs x))
1131 (float-infinity-p (abs y))))
1132 (values ext:double-float-positive-infinity 0))
1133 ((let ((threshold #.(/ least-positive-double-float
1134 double-float-epsilon))
1135 (traps (ldb vm::float-sticky-bits
1136 (vm:floating-point-modes))))
1137 ;; Overflow raised or (underflow raised and rho <
1138 ;; lambda/eps)
1139 (or (not (zerop (logand vm:float-overflow-trap-bit traps)))
1140 (and (not (zerop (logand vm:float-underflow-trap-bit traps)))
1141 (< rho threshold))))
1142 ;; If we're here, neither x nor y are infinity and at
1143 ;; least one is non-zero.. Thus logb returns a nice
1144 ;; integer.
1145 (let ((k (- (logb-finite (max (abs x) (abs y))))))
1146 (values (+ (square (scalb x k))
1147 (square (scalb y k)))
1148 (- k))))
1149 (t
1150 (values rho 0)))))))
1151
1152 (defun complex-sqrt (z)
1153 "Principle square root of Z
1154
1155 Z may be any number, but the result is always a complex."
1156 (declare (number z))
1157 #+double-double
1158 (when (typep z '(or double-double-float (complex double-double-float)))
1159 (return-from complex-sqrt (dd-complex-sqrt z)))
1160 (multiple-value-bind (rho k)
1161 (cssqs z)
1162 (declare (type (or (member 0d0) (double-float 0d0)) rho)
1163 (type fixnum k))
1164 (let ((x (float (realpart z) 1.0d0))
1165 (y (float (imagpart z) 1.0d0))
1166 (eta 0d0)
1167 (nu 0d0))
1168 (declare (double-float x y eta nu))
1169
1170 (locally
1171 ;; space 0 to get maybe-inline functions inlined.
1172 (declare (optimize (speed 3) (space 0)))
1173
1174 (if (not (locally (declare (optimize (inhibit-warnings 3)))
1175 (float-nan-p x)))
1176 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
1177
1178 (cond ((oddp k)
1179 (setf k (ash k -1)))
1180 (t
1181 (setf k (1- (ash k -1)))
1182 (setf rho (+ rho rho))))
1183
1184 (setf rho (scalb (sqrt rho) k))
1185
1186 (setf eta rho)
1187 (setf nu y)
1188
1189 (when (/= rho 0d0)
1190 (when (not (float-infinity-p (abs nu)))
1191 (setf nu (/ (/ nu rho) 2d0)))
1192 (when (< x 0d0)
1193 (setf eta (abs nu))
1194 (setf nu (float-sign y rho))))
1195 (coerce-to-complex-type eta nu z)))))
1196
1197 (defun complex-log-scaled (z j)
1198 "Compute log(2^j*z).
1199
1200 This is for use with J /= 0 only when |z| is huge."
1201 (declare (number z)
1202 (fixnum j))
1203 ;; The constants t0, t1, t2 should be evaluated to machine
1204 ;; precision. In addition, Kahan says the accuracy of log1p
1205 ;; influences the choices of these constants but doesn't say how to
1206 ;; choose them. We'll just assume his choices matches our
1207 ;; implementation of log1p.
1208 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
1209 (t1 1.2d0)
1210 (t2 3d0)
1211 (ln2 #.(log 2d0))
1212 (x (float (realpart z) 1.0d0))
1213 (y (float (imagpart z) 1.0d0)))
1214 (multiple-value-bind (rho k)
1215 (cssqs z)
1216 (declare (optimize (speed 3)))
1217 (let ((beta (max (abs x) (abs y)))
1218 (theta (min (abs x) (abs y))))
1219 (coerce-to-complex-type (if (and (zerop k)
1220 (< t0 beta)
1221 (or (<= beta t1)
1222 (< rho t2)))
1223 (/ (%log1p (+ (* (- beta 1.0d0)
1224 (+ beta 1.0d0))
1225 (* theta theta)))
1226 2d0)
1227 (+ (/ (log rho) 2d0)
1228 (* (+ k j) ln2)))
1229 (atan y x)
1230 z)))))
1231
1232 (defun complex-log (z)
1233 "Log of Z = log |Z| + i * arg Z
1234
1235 Z may be any number, but the result is always a complex."
1236 (declare (number z))
1237 #+double-double
1238 (when (typep z '(or double-double-float (complex double-double-float)))
1239 (return-from complex-log (dd-complex-log-scaled z 0)))
1240 (complex-log-scaled z 0))
1241
1242 ;; Let us note the following "strange" behavior. atanh 1.0d0 is
1243 ;; +infinity, but the following code returns approx 176 + i*pi/4. The
1244 ;; reason for the imaginary part is caused by the fact that arg i*y is
1245 ;; never 0 since we have positive and negative zeroes.
1246
1247 (defun complex-atanh (z)
1248 "Compute atanh z = (log(1+z) - log(1-z))/2"
1249 (declare (number z))
1250 #+double-double
1251 (when (typep z '(or double-double-float (complex double-double-float)))
1252 (return-from complex-atanh (dd-complex-atanh z)))
1253
1254 (if (and (realp z) (< z -1))
1255 ;; atanh is continuous in quadrant III in this case.
1256 (complex-atanh (complex z -0f0))
1257 (let* ( ;; Constants
1258 (theta (/ (sqrt most-positive-double-float) 4.0d0))
1259 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
1260 (half-pi (/ pi 2.0d0))
1261 (rp (float (realpart z) 1.0d0))
1262 (beta (float-sign rp 1.0d0))
1263 (x (* beta rp))
1264 (y (* beta (- (float (imagpart z) 1.0d0))))
1265 (eta 0.0d0)
1266 (nu 0.0d0))
1267 ;; Shouldn't need this declare.
1268 (declare (double-float x y))
1269 (locally
1270 (declare (optimize (speed 3)))
1271 (cond ((or (> x theta)
1272 (> (abs y) theta))
1273 ;; To avoid overflow...
1274 (setf nu (float-sign y half-pi))
1275 ;; eta is real part of 1/(x + iy). This is x/(x^2+y^2),
1276 ;; which can cause overflow. Arrange this computation so
1277 ;; that it won't overflow.
1278 (setf eta (let* ((x-bigger (> x (abs y)))
1279 (r (if x-bigger (/ y x) (/ x y)))
1280 (d (+ 1.0d0 (* r r))))
1281 (if x-bigger
1282 (/ (/ x) d)
1283 (/ (/ r y) d)))))
1284 ((= x 1.0d0)
1285 ;; Should this be changed so that if y is zero, eta is set
1286 ;; to +infinity instead of approx 176? In any case
1287 ;; tanh(176) is 1.0d0 within working precision.
1288 (let ((t1 (+ 4d0 (square y)))
1289 (t2 (+ (abs y) rho)))
1290 (setf eta (log (/ (sqrt (sqrt t1))
1291 (sqrt t2))))
1292 (setf nu (* 0.5d0
1293 (float-sign y
1294 (+ half-pi (atan (* 0.5d0 t2))))))))
1295 (t
1296 (let ((t1 (+ (abs y) rho)))
1297 ;; Normal case using log1p(x) = log(1 + x)
1298 (setf eta (* 0.25d0
1299 (%log1p (/ (* 4.0d0 x)
1300 (+ (square (- 1.0d0 x))
1301 (square t1))))))
1302 (setf nu (* 0.5d0
1303 (atan (* 2.0d0 y)
1304 (- (* (- 1.0d0 x)
1305 (+ 1.0d0 x))
1306 (square t1))))))))
1307 (coerce-to-complex-type (* beta eta)
1308 (- (* beta nu))
1309 z)))))
1310
1311 (defun complex-tanh (z)
1312 "Compute tanh z = sinh z / cosh z"
1313 (declare (number z))
1314 #+double-double
1315 (when (typep z '(or double-double-float (complex double-double-float)))
1316 (return-from complex-tanh (dd-complex-tanh z)))
1317
1318 (let ((x (float (realpart z) 1.0d0))
1319 (y (float (imagpart z) 1.0d0)))
1320 (locally
1321 ;; space 0 to get maybe-inline functions inlined
1322 (declare (optimize (speed 3) (space 0)))
1323 (cond ((> (abs x)
1324 #-(or linux hpux) #.(/ (%asinh most-positive-double-float) 4d0)
1325 ;; This is more accurate under linux.
1326 #+(or linux hpux) #.(/ (+ (%log 2.0d0)
1327 (%log most-positive-double-float)) 4d0))
1328 (coerce-to-complex-type (float-sign x)
1329 (float-sign y) z))
1330 (t
1331 (let* ((tv (%tan y))
1332 (beta (+ 1.0d0 (* tv tv)))
1333 (s (sinh x))
1334 (rho (sqrt (+ 1.0d0 (* s s)))))
1335 (if (float-infinity-p (abs tv))
1336 (coerce-to-complex-type (/ rho s)
1337 (/ tv)
1338 z)
1339 (let ((den (+ 1.0d0 (* beta s s))))
1340 (coerce-to-complex-type (/ (* beta rho s)
1341 den)
1342 (/ tv den)
1343 z)))))))))
1344
1345 ;; Kahan says we should only compute the parts needed. Thus, the
1346 ;; realpart's below should only compute the real part, not the whole
1347 ;; complex expression. Doing this can be important because we may get
1348 ;; spurious signals that occur in the part that we are not using.
1349 ;;
1350 ;; However, we take a pragmatic approach and just use the whole
1351 ;; expression.
1352
1353 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1354 ;; it's the conjugate of the square root or the square root of the
1355 ;; conjugate. This needs to be checked.
1356
1357 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1358 ;; same as (sqrt (conjugate z)) for all z. This follows because
1359 ;;
1360 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1361 ;;
1362 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1363 ;;
1364 ;; and these two expressions are equal if and only if arg conj z =
1365 ;; -arg z, which is clearly true for all z.
1366
1367 ;; NOTE: The rules of Common Lisp says that if you mix a real with a
1368 ;; complex, the real is converted to a complex before performing the
1369 ;; operation. However, Kahan says in this paper (pg 176):
1370 ;;
1371 ;; (iii) Careless handling can turn infinity or the sign of zero into
1372 ;; misinformation that subsequently disappears leaving behind
1373 ;; only a plausible but incorrect result. That is why compilers
1374 ;; must not transform z-1 into z-(1+i*0), as we have seen above,
1375 ;; nor -(-x-x^2) into (x+x^2), as we shall see below, lest a
1376 ;; subsequent logarithm or square root produce a non-zero
1377 ;; imaginary part whose sign is opposite to what was intended.
1378 ;;
1379 ;; The interesting examples are too long and complicated to reproduce
1380 ;; here. We refer the reader to his paper.
1381 ;;
1382 ;; The functions below are intended to handle the cases where a real
1383 ;; is mixed with a complex and we don't want CL complex contagion to
1384 ;; occur..
1385
1386 (declaim (inline 1+z 1-z z-1 z+1))
1387 (defun 1+z (z)
1388 (complex (+ 1 (realpart z)) (imagpart z)))
1389 (defun 1-z (z)
1390 (complex (- 1 (realpart z)) (- (imagpart z))))
1391 (defun z-1 (z)
1392 (complex (- (realpart z) 1) (imagpart z)))
1393 (defun z+1 (z)
1394 (complex (+ (realpart z) 1) (imagpart z)))
1395
1396 (defun complex-acos (z)
1397 "Compute acos z = pi/2 - asin z
1398
1399 Z may be any number, but the result is always a complex."
1400 (declare (number z))
1401 #+double-double
1402 (when (typep z '(or double-double-float (complex double-double-float)))
1403 (return-from complex-acos (dd-complex-acos z)))
1404 (if (and (realp z) (> z 1))
1405 ;; acos is continuous in quadrant IV in this case.
1406 (complex-acos (complex z -0f0))
1407 (let ((sqrt-1+z (complex-sqrt (1+z z)))
1408 (sqrt-1-z (complex-sqrt (1-z z))))
1409 (with-float-traps-masked (:divide-by-zero)
1410 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1411 (realpart sqrt-1+z))))
1412 (asinh (imagpart (* (conjugate sqrt-1+z)
1413 sqrt-1-z))))))))
1414
1415 (defun complex-acosh (z)
1416 "Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1417
1418 Z may be any number, but the result is always a complex."
1419 (declare (number z))
1420 (let ((sqrt-z-1 (complex-sqrt (z-1 z)))
1421 (sqrt-z+1 (complex-sqrt (z+1 z))))
1422 (with-float-traps-masked (:divide-by-zero)
1423 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1424 sqrt-z+1)))
1425 (* 2 (atan (/ (imagpart sqrt-z-1)
1426 (realpart sqrt-z+1))))))))
1427
1428
1429 (defun complex-asin (z)
1430 "Compute asin z = asinh(i*z)/i
1431
1432 Z may be any number, but the result is always a complex."
1433 (declare (number z))
1434 #+double-double
1435 (when (typep z '(or double-double-float (complex double-double-float)))
1436 (return-from complex-asin (dd-complex-asin z)))
1437 (if (and (realp z) (> z 1))
1438 ;; asin is continuous in quadrant IV in this case.
1439 (complex-asin (complex z -0f0))
1440 (let ((sqrt-1-z (complex-sqrt (1-z z)))
1441 (sqrt-1+z (complex-sqrt (1+z z))))
1442 (with-float-traps-masked (:divide-by-zero)
1443 (complex (atan (/ (realpart z)
1444 (realpart (* sqrt-1-z sqrt-1+z))))
1445 (asinh (imagpart (* (conjugate sqrt-1-z)
1446 sqrt-1+z))))))))
1447
1448 (defun complex-asinh (z)
1449 "Compute asinh z = log(z + sqrt(1 + z*z))
1450
1451 Z may be any number, but the result is always a complex."
1452 (declare (number z))
1453 ;; asinh z = -i * asin (i*z)
1454 #+double-double
1455 (when (typep z '(or double-double-float (complex double-double-float)))
1456 (return-from complex-asinh (dd-complex-asinh z)))
1457 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1458 (result (complex-asin iz)))
1459 (complex (imagpart result)
1460 (- (realpart result)))))
1461
1462 (defun complex-atan (z)
1463 "Compute atan z = atanh (i*z) / i
1464
1465 Z may be any number, but the result is always a complex."
1466 (declare (number z))
1467 ;; atan z = -i * atanh (i*z)
1468 #+double-double
1469 (when (typep z '(or double-double-float (complex double-double-float)))
1470 (return-from complex-atan (dd-complex-atan z)))
1471 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1472 (result (complex-atanh iz)))
1473 (complex (imagpart result)
1474 (- (realpart result)))))
1475
1476 (defun complex-tan (z)
1477 "Compute tan z = -i * tanh(i * z)
1478
1479 Z may be any number, but the result is always a complex."
1480 (declare (number z))
1481 ;; tan z = -i * tanh(i*z)
1482 #+double-double
1483 (when (typep z '(or double-double-float (complex double-double-float)))
1484 (return-from complex-tan (dd-complex-tan z)))
1485 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1486 (result (complex-tanh iz)))
1487 (complex (imagpart result)
1488 (- (realpart result)))))
1489

  ViewVC Help
Powered by ViewVC 1.1.5