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

Contents of /src/code/irrat.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5