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

Contents of /src/code/irrat.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.37.14.1 - (show annotations)
Fri May 14 16:26:07 2004 UTC (9 years, 11 months ago) by rtoy
Branch: release-19a-branch
Changes since 1.37: +36 -7 lines
Merge in rev 1.38 to fix the problem where we were returning wrong
values for asin and acos when the arg was on the branch cut.
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.37.14.1 2004/05/14 16:26:07 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
51 ); eval-when (compile load eval)
52
53
54 ;;;; Stubs for the Unix math library.
55
56 ;;; Please refer to the Unix man pages for details about these routines.
57
58 ;;; Trigonometric.
59 #-x86 (def-math-rtn "sin" 1)
60 #-x86 (def-math-rtn "cos" 1)
61 #-x86 (def-math-rtn "tan" 1)
62 (def-math-rtn "asin" 1)
63 (def-math-rtn "acos" 1)
64 #-x86 (def-math-rtn "atan" 1)
65 #-x86 (def-math-rtn "atan2" 2)
66 (def-math-rtn "sinh" 1)
67 (def-math-rtn "cosh" 1)
68 (def-math-rtn "tanh" 1)
69 (def-math-rtn "asinh" 1)
70 (def-math-rtn "acosh" 1)
71 (def-math-rtn "atanh" 1)
72
73 ;;; Exponential and Logarithmic.
74 #-x86 (def-math-rtn "exp" 1)
75 #-x86 (def-math-rtn "log" 1)
76 #-x86 (def-math-rtn "log10" 1)
77 (def-math-rtn "pow" 2)
78 #-(or x86 sparc-v7 sparc-v8 sparc-v9) (def-math-rtn "sqrt" 1)
79 (def-math-rtn "hypot" 2)
80 #-(or hpux x86) (def-math-rtn "log1p" 1)
81
82 #+x86 ;; These are needed for use by byte-compiled files.
83 (progn
84 (defun %sin (x)
85 (declare (double-float x)
86 (values double-float))
87 (%sin x))
88 (defun %sin-quick (x)
89 (declare (double-float x)
90 (values double-float))
91 (%sin-quick x))
92 (defun %cos (x)
93 (declare (double-float x)
94 (values double-float))
95 (%cos x))
96 (defun %cos-quick (x)
97 (declare (double-float x)
98 (values double-float))
99 (%cos-quick x))
100 (defun %tan (x)
101 (declare (double-float x)
102 (values double-float))
103 (%tan x))
104 (defun %tan-quick (x)
105 (declare (double-float x)
106 (values double-float))
107 (%tan-quick x))
108 (defun %atan (x)
109 (declare (double-float x)
110 (values double-float))
111 (%atan x))
112 (defun %atan2 (x y)
113 (declare (double-float x y)
114 (values double-float))
115 (%atan2 x y))
116 (defun %exp (x)
117 (declare (double-float x)
118 (values double-float))
119 (%exp x))
120 (defun %log (x)
121 (declare (double-float x)
122 (values double-float))
123 (%log x))
124 (defun %log10 (x)
125 (declare (double-float x)
126 (values double-float))
127 (%log10 x))
128 #+nil ;; notyet
129 (defun %pow (x y)
130 (declare (type (double-float 0d0) x)
131 (double-float y)
132 (values (double-float 0d0)))
133 (%pow x y))
134 (defun %sqrt (x)
135 (declare (double-float x)
136 (values double-float))
137 (%sqrt x))
138 (defun %scalbn (f ex)
139 (declare (double-float f)
140 (type (signed-byte 32) ex)
141 (values double-float))
142 (%scalbn f ex))
143 (defun %scalb (f ex)
144 (declare (double-float f ex)
145 (values double-float))
146 (%scalb f ex))
147 (defun %logb (x)
148 (declare (double-float x)
149 (values double-float))
150 (%logb x))
151 (defun %log1p (x)
152 (declare (double-float x)
153 (values double-float))
154 (%log1p x))
155 ) ; progn
156
157
158 ;;;; Power functions.
159
160 (defun exp (number)
161 "Return e raised to the power NUMBER."
162 (number-dispatch ((number number))
163 (handle-reals %exp number)
164 ((complex)
165 (* (exp (realpart number))
166 (cis (imagpart number))))))
167
168 ;;; INTEXP -- Handle the rational base, integer power case.
169
170 (defparameter *intexp-maximum-exponent* 10000)
171
172 ;;; This function precisely calculates base raised to an integral power. It
173 ;;; separates the cases by the sign of power, for efficiency reasons, as powers
174 ;;; can be calculated more efficiently if power is a positive integer. Values
175 ;;; of power are calculated as positive integers, and inverted if negative.
176 ;;;
177 (defun intexp (base power)
178 (when (> (abs power) *intexp-maximum-exponent*)
179 (cerror "Continue with calculation."
180 "The absolute value of ~S exceeds ~S."
181 power '*intexp-maximum-exponent* base power))
182 (cond ((minusp power)
183 (/ (intexp base (- power))))
184 ((eql base 2)
185 (ash 1 power))
186 (t
187 (do ((nextn (ash power -1) (ash power -1))
188 (total (if (oddp power) base 1)
189 (if (oddp power) (* base total) total)))
190 ((zerop nextn) total)
191 (setq base (* base base))
192 (setq power nextn)))))
193
194
195 ;;; EXPT -- Public
196 ;;;
197 ;;; If an integer power of a rational, use INTEXP above. Otherwise, do
198 ;;; floating point stuff. If both args are real, we try %POW right off,
199 ;;; assuming it will return 0 if the result may be complex. If so, we call
200 ;;; COMPLEX-POW which directly computes the complex result. We also separate
201 ;;; the complex-real and real-complex cases from the general complex case.
202 ;;;
203 (defun expt (base power)
204 "Returns BASE raised to the POWER."
205 (if (zerop power)
206 (1+ (* base power))
207 (labels (;; determine if the double float is an integer.
208 ;; 0 - not an integer
209 ;; 1 - an odd int
210 ;; 2 - an even int
211 (isint (ihi lo)
212 (declare (type (unsigned-byte 31) ihi)
213 (type (unsigned-byte 32) lo)
214 (optimize (speed 3) (safety 0)))
215 (let ((isint 0))
216 (declare (type fixnum isint))
217 (cond ((>= ihi #x43400000) ; exponent >= 53
218 (setq isint 2))
219 ((>= ihi #x3ff00000)
220 (let ((k (- (ash ihi -20) #x3ff))) ; exponent
221 (declare (type (mod 53) k))
222 (cond ((> k 20)
223 (let* ((shift (- 52 k))
224 (j (logand (ash lo (- shift))))
225 (j2 (ash j shift)))
226 (declare (type (mod 32) shift)
227 (type (unsigned-byte 32) j j2))
228 (when (= j2 lo)
229 (setq isint (- 2 (logand j 1))))))
230 ((= lo 0)
231 (let* ((shift (- 20 k))
232 (j (ash ihi (- shift)))
233 (j2 (ash j shift)))
234 (declare (type (mod 32) shift)
235 (type (unsigned-byte 31) j j2))
236 (when (= j2 ihi)
237 (setq isint (- 2 (logand j 1))))))))))
238 isint))
239 (real-expt (x y rtype)
240 (let ((x (coerce x 'double-float))
241 (y (coerce y 'double-float)))
242 (declare (double-float x y))
243 (let* ((x-hi (kernel:double-float-high-bits x))
244 (x-lo (kernel:double-float-low-bits x))
245 (x-ihi (logand x-hi #x7fffffff))
246 (y-hi (kernel:double-float-high-bits y))
247 (y-lo (kernel:double-float-low-bits y))
248 (y-ihi (logand y-hi #x7fffffff)))
249 (declare (type (signed-byte 32) x-hi y-hi)
250 (type (unsigned-byte 31) x-ihi y-ihi)
251 (type (unsigned-byte 32) x-lo y-lo))
252 ;; y==zero: x**0 = 1
253 (when (zerop (logior y-ihi y-lo))
254 (return-from real-expt (coerce 1d0 rtype)))
255 ;; +-NaN return x+y
256 (when (or (> x-ihi #x7ff00000)
257 (and (= x-ihi #x7ff00000) (/= x-lo 0))
258 (> y-ihi #x7ff00000)
259 (and (= y-ihi #x7ff00000) (/= y-lo 0)))
260 (return-from real-expt (coerce (+ x y) rtype)))
261 (let ((yisint (if (< x-hi 0) (isint y-ihi y-lo) 0)))
262 (declare (type fixnum yisint))
263 ;; special value of y
264 (when (and (zerop y-lo) (= y-ihi #x7ff00000))
265 ;; y is +-inf
266 (return-from real-expt
267 (cond ((and (= x-ihi #x3ff00000) (zerop x-lo))
268 ;; +-1**inf is NaN
269 (coerce (- y y) rtype))
270 ((>= x-ihi #x3ff00000)
271 ;; (|x|>1)**+-inf = inf,0
272 (if (>= y-hi 0)
273 (coerce y rtype)
274 (coerce 0 rtype)))
275 (t
276 ;; (|x|<1)**-,+inf = inf,0
277 (if (< y-hi 0)
278 (coerce (- y) rtype)
279 (coerce 0 rtype))))))
280
281 (let ((abs-x (abs x)))
282 (declare (double-float abs-x))
283 ;; special value of x
284 (when (and (zerop x-lo)
285 (or (= x-ihi #x7ff00000) (zerop x-ihi)
286 (= x-ihi #x3ff00000)))
287 ;; x is +-0,+-inf,+-1
288 (let ((z (if (< y-hi 0)
289 (/ 1 abs-x) ; z = (1/|x|)
290 abs-x)))
291 (declare (double-float z))
292 (when (< x-hi 0)
293 (cond ((and (= x-ihi #x3ff00000) (zerop yisint))
294 ;; (-1)**non-int
295 (let ((y*pi (* y pi)))
296 (declare (double-float y*pi))
297 (return-from real-expt
298 (complex
299 (coerce (%cos y*pi) rtype)
300 (coerce (%sin y*pi) rtype)))))
301 ((= yisint 1)
302 ;; (x<0)**odd = -(|x|**odd)
303 (setq z (- z)))))
304 (return-from real-expt (coerce z rtype))))
305
306 (if (>= x-hi 0)
307 ;; x>0
308 (coerce (kernel::%pow x y) rtype)
309 ;; x<0
310 (let ((pow (kernel::%pow abs-x y)))
311 (declare (double-float pow))
312 (case yisint
313 (1 ; Odd
314 (coerce (* -1d0 pow) rtype))
315 (2 ; Even
316 (coerce pow rtype))
317 (t ; Non-integer
318 (let ((y*pi (* y pi)))
319 (declare (double-float y*pi))
320 (complex
321 (coerce (* pow (%cos y*pi)) rtype)
322 (coerce (* pow (%sin y*pi)) rtype)))))))))))))
323 (declare (inline real-expt))
324 (number-dispatch ((base number) (power number))
325 (((foreach fixnum (or bignum ratio) (complex rational)) integer)
326 (intexp base power))
327 (((foreach single-float double-float) rational)
328 (real-expt base power '(dispatch-type base)))
329 (((foreach fixnum (or bignum ratio) single-float)
330 (foreach ratio single-float))
331 (real-expt base power 'single-float))
332 (((foreach fixnum (or bignum ratio) single-float double-float)
333 double-float)
334 (real-expt base power 'double-float))
335 ((double-float single-float)
336 (real-expt base power 'double-float))
337 (((foreach (complex rational) (complex float)) rational)
338 (* (expt (abs base) power)
339 (cis (* power (phase base)))))
340 (((foreach fixnum (or bignum ratio) single-float double-float)
341 complex)
342 (if (and (zerop base) (plusp (realpart power)))
343 (* base power)
344 (exp (* power (log base)))))
345 (((foreach (complex float) (complex rational))
346 (foreach complex double-float single-float))
347 (if (and (zerop base) (plusp (realpart power)))
348 (* base power)
349 (exp (* power (log base)))))))))
350
351 ;; Compute the base 2 log of an integer
352 (defun log2 (x)
353 ;; Write x = 2^n*f where 1/2 < f <= 1. Then log2(x) = n + log2(f).
354 ;;
355 ;; So we grab the top few bits of x and scale that appropriately,
356 ;; take the log of it and add it to n.
357 (let ((n (integer-length x)))
358 (if (< n vm:double-float-digits)
359 (log (coerce x 'double-float) 2d0)
360 (let ((exp (min vm:double-float-digits n))
361 (f (ldb (byte vm:double-float-digits
362 (max 0 (- n vm:double-float-digits)))
363 x)))
364 (+ n (log (scale-float (float f 1d0) (- exp))
365 2d0))))))
366
367 (defun log (number &optional (base nil base-p))
368 "Return the logarithm of NUMBER in the base BASE, which defaults to e."
369 (if base-p
370 (cond ((zerop base)
371 ;; ANSI spec
372 base)
373 ((and (integerp number) (integerp base)
374 (plusp number) (plusp base))
375 ;; Let's try to do something nice when both the number
376 ;; and the base are positive integers. Use the rule that
377 ;; log_b(x) = log_2(x)/log_2(b)
378 (coerce (/ (log2 number) (log2 base)) 'single-float))
379 (t
380 (/ (log number) (log base))))
381 (number-dispatch ((number number))
382 (((foreach fixnum bignum))
383 (if (minusp number)
384 (complex (coerce (log (- number)) 'single-float)
385 (coerce pi 'single-float))
386 (coerce (/ (log2 number) #.(log (exp 1d0) 2d0)) 'single-float)))
387 ((ratio)
388 (if (minusp number)
389 (complex (coerce (log (- number)) 'single-float)
390 (coerce pi 'single-float))
391 ;; What happens when the ratio is close to 1? We need to
392 ;; be careful to preserve accuracy.
393 (let ((top (numerator number))
394 (bot (denominator number)))
395 ;; If the number of bits in the numerator and
396 ;; denominator are different, just use the fact
397 ;; log(x/y) = log(x) - log(y). But to preserve
398 ;; accuracy, we actually do
399 ;; (log2(x)-log2(y))/log2(e)).
400 ;;
401 ;; However, if the numerator and denominator have the
402 ;; same number of bits, implying the quotient is near
403 ;; one, we use log1p(x) = log(1+x). Since the number is
404 ;; rational, we don't lose precision subtracting 1 from
405 ;; it, and converting it to double-float is accurate.
406 (if (= (integer-length top)
407 (integer-length bot))
408 (coerce (%log1p (coerce (- number 1) 'double-float))
409 'single-float)
410 (coerce (/ (- (log2 top) (log2 bot))
411 #.(log (exp 1d0) 2d0))
412 'single-float)))))
413 (((foreach single-float double-float))
414 ;; Is (log -0) -infinity (libm.a) or -infinity + i*pi (Kahan)?
415 ;; Since this doesn't seem to be an implementation issue
416 ;; I (pw) take the Kahan result.
417 (if (< (float-sign number)
418 (coerce 0 '(dispatch-type number)))
419 (complex (log (- number)) (coerce pi '(dispatch-type number)))
420 (coerce (%log (coerce number 'double-float))
421 '(dispatch-type number))))
422 ((complex)
423 (complex-log number)))))
424
425 (defun sqrt (number)
426 "Return the square root of NUMBER."
427 (number-dispatch ((number number))
428 (((foreach fixnum bignum ratio))
429 (if (minusp number)
430 (complex-sqrt number)
431 (coerce (%sqrt (coerce number 'double-float)) 'single-float)))
432 (((foreach single-float double-float))
433 (if (minusp number)
434 (complex-sqrt number)
435 (coerce (%sqrt (coerce number 'double-float))
436 '(dispatch-type number))))
437 ((complex)
438 (complex-sqrt number))))
439
440
441 ;;;; Trigonometic and Related Functions
442
443 (defun abs (number)
444 "Returns the absolute value of the number."
445 (number-dispatch ((number number))
446 (((foreach single-float double-float fixnum rational))
447 (abs number))
448 ((complex)
449 (let ((rx (realpart number))
450 (ix (imagpart number)))
451 (etypecase rx
452 (rational
453 (sqrt (+ (* rx rx) (* ix ix))))
454 (single-float
455 (coerce (%hypot (coerce rx 'double-float)
456 (coerce ix 'double-float))
457 'single-float))
458 (double-float
459 (%hypot rx ix)))))))
460
461 (defun phase (number)
462 "Returns the angle part of the polar representation of a complex number.
463 For complex numbers, this is (atan (imagpart number) (realpart number)).
464 For non-complex positive numbers, this is 0. For non-complex negative
465 numbers this is PI."
466 (etypecase number
467 (rational
468 (if (minusp number)
469 (coerce pi 'single-float)
470 0.0f0))
471 (single-float
472 (if (minusp (float-sign number))
473 (coerce pi 'single-float)
474 0.0f0))
475 (double-float
476 (if (minusp (float-sign number))
477 (coerce pi 'double-float)
478 0.0d0))
479 (complex
480 (atan (imagpart number) (realpart number)))))
481
482
483 (defun sin (number)
484 "Return the sine of NUMBER."
485 (number-dispatch ((number number))
486 (handle-reals %sin number)
487 ((complex)
488 (let ((x (realpart number))
489 (y (imagpart number)))
490 (complex (* (sin x) (cosh y))
491 (* (cos x) (sinh y)))))))
492
493 (defun cos (number)
494 "Return the cosine of NUMBER."
495 (number-dispatch ((number number))
496 (handle-reals %cos number)
497 ((complex)
498 (let ((x (realpart number))
499 (y (imagpart number)))
500 (complex (* (cos x) (cosh y))
501 (- (* (sin x) (sinh y))))))))
502
503 (defun tan (number)
504 "Return the tangent of NUMBER."
505 (number-dispatch ((number number))
506 (handle-reals %tan number)
507 ((complex)
508 (complex-tan number))))
509
510 (defun cis (theta)
511 "Return cos(Theta) + i sin(Theta), AKA exp(i Theta)."
512 (if (complexp theta)
513 (error "Argument to CIS is complex: ~S" theta)
514 (complex (cos theta) (sin theta))))
515
516 (defun asin (number)
517 "Return the arc sine of NUMBER."
518 (number-dispatch ((number number))
519 ((rational)
520 (if (or (> number 1) (< number -1))
521 (complex-asin number)
522 (coerce (%asin (coerce number 'double-float)) 'single-float)))
523 (((foreach single-float double-float))
524 (if (or (> number (coerce 1 '(dispatch-type number)))
525 (< number (coerce -1 '(dispatch-type number))))
526 (complex-asin number)
527 (coerce (%asin (coerce number 'double-float))
528 '(dispatch-type number))))
529 ((complex)
530 (complex-asin number))))
531
532 (defun acos (number)
533 "Return the arc cosine of NUMBER."
534 (number-dispatch ((number number))
535 ((rational)
536 (if (or (> number 1) (< number -1))
537 (complex-acos number)
538 (coerce (%acos (coerce number 'double-float)) 'single-float)))
539 (((foreach single-float double-float))
540 (if (or (> number (coerce 1 '(dispatch-type number)))
541 (< number (coerce -1 '(dispatch-type number))))
542 (complex-acos number)
543 (coerce (%acos (coerce number 'double-float))
544 '(dispatch-type number))))
545 ((complex)
546 (complex-acos number))))
547
548
549 (defun atan (y &optional (x nil xp))
550 "Return the arc tangent of Y if X is omitted or Y/X if X is supplied."
551 (if xp
552 (flet ((atan2 (y x)
553 (declare (type double-float y x)
554 (values double-float))
555 (if (zerop x)
556 (if (zerop y)
557 (if (plusp (float-sign x))
558 y
559 (float-sign y pi))
560 (float-sign y (/ pi 2)))
561 (%atan2 y x))))
562 ;; If X is given, both X and Y must be real numbers.
563 (number-dispatch ((y real) (x real))
564 ((double-float
565 (foreach double-float single-float fixnum bignum ratio))
566 (atan2 y (coerce x 'double-float)))
567 (((foreach single-float fixnum bignum ratio)
568 double-float)
569 (atan2 (coerce y 'double-float) x))
570 (((foreach single-float fixnum bignum ratio)
571 (foreach single-float fixnum bignum ratio))
572 (coerce (atan2 (coerce y 'double-float) (coerce x 'double-float))
573 'single-float))))
574 (number-dispatch ((y number))
575 (handle-reals %atan y)
576 ((complex)
577 (complex-atan y)))))
578
579 (defun sinh (number)
580 "Return the hyperbolic sine of NUMBER."
581 (number-dispatch ((number number))
582 (handle-reals %sinh number)
583 ((complex)
584 (let ((x (realpart number))
585 (y (imagpart number)))
586 (complex (* (sinh x) (cos y))
587 (* (cosh x) (sin y)))))))
588
589 (defun cosh (number)
590 "Return the hyperbolic cosine of NUMBER."
591 (number-dispatch ((number number))
592 (handle-reals %cosh number)
593 ((complex)
594 (let ((x (realpart number))
595 (y (imagpart number)))
596 (complex (* (cosh x) (cos y))
597 (* (sinh x) (sin y)))))))
598
599 (defun tanh (number)
600 "Return the hyperbolic tangent of NUMBER."
601 (number-dispatch ((number number))
602 (handle-reals %tanh number)
603 ((complex)
604 (complex-tanh number))))
605
606 (defun asinh (number)
607 "Return the hyperbolic arc sine of NUMBER."
608 (number-dispatch ((number number))
609 (handle-reals %asinh number)
610 ((complex)
611 (complex-asinh number))))
612
613 (defun acosh (number)
614 "Return the hyperbolic arc cosine of NUMBER."
615 (number-dispatch ((number number))
616 ((rational)
617 ;; acosh is complex if number < 1
618 (if (< number 1)
619 (complex-acosh number)
620 (coerce (%acosh (coerce number 'double-float)) 'single-float)))
621 (((foreach single-float double-float))
622 (if (< number (coerce 1 '(dispatch-type number)))
623 (complex-acosh number)
624 (coerce (%acosh (coerce number 'double-float))
625 '(dispatch-type number))))
626 ((complex)
627 (complex-acosh number))))
628
629 (defun atanh (number)
630 "Return the hyperbolic arc tangent of NUMBER."
631 (number-dispatch ((number number))
632 ((rational)
633 ;; atanh is complex if |number| > 1
634 (if (or (> number 1) (< number -1))
635 (complex-atanh number)
636 (coerce (%atanh (coerce number 'double-float)) 'single-float)))
637 (((foreach single-float double-float))
638 (if (or (> number (coerce 1 '(dispatch-type number)))
639 (< number (coerce -1 '(dispatch-type number))))
640 (complex-atanh number)
641 (coerce (%atanh (coerce number 'double-float))
642 '(dispatch-type number))))
643 ((complex)
644 (complex-atanh number))))
645
646 ;;; HP-UX does not supply a C version of log1p, so use the definition.
647 ;;; We really need to fix this. The definition really loses big-time
648 ;;; in roundoff as x gets small.
649
650 #+hpux
651 (declaim (inline %log1p))
652 #+hpux
653 (defun %log1p (number)
654 (declare (double-float number)
655 (optimize (speed 3) (safety 0)))
656 (the double-float (log (the (double-float 0d0) (+ number 1d0)))))
657
658
659 ;;;;
660 ;;;; This is a set of routines that implement many elementary
661 ;;;; transcendental functions as specified by ANSI Common Lisp. The
662 ;;;; implementation is based on Kahan's paper.
663 ;;;;
664 ;;;; I believe I have accurately implemented the routines and are
665 ;;;; correct, but you may want to check for your self.
666 ;;;;
667 ;;;; These functions are written for CMU Lisp and take advantage of
668 ;;;; some of the features available there. It may be possible,
669 ;;;; however, to port this to other Lisps.
670 ;;;;
671 ;;;; Some functions are significantly more accurate than the original
672 ;;;; definitions in CMU Lisp. In fact, some functions in CMU Lisp
673 ;;;; give the wrong answer like (acos #c(-2.0 0.0)), where the true
674 ;;;; answer is pi + i*log(2-sqrt(3)).
675 ;;;;
676 ;;;; All of the implemented functions will take any number for an
677 ;;;; input, but the result will always be a either a complex
678 ;;;; single-float or a complex double-float.
679 ;;;;
680 ;;;; General functions
681 ;;;; complex-sqrt
682 ;;;; complex-log
683 ;;;; complex-atanh
684 ;;;; complex-tanh
685 ;;;; complex-acos
686 ;;;; complex-acosh
687 ;;;; complex-asin
688 ;;;; complex-asinh
689 ;;;; complex-atan
690 ;;;; complex-tan
691 ;;;;
692 ;;;; Utility functions:
693 ;;;; scalb logb
694 ;;;;
695 ;;;; Internal functions:
696 ;;;; square coerce-to-complex-type cssqs complex-log-scaled
697 ;;;;
698 ;;;;
699 ;;;; Please send any bug reports, comments, or improvements to Raymond
700 ;;;; Toy at toy@rtp.ericsson.se.
701 ;;;;
702 ;;;; References
703 ;;;;
704 ;;;; Kahan, W. "Branch Cuts for Complex Elementary Functions, or Much
705 ;;;; Ado About Nothing's Sign Bit" in Iserles and Powell (eds.) "The
706 ;;;; State of the Art in Numerical Analysis", pp. 165-211, Clarendon
707 ;;;; Press, 1987
708 ;;;;
709
710 (declaim (inline square))
711 (defun square (x)
712 (declare (double-float x))
713 (* x x))
714
715 ;; If you have these functions in libm, perhaps they should be used
716 ;; instead of these Lisp versions. These versions are probably good
717 ;; enough, especially since they are portable.
718
719 (declaim (inline scalb))
720 (defun scalb (x n)
721 "Compute 2^N * X without compute 2^N first (use properties of the
722 underlying floating-point format"
723 (declare (type double-float x)
724 (type double-float-exponent n))
725 (scale-float x n))
726
727 (declaim (inline logb-finite))
728 (defun logb-finite (x)
729 "Same as logb but X is not infinity and non-zero and not a NaN, so
730 that we can always return an integer"
731 (declare (type double-float x))
732 (multiple-value-bind (signif expon sign)
733 (decode-float x)
734 (declare (ignore signif sign))
735 ;; decode-float is almost right, except that the exponent
736 ;; is off by one
737 (1- expon)))
738
739 (defun logb (x)
740 "Compute an integer N such that 1 <= |2^(-N) * x| < 2.
741 For the special cases, the following values are used:
742
743 x logb
744 NaN NaN
745 +/- infinity +infinity
746 0 -infinity
747 "
748 (declare (type double-float x))
749 (cond ((float-nan-p x)
750 x)
751 ((float-infinity-p x)
752 #.ext:double-float-positive-infinity)
753 ((zerop x)
754 ;; The answer is negative infinity, but we are supposed to
755 ;; signal divide-by-zero, so do the actual division
756 (/ -1.0d0 x)
757 )
758 (t
759 (logb-finite x))))
760
761
762
763 ;; This function is used to create a complex number of the appropriate
764 ;; type.
765
766 (declaim (inline coerce-to-complex-type))
767 (defun coerce-to-complex-type (x y z)
768 "Create complex number with real part X and imaginary part Y such that
769 it has the same type as Z. If Z has type (complex rational), the X
770 and Y are coerced to single-float."
771 (declare (double-float x y)
772 (number z)
773 (optimize (extensions:inhibit-warnings 3)))
774 (if (typep (realpart z) 'double-float)
775 (complex x y)
776 ;; Convert anything that's not a double-float to a single-float.
777 (complex (float x 1f0)
778 (float y 1f0))))
779
780 (defun cssqs (z)
781 ;; Compute |(x+i*y)/2^k|^2 scaled to avoid over/underflow. The
782 ;; result is r + i*k, where k is an integer.
783
784 ;; Save all FP flags
785 (let ((x (float (realpart z) 1d0))
786 (y (float (imagpart z) 1d0)))
787 ;; Would this be better handled using an exception handler to
788 ;; catch the overflow or underflow signal? For now, we turn all
789 ;; traps off and look at the accrued exceptions to see if any
790 ;; signal would have been raised.
791 (with-float-traps-masked (:underflow :overflow)
792 (let ((rho (+ (square x) (square y))))
793 (declare (optimize (speed 3) (space 0)))
794 (cond ((and (or (float-nan-p rho)
795 (float-infinity-p rho))
796 (or (float-infinity-p (abs x))
797 (float-infinity-p (abs y))))
798 (values ext:double-float-positive-infinity 0))
799 ((let ((threshold #.(/ least-positive-double-float
800 double-float-epsilon))
801 (traps (ldb vm::float-sticky-bits
802 (vm:floating-point-modes))))
803 ;; Overflow raised or (underflow raised and rho <
804 ;; lambda/eps)
805 (or (not (zerop (logand vm:float-overflow-trap-bit traps)))
806 (and (not (zerop (logand vm:float-underflow-trap-bit traps)))
807 (< rho threshold))))
808 ;; If we're here, neither x nor y are infinity and at
809 ;; least one is non-zero.. Thus logb returns a nice
810 ;; integer.
811 (let ((k (- (logb-finite (max (abs x) (abs y))))))
812 (values (+ (square (scalb x k))
813 (square (scalb y k)))
814 (- k))))
815 (t
816 (values rho 0)))))))
817
818 (defun complex-sqrt (z)
819 "Principle square root of Z
820
821 Z may be any number, but the result is always a complex."
822 (declare (number z))
823 (multiple-value-bind (rho k)
824 (cssqs z)
825 (declare (type (or (member 0d0) (double-float 0d0)) rho)
826 (type fixnum k))
827 (let ((x (float (realpart z) 1.0d0))
828 (y (float (imagpart z) 1.0d0))
829 (eta 0d0)
830 (nu 0d0))
831 (declare (double-float x y eta nu))
832
833 (locally
834 ;; space 0 to get maybe-inline functions inlined.
835 (declare (optimize (speed 3) (space 0)))
836
837 (if (not (float-nan-p x))
838 (setf rho (+ (scalb (abs x) (- k)) (sqrt rho))))
839
840 (cond ((oddp k)
841 (setf k (ash k -1)))
842 (t
843 (setf k (1- (ash k -1)))
844 (setf rho (+ rho rho))))
845
846 (setf rho (scalb (sqrt rho) k))
847
848 (setf eta rho)
849 (setf nu y)
850
851 (when (/= rho 0d0)
852 (when (not (float-infinity-p (abs nu)))
853 (setf nu (/ (/ nu rho) 2d0)))
854 (when (< x 0d0)
855 (setf eta (abs nu))
856 (setf nu (float-sign y rho))))
857 (coerce-to-complex-type eta nu z)))))
858
859 (defun complex-log-scaled (z j)
860 "Compute log(2^j*z).
861
862 This is for use with J /= 0 only when |z| is huge."
863 (declare (number z)
864 (fixnum j))
865 ;; The constants t0, t1, t2 should be evaluated to machine
866 ;; precision. In addition, Kahan says the accuracy of log1p
867 ;; influences the choices of these constants but doesn't say how to
868 ;; choose them. We'll just assume his choices matches our
869 ;; implementation of log1p.
870 (let ((t0 #.(/ 1 (sqrt 2.0d0)))
871 (t1 1.2d0)
872 (t2 3d0)
873 (ln2 #.(log 2d0))
874 (x (float (realpart z) 1.0d0))
875 (y (float (imagpart z) 1.0d0)))
876 (multiple-value-bind (rho k)
877 (cssqs z)
878 (declare (optimize (speed 3)))
879 (let ((beta (max (abs x) (abs y)))
880 (theta (min (abs x) (abs y))))
881 (coerce-to-complex-type (if (and (zerop k)
882 (< t0 beta)
883 (or (<= beta t1)
884 (< rho t2)))
885 (/ (%log1p (+ (* (- beta 1.0d0)
886 (+ beta 1.0d0))
887 (* theta theta)))
888 2d0)
889 (+ (/ (log rho) 2d0)
890 (* (+ k j) ln2)))
891 (atan y x)
892 z)))))
893
894 (defun complex-log (z)
895 "Log of Z = log |Z| + i * arg Z
896
897 Z may be any number, but the result is always a complex."
898 (declare (number z))
899 (complex-log-scaled z 0))
900
901 ;; Let us note the following "strange" behavior. atanh 1.0d0 is
902 ;; +infinity, but the following code returns approx 176 + i*pi/4. The
903 ;; reason for the imaginary part is caused by the fact that arg i*y is
904 ;; never 0 since we have positive and negative zeroes.
905
906 (defun complex-atanh (z)
907 "Compute atanh z = (log(1+z) - log(1-z))/2"
908 (declare (number z))
909 (let* (;; Constants
910 (theta (/ (sqrt most-positive-double-float) 4.0d0))
911 (rho (/ 4.0d0 (sqrt most-positive-double-float)))
912 (half-pi (/ pi 2.0d0))
913 (rp (float (realpart z) 1.0d0))
914 (beta (float-sign rp 1.0d0))
915 (x (* beta rp))
916 (y (* beta (- (float (imagpart z) 1.0d0))))
917 (eta 0.0d0)
918 (nu 0.0d0))
919 ;; Shouldn't need this declare.
920 (declare (double-float x y))
921 (locally
922 (declare (optimize (speed 3)))
923 (cond ((or (> x theta)
924 (> (abs y) theta))
925 ;; To avoid overflow...
926 (setf eta (float-sign y half-pi))
927 ;; nu is real part of 1/(x + iy). This is x/(x^2+y^2),
928 ;; which can cause overflow. Arrange this computation so
929 ;; that it won't overflow.
930 (setf nu (let* ((x-bigger (> x (abs y)))
931 (r (if x-bigger (/ y x) (/ x y)))
932 (d (+ 1.0d0 (* r r))))
933 (if x-bigger
934 (/ (/ x) d)
935 (/ (/ r y) d)))))
936 ((= x 1.0d0)
937 ;; Should this be changed so that if y is zero, eta is set
938 ;; to +infinity instead of approx 176? In any case
939 ;; tanh(176) is 1.0d0 within working precision.
940 (let ((t1 (+ 4d0 (square y)))
941 (t2 (+ (abs y) rho)))
942 (setf eta (log (/ (sqrt (sqrt t1)))
943 (sqrt t2)))
944 (setf nu (* 0.5d0
945 (float-sign y
946 (+ half-pi (atan (* 0.5d0 t2))))))))
947 (t
948 (let ((t1 (+ (abs y) rho)))
949 ;; Normal case using log1p(x) = log(1 + x)
950 (setf eta (* 0.25d0
951 (%log1p (/ (* 4.0d0 x)
952 (+ (square (- 1.0d0 x))
953 (square t1))))))
954 (setf nu (* 0.5d0
955 (atan (* 2.0d0 y)
956 (- (* (- 1.0d0 x)
957 (+ 1.0d0 x))
958 (square t1))))))))
959 (coerce-to-complex-type (* beta eta)
960 (- (* beta nu))
961 z))))
962
963 (defun complex-tanh (z)
964 "Compute tanh z = sinh z / cosh z"
965 (declare (number z))
966 (let ((x (float (realpart z) 1.0d0))
967 (y (float (imagpart z) 1.0d0)))
968 (locally
969 ;; space 0 to get maybe-inline functions inlined
970 (declare (optimize (speed 3) (space 0)))
971 (cond ((> (abs x)
972 #-(or linux hpux) #.(/ (%asinh most-positive-double-float) 4d0)
973 ;; This is more accurate under linux.
974 #+(or linux hpux) #.(/ (+ (%log 2.0d0)
975 (%log most-positive-double-float)) 4d0))
976 (coerce-to-complex-type (float-sign x)
977 (float-sign y) z))
978 (t
979 (let* ((tv (%tan y))
980 (beta (+ 1.0d0 (* tv tv)))
981 (s (sinh x))
982 (rho (sqrt (+ 1.0d0 (* s s)))))
983 (if (float-infinity-p (abs tv))
984 (coerce-to-complex-type (/ rho s)
985 (/ tv)
986 z)
987 (let ((den (+ 1.0d0 (* beta s s))))
988 (coerce-to-complex-type (/ (* beta rho s)
989 den)
990 (/ tv den)
991 z)))))))))
992
993 ;; Kahan says we should only compute the parts needed. Thus, the
994 ;; realpart's below should only compute the real part, not the whole
995 ;; complex expression. Doing this can be important because we may get
996 ;; spurious signals that occur in the part that we are not using.
997 ;;
998 ;; However, we take a pragmatic approach and just use the whole
999 ;; expression.
1000
1001 ;; NOTE: The formula given by Kahan is somewhat ambiguous in whether
1002 ;; it's the conjugate of the square root or the square root of the
1003 ;; conjugate. This needs to be checked.
1004
1005 ;; I checked. It doesn't matter because (conjugate (sqrt z)) is the
1006 ;; same as (sqrt (conjugate z)) for all z. This follows because
1007 ;;
1008 ;; (conjugate (sqrt z)) = exp(0.5*log |z|)*exp(-0.5*j*arg z).
1009 ;;
1010 ;; (sqrt (conjugate z)) = exp(0.5*log|z|)*exp(0.5*j*arg conj z)
1011 ;;
1012 ;; and these two expressions are equal if and only if arg conj z =
1013 ;; -arg z, which is clearly true for all z.
1014
1015 ;; NOTE: The rules of Common Lisp says that if you mix a real with a
1016 ;; complex, the real is converted to a complex before performing the
1017 ;; operation. However, Kahan says in this paper (pg 176):
1018 ;;
1019 ;; (iii) Careless handling can turn infinity or the sign of zero into
1020 ;; misinformation that subsequently disappears leaving behind
1021 ;; only a plausible but incorrect result. That is why compilers
1022 ;; must not transform z-1 into z-(1+i*0), as we have seen above,
1023 ;; nor -(-x-x^2) into (x+x^2), as we shall see below, lest a
1024 ;; subsequent logarithm or square root produce a non-zero
1025 ;; imaginary part whose sign is opposite to what was intended.
1026 ;;
1027 ;; The interesting examples are too long and complicated to reproduce
1028 ;; here. We refer the reader to his paper.
1029 ;;
1030 ;; The functions below are intended to handle the cases where a real
1031 ;; is mixed with a complex and we don't want CL complex contagion to
1032 ;; occur..
1033
1034 (declaim (inline 1+z 1-z z-1 z+1))
1035 (defun 1+z (z)
1036 (complex (+ 1 (realpart z)) (imagpart z)))
1037 (defun 1-z (z)
1038 (complex (- 1 (realpart z)) (- (imagpart z))))
1039 (defun z-1 (z)
1040 (complex (- (realpart z) 1) (imagpart z)))
1041 (defun z+1 (z)
1042 (complex (+ (realpart z) 1) (imagpart z)))
1043
1044 (defun complex-acos (z)
1045 "Compute acos z = pi/2 - asin z
1046
1047 Z may be any number, but the result is always a complex."
1048 (declare (number z))
1049 (let ((sqrt-1+z (complex-sqrt (1+z z)))
1050 (sqrt-1-z (complex-sqrt (1-z z))))
1051 (with-float-traps-masked (:divide-by-zero)
1052 (complex (* 2 (atan (/ (realpart sqrt-1-z)
1053 (realpart sqrt-1+z))))
1054 (asinh (imagpart (* (conjugate sqrt-1+z)
1055 sqrt-1-z)))))))
1056
1057 (defun complex-acosh (z)
1058 "Compute acosh z = 2 * log(sqrt((z+1)/2) + sqrt((z-1)/2))
1059
1060 Z may be any number, but the result is always a complex."
1061 (declare (number z))
1062 (let ((sqrt-z-1 (complex-sqrt (z-1 z)))
1063 (sqrt-z+1 (complex-sqrt (z+1 z))))
1064 (with-float-traps-masked (:divide-by-zero)
1065 (complex (asinh (realpart (* (conjugate sqrt-z-1)
1066 sqrt-z+1)))
1067 (* 2 (atan (/ (imagpart sqrt-z-1)
1068 (realpart sqrt-z+1))))))))
1069
1070
1071 (defun complex-asin (z)
1072 "Compute asin z = asinh(i*z)/i
1073
1074 Z may be any number, but the result is always a complex."
1075 (declare (number z))
1076 (let ((sqrt-1-z (complex-sqrt (1-z z)))
1077 (sqrt-1+z (complex-sqrt (1+z z))))
1078 (with-float-traps-masked (:divide-by-zero)
1079 (complex (atan (/ (realpart z)
1080 (realpart (* sqrt-1-z sqrt-1+z))))
1081 (asinh (imagpart (* (conjugate sqrt-1-z)
1082 sqrt-1+z)))))))
1083
1084 (defun complex-asinh (z)
1085 "Compute asinh z = log(z + sqrt(1 + z*z))
1086
1087 Z may be any number, but the result is always a complex."
1088 (declare (number z))
1089 ;; asinh z = -i * asin (i*z)
1090 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1091 (result (complex-asin iz)))
1092 (complex (imagpart result)
1093 (- (realpart result)))))
1094
1095 (defun complex-atan (z)
1096 "Compute atan z = atanh (i*z) / i
1097
1098 Z may be any number, but the result is always a complex."
1099 (declare (number z))
1100 ;; atan z = -i * atanh (i*z)
1101 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1102 (result (complex-atanh iz)))
1103 (complex (imagpart result)
1104 (- (realpart result)))))
1105
1106 (defun complex-tan (z)
1107 "Compute tan z = -i * tanh(i * z)
1108
1109 Z may be any number, but the result is always a complex."
1110 (declare (number z))
1111 ;; tan z = -i * tanh(i*z)
1112 (let* ((iz (complex (- (imagpart z)) (realpart z)))
1113 (result (complex-tanh iz)))
1114 (complex (imagpart result)
1115 (- (realpart result)))))
1116

  ViewVC Help
Powered by ViewVC 1.1.5