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

Contents of /src/code/irrat.lisp

Parent Directory Parent Directory | Revision Log Revision Log


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

  ViewVC Help
Powered by ViewVC 1.1.5