Fix the inefficient evaluation of translated predicates
[maxima.git] / src / float.lisp
blobc236f4dc3b54ee9e80afbc21ea3e0836029123c3
1 ;;; -*- Mode: Lisp; Package: Maxima; Syntax: Common-Lisp; Base: 10 -*- ;;;;
2 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3 ;;; The data in this file contains enhancments. ;;;;;
4 ;;; ;;;;;
5 ;;; Copyright (c) 1984,1987 by William Schelter,University of Texas ;;;;;
6 ;;; All rights reserved ;;;;;
7 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
8 ;;; (c) Copyright 1982 Massachusetts Institute of Technology ;;;
9 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
11 (in-package :maxima)
13 (macsyma-module float)
15 ;; EXPERIMENTAL BIGFLOAT PACKAGE VERSION 2- USING BINARY MANTISSA
16 ;; AND POWER-OF-2 EXPONENT.
17 ;; EXPONENTS MAY BE BIG NUMBERS NOW (AUG. 1975 --RJF)
18 ;; Modified: July 1979 by CWH to run on the Lisp Machine and to comment
19 ;; the code.
20 ;; August 1980 by CWH to run on Multics and to install
21 ;; new FIXFLOAT.
22 ;; December 1980 by JIM to fix BIGLSH not to pass LSH a second
23 ;; argument with magnitude greater than MACHINE-FIXNUM-PRECISION.
25 ;; Number of bits of precision in a fixnum and in the fields of a flonum for
26 ;; a particular machine. These variables should only be around at eval
27 ;; and compile time. These variables should probably be set up in a prelude
28 ;; file so they can be accessible to all Macsyma files.
30 (eval-when
31 #+gcl (compile load eval)
32 #-gcl (:compile-toplevel :load-toplevel :execute)
33 (defconstant +machine-fixnum-precision+ (integer-length most-positive-fixnum)))
35 ;; External variables
37 (defmvar $float2bf t
38 "If TRUE, no MAXIMA-ERROR message is printed when a floating point number is
39 converted to a bigfloat number.")
41 (defmvar $bftorat nil
42 "Controls the conversion of bigfloat numbers to rational numbers. If
43 FALSE, RATEPSILON will be used to control the conversion (this results in
44 relatively small rational numbers). If TRUE, the rational number generated
45 will accurately represent the bigfloat.")
47 (defmvar $bftrunc t
48 "If TRUE, printing of bigfloat numbers will truncate trailing zeroes.
49 Otherwise, all trailing zeroes are printed.")
51 (defmvar $fpprintprec 0
52 "Controls the number of significant digits printed for floats. If
53 0, then full precision is used."
54 fixnum)
56 (defmvar $maxfpprintprec (ceiling (log (expt 2 (float-digits 1.0)) 10.0))
57 "The maximum number of significant digits printed for floats.")
59 (defmvar $fpprec $maxfpprintprec
60 "Number of decimal digits of precision to use when creating new bigfloats.
61 One extra decimal digit in actual representation for rounding purposes.")
63 (defmvar bigfloatzero '((bigfloat simp 56.) 0 0)
64 "Bigfloat representation of 0" in-core)
66 (defmvar bigfloatone '((bigfloat simp 56.) #.(expt 2 55.) 1)
67 "Bigfloat representation of 1" in-core)
69 (defmvar bfhalf '((bigfloat simp 56.) #.(expt 2 55.) 0)
70 "Bigfloat representation of 1/2")
72 (defmvar bfmhalf '((bigfloat simp 56.) #.(- (expt 2 55.)) 0)
73 "Bigfloat representation of -1/2")
75 (defmvar bigfloat%e '((bigfloat simp 56.) 48968212118944587. 2)
76 "Bigfloat representation of %E")
78 (defmvar bigfloat%pi '((bigfloat simp 56.) 56593902016227522. 2)
79 "Bigfloat representation of %pi")
81 (defmvar bigfloat%gamma '((bigfloat simp 56.) 41592772053807304. 0)
82 "Bigfloat representation of %gamma")
84 (defmvar bigfloat_log2 '((bigfloat simp 56.) 49946518145322874. 0)
85 "Bigfloat representation of log(2)")
87 ;; Internal specials
89 ;; Number of bits of precision in the mantissa of newly created bigfloats.
90 ;; FPPREC = ($FPPREC+1)*(Log base 2 of 10)
92 (defvar fpprec)
94 ;; FPROUND uses this to return a second value, i.e. it sets it before
95 ;; returning. This number represents the number of binary digits its input
96 ;; bignum had to be shifted right to be aligned into the mantissa. For
97 ;; example, aligning 1 would mean shifting it FPPREC-1 places left, and
98 ;; aligning 7 would mean shifting FPPREC-3 places left.
100 (defvar *m)
102 ;; *DECFP = T if the computation is being done in decimal radix. NIL implies
103 ;; base 2. Decimal radix is used only during output.
105 (defvar *decfp nil)
107 (defvar max-bfloat-%pi bigfloat%pi)
108 (defvar max-bfloat-%e bigfloat%e)
109 (defvar max-bfloat-%gamma bigfloat%gamma)
110 (defvar max-bfloat-log2 bigfloat_log2)
113 (declare-top (special *cancelled $float $bfloat $ratprint $ratepsilon $domain $m1pbranch))
115 ;; Representation of a Bigfloat: ((BIGFLOAT SIMP precision) mantissa exponent)
116 ;; precision -- number of bits of precision in the mantissa.
117 ;; precision = (integer-length mantissa)
118 ;; mantissa -- a signed integer representing a fractional portion computed by
119 ;; fraction = (// mantissa (^ 2 precision)).
120 ;; exponent -- a signed integer representing the scale of the number.
121 ;; The actual number represented is (* fraction (^ 2 exponent)).
123 (defun hipart (x nn)
124 (if (bignump nn)
125 (abs x)
126 (haipart x nn)))
128 (defun fpprec1 (assign-var q)
129 (declare (ignore assign-var))
130 (if (or (not (fixnump q)) (< q 1))
131 (merror (intl:gettext "fpprec: value must be a positive integer; found: ~M") q))
132 (setq fpprec (+ 2 (integer-length (expt 10. q)))
133 bigfloatone ($bfloat 1)
134 bigfloatzero ($bfloat 0)
135 bfhalf (list (car bigfloatone) (cadr bigfloatone) 0)
136 bfmhalf (list (car bigfloatone) (- (cadr bigfloatone)) 0))
139 ;; FPSCAN is called by lexical scan when a
140 ;; bigfloat is encountered. For example, 12.01B-3
141 ;; would be the result of (FPSCAN '(/1 /2) '(/0 /1) '(/- /3))
142 ;; Arguments to FPSCAN are a list of characters to the left of the
143 ;; decimal point, to the right of the decimal point, and in the exponent.
145 (defun fpscan (lft rt exp &aux (*read-base* 10.) (*m 1) (*cancelled 0))
146 (setq exp (readlist exp))
147 (bigfloatp
148 (let ((fpprec (+ 4 fpprec (integer-length exp)
149 (floor (1+ (* #.(/ (log 10.0) (log 2.0)) (length lft))))))
150 $float temp)
151 (setq temp (add (readlist lft)
152 (div (readlist rt) (expt 10. (length rt)))))
153 ($bfloat (cond ((> (abs exp) 1000.)
154 (cons '(mtimes) (list temp (list '(mexpt) 10. exp))))
155 (t (mul2 temp (power 10. exp))))))))
157 (defun dim-bigfloat (form result)
158 (let (($lispdisp nil))
159 (dimension-atom (maknam (fpformat form)) result)))
161 ;; Assume that X has the form ((BIGFLOAT ... <prec>) ...).
162 ;; Return <prec>.
163 (defun bigfloat-prec (x)
164 (car (last (car x))))
166 ;; Converts the bigfloat L to list of digits including |.| and the
167 ;; exponent marker |b|. The number of significant digits is controlled
168 ;; by $fpprintprec.
169 (defun fpformat (l)
170 (if (not (member 'simp (cdar l) :test #'eq))
171 (setq l (cons (cons (caar l) (cons 'simp (cdar l))) (cdr l))))
172 (cond ((equal (cadr l) 0)
173 (if (not (equal (caddr l) 0))
174 (mtell "FPFORMAT: warning: detected an incorrect form of 0.0b0: ~M, ~M~%"
175 (cadr l) (caddr l)))
176 (list '|0| '|.| '|0| '|b| '|0|))
177 (t ;; L IS ALWAYS POSITIVE FP NUMBER
178 (let* ((extradigs (floor (1+ (quotient (integer-length (caddr l)) #.(/ (log 10.0) (log 2.0))))))
179 (fpprec (+ extradigs (decimalsin (- (bigfloat-prec l) 2))))
180 (*m 1)
181 (*cancelled 0))
182 (setq l
183 (let ((*decfp t)
184 (of (bigfloat-prec l))
185 (l (cdr l))
186 (expon nil))
187 (setq expon (- (cadr l) of))
188 (setq l (if (minusp expon)
189 (fpquotient (intofp (car l)) (fpintexpt 2 (- expon) of))
190 (fptimes* (intofp (car l)) (fpintexpt 2 expon of))))
191 (incf fpprec (- extradigs))
192 (list (fpround (car l)) (+ (- extradigs) *m (cadr l)))))
193 (let ((*print-base* 10.)
194 *print-radix*
195 (expo-adjust 0)
196 (l1 nil))
197 (setq l1 (let*
198 ((effective-printprec (if (or (= $fpprintprec 0) (> $fpprintprec fpprec)) fpprec $fpprintprec))
199 (integer-to-explode (round (car l) (expt 10 (- fpprec effective-printprec))))
200 (exploded-integer (explodec integer-to-explode)))
201 ;; If the rounded integer has more digits than
202 ;; expected, we need to adjust the exponent by
203 ;; this amount. This also means we need to remove
204 ;; these extra digits so that the result has the
205 ;; desired number of digits.
206 (setf expo-adjust (- (length exploded-integer) effective-printprec))
207 (when (plusp expo-adjust)
208 (setf exploded-integer (butlast exploded-integer expo-adjust)))
209 (if $bftrunc
210 (do ((l (nreverse exploded-integer) (cdr l)))
211 ((not (eq '|0| (car l))) (nreverse l)))
212 exploded-integer)))
213 (nconc (ncons (car l1)) (ncons '|.|)
214 (or (cdr l1) (ncons '|0|))
215 (ncons '|b|)
216 (explodec (+ (1- (cadr l)) expo-adjust))))))))
218 ;; NOTE: This is a modified version of FORMAT-EXP-AUX from CMUCL to
219 ;; support printing of bfloats.
220 (defun bfloat-format-e (stream arg colonp atp
221 &optional w d e (k 1)
222 overflowchar (padchar #\space) exponentchar)
223 (declare (ignore colonp))
224 (flet ((exponent-value (x)
225 ;; Compute the (decimal exponent) of the bfloat number X.
226 (let* (($fpprintprec 1)
227 (f (fpformat x))
228 (marker (position '|b| f)))
229 ;; FIXME: do something better than printing and reading
230 ;; the result.
231 (read-from-string
232 (format nil "~{~A~}" (nthcdr (1+ marker) f)))))
233 (bfloat-to-string (x fdigits scale)
234 ;; Print the bfloat X with FDIGITS after the decimal
235 ;; point. This means, roughtly, FDIGITS+1 significant
236 ;; digits.
237 (let* (($fpprintprec (if fdigits
238 (if (zerop fdigits)
240 (+ fdigits scale))
242 (f (fpformat (bcons (fpabs (cdr x)))))
243 (marker (position '|b| f))
244 (digits (remove '|.| (subseq f 0 marker))))
245 ;; Depending on the value of k, move the decimal
246 ;; point. DIGITS was printed assuming the decimal point
247 ;; is after the first digit. But if fdigits = 0, fpformat
248 ;; actually printed out one too many digits, so we need
249 ;; to remove that.
250 (when (and fdigits (zerop fdigits))
251 (setf digits (butlast digits)))
252 (cond ((zerop k)
253 (push '|.| digits))
254 ((minusp k)
255 ;; Put the leading decimal and then some zeroes
256 (dotimes (i (abs k))
257 (push #\0 digits))
258 (push '|.| digits))
260 ;; The number is scaled by 10^k. Do this by
261 ;; putting the decimal point in the right place,
262 ;; appending zeroes if needed.
263 (setf digits
264 (cond ((> k (length digits))
265 (concatenate 'list
266 digits
267 (make-list (- k (length digits))
268 :initial-element #\0)
269 (list '|.|)))
271 (concatenate 'list
272 (subseq digits 0 k)
273 (list '|.|)
274 (subseq digits k)))))))
275 (let* ((str (format nil "~{~A~}" digits))
276 (len (length str)))
277 (when (and fdigits (>= fdigits len))
278 ;; Append some zeroes to get the desired number of digits
279 (setf str (concatenate 'string str
280 (make-string (+ 1 k (- fdigits len))
281 :initial-element #\0)))
282 (setf len (length str)))
283 (values str
285 (char= (aref str 0) #\.)
286 (char= (aref str (1- (length str))) #\.)
288 0)))))
289 (let* ((num-expt (exponent-value arg))
290 (expt (if (zerop (second arg))
292 (1+ (- num-expt k))))
293 (estr (format nil "~D" (abs expt)))
294 (elen (if e (max (length estr) e) (length estr)))
295 (add-zero-p nil))
296 (cond ((and w overflowchar e (> elen e))
297 ;; Exponent overflow
298 (dotimes (i w)
299 (write-char overflowchar stream)))
301 ;; The hairy case
302 (let* ((fdig (if d
303 (if (plusp k)
304 (1+ (- d k))
306 nil))
307 (spaceleft (if w
308 (- w 2 elen
309 (if (or atp (minusp (second arg)))
310 1 0))
311 nil)))
312 #+(or)
313 (progn
314 (format t "d, k = ~D ~D~%" d k)
315 (format t "fdig = ~D, spaceleft = ~D~%" fdig spaceleft))
317 (multiple-value-bind (fstr flen lpoint tpoint)
318 (bfloat-to-string arg fdig (or k 1))
319 #+(or)
320 (format t "fstr flen lpoint tpoint = ~S ~S ~S ~S~%"
321 fstr flen lpoint tpoint)
322 (when (and d (zerop d)) (setq tpoint nil))
323 (when w
324 (decf spaceleft flen)
325 ;; See CLHS 22.3.3.2. "If the parameter d is
326 ;; omitted, ... [and] if the fraction to be
327 ;; printed is zero then a single zero digit should
328 ;; appear after the decimal point." So we need to
329 ;; subtract one from here because we're going to
330 ;; add an extra 0 digit later.
331 (when (and (null d) (char= (aref fstr (1- flen)) #\.))
332 (setf add-zero-p t)
333 (decf spaceleft))
334 (when lpoint
335 (if (or (> spaceleft 0) tpoint)
336 (decf spaceleft)
337 (setq lpoint nil)))
338 (when (and tpoint (<= spaceleft 0))
339 (setq tpoint nil)))
340 #+(or)
341 (format t "w, spaceleft overflowchar = ~S ~S ~S~%"
342 w spaceleft overflowchar)
343 (cond ((and w (< spaceleft 0) overflowchar)
344 ;; Significand overflow; output the overflow char
345 (dotimes (i w)
346 (write-char overflowchar stream)))
348 (when w
349 (dotimes (i spaceleft)
350 (write-char padchar stream)))
351 (if (minusp (second arg))
352 (write-char #\- stream)
353 (when atp (write-char #\+ stream)))
354 (when lpoint
355 (write-char #\0 stream))
357 (write-string fstr stream)
358 ;; Add a zero if we need it. Which means
359 ;; we figured out we need one above, or
360 ;; another condition. Basically, append a
361 ;; zero if there are no width constraints
362 ;; and if the last char to print was a
363 ;; decimal (so the trailing fraction is
364 ;; zero.)
365 (when (or add-zero-p
366 (and (null w)
367 (char= (aref fstr (1- flen)) #\.)))
368 (write-char #\0 stream))
369 (write-char (if exponentchar
370 exponentchar
371 #\b)
372 stream)
373 (write-char (if (minusp expt) #\- #\+) stream)
374 (when e
375 (dotimes (i (- e (length estr)))
376 (write-char #\0 stream)))
377 (write-string estr stream)))))))))
378 (values))
380 ;; NOTE: This is a modified version of FORMAT-FIXED-AUX from CMUCL to
381 ;; support printing of bfloats.
382 (defun bfloat-format-f (stream number colonp atsign &optional w d (k 0) ovf (pad #\space))
383 (declare (ignore colonp))
384 (labels
385 ((exponent-value (x)
386 ;; Compute the (decimal exponent) of the bfloat number X.
387 (let* (($fpprintprec 1)
388 (f (fpformat x))
389 (marker (position '|b| f)))
390 ;; FIXME: do something better than printing and reading
391 ;; the result.
392 (read-from-string
393 (format nil "~{~A~}" (nthcdr (1+ marker) f)))))
394 (bfloat-to-string (x fdigits scale spaceleft)
395 ;; Print the bfloat X with FDIGITS after the decimal
396 ;; point. To do this we need to know the exponent because
397 ;; fpformat always produces exponential output. If the
398 ;; exponent is E, and we want FDIGITS after the decimal
399 ;; point, we need FDIGITS + E digits printed.
400 (flet ((compute-prec (exp spaceleft)
401 #+nil
402 (format t "compute-prec ~D ~D~%" exp spaceleft)
403 (cond (fdigits
404 (+ fdigits exp 1))
405 (spaceleft
406 (max (1- spaceleft) (1+ exp)))
408 (max (1+ exp) 0)))))
409 (let* ((exp (+ k (exponent-value x)))
410 ($fpprintprec (compute-prec exp spaceleft))
411 (f (let ((maxima::$bftrunc nil))
412 #+nil
413 (format t "printprec = ~D~%" $fpprintprec)
414 (fpformat (bcons (fpabs (cdr x))))))
415 (marker (position '|b| f))
416 (digits (remove '|.| (subseq f 0 marker))))
417 ;; Depending on the value of scale, move the decimal
418 ;; point. DIGITS was printed assuming the decimal point
419 ;; is after the first digit. But if fdigits = 0, fpformat
420 ;; actually printed out one too many digits, so we need
421 ;; to remove that.
422 #+nil
423 (format t "exp, fdigits = ~D ~D, digits = ~S~%" exp fdigits digits)
424 #+nil
425 (when (and fdigits (zerop fdigits))
426 (setf digits (butlast digits)))
427 ;; Figure out where the decimal point should go. An
428 ;; exponent of 0 means the decimal is after the first
429 ;; digit.
430 (cond ((minusp exp)
431 (dotimes (k (1- (abs exp)))
432 (push '|0| digits))
433 (push '|.| digits))
434 ((< exp (length digits))
435 #+nil
436 (format t "exp, len = ~D ~D~%" exp (length digits))
437 (setf digits (concatenate 'list
438 (subseq digits 0 (1+ exp))
439 (list '|.|)
440 (subseq digits (1+ exp)))))
442 (setf digits (append digits (list '|.|)))))
443 (let* ((str (format nil "~{~A~}" digits))
444 (len (length str)))
445 #+nil
446 (format t "str = ~S~%" str)
447 (when (and fdigits (>= fdigits len))
448 ;; Append some zeroes to get the desired number of digits
449 (setf str (concatenate 'string str
450 (make-string (+ 1 scale (- fdigits len))
451 :initial-element #\0)))
452 (setf len (length str)))
453 (values str
455 (char= (aref str 0) #\.)
456 (char= (aref str (1- (length str))) #\.)
458 0))))))
459 (let ((spaceleft w))
460 (when (and w (or atsign (minusp (second number))))
461 (decf spaceleft))
462 (multiple-value-bind (str len lpoint tpoint)
463 (bfloat-to-string number d k spaceleft)
464 ;;if caller specifically requested no fraction digits, suppress the
465 ;;optional trailing zero
466 (when (and d (zerop d)) (setq tpoint nil))
467 (when w
468 (decf spaceleft len)
469 ;;optional leading zero
470 (when lpoint
471 (if (or (> spaceleft 0) tpoint) ;force at least one digit
472 (decf spaceleft)
473 (setq lpoint nil)))
474 ;;optional trailing zero
475 (when tpoint
476 (if (> spaceleft 0)
477 (decf spaceleft)
478 (setq tpoint nil))))
479 (cond ((and w (< spaceleft 0) ovf)
480 ;;field width overflow
481 (dotimes (i w) (write-char ovf stream))
484 (when w (dotimes (i spaceleft) (write-char pad stream)))
485 (if (minusp (second number))
486 (write-char #\- stream)
487 (if atsign (write-char #\+ stream)))
488 (when lpoint (write-char #\0 stream))
489 (write-string str stream)
490 (when tpoint (write-char #\0 stream))
491 nil))))))
493 ;; NOTE: This is a modified version of FORMAT-EXP-AUX from CMUCL to
494 ;; support printing of bfloats.
495 (defun bfloat-format-g (stream arg colonp atsign
496 &optional w d e (k 1)
497 ovf (pad #\space) exponentchar)
498 (declare (ignore colonp))
499 (flet ((exponent-value (x)
500 ;; Compute the (decimal exponent) of the bfloat number X.
501 (let* (($fpprintprec 1)
502 (f (fpformat x))
503 (marker (position '|b| f)))
504 ;; FIXME: do something better than printing and reading
505 ;; the result.
506 (read-from-string
507 (format nil "~{~A~}" (nthcdr (1+ marker) f)))))
508 (bfloat-to-string (x fdigits)
509 ;; Print the bfloat X with FDIGITS after the decimal
510 ;; point. This means, roughtly, FDIGITS+1 significant
511 ;; digits.
512 (let* (($fpprintprec (if fdigits
513 (if (zerop fdigits)
515 (1+ fdigits))
517 (f (fpformat (bcons (fpabs (cdr x)))))
518 (marker (position '|b| f))
519 (digits (remove '|.| (subseq f 0 marker))))
520 ;; Depending on the value of k, move the decimal
521 ;; point. DIGITS was printed assuming the decimal point
522 ;; is after the first digit. But if fdigits = 0, fpformat
523 ;; actually printed out one too many digits, so we need
524 ;; to remove that.
525 (when (and fdigits (zerop fdigits))
526 (setf digits (butlast digits)))
527 (cond ((zerop k)
528 (push '|.| digits))
529 ((minusp k)
530 ;; Put the leading decimal and then some zeroes
531 (dotimes (i (abs k))
532 (push #\0 digits))
533 (push '|.| digits))
535 ;; The number is scaled by 10^k. Do this by
536 ;; putting the decimal point in the right place,
537 ;; appending zeroes if needed.
538 (setf digits
539 (cond ((> k (length digits))
540 (concatenate 'list
541 digits
542 (make-list (- k (length digits))
543 :initial-element #\0)
544 (list '|.|)))
546 (concatenate 'list
547 (subseq digits 0 k)
548 (list '|.|)
549 (subseq digits k)))))))
550 (let* ((str (format nil "~{~A~}" digits))
551 (len (length str)))
552 (when (and fdigits (>= fdigits len))
553 ;; Append some zeroes to get the desired number of digits
554 (setf str (concatenate 'string str
555 (make-string (+ 1 k (- fdigits len))
556 :initial-element #\0)))
557 (setf len (length str)))
558 (values str
560 (char= (aref str 0) #\.)
561 (char= (aref str (1- (length str))) #\.)
563 0)))))
564 (let* ((n (1+ (exponent-value arg)))
565 (orig-d d))
566 ;; Default d if omitted. The procedure is taken directly from
567 ;; the definition given in the manual (CLHS 22.3.3.3), and is
568 ;; not very efficient, since we generate the digits twice.
569 ;; Future maintainers are encouraged to improve on this.
571 ;; It's also not very clear whether q in the spec is the
572 ;; number of significant digits or not. I (rtoy) think it
573 ;; makes more sense if q is the number of significant digits.
574 ;; That way 1d300 isn't printed as 1 followed by 300 zeroes.
575 ;; Exponential notation would be used instead.
576 (unless d
577 (let* ((q (1- (nth-value 1 (bfloat-to-string arg nil)))))
578 (setq d (max q (min n 7)))))
579 (let* ((ee (if e (+ e 2) 4))
580 (ww (if w (- w ee) nil))
581 (dd (- d n)))
582 #+(or)
583 (progn
584 (format t "d = ~A~%" d)
585 (format t "ee = ~A~%" ee)
586 (format t "ww = ~A~%" ww)
587 (format t "dd = ~A~%" dd)
588 (format t "n = ~A~%" n))
589 (cond ((<= 0 dd d)
590 ;; Use dd fraction digits, even if that would cause
591 ;; the width to be exceeded. We choose accuracy over
592 ;; width in this case.
593 (let* ((fill-char (if (bfloat-format-f stream arg nil atsign
597 ovf pad)
599 #\space)))
600 (dotimes (i ee) (write-char fill-char stream))))
602 (bfloat-format-e stream arg nil atsign
604 orig-d
605 e (or k 1)
606 ovf pad exponentchar)))))))
608 ;; Tells you if you have a bigfloat object. BUT, if it is a bigfloat,
609 ;; it will normalize it by making the precision of the bigfloat match
610 ;; the current precision setting in fpprec. And it will also convert
611 ;; bogus zeroes (mantissa is zero, but exponent is not) to a true
612 ;; zero.
613 (defun bigfloatp (x)
614 ;; A bigfloat object looks like '((bigfloat simp <prec>) <mantissa> <exp>)
615 ;; Note bene that the simp flag is optional -- don't count on its presence.
616 (prog (x-prec)
617 (cond ((not ($bfloatp x)) (return nil))
618 ((= fpprec (setq x-prec (bigfloat-prec x)))
619 ;; Precision matches. (Should we fix up bogus bigfloat
620 ;; zeros?)
621 (return x))
622 ((> fpprec x-prec)
623 ;; Current precision is higher than bigfloat precision.
624 ;; Scale up mantissa and adjust exponent to get the
625 ;; correct precision.
626 (setq x (bcons (list (fpshift (cadr x) (- fpprec x-prec))
627 (caddr x)))))
629 ;; Current precision is LOWER than bigfloat precision.
630 ;; Round the number to the desired precision.
631 (setq x (bcons (list (fpround (cadr x))
632 (+ (caddr x) *m fpprec (- x-prec)))))))
633 ;; Fix up any bogus zeros that we might have created.
634 (return (if (equal (cadr x) 0) (bcons (list 0 0)) x))))
636 (defun bigfloat2rat (x)
637 (setq x (bigfloatp x))
638 (let (($float2bf t)
639 (exp nil)
640 (y nil)
641 (sign nil))
642 (setq exp (cond ((minusp (cadr x))
643 (setq sign t
644 y (fpration1 (cons (car x) (fpabs (cdr x)))))
645 (rplaca y (* -1 (car y))))
646 (t (fpration1 x))))
647 (when $ratprint
648 (princ "`rat' replaced ")
649 (when sign (princ "-"))
650 (princ (maknam (fpformat (cons (car x) (fpabs (cdr x))))))
651 (princ " by ")
652 (princ (car exp))
653 (write-char #\/)
654 (princ (cdr exp))
655 (princ " = ")
656 (setq x ($bfloat (list '(rat simp) (car exp) (cdr exp))))
657 (when sign (princ "-"))
658 (princ (maknam (fpformat (cons (car x) (fpabs (cdr x))))))
659 (terpri)
660 (finish-output))
661 exp))
663 (defun fpration1 (x)
664 (let ((fprateps (cdr ($bfloat (if $bftorat
665 (list '(rat simp) 1 (exptrl 2 (1- fpprec)))
666 $ratepsilon)))))
667 (or (and (equal x bigfloatzero) (cons 0 1))
668 (prog (y a)
669 (return (do ((xx x (setq y (invertbigfloat
670 (bcons (fpdifference (cdr xx) (cdr ($bfloat a)))))))
671 (num (setq a (fpentier x))
672 (+ (* (setq a (fpentier y)) num) onum))
673 (den 1 (+ (* a den) oden))
674 (onum 1 num)
675 (oden 0 den))
676 ((and (not (zerop den))
677 (not (fpgreaterp
678 (fpabs (fpquotient
679 (fpdifference (cdr x)
680 (fpquotient (cdr ($bfloat num))
681 (cdr ($bfloat den))))
682 (cdr x)))
683 fprateps)))
684 (cons num den))))))))
686 (defun float-nan-p (x)
687 (and (floatp x) (not (= x x))))
689 (defun float-inf-p (x)
690 (and (floatp x) (not (float-nan-p x)) (beyond-extreme-values x)))
692 (defun beyond-extreme-values (x)
693 (multiple-value-bind (most-negative most-positive) (extreme-float-values x)
694 (cond
695 ((< x 0) (< x most-negative))
696 ((> x 0) (> x most-positive))
697 (t nil))))
699 (defun extreme-float-values (x)
700 ;; BLECHH, I HATE ENUMERATING CASES. IS THERE A BETTER WAY ??
701 (typecase x ;gcl returns an atomic list type with type-of
702 (short-float (values most-negative-short-float most-positive-short-float))
703 (single-float (values most-negative-single-float most-positive-single-float))
704 (double-float (values most-negative-double-float most-positive-double-float))
705 (long-float (values most-negative-long-float most-positive-long-float))
706 ;; NOT SURE THE FOLLOWING REALLY WORKS
707 ;; #+(and cmu double-double)
708 ;; (kernel:double-double-float
709 ;; (values most-negative-double-double-float most-positive-double-double-float))
712 ;; Convert a floating point number into a bigfloat.
713 (defun floattofp (x)
714 (if (float-nan-p x)
715 (merror (intl:gettext "bfloat: attempted conversion of floating point NaN (not-a-number).~%")))
716 (if (float-inf-p x)
717 (merror (intl:gettext "bfloat: attempted conversion of floating-point infinity.~%")))
718 (unless $float2bf
719 (let ((p (float-precision x)))
720 (if (< fpprec p)
721 (mtell (intl:gettext "bfloat: converting float ~S to bigfloat.~%") x))))
723 ;; Need to check for zero because different lisps return different
724 ;; values for integer-decode-float of a 0. In particular CMUCL
725 ;; returns 0, -1075. A bigfloat zero needs to have an exponent and
726 ;; mantissa of zero.
727 (if (zerop x)
728 (list 0 0)
729 (multiple-value-bind (frac exp sign)
730 (integer-decode-float x)
731 ;; Scale frac to the desired number of bits, and adjust the
732 ;; exponent accordingly.
733 (let ((scale (- fpprec (integer-length frac))))
734 (list (ash (* sign frac) scale)
735 (+ fpprec (- exp scale)))))))
737 ;; Convert a bigfloat into a floating point number.
738 (defun fp2flo (l)
739 (let ((precision (bigfloat-prec l))
740 (mantissa (cadr l))
741 (exponent (caddr l))
742 (fpprec machine-mantissa-precision)
743 (*m 0))
744 ;; Round the mantissa to the number of bits of precision of the
745 ;; machine, and then convert it to a floating point fraction. We
746 ;; have 0.5 <= mantissa < 1
747 (setq mantissa (quotient (fpround mantissa) (expt 2.0 machine-mantissa-precision)))
748 ;; Multiply the mantissa by the exponent portion. I'm not sure
749 ;; why the exponent computation is so complicated.
751 ;; GCL doesn't signal overflow from scale-float if the number
752 ;; would overflow. We have to do it this way. 0.5 <= mantissa <
753 ;; 1. The largest double-float is .999999 * 2^1024. So if the
754 ;; exponent is 1025 or higher, we have an overflow.
755 (let ((e (+ exponent (- precision) *m machine-mantissa-precision)))
756 (if (>= e 1025)
757 (merror (intl:gettext "float: floating point overflow converting ~:M") l)
758 (scale-float mantissa e)))))
760 ;; New machine-independent version of FIXFLOAT. This may be buggy. - CWH
761 ;; It is buggy! On the PDP10 it dies on (RATIONALIZE -1.16066076E-7)
762 ;; which calls FLOAT on some rather big numbers. ($RATEPSILON is approx.
763 ;; 7.45E-9) - JPG
765 (defun fixfloat (x)
766 (let (($ratepsilon (expt 2.0 (- machine-mantissa-precision))))
767 (maxima-rationalize x)))
769 ;; Takes a flonum arg and returns a rational number corresponding to the flonum
770 ;; in the form of a dotted pair of two integers. Since the denominator will
771 ;; always be a positive power of 2, this number will not always be in lowest
772 ;; terms.
774 (defun bcons (s)
775 `((bigfloat simp ,fpprec) . ,s))
777 (defmfun $bfloat (x)
778 (let (y)
779 (cond ((bigfloatp x))
780 ((or (numberp x)
781 (member x '($%e $%pi $%gamma) :test #'eq))
782 (bcons (intofp x)))
783 ((or (atom x) (member 'array (cdar x) :test #'eq))
784 (if (eq x '$%phi)
785 ($bfloat '((mtimes simp)
786 ((rat simp) 1 2)
787 ((mplus simp) 1 ((mexpt simp) 5 ((rat simp) 1 2)))))
789 ((eq (caar x) 'mexpt)
790 (if (equal (cadr x) '$%e)
791 (*fpexp ($bfloat (caddr x)))
792 (exptbigfloat ($bfloat (cadr x)) (caddr x))))
793 ((eq (caar x) 'mncexpt)
794 (list '(mncexpt) ($bfloat (cadr x)) (caddr x)))
795 ((eq (caar x) 'rat)
796 (ratbigfloat (cdr x)))
797 ((setq y (safe-get (caar x) 'floatprog))
798 (funcall y (mapcar #'$bfloat (cdr x))))
799 ((or (trigp (caar x)) (arcp (caar x)) (eq (caar x) '$entier))
800 (setq y ($bfloat (cadr x)))
801 (if ($bfloatp y)
802 (cond ((eq (caar x) '$entier) ($entier y))
803 ((arcp (caar x))
804 (setq y ($bfloat (logarc (caar x) y)))
805 (if (free y '$%i)
806 y (let ($ratprint) (fparcsimp ($rectform y)))))
807 ((member (caar x) '(%cot %sec %csc) :test #'eq)
808 (invertbigfloat
809 ($bfloat (list (ncons (safe-get (caar x) 'recip)) y))))
810 (t ($bfloat (exponentialize (caar x) y))))
811 (subst0 (list (ncons (caar x)) y) x)))
812 (t (recur-apply #'$bfloat x)))))
814 (defprop mplus addbigfloat floatprog)
815 (defprop mtimes timesbigfloat floatprog)
816 (defprop %sin sinbigfloat floatprog)
817 (defprop %cos cosbigfloat floatprog)
818 (defprop rat ratbigfloat floatprog)
819 (defprop %atan atanbigfloat floatprog)
820 (defprop %tan tanbigfloat floatprog)
821 (defprop %log logbigfloat floatprog)
822 (defprop mabs mabsbigfloat floatprog)
824 (defun addbigfloat (h)
825 (prog (fans tst r nfans)
826 (setq fans (setq tst bigfloatzero) nfans 0)
827 (do ((l h (cdr l)))
828 ((null l))
829 (cond ((setq r (bigfloatp (car l)))
830 (setq fans (bcons (fpplus (cdr r) (cdr fans)))))
831 (t (setq nfans (list '(mplus) (car l) nfans)))))
832 (return (cond ((equal nfans 0) fans)
833 ((equal fans tst) nfans)
834 (t (simplify (list '(mplus) fans nfans)))))))
836 (defun ratbigfloat (r)
837 ;; R is a Maxima ratio, represented as a list of the numerator and
838 ;; denominator. FLOAT-RATIO doesn't like it if the numerator is 0,
839 ;; so handle that here.
840 (if (zerop (car r))
841 (bcons (list 0 0))
842 (bcons (float-ratio r))))
844 ;; This is borrowed from CMUCL (float-ratio-float), and modified for
845 ;; converting ratios to Maxima's bfloat numbers.
846 (defun float-ratio (x)
847 (let* ((signed-num (first x))
848 (plusp (plusp signed-num))
849 (num (if plusp signed-num (- signed-num)))
850 (den (second x))
851 (digits fpprec)
852 (scale 0))
853 (declare (fixnum digits scale))
855 ;; Strip any trailing zeros from the denominator and move it into the scale
856 ;; factor (to minimize the size of the operands.)
857 (let ((den-twos (1- (integer-length (logxor den (1- den))))))
858 (declare (fixnum den-twos))
859 (decf scale den-twos)
860 (setq den (ash den (- den-twos))))
862 ;; Guess how much we need to scale by from the magnitudes of the numerator
863 ;; and denominator. We want one extra bit for a guard bit.
864 (let* ((num-len (integer-length num))
865 (den-len (integer-length den))
866 (delta (- den-len num-len))
867 (shift (1+ (the fixnum (+ delta digits))))
868 (shifted-num (ash num shift)))
869 (declare (fixnum delta shift))
870 (decf scale delta)
871 (labels ((float-and-scale (bits)
872 (let* ((bits (ash bits -1))
873 (len (integer-length bits)))
874 (cond ((> len digits)
875 (assert (= len (the fixnum (1+ digits))))
876 (multiple-value-bind (f0)
877 (floatit (ash bits -1))
878 (list (first f0) (+ (second f0)
879 (1+ scale)))))
881 (multiple-value-bind (f0)
882 (floatit bits)
883 (list (first f0) (+ (second f0) scale)))))))
884 (floatit (bits)
885 (let ((sign (if plusp 1 -1)))
886 (list (* sign bits) 0))))
887 (loop
888 (multiple-value-bind (fraction-and-guard rem)
889 (truncate shifted-num den)
890 (let ((extra (- (integer-length fraction-and-guard) digits)))
891 (declare (fixnum extra))
892 (cond ((/= extra 1)
893 (assert (> extra 1)))
894 ((oddp fraction-and-guard)
895 (return
896 (if (zerop rem)
897 (float-and-scale
898 (if (zerop (logand fraction-and-guard 2))
899 fraction-and-guard
900 (1+ fraction-and-guard)))
901 (float-and-scale (1+ fraction-and-guard)))))
903 (return (float-and-scale fraction-and-guard)))))
904 (setq shifted-num (ash shifted-num -1))
905 (incf scale)))))))
907 (defun decimalsin (x)
908 (do ((i (quotient (* 59. x) 196.) (1+ i))) ;log[10](2)=.301029
909 (nil)
910 (when (> (integer-length (expt 10. i)) x)
911 (return (1- i)))))
913 (defun atanbigfloat (x)
914 (*fpatan (car x) (cdr x)))
916 (defun *fpatan (a y)
917 (fpend (let ((fpprec (+ 8. fpprec)))
918 (if (null y)
919 (if ($bfloatp a) (fpatan (cdr ($bfloat a)))
920 (list '(%atan) a))
921 (fpatan2 (cdr ($bfloat a)) (cdr ($bfloat (car y))))))))
923 ;; Bigfloat atan
924 (defun fpatan (x)
925 (prog (term x2 ans oans one two tmp)
926 (setq one (intofp 1) two (intofp 2))
927 (cond ((fpgreaterp (fpabs x) one)
928 ;; |x| > 1.
930 ;; Use A&S 4.4.5:
931 ;; atan(x) + acot(x) = +/- pi/2 (+ for x >= 0, - for x < 0)
933 ;; and A&S 4.4.8
934 ;; acot(z) = atan(1/z)
935 (setq tmp (fpquotient (fppi) two))
936 (setq ans (fpdifference tmp (fpatan (fpquotient one x))))
937 (return (cond ((fplessp x (intofp 0))
938 (fpdifference ans (fppi)))
939 (t ans))))
940 ((fpgreaterp (fpabs x) (fpquotient one two))
941 ;; |x| > 1/2
943 ;; Use A&S 4.4.42, third formula:
945 ;; atan(z) = z/(1+z^2)*[1 + 2/3*r + (2*4)/(3*5)*r^2 + ...]
947 ;; r = z^2/(1+z^2)
948 (setq tmp (fpquotient x (fpplus (fptimes* x x) one)))
949 (setq x2 (fptimes* x tmp) term (setq ans one))
950 (do ((n 0 (1+ n)))
951 ((equal ans oans))
952 (setq term
953 (fptimes* term (fptimes* x2 (fpquotient
954 (intofp (+ 2 (* 2 n)))
955 (intofp (+ (* 2 n) 3))))))
956 (setq oans ans ans (fpplus term ans)))
957 (setq ans (fptimes* tmp ans)))
959 ;; |x| <= 1/2. Use Taylor series (A&S 4.4.42, first
960 ;; formula).
961 (setq ans x x2 (fpminus (fptimes* x x)) term x)
962 (do ((n 3 (+ n 2)))
963 ((equal ans oans))
964 (setq term (fptimes* term x2))
965 (setq oans ans
966 ans (fpplus ans (fpquotient term (intofp n)))))))
967 (return ans)))
969 ;; atan(y/x) taking into account the quadrant. (Also equal to
970 ;; arg(x+%i*y).)
971 (defun fpatan2 (y x)
972 (cond ((equal (car x) 0)
973 ;; atan(y/0) = atan(inf), but what sign?
974 (cond ((equal (car y) 0)
975 (merror (intl:gettext "atan2: atan2(0, 0) is undefined.")))
976 ((minusp (car y))
977 ;; We're on the negative imaginary axis, so -pi/2.
978 (fpquotient (fppi) (intofp -2)))
980 ;; The positive imaginary axis, so +pi/2
981 (fpquotient (fppi) (intofp 2)))))
982 ((signp g (car x))
983 ;; x > 0. atan(y/x) is the correct value.
984 (fpatan (fpquotient y x)))
985 ((signp g (car y))
986 ;; x < 0, and y > 0. We're in quadrant II, so the angle we
987 ;; want is pi+atan(y/x).
988 (fpplus (fppi) (fpatan (fpquotient y x))))
990 ;; x <= 0 and y <= 0. We're in quadrant III, so the angle we
991 ;; want is atan(y/x)-pi.
992 (fpdifference (fpatan (fpquotient y x)) (fppi)))))
994 (defun tanbigfloat (a)
995 (setq a (car a))
996 (fpend (let ((fpprec (+ 8. fpprec)))
997 (cond (($bfloatp a)
998 (setq a (cdr ($bfloat a)))
999 (fpquotient (fpsin a t) (fpsin a nil)))
1000 (t (list '(%tan) a))))))
1002 ;; Returns a list of a mantissa and an exponent.
1003 (defun intofp (l)
1004 (cond ((not (atom l)) ($bfloat l))
1005 ((floatp l) (floattofp l))
1006 ((equal 0 l) '(0 0))
1007 ((eq l '$%pi) (fppi))
1008 ((eq l '$%e) (fpe))
1009 ((eq l '$%gamma) (fpgamma))
1010 (t (list (fpround l) (+ *m fpprec)))))
1012 ;; It seems to me that this function gets called on an integer
1013 ;; and returns the mantissa portion of the mantissa/exponent pair.
1015 ;; "STICKY BIT" CALCULATION FIXED 10/14/75 --RJF
1016 ;; BASE must not get temporarily bound to NIL by being placed
1017 ;; in a PROG list as this will confuse stepping programs.
1019 (defun fpround (l &aux (*print-base* 10.) *print-radix*)
1020 (prog (adjust)
1021 (cond
1022 ((null *decfp)
1023 ;;*M will be positive if the precision of the argument is greater than
1024 ;;the current precision being used.
1025 (setq *m (- (integer-length l) fpprec))
1026 (when (= *m 0)
1027 (setq *cancelled 0)
1028 (return l))
1029 ;;FPSHIFT is essentially LSH.
1030 (setq adjust (fpshift 1 (1- *m)))
1031 (when (minusp l) (setq adjust (- adjust)))
1032 (incf l adjust)
1033 (setq *m (- (integer-length l) fpprec))
1034 (setq *cancelled (abs *m))
1035 (cond ((zerop (hipart l (- *m)))
1036 ;ONLY ZEROES SHIFTED OFF
1037 (return (fpshift (fpshift l (- -1 *m))
1038 1))) ; ROUND TO MAKE EVEN
1039 (t (return (fpshift l (- *m))))))
1041 (setq *m (- (flatsize (abs l)) fpprec))
1042 (setq adjust (fpshift 1 (1- *m)))
1043 (when (minusp l) (setq adjust (- adjust)))
1044 (setq adjust (* 5 adjust))
1045 (setq *m (- (flatsize (abs (setq l (+ l adjust)))) fpprec))
1046 (return (fpshift l (- *m)))))))
1048 ;; Compute (* L (expt d n)) where D is 2 or 10 depending on
1049 ;; *decfp. Throw away an fractional part by truncating to zero.
1050 (defun fpshift (l n)
1051 (cond ((null *decfp)
1052 (cond ((and (minusp n) (minusp l))
1053 ;; Left shift of negative number requires some
1054 ;; care. (That is, (truncate l (expt 2 n)), but use
1055 ;; shifts instead.)
1056 (- (ash (- l) n)))
1058 (ash l n))))
1059 ((> n 0)
1060 (* l (expt 10. n)))
1061 ((< n 0.)
1062 (quotient l (expt 10. (- n))))
1063 (t l)))
1065 ;; Bignum LSH -- N is assumed (and declared above) to be a fixnum.
1066 ;; This isn't really LSH, since the sign bit isn't propagated when
1067 ;; shifting to the right, i.e. (BIGLSH -100 -3) = -40, whereas
1068 ;; (LSH -100 -3) = 777777777770 (on a 36 bit machine).
1069 ;; This actually computes (* X (EXPT 2 N)). As of 12/21/80, this function
1070 ;; was only called by FPSHIFT. I would like to hear an argument as why this
1071 ;; is more efficient than simply writing (* X (EXPT 2 N)). Is the
1072 ;; intermediate result created by (EXPT 2 N) the problem? I assume that
1073 ;; EXPT tries to LSH when possible.
1075 (defun biglsh (x n)
1076 (cond ((and (not (bignump x))
1077 (< n #.(- +machine-fixnum-precision+)))
1079 ;; Either we are shifting a fixnum to the right, or shifting
1080 ;; a fixnum to the left, but not far enough left for it to become
1081 ;; a bignum.
1082 ((and (not (bignump x))
1083 (or (<= n 0)
1084 (< (+ (integer-length x) n) #.+machine-fixnum-precision+)))
1085 ;; The form which follows is nearly identical to (ASH X N), however
1086 ;; (ASH -100 -20) = -1, whereas (BIGLSH -100 -20) = 0.
1087 (if (>= x 0)
1088 (ash x n)
1089 (- (biglsh (- x) n)))) ;(- x) may be a bignum even is x is a fixnum.
1090 ;; If we get here, then either X is a bignum or our answer is
1091 ;; going to be a bignum.
1092 ((< n 0)
1093 (cond ((> (abs n) (integer-length x)) 0)
1094 ((> x 0)
1095 (hipart x (+ (integer-length x) n)))
1096 (t (- (hipart x (+ (integer-length x) n))))))
1097 ((= n 0) x)
1098 ;; Isn't this the kind of optimization that compilers are
1099 ;; supposed to make?
1100 ((< n #.(1- +machine-fixnum-precision+)) (* x (ash 1 n)))
1101 (t (* x (expt 2 n)))))
1104 ;; exp(x)
1106 ;; For negative x, use exp(-x) = 1/exp(x)
1108 ;; For x > 0, exp(x) = exp(r+y) = exp(r) * exp(y), where x = r + y and
1109 ;; r = floor(x).
1110 (defun fpexp (x)
1111 (prog (r s)
1112 (unless (signp ge (car x))
1113 (return (fpquotient (fpone) (fpexp (fpabs x)))))
1114 (setq r (fpintpart x :skip-exponent-check-p t))
1115 (return (cond ((< r 2)
1116 (fpexp1 x))
1118 (setq s (fpexp1 (fpdifference x (intofp r))))
1119 (fptimes* s
1120 (cdr (bigfloatp
1121 (let ((fpprec (+ fpprec (integer-length r) -1))
1122 (r r))
1123 (bcons (fpexpt (fpe) r))))))))))) ; patch for full precision %E
1125 ;; exp(x) for small x, using Taylor series.
1126 (defun fpexp1 (x)
1127 (prog (term ans oans)
1128 (setq ans (setq term (fpone)))
1129 (do ((n 1 (1+ n)))
1130 ((equal ans oans))
1131 (setq term (fpquotient (fptimes* x term) (intofp n)))
1132 (setq oans ans)
1133 (setq ans (fpplus ans term)))
1134 (return ans)))
1136 ;; Does one higher precision to round correctly.
1137 ;; A and B are each a list of a mantissa and an exponent.
1138 (defun fpquotient (a b)
1139 (cond ((equal (car b) 0)
1140 (merror (intl:gettext "pquotient: attempted quotient by zero.")))
1141 ((equal (car a) 0) '(0 0))
1142 (t (list (fpround (quotient (fpshift (car a) (+ 3 fpprec)) (car b)))
1143 (+ -3 (- (cadr a) (cadr b)) *m)))))
1145 (defun fpgreaterp (a b)
1146 (fpposp (fpdifference a b)))
1148 (defun fplessp (a b)
1149 (fpposp (fpdifference b a)))
1151 (defun fpposp (x)
1152 (> (car x) 0))
1154 (defun fpmin (arg1 &rest args)
1155 (let ((min arg1))
1156 (mapc #'(lambda (u) (if (fplessp u min) (setq min u))) args)
1157 min))
1159 (defun fpmax (arg1 &rest args)
1160 (let ((max arg1))
1161 (mapc #'(lambda (u) (if (fpgreaterp u max) (setq max u))) args)
1162 max))
1164 ;; The following functions compute bigfloat values for %e, %pi,
1165 ;; %gamma, and log(2). For each precision, the computed value is
1166 ;; cached in a hash table so it doesn't need to be computed again.
1167 ;; There are functions to return the hash table or clear the hash
1168 ;; table, for debugging.
1170 ;; Note that each of these return a bigfloat number, but without the
1171 ;; bigfloat tag.
1173 ;; See
1174 ;; https://sourceforge.net/p/maxima/bugs/1842/
1175 ;; for an explanation.
1176 (let ((table (make-hash-table)))
1177 (defun fpe ()
1178 (let ((value (gethash fpprec table)))
1179 (if value
1180 value
1181 (setf (gethash fpprec table) (cdr (fpe1))))))
1182 (defun fpe-table ()
1183 table)
1184 (defun clear_fpe_table ()
1185 (clrhash table)))
1187 (let ((table (make-hash-table)))
1188 (defun fppi ()
1189 (let ((value (gethash fpprec table)))
1190 (if value
1191 value
1192 (setf (gethash fpprec table) (cdr (fppi1))))))
1193 (defun fppi-table ()
1194 table)
1195 (defun clear_fppi_table ()
1196 (clrhash table)))
1198 (let ((table (make-hash-table)))
1199 (defun fpgamma ()
1200 (let ((value (gethash fpprec table)))
1201 (if value
1202 value
1203 (setf (gethash fpprec table) (cdr (fpgamma1))))))
1204 (defun fpgamma-table ()
1205 table)
1206 (defun clear_fpgamma_table ()
1207 (clrhash table)))
1209 (let ((table (make-hash-table)))
1210 (defun fplog2 ()
1211 (let ((value (gethash fpprec table)))
1212 (if value
1213 value
1214 (setf (gethash fpprec table) (comp-log2)))))
1215 (defun fplog2-table ()
1216 table)
1217 (defun clear_fplog2_table ()
1218 (clrhash table)))
1220 ;; This doesn't need a hash table because there's never a problem with
1221 ;; using a high precision value and rounding to a lower precision
1222 ;; value because 1 is always an exact bfloat.
1223 (defun fpone ()
1224 (cond (*decfp (intofp 1))
1225 ((= fpprec (bigfloat-prec bigfloatone)) (cdr bigfloatone))
1226 (t (intofp 1))))
1228 ;;----------------------------------------------------------------------------;;
1230 ;; The values of %e, %pi, %gamma and log(2) are computed by the technique of
1231 ;; binary splitting. See http://www.ginac.de/CLN/binsplit.pdf for details.
1233 ;; Volker van Nek, Sept. 2014
1236 ;; Euler's number E
1238 (defun fpe1 ()
1239 (let ((e (compe (+ fpprec 12)))) ;; compute additional bits
1240 (bcons (list (fpround (car e)) (cadr e))) )) ;; round to fpprec
1242 ;; Taylor: %e = sum(s[i] ,i,0,inf) where s[i] = 1/i!
1244 (defun compe (prec)
1245 (let ((fpprec prec))
1246 (multiple-value-bind (tt qq) (split-taylor-e 0 (taylor-e-size prec))
1247 (fpquotient (intofp tt) (intofp qq)) )))
1249 ;; binary splitting:
1251 ;; 1
1252 ;; s[i] = ----------------------
1253 ;; q[0]*q[1]*q[2]*..*q[i]
1255 ;; where q[0] = 1
1256 ;; q[i] = i
1258 (defun split-taylor-e (i j)
1259 (let (qq tt)
1260 (if (= (- j i) 1)
1261 (setq qq (if (= i 0) 1 i)
1262 tt 1 )
1263 (let ((m (ash (+ i j) -1)))
1264 (multiple-value-bind (tl ql) (split-taylor-e i m)
1265 (multiple-value-bind (tr qr) (split-taylor-e m j)
1266 (setq qq (* ql qr)
1267 tt (+ (* qr tl) tr) )))))
1268 (values tt qq) ))
1270 ;; stop when i! > 2^fpprec
1272 ;; log(i!) = sum(log(k), k,1,i) > fpprec * log(2)
1274 (defun taylor-e-size (prec)
1275 (let ((acc 0)
1276 (lim (* prec (log 2))) )
1277 (do ((i 1 (1+ i)))
1278 ((> acc lim) i)
1279 (incf acc (log i)) )))
1281 ;;----------------------------------------------------------------------------;;
1283 ;; PI
1285 (defun fppi1 ()
1286 (let ((pi1 (comppi (+ fpprec 10))))
1287 (bcons (list (fpround (car pi1)) (cadr pi1))) ))
1289 ;; Chudnovsky & Chudnovsky:
1291 ;; C^(3/2)/(12*%pi) = sum(s[i], i,0,inf),
1293 ;; where s[i] = (-1)^i*(6*i)!*(A*i+B) / (i!^3*(3*i)!*C^(3*i))
1295 ;; and A = 545140134, B = 13591409, C = 640320
1297 (defun comppi (prec)
1298 (let ((fpprec prec)
1299 nr n d oldn tt qq n*qq )
1300 ;; STEP 1:
1301 ;; compute n/d = sqrt(10005) :
1303 ;; n[0] n[i+1] = n[i]^2+a*d[i]^2 n[inf]
1304 ;; quadratic Heron: x[0] = ----, , sqrt(a) = ------
1305 ;; d[0] d[i+1] = 2*n[i]*d[i] d[inf]
1307 (multiple-value-setq (nr n d) (sqrt-10005-constants fpprec))
1308 (dotimes (i nr)
1309 (setq oldn n
1310 n (+ (* n n) (* 10005 d d))
1311 d (* 2 oldn d) ))
1312 ;; STEP 2:
1313 ;; divide C^(3/2)/12 = 3335*2^7*sqrt(10005)
1314 ;; by Chudnovsky-sum = tt/qq :
1316 (setq nr (ceiling (* fpprec 0.021226729578153))) ;; nr of summands
1317 ;; fpprec*log(2)/log(C^3/(24*6*2*6))
1318 (multiple-value-setq (tt qq) (split-chudnovsky 0 (1+ nr)))
1319 (setq n (* 3335 n)
1320 n*qq (intofp (* n qq)) )
1321 (fpquotient (list (car n*qq) (+ (cadr n*qq) 7))
1322 (intofp (* d tt)) )))
1324 ;; The returned n and d serve as start values for the iteration.
1325 ;; n/d = sqrt(10005) with a precision of p = ceiling(prec/2^nr) bits
1326 ;; where nr is the number of needed iterations.
1328 (defun sqrt-10005-constants (prec)
1329 (let (ilen p nr n d)
1330 (if (< prec 128)
1331 (setq nr 0 p prec)
1332 (setq ilen (integer-length prec)
1333 nr (- ilen 7)
1334 p (ceiling (* prec (expt 2.0 (- nr)))) ))
1335 (cond
1336 ((<= p 76) (setq n 256192036001 d 2561280120))
1337 ((<= p 89) (setq n 51244811200700 d 512320048001))
1338 ((<= p 102) (setq n 2050048640064001 d 20495363200160))
1339 ((<= p 115) (setq n 410060972824000900 d 4099584960080001))
1340 (t (setq n 16404488961600100001 d 164003893766400200)) )
1341 (values nr n d) ))
1343 ;; binary splitting:
1345 ;; a[i] * p[0]*p[1]*p[2]*..*p[i]
1346 ;; s[i] = -----------------------------
1347 ;; q[0]*q[1]*q[2]*..*q[i]
1349 ;; where a[0] = B
1350 ;; p[0] = q[0] = 1
1351 ;; a[i] = A*i+B
1352 ;; p[i] = - (6*i-5)*(2*i-1)*(6*i-1)
1353 ;; q[i] = C^3/24*i^3
1355 (defun split-chudnovsky (i j)
1356 (let (aa pp/qq pp qq tt)
1357 (if (= (- j i) 1)
1358 (if (= i 0)
1359 (setq aa 13591409 pp 1 qq 1 tt aa)
1360 (setq aa (+ (* i 545140134) 13591409)
1361 pp/qq (/ (* (- 5 (* 6 i)) (- (* 2 i) 1) (- (* 6 i) 1))
1362 10939058860032000 ) ; C^3/24
1363 pp (numerator pp/qq)
1364 qq (* (denominator pp/qq) (expt i 3))
1365 tt (* aa pp) ))
1366 (let ((m (ash (+ i j) -1)))
1367 (multiple-value-bind (tl ql pl) (split-chudnovsky i m)
1368 (multiple-value-bind (tr qr pr) (split-chudnovsky m j)
1369 (setq pp (* pl pr)
1370 qq (* ql qr)
1371 tt (+ (* qr tl) (* pl tr)) )))))
1372 (values tt qq pp) ))
1374 ;;----------------------------------------------------------------------------;;
1376 ;; Euler-Mascheroni constant GAMMA
1378 (defun fpgamma1 ()
1379 (let ((res (comp-bf%gamma (+ fpprec 14))))
1380 (bcons (list (fpround (car res)) (cadr res))) ))
1382 ;; Brent-McMillan algorithm
1384 ;; Let
1385 ;; alpha = 4.970625759544
1387 ;; n > 0 and N-1 >= alpha*n
1389 ;; H(k) = sum(1/i, i,1,k)
1391 ;; S = sum(H(k)*(n^k/k!)^2, k,0,N-1)
1393 ;; I = sum((n^k/k!)^2, k,0,N-1)
1395 ;; T = 1/(4*n)*sum((2*k)!^3/(k!^4*(16*n)^(2*k)), k,0,2*n-1)
1397 ;; and
1398 ;; %gamma = S/I - T/I^2 - log(n)
1400 ;; Then
1401 ;; |%gamma - gamma| < 24 * e^(-8*n)
1403 ;; (Corollary 2, Remark 2, Brent/Johansson http://arxiv.org/pdf/1312.0039v1.pdf)
1405 (defun comp-bf%gamma (prec)
1406 (let* ((fpprec prec)
1407 (n (ceiling (* 1/8 (+ (* prec (log 2.0)) (log 24.0)))))
1408 (n2 (* n n))
1409 (alpha 4.970625759544)
1410 (lim (ceiling (* alpha n)))
1411 sums/sumi ;; S/I
1412 sumi sumi2 ;; I and I^2
1413 sumt/sumi2 ) ;; T/I^2
1414 (multiple-value-bind (vv tt qq dd) (split-gamma-1 1 (1+ lim) n2)
1416 ;; sums = vv/(qq*dd)
1417 ;; sumi = tt/qq
1418 ;; sums/sumi = vv/(qq*dd)*qq/tt = vv/(dd*tt)
1420 (setq sums/sumi (fpquotient (intofp vv) (intofp (* dd tt)))
1421 sumi (fpquotient (intofp tt) (intofp qq))
1422 sumi2 (fptimes* sumi sumi) )
1424 (multiple-value-bind (ttt qqq) (split-gamma-2 0 (* 2 n) (* 32 n2))
1426 ;; sumt = 1/(4*n)*ttt/qqq
1427 ;; sumt/sumi2 = ttt/(4*n*qqq*sumi2)
1429 (setq sumt/sumi2 (fpquotient (intofp ttt)
1430 (fptimes* (intofp (* 4 n qqq)) sumi2) ))
1431 ;; %gamma :
1432 (fpdifference sums/sumi (fpplus sumt/sumi2 (log-n n)) )))))
1434 ;; split S and I simultaneously:
1436 ;; summands I[0] = 1, I[i]/I[i-1] = n^2/i^2
1438 ;; S[0] = 0, S[i]/S[i-1] = n^2/i^2*H(i)/H(i-1)
1440 ;; p[0]*p[1]*p[2]*..*p[i]
1441 ;; I[i] = ----------------------
1442 ;; q[0]*q[1]*q[2]*..*q[i]
1444 ;; where p[0] = n^2
1445 ;; q[0] = 1
1446 ;; p[i] = n^2
1447 ;; q[i] = i^2
1448 ;; c[0] c[1] c[2] c[i]
1449 ;; S[i] = H[i] * I[i], where H[i] = ---- + ---- + ---- + .. + ----
1450 ;; d[0] d[1] d[2] d[i]
1451 ;; and c[0] = 0
1452 ;; d[0] = 1
1453 ;; c[i] = 1
1454 ;; d[i] = i
1456 (defun split-gamma-1 (i j n2)
1457 (let (pp cc dd qq tt vv)
1458 (cond
1459 ((= (- j i) 1)
1460 (if (= i 1) ;; S[0] is 0 -> start with i=1 and add I[0]=1 to tt :
1461 (setq pp n2 cc 1 dd 1 qq 1 tt (1+ n2) vv n2)
1462 (setq pp n2 cc 1 dd i qq (* i i) tt pp vv tt) ))
1464 (let* ((m (ash (+ i j) -1)) tmp)
1465 (multiple-value-bind (vl tl ql dl cl pl) (split-gamma-1 i m n2)
1466 (multiple-value-bind (vr tr qr dr cr pr) (split-gamma-1 m j n2)
1467 (setq pp (* pl pr)
1468 cc (+ (* cl dr) (* dl cr))
1469 dd (* dl dr)
1470 qq (* ql qr)
1471 tmp (* pl tr)
1472 tt (+ (* tl qr) tmp)
1473 vv (+ (* dr (+ (* vl qr) (* cl tmp))) (* dl pl vr)) ))))))
1474 (values vv tt qq dd cc pp) ))
1476 ;; split 4*n*T:
1478 ;; summands T[0] = 1, T[i]/T[i-1] = (2*i-1)^3/(32*i*n^2)
1480 ;; p[0]*p[1]*p[2]*..*p[i]
1481 ;; T[i] = ----------------------
1482 ;; q[0]*q[1]*q[2]*..*q[i]
1484 ;; where p[0] = q[0] = 1
1485 ;; p[i] = (2*i-1)^3
1486 ;; q[i] = 32*i*n^2
1488 (defun split-gamma-2 (i j n2*32)
1489 (let (pp qq tt)
1490 (cond
1491 ((= (- j i) 1)
1492 (if (= i 0)
1493 (setq pp 1 qq 1 tt 1)
1494 (setq pp (expt (1- (* 2 i)) 3) qq (* i n2*32) tt pp) ))
1496 (let* ((m (ash (+ i j) -1)))
1497 (multiple-value-bind (tl ql pl) (split-gamma-2 i m n2*32)
1498 (multiple-value-bind (tr qr pr) (split-gamma-2 m j n2*32)
1499 (setq pp (* pl pr)
1500 qq (* ql qr)
1501 tt (+ (* tl qr) (* pl tr)) ))))))
1502 (values tt qq pp) ))
1504 ;;----------------------------------------------------------------------------;;
1506 ;; log(2) = 18*L(26) - 2*L(4801) + 8*L(8749)
1508 ;; where L(k) = atanh(1/k)
1510 ;; see http://numbers.computation.free.fr/Constants/constants.html
1512 ;;;(defun $log2 () (bcons (comp-log2))) ;; checked against reference table
1514 (defun comp-log2 ()
1515 (let ((res
1516 (let ((fpprec (+ fpprec 12)))
1517 (fpplus
1518 (fpdifference (n*atanh-1/k 18 26) (n*atanh-1/k 2 4801))
1519 (n*atanh-1/k 8 8749) ))))
1520 (list (fpround (car res)) (cadr res)) ))
1522 ;; Taylor: atanh(1/k) = sum(s[i], i,0,inf)
1524 ;; where s[i] = 1/((2*i+1)*k^(2*i+1))
1526 (defun n*atanh-1/k (n k) ;; integer n,k
1527 (let* ((k2 (* k k))
1528 (nr (ceiling (* fpprec (/ (log 2) (log k2))))) )
1529 (multiple-value-bind (tt qq bb) (split-atanh-1/k 0 (1+ nr) k k2)
1530 (fpquotient (intofp (* n tt)) (intofp (* bb qq))) )))
1532 ;; binary splitting:
1533 ;; 1
1534 ;; s[i] = -----------------------------
1535 ;; b[i] * q[0]*q[1]*q[2]*..*q[i]
1537 ;; where b[0] = 1
1538 ;; q[0] = k
1539 ;; b[i] = 2*i+1
1540 ;; q[i] = k^2
1542 (defun split-atanh-1/k (i j k k2)
1543 (let (bb qq tt)
1544 (if (= (- j i) 1)
1545 (if (= i 0)
1546 (setq bb 1 qq k tt 1)
1547 (setq bb (1+ (* 2 i)) qq k2 tt 1) )
1548 (let ((m (ash (+ i j) -1)))
1549 (multiple-value-bind (tl ql bl) (split-atanh-1/k i m k k2)
1550 (multiple-value-bind (tr qr br) (split-atanh-1/k m j k k2)
1551 (setq bb (* bl br)
1552 qq (* ql qr)
1553 tt (+ (* br qr tl) (* bl tr)) )))))
1554 (values tt qq bb) ))
1556 ;;----------------------------------------------------------------------------;;
1558 ;; log(n) = log(n/2^k) + k*log(2)
1560 ;;;(defun $log10 () (bcons (log-n 10))) ;; checked against reference table
1562 (defun log-n (n) ;; integer n > 0
1563 (cond
1564 ((= 1 n) (list 0 0))
1565 ((= 2 n) (comp-log2))
1567 (let ((res
1568 (let ((fpprec (+ fpprec 10))
1569 (k (integer-length n)) )
1570 ;; choose k so that |n/2^k - 1| is as small as possible:
1571 (when (< n (* (coerce 2/3 'flonum) (ash 1 k))) (decf k))
1572 ;; now |n/2^k - 1| <= 1/3
1573 (fpplus (log-u/2^k n k fpprec)
1574 (fptimes* (intofp k) (comp-log2)) ))))
1575 (list (fpround (car res)) (cadr res)) ))))
1577 ;; log(1+u/v) = 2 * sum(s[i], i,0,inf)
1579 ;; where s[i] = (u/(2*v+u))^(2*i+1)/(2*i+1)
1581 (defun log-u/2^k (u k prec) ;; integer u k; x = u/2^k; |x - 1| < 1
1582 (setq u (- u (ash 1 k))) ;; x <-- x - 1
1583 (cond
1584 ((= 0 u) (list 0 0))
1586 (while (evenp u) (setq u (ash u -1)) (decf k))
1587 (let* ((u2 (* u u))
1588 (w (+ u (ash 2 k)))
1589 (w2 (* w w))
1590 (nr (ceiling (* prec (/ (log 2) 2 (log (abs (/ w u)))))))
1591 lg/2 )
1592 (multiple-value-bind (tt qq bb) (split-log-1+u/v 0 (1+ nr) u u2 w w2)
1593 (setq lg/2 (fpquotient (intofp tt) (intofp (* bb qq)))) ;; sum
1594 (list (car lg/2) (1+ (cadr lg/2))) ))))) ;; 2*sum
1596 ;; binary splitting:
1598 ;; p[0]*p[1]*p[2]*..*p[i]
1599 ;; s[i] = -----------------------------
1600 ;; b[i] * q[0]*q[1]*q[2]*..*q[i]
1602 ;; where b[0] = 1
1603 ;; p[0] = u
1604 ;; q[0] = w = 2*v+u
1605 ;; b[i] = 2*i+1
1606 ;; p[i] = u^2
1607 ;; q[i] = w^2
1609 (defun split-log-1+u/v (i j u u2 w w2)
1610 (let (pp bb qq tt)
1611 (if (= (- j i) 1)
1612 (if (= i 0)
1613 (setq pp u bb 1 qq w tt u)
1614 (setq pp u2 bb (1+ (* 2 i)) qq w2 tt pp) )
1615 (let ((m (ash (+ i j) -1)))
1616 (multiple-value-bind (tl ql bl pl) (split-log-1+u/v i m u u2 w w2)
1617 (multiple-value-bind (tr qr br pr) (split-log-1+u/v m j u u2 w w2)
1618 (setq bb (* bl br)
1619 pp (* pl pr)
1620 qq (* ql qr)
1621 tt (+ (* br qr tl) (* bl pl tr)) )))))
1622 (values tt qq bb pp) ))
1624 ;;----------------------------------------------------------------------------;;
1627 (defun fpdifference (a b)
1628 (fpplus a (fpminus b)))
1630 (defun fpminus (x)
1631 (if (equal (car x) 0)
1633 (list (- (car x)) (cadr x))))
1635 (defun fpplus (a b)
1636 (prog (*m exp man sticky)
1637 (setq *cancelled 0)
1638 (cond ((equal (car a) 0) (return b))
1639 ((equal (car b) 0) (return a)))
1640 (setq exp (- (cadr a) (cadr b)))
1641 (setq man (cond ((equal exp 0)
1642 (setq sticky 0)
1643 (fpshift (+ (car a) (car b)) 2))
1644 ((> exp 0)
1645 (setq sticky (hipart (car b) (- 1 exp)))
1646 (setq sticky (cond ((signp e sticky) 0)
1647 ((signp l (car b)) -1)
1648 (t 1)))
1649 ; COMPUTE STICKY BIT
1650 (+ (fpshift (car a) 2)
1651 ; MAKE ROOM FOR GUARD DIGIT & STICKY BIT
1652 (fpshift (car b) (- 2 exp))))
1653 (t (setq sticky (hipart (car a) (1+ exp)))
1654 (setq sticky (cond ((signp e sticky) 0)
1655 ((signp l (car a)) -1)
1656 (t 1)))
1657 (+ (fpshift (car b) 2)
1658 (fpshift (car a) (+ 2 exp))))))
1659 (setq man (+ man sticky))
1660 (return (cond ((equal man 0) '(0 0))
1661 (t (setq man (fpround man))
1662 (setq exp (+ -2 *m (max (cadr a) (cadr b))))
1663 (list man exp))))))
1665 (defun fptimes* (a b)
1666 (if (or (zerop (car a)) (zerop (car b)))
1667 '(0 0)
1668 (list (fpround (* (car a) (car b)))
1669 (+ *m (cadr a) (cadr b) (- fpprec)))))
1671 ;; Don't use the symbol BASE since it is SPECIAL.
1673 (defun fpintexpt (int nn fixprec) ;INT is integer
1674 (setq fixprec (truncate fixprec (1- (integer-length int)))) ;NN is pos
1675 (let ((bas (intofp (expt int (min nn fixprec)))))
1676 (if (> nn fixprec)
1677 (fptimes* (intofp (expt int (rem nn fixprec)))
1678 (fpexpt bas (quotient nn fixprec)))
1679 bas)))
1681 ;; NN is positive or negative integer
1683 (defun fpexpt (p nn)
1684 (cond ((zerop nn) (fpone))
1685 ((eql nn 1) p)
1686 ((< nn 0) (fpquotient (fpone) (fpexpt p (- nn))))
1687 (t (prog (u)
1688 (if (oddp nn)
1689 (setq u p)
1690 (setq u (fpone)))
1691 (do ((ii (quotient nn 2) (quotient ii 2)))
1692 ((zerop ii))
1693 (setq p (fptimes* p p))
1694 (when (oddp ii)
1695 (setq u (fptimes* u p))))
1696 (return u)))))
1698 (defun exptbigfloat (p n)
1699 (cond ((equal n 1) p)
1700 ((equal n 0) ($bfloat 1))
1701 ((not ($bfloatp p)) (list '(mexpt) p n))
1702 ((equal (cadr p) 0) ($bfloat 0))
1703 ((and (< (cadr p) 0) (ratnump n))
1704 (mul2 (let ($numer $float $keepfloat $ratprint)
1705 (power -1 n))
1706 (exptbigfloat (bcons (fpminus (cdr p))) n)))
1707 ((and (< (cadr p) 0) (not (integerp n)))
1708 (cond ((or (equal n 0.5) (equal n bfhalf))
1709 (exptbigfloat p '((rat simp) 1 2)))
1710 ((or (equal n -0.5) (equal n bfmhalf))
1711 (exptbigfloat p '((rat simp) -1 2)))
1712 (($bfloatp (setq n ($bfloat n)))
1713 (cond ((equal n ($bfloat (fpentier n)))
1714 (exptbigfloat p (fpentier n)))
1715 (t ;; for P<0: P^N = (-P)^N*cos(pi*N) + i*(-P)^N*sin(pi*N)
1716 (setq p (exptbigfloat (bcons (fpminus (cdr p))) n)
1717 n ($bfloat `((mtimes) $%pi ,n)))
1718 (add2 ($bfloat `((mtimes) ,p ,(*fpsin n nil)))
1719 `((mtimes simp) ,($bfloat `((mtimes) ,p ,(*fpsin n t)))
1720 $%i)))))
1721 (t (list '(mexpt) p n))))
1722 ((and (ratnump n) (< (caddr n) 10.))
1723 (bcons (fpexpt (fproot p (caddr n)) (cadr n))))
1724 ((not (integerp n))
1725 (setq n ($bfloat n))
1726 (cond
1727 ((not ($bfloatp n)) (list '(mexpt) p n))
1729 (let ((extrabits (max 1 (+ (caddr n) (integer-length (caddr p))))))
1730 (setq p
1731 (let ((fpprec (+ extrabits fpprec)))
1732 (fpexp (fptimes* (cdr (bigfloatp n)) (fplog (cdr (bigfloatp p)))))))
1733 (setq p (list (fpround (car p)) (+ (- extrabits) *m (cadr p))))
1734 (bcons p)))))
1735 ;; The number of extra bits required
1736 ((< n 0) (invertbigfloat (exptbigfloat p (- n))))
1737 (t (bcons (fpexpt (cdr p) n)))))
1739 (defun fproot (a n) ; computes a^(1/n) see Fitch, SIGSAM Bull Nov 74
1741 ;; Special case for a = 0b0. General algorithm loops endlessly in that case.
1743 ;; Unlike many or maybe all of the other functions named FP-something,
1744 ;; FPROOT assumes it is called with an argument like
1745 ;; '((BIGFLOAT ...) FOO BAR) instead of '(FOO BAR).
1746 ;; However FPROOT does return something like '(FOO BAR).
1748 (if (eql (cadr a) 0)
1749 '(0 0)
1750 (progn
1751 (let* ((ofprec fpprec)
1752 (fpprec (+ fpprec 2)) ;assumes a>0 n>=2
1753 (bk (fpexpt (intofp 2) (1+ (quotient (cadr (setq a (cdr (bigfloatp a)))) n)))))
1754 (do ((x bk (fpdifference x
1755 (setq bk (fpquotient (fpdifference
1756 x (fpquotient a (fpexpt x n1))) n))))
1757 (n1 (1- n))
1758 (n (intofp n)))
1759 ((or (equal bk '(0 0))
1760 (> (- (cadr x) (cadr bk)) ofprec))
1761 (setq a x))))
1762 (list (fpround (car a)) (+ -2 *m (cadr a))))))
1764 (defun timesbigfloat (h)
1765 (prog (fans r nfans)
1766 (setq fans (bcons (fpone)) nfans 1)
1767 (do ((l h (cdr l)))
1768 ((null l))
1769 (if (setq r (bigfloatp (car l)))
1770 (setq fans (bcons (fptimes* (cdr r) (cdr fans))))
1771 (setq nfans (list '(mtimes) (car l) nfans))))
1772 (return (if (equal nfans 1)
1773 fans
1774 (simplify (list '(mtimes) fans nfans))))))
1776 (defun invertbigfloat (a)
1777 ;; If A is a bigfloat, be sure to round it to the current precision.
1778 ;; (See Bug 2543079 for one of the symptoms.)
1779 (let ((b (bigfloatp a)))
1780 (if b
1781 (bcons (fpquotient (fpone) (cdr b)))
1782 (simplify (list '(mexpt) a -1)))))
1784 (defun *fpexp (a)
1785 (fpend (let ((fpprec (+ 8. fpprec)))
1786 (if ($bfloatp a)
1787 (fpexp (cdr (bigfloatp a)))
1788 (list '(mexpt) '$%e a)))))
1790 (defun *fpsin (a fl)
1791 (fpend (let ((fpprec (+ 8. fpprec)))
1792 (cond (($bfloatp a) (fpsin (cdr ($bfloat a)) fl))
1793 (fl (list '(%sin) a))
1794 (t (list '(%cos) a))))))
1796 (defun fpend (a)
1797 (cond ((equal (car a) 0) (bcons a))
1798 ((numberp (car a))
1799 (setq a (list (fpround (car a)) (+ -8. *m (cadr a))))
1800 (bcons a))
1801 (t a)))
1803 (defun fparcsimp (e) ; needed for e.g. ASIN(.123567812345678B0) with
1804 ;; FPPREC 16, to get rid of the miniscule imaginary
1805 ;; part of the a+bi answer.
1806 (if (and (mplusp e) (null (cdddr e))
1807 (mtimesp (caddr e)) (null (cdddr (caddr e)))
1808 ($bfloatp (cadr (caddr e)))
1809 (eq (caddr (caddr e)) '$%i)
1810 (< (caddr (cadr (caddr e))) (+ (- fpprec) 2)))
1811 (cadr e)
1814 (defun sinbigfloat (x)
1815 (*fpsin (car x) t))
1817 (defun cosbigfloat (x)
1818 (*fpsin (car x) nil))
1820 ;; THIS VERSION OF FPSIN COMPUTES SIN OR COS TO PRECISION FPPREC,
1821 ;; BUT CHECKS FOR THE POSSIBILITY OF CATASTROPHIC CANCELLATION DURING
1822 ;; ARGUMENT REDUCTION (E.G. SIN(N*%PI+EPSILON))
1823 ;; *FPSINCHECK* WILL CAUSE PRINTOUT OF ADDITIONAL INFO WHEN
1824 ;; EXTRA PRECISION IS NEEDED FOR SIN/COS CALCULATION. KNOWN
1825 ;; BAD FEATURES: IT IS NOT NECESSARY TO USE EXTRA PRECISION FOR, E.G.
1826 ;; SIN(PI/2), WHICH IS NOT NEAR ZERO, BUT EXTRA
1827 ;; PRECISION IS USED SINCE IT IS NEEDED FOR COS(PI/2).
1828 ;; PRECISION SEEMS TO BE 100% SATSIFACTORY FOR LARGE ARGUMENTS, E.G.
1829 ;; SIN(31415926.0B0), BUT LESS SO FOR SIN(3.1415926B0). EXPLANATION
1830 ;; NOT KNOWN. (9/12/75 RJF)
1832 (defvar *fpsincheck* nil)
1834 ;; FL is a T for sin and NIL for cos.
1835 (defun fpsin (x fl)
1836 (prog (piby2 r sign res k *cancelled)
1837 (setq sign (cond (fl (signp g (car x)))
1838 (t))
1839 x (fpabs x))
1840 (when (equal (car x) 0)
1841 (return (if fl (intofp 0) (intofp 1))))
1842 (return
1843 (cdr
1844 (bigfloatp
1845 (let ((fpprec (max fpprec (+ fpprec (cadr x))))
1846 (xt (bcons x))
1847 (*cancelled 0)
1848 (oldprec fpprec))
1849 (prog (x)
1850 loop (setq x (cdr (bigfloatp xt)))
1851 (setq piby2 (fpquotient (fppi) (intofp 2)))
1852 (setq r (fpintpart (fpquotient x piby2) :skip-exponent-check-p t))
1853 (setq x (fpplus x (fptimes* (intofp (- r)) piby2)))
1854 (setq k *cancelled)
1855 (fpplus x (fpminus piby2))
1856 (setq *cancelled (max k *cancelled))
1857 (when *fpsincheck*
1858 (print `(*canc= ,*cancelled fpprec= ,fpprec oldprec= ,oldprec)))
1859 (cond ((not (> oldprec (- fpprec *cancelled)))
1860 (setq r (rem r 4))
1861 (setq res
1862 (cond (fl (cond ((= r 0) (fpsin1 x))
1863 ((= r 1) (fpcos1 x))
1864 ((= r 2) (fpminus (fpsin1 x)))
1865 ((= r 3) (fpminus (fpcos1 x)))))
1866 (t (cond ((= r 0) (fpcos1 x))
1867 ((= r 1) (fpminus (fpsin1 x)))
1868 ((= r 2) (fpminus (fpcos1 x)))
1869 ((= r 3) (fpsin1 x))))))
1870 (return (bcons (if sign res (fpminus res)))))
1872 (incf fpprec *cancelled)
1873 (go loop))))))))))
1875 (defun fpcos1 (x)
1876 (fpsincos1 x nil))
1878 ;; Compute SIN or COS in (0,PI/2). FL is T for SIN, NIL for COS.
1880 ;; Use Taylor series
1881 (defun fpsincos1 (x fl)
1882 (prog (ans term oans x2)
1883 (setq ans (if fl x (intofp 1))
1884 x2 (fpminus(fptimes* x x)))
1885 (setq term ans)
1886 (do ((n (if fl 3 2) (+ n 2)))
1887 ((equal ans oans))
1888 (setq term (fptimes* term (fpquotient x2 (intofp (* n (1- n))))))
1889 (setq oans ans
1890 ans (fpplus ans term)))
1891 (return ans)))
1893 (defun fpsin1(x)
1894 (fpsincos1 x t))
1896 (defun fpabs (x)
1897 (if (signp ge (car x))
1899 (cons (- (car x)) (cdr x))))
1901 (defun fpentier (f)
1902 (let ((fpprec (bigfloat-prec f)))
1903 (fpintpart (cdr f))))
1905 ;; Calculate the integer part of a floating point number that is represented as
1906 ;; a list
1908 ;; (MANTISSA EXPONENT)
1910 ;; The special variable fpprec should be bound to the precision (in bits) of the
1911 ;; number. This encodes how many bits are known of the result and also a right
1912 ;; shift. The pair denotes the number MANTISSA * 2^(EXPONENT - FPPREC), of which
1913 ;; FPPREC bits are known.
1915 ;; If EXPONENT is large and positive then we might not have enough
1916 ;; information to calculate the integer part. Specifically, we only
1917 ;; have enough information if EXPONENT < FPPREC. If that isn't the
1918 ;; case, we signal a Maxima error. However, if SKIP-EXPONENT-CHECK-P
1919 ;; is non-NIL, this check is skipped, and we compute the integer part
1920 ;; as requested.
1922 ;; For the bigfloat code here, skip-exponent-check-p should be true.
1923 ;; For other uses (see commit 576c7508 and bug #2784), this should be
1924 ;; nil, which is the default.
1925 (defun fpintpart (f &key skip-exponent-check-p)
1926 (destructuring-bind (mantissa exponent)
1928 (let ((m (- fpprec exponent)))
1929 (if (plusp m)
1930 (quotient mantissa (expt 2 (- fpprec exponent)))
1931 (if (and (not skip-exponent-check-p) (< exponent fpprec))
1932 (merror "~M doesn't have enough precision to compute its integer part"
1933 `((bigfloat ,fpprec) ,mantissa ,exponent))
1934 (* mantissa (expt 2 (- m))))))))
1936 (defun logbigfloat (a)
1937 (cond (($bfloatp (car a))
1938 (big-float-log ($bfloat (car a))))
1940 (list '(%log) (car a)))))
1943 ;;; Computes the log of a bigfloat number.
1945 ;;; Uses the series
1947 ;;; log(1+x) = sum((x/(x+2))^(2*n+1)/(2*n+1),n,0,inf);
1950 ;;; INF x 2 n + 1
1951 ;;; ==== (-----)
1952 ;;; \ x + 2
1953 ;;; = 2 > --------------
1954 ;;; / 2 n + 1
1955 ;;; ====
1956 ;;; n = 0
1959 ;;; which converges for x > 0.
1961 ;;; Note that FPLOG is given 1+X, not X.
1963 ;;; However, to aid convergence of the series, we scale 1+x until 1/e
1964 ;;; < 1+x <= e.
1966 (defun fplog (x)
1967 (prog (over two ans oldans term e sum)
1968 (unless (> (car x) 0)
1969 (merror (intl:gettext "fplog: argument must be positive; found: ~M") (car x)))
1970 (setq e (fpe)
1971 over (fpquotient (fpone) e)
1972 ans 0)
1973 ;; Scale X until 1/e < X <= E. ANS keeps track of how
1974 ;; many factors of E were used. Set X to NIL if X is E.
1975 (do ()
1976 (nil)
1977 (cond ((equal x e) (setq x nil) (return nil))
1978 ((and (fplessp x e) (fplessp over x))
1979 (return nil))
1980 ((fplessp x over)
1981 (setq x (fptimes* x e))
1982 (decf ans))
1984 (incf ans)
1985 (setq x (fpquotient x e)))))
1986 (when (null x) (return (intofp (1+ ans))))
1987 ;; Prepare X for the series. The series is for 1 + x, so
1988 ;; get x from our X. TERM is (x/(x+2)). X becomes
1989 ;; (x/(x+2))^2.
1990 (setq x (fpdifference x (fpone))
1991 ans (intofp ans))
1992 (setq x (fpexpt (setq term (fpquotient x (fpplus x (setq two (intofp 2))))) 2))
1993 ;; Sum the series until the sum (in ANS) doesn't change
1994 ;; anymore.
1995 (setq sum (intofp 0))
1996 (do ((n 1 (+ n 2)))
1997 ((equal sum oldans))
1998 (setq oldans sum)
1999 (setq sum (fpplus sum (fpquotient term (intofp n))))
2000 (setq term (fptimes* term x)))
2001 (return (fpplus ans (fptimes* two sum)))))
2003 (defun mabsbigfloat (l)
2004 (prog (r)
2005 (setq r (bigfloatp (car l)))
2006 (return (if (null r)
2007 (list '(mabs) (car l))
2008 (bcons (fpabs (cdr r)))))))
2011 ;;;; Bigfloat implementations of special functions.
2012 ;;;;
2014 ;;; This is still a bit messy. Some functions here take bigfloat
2015 ;;; numbers, represented by ((bigfloat) <mant> <exp>), but others want
2016 ;;; just the FP number, represented by (<mant> <exp>). Likewise, some
2017 ;;; return a bigfloat, some return just the FP.
2019 ;;; This needs to be systemized somehow. It isn't helped by the fact
2020 ;;; that some of the routines above also do the samething.
2022 ;;; The implementation for the special functions for a complex
2023 ;;; argument are mostly taken from W. Kahan, "Branch Cuts for Complex
2024 ;;; Elementary Functions or Much Ado About Nothing's Sign Bit", in
2025 ;;; Iserles and Powell (eds.) "The State of the Art in Numerical
2026 ;;; Analysis", pp 165-211, Clarendon Press, 1987
2028 ;; Compute exp(x) - 1, but do it carefully to preserve precision when
2029 ;; |x| is small. X is a FP number, and a FP number is returned. That
2030 ;; is, no bigfloat stuff.
2031 (defun fpexpm1 (x)
2032 ;; What is the right breakpoint here? Is 1 ok? Perhaps 1/e is better?
2033 (cond ((fpgreaterp (fpabs x) (fpone))
2034 ;; exp(x) - 1
2035 (fpdifference (fpexp x) (fpone)))
2037 ;; Use Taylor series for exp(x) - 1
2038 (let ((ans x)
2039 (oans nil)
2040 (term x))
2041 (do ((n 2 (1+ n)))
2042 ((equal ans oans))
2043 (setf term (fpquotient (fptimes* x term) (intofp n)))
2044 (setf oans ans)
2045 (setf ans (fpplus ans term)))
2046 ans))))
2048 ;; log(1+x) for small x. X is FP number, and a FP number is returned.
2049 (defun fplog1p (x)
2050 ;; Use the same series as given above for fplog. For small x we use
2051 ;; the series, otherwise fplog is accurate enough.
2052 (cond ((fpgreaterp (fpabs x) (fpone))
2053 (fplog (fpplus x (fpone))))
2055 (let* ((sum (intofp 0))
2056 (term (fpquotient x (fpplus x (intofp 2))))
2057 (f (fptimes* term term))
2058 (oldans nil))
2059 (do ((n 1 (+ n 2)))
2060 ((equal sum oldans))
2061 (setq oldans sum)
2062 (setq sum (fpplus sum (fpquotient term (intofp n))))
2063 (setq term (fptimes* term f)))
2064 (fptimes* sum (intofp 2))))))
2066 ;; sinh(x) for real x. X is a bigfloat, and a bigfloat is returned.
2067 (defun fpsinh (x)
2068 ;; X must be a maxima bigfloat
2070 ;; See, for example, Hart et al., Computer Approximations, 6.2.27:
2072 ;; sinh(x) = 1/2*(D(x) + D(x)/(1+D(x)))
2074 ;; where D(x) = exp(x) - 1.
2076 ;; But for negative x, use sinh(x) = -sinh(-x) because D(x)
2077 ;; approaches -1 for large negative x.
2078 (cond ((equal 0 (cadr x))
2079 ;; Special case: x=0. Return immediately.
2080 (bigfloatp x))
2081 ((fpposp (cdr x))
2082 ;; x is positive.
2083 (let ((d (fpexpm1 (cdr (bigfloatp x)))))
2084 (bcons (fpquotient (fpplus d (fpquotient d (fpplus d (fpone))))
2085 (intofp 2)))))
2087 ;; x is negative.
2088 (bcons
2089 (fpminus (cdr (fpsinh (bcons (fpminus (cdr (bigfloatp x)))))))))))
2091 (defun big-float-sinh (x &optional y)
2092 ;; The rectform for sinh for complex args should be numerically
2093 ;; accurate, so return nil in that case.
2094 (unless y
2095 (fpsinh x)))
2097 ;; asinh(x) for real x. X is a bigfloat, and a bigfloat is returned.
2098 (defun fpasinh (x)
2099 ;; asinh(x) = sign(x) * log(|x| + sqrt(1+x*x))
2101 ;; And
2103 ;; asinh(x) = x, if 1+x*x = 1
2104 ;; = sign(x) * (log(2) + log(x)), large |x|
2105 ;; = sign(x) * log(2*|x| + 1/(|x|+sqrt(1+x*x))), if |x| > 2
2106 ;; = sign(x) * log1p(|x|+x^2/(1+sqrt(1+x*x))), otherwise.
2108 ;; But I'm lazy right now and we only implement the last 2 cases.
2109 ;; We should implement all cases.
2110 (let* ((fp-x (cdr (bigfloatp x)))
2111 (absx (fpabs fp-x))
2112 (one (fpone))
2113 (two (intofp 2))
2114 (minus (minusp (car fp-x)))
2115 result)
2116 ;; We only use two formulas here. |x| <= 2 and |x| > 2. Should
2117 ;; we add one for very big x and one for very small x, as given above.
2118 (cond ((fpgreaterp absx two)
2119 ;; |x| > 2
2121 ;; log(2*|x| + 1/(|x|+sqrt(1+x^2)))
2122 (setf result (fplog (fpplus (fptimes* absx two)
2123 (fpquotient one
2124 (fpplus absx
2125 (fproot (bcons (fpplus one
2126 (fptimes* absx absx)))
2127 2)))))))
2129 ;; |x| <= 2
2131 ;; log1p(|x|+x^2/(1+sqrt(1+x^2)))
2132 (let ((x*x (fptimes* absx absx)))
2133 (setq result (fplog1p (fpplus absx
2134 (fpquotient x*x
2135 (fpplus one
2136 (fproot (bcons (fpplus one x*x))
2137 2)))))))))
2138 (if minus
2139 (bcons (fpminus result))
2140 (bcons result))))
2142 (defun complex-asinh (x y)
2143 ;; asinh(z) = -%i * asin(%i*z)
2144 (multiple-value-bind (u v)
2145 (complex-asin (mul -1 y) x)
2146 (values v (bcons (fpminus (cdr u))))))
2148 (defun big-float-asinh (x &optional y)
2149 (if y
2150 (multiple-value-bind (u v)
2151 (complex-asinh x y)
2152 (add u (mul '$%i v)))
2153 (fpasinh x)))
2155 (defun fpasin-core (x)
2156 ;; asin(x) = atan(x/(sqrt(1-x^2))
2157 ;; = sgn(x)*[%pi/2 - atan(sqrt(1-x^2)/abs(x))]
2159 ;; Use the first for 0 <= x < 1/2 and the latter for 1/2 < x <= 1.
2161 ;; If |x| > 1, we need to do something else.
2163 ;; asin(x) = -%i*log(sqrt(1-x^2)+%i*x)
2164 ;; = -%i*log(%i*x + %i*sqrt(x^2-1))
2165 ;; = -%i*[log(|x + sqrt(x^2-1)|) + %i*%pi/2]
2166 ;; = %pi/2 - %i*log(|x+sqrt(x^2-1)|)
2168 (let ((fp-x (cdr (bigfloatp x))))
2169 (cond ((minusp (car fp-x))
2170 ;; asin(-x) = -asin(x);
2171 (mul -1 (fpasin (bcons (fpminus fp-x)))))
2172 ((fplessp fp-x (cdr bfhalf))
2173 ;; 0 <= x < 1/2
2174 ;; asin(x) = atan(x/sqrt(1-x^2))
2175 (bcons
2176 (fpatan (fpquotient fp-x
2177 (fproot (bcons
2178 (fptimes* (fpdifference (fpone) fp-x)
2179 (fpplus (fpone) fp-x)))
2180 2)))))
2181 ((fpgreaterp fp-x (fpone))
2182 ;; x > 1
2183 ;; asin(x) = %pi/2 - %i*log(|x+sqrt(x^2-1)|)
2185 ;; Should we try to do something a little fancier with the
2186 ;; argument to log and use log1p for better accuracy?
2187 (let ((arg (fpplus fp-x
2188 (fproot (bcons (fptimes* (fpdifference fp-x (fpone))
2189 (fpplus fp-x (fpone))))
2190 2))))
2191 (add (div '$%pi 2)
2192 (mul -1 '$%i (bcons (fplog arg))))))
2195 ;; 1/2 <= x <= 1
2196 ;; asin(x) = %pi/2 - atan(sqrt(1-x^2)/x)
2197 (add (div '$%pi 2)
2198 (mul -1
2199 (bcons
2200 (fpatan
2201 (fpquotient (fproot (bcons (fptimes* (fpdifference (fpone) fp-x)
2202 (fpplus (fpone) fp-x)))
2204 fp-x)))))))))
2206 ;; asin(x) for real x. X is a bigfloat, and a maxima number (real or
2207 ;; complex) is returned.
2208 (defun fpasin (x)
2209 ;; asin(x) = atan(x/(sqrt(1-x^2))
2210 ;; = sgn(x)*[%pi/2 - atan(sqrt(1-x^2)/abs(x))]
2212 ;; Use the first for 0 <= x < 1/2 and the latter for 1/2 < x <= 1.
2214 ;; If |x| > 1, we need to do something else.
2216 ;; asin(x) = -%i*log(sqrt(1-x^2)+%i*x)
2217 ;; = -%i*log(%i*x + %i*sqrt(x^2-1))
2218 ;; = -%i*[log(|x + sqrt(x^2-1)|) + %i*%pi/2]
2219 ;; = %pi/2 - %i*log(|x+sqrt(x^2-1)|)
2221 ($bfloat (fpasin-core x)))
2223 ;; Square root of a complex number (xx, yy). Both are bigfloats. FP
2224 ;; (non-bigfloat) numbers are returned.
2225 (defun complex-sqrt (xx yy)
2226 (let* ((x (cdr (bigfloatp xx)))
2227 (y (cdr (bigfloatp yy)))
2228 (rho (fpplus (fptimes* x x)
2229 (fptimes* y y))))
2230 (setf rho (fpplus (fpabs x) (fproot (bcons rho) 2)))
2231 (setf rho (fpplus rho rho))
2232 (setf rho (fpquotient (fproot (bcons rho) 2) (intofp 2)))
2234 (let ((eta rho)
2235 (nu y))
2236 (when (fpgreaterp rho (intofp 0))
2237 (setf nu (fpquotient (fpquotient nu rho) (intofp 2)))
2238 (when (fplessp x (intofp 0))
2239 (setf eta (fpabs nu))
2240 (setf nu (if (minusp (car y))
2241 (fpminus rho)
2242 rho))))
2243 (values eta nu))))
2245 ;; asin(z) for complex z = x + %i*y. X and Y are bigfloats. The real
2246 ;; and imaginary parts are returned as bigfloat numbers.
2247 (defun complex-asin (x y)
2248 (let ((x (cdr (bigfloatp x)))
2249 (y (cdr (bigfloatp y))))
2250 (multiple-value-bind (re-sqrt-1-z im-sqrt-1-z)
2251 (complex-sqrt (bcons (fpdifference (intofp 1) x))
2252 (bcons (fpminus y)))
2253 (multiple-value-bind (re-sqrt-1+z im-sqrt-1+z)
2254 (complex-sqrt (bcons (fpplus (intofp 1) x))
2255 (bcons y))
2256 ;; Realpart is atan(x/Re(sqrt(1-z)*sqrt(1+z)))
2257 ;; Imagpart is asinh(Im(conj(sqrt(1-z))*sqrt(1+z)))
2258 (values (bcons
2259 (let ((d (fpdifference (fptimes* re-sqrt-1-z
2260 re-sqrt-1+z)
2261 (fptimes* im-sqrt-1-z
2262 im-sqrt-1+z))))
2263 ;; Check for division by zero. If we would divide
2264 ;; by zero, return pi/2 or -pi/2 according to the
2265 ;; sign of X.
2266 (cond ((equal d '(0 0))
2267 (if (fplessp x '(0 0))
2268 (fpminus (fpquotient (fppi) (intofp 2)))
2269 (fpquotient (fppi) (intofp 2))))
2271 (fpatan (fpquotient x d))))))
2272 (fpasinh (bcons
2273 (fpdifference (fptimes* re-sqrt-1-z
2274 im-sqrt-1+z)
2275 (fptimes* im-sqrt-1-z
2276 re-sqrt-1+z)))))))))
2278 (defun big-float-asin (x &optional y)
2279 (if y
2280 (multiple-value-bind (u v) (complex-asin x y)
2281 (add u (mul '$%i v)))
2282 (fpasin x)))
2285 ;; tanh(x) for real x. X is a bigfloat, and a bigfloat is returned.
2286 (defun fptanh (x)
2287 ;; X is Maxima bigfloat
2288 ;; tanh(x) = D(2*x)/(2+D(2*x))
2289 (let* ((two (intofp 2))
2290 (fp (cdr (bigfloatp x)))
2291 (d (fpexpm1 (fptimes* fp two))))
2292 (bcons (fpquotient d (fpplus d two)))))
2294 ;; tanh(z), z = x + %i*y. X, Y are bigfloats, and a maxima number is
2295 ;; returned.
2296 (defun complex-tanh (x y)
2297 (let* ((tv (cdr (tanbigfloat (list y))))
2298 (beta (fpplus (fpone) (fptimes* tv tv)))
2299 (s (cdr (fpsinh x)))
2300 (s^2 (fptimes* s s))
2301 (rho (fproot (bcons (fpplus (fpone) s^2)) 2))
2302 (den (fpplus (fpone) (fptimes* beta s^2))))
2303 (values (bcons (fpquotient (fptimes* beta (fptimes* rho s)) den))
2304 (bcons (fpquotient tv den)))))
2306 (defun big-float-tanh (x &optional y)
2307 (if y
2308 (multiple-value-bind (u v) (complex-tanh x y)
2309 (add u (mul '$%i v)))
2310 (fptanh x)))
2312 ;; atanh(x) for real x, |x| <= 1. X is a bigfloat, and a bigfloat is
2313 ;; returned.
2314 (defun fpatanh (x)
2315 ;; atanh(x) = -atanh(-x)
2316 ;; = 1/2*log1p(2*x/(1-x)), x >= 0.5
2317 ;; = 1/2*log1p(2*x+2*x*x/(1-x)), x <= 0.5
2319 (let* ((fp-x (cdr (bigfloatp x))))
2320 (cond ((fplessp fp-x (intofp 0))
2321 ;; atanh(x) = -atanh(-x)
2322 (mul -1 (fpatanh (bcons (fpminus fp-x)))))
2323 ((fpgreaterp fp-x (fpone))
2324 ;; x > 1, so use complex version.
2325 (multiple-value-bind (u v)
2326 (complex-atanh x (bcons (intofp 0)))
2327 (add u (mul '$%i v))))
2328 ((fpgreaterp fp-x (cdr bfhalf))
2329 ;; atanh(x) = 1/2*log1p(2*x/(1-x))
2330 (bcons
2331 (fptimes* (cdr bfhalf)
2332 (fplog1p (fpquotient (fptimes* (intofp 2) fp-x)
2333 (fpdifference (fpone) fp-x))))))
2335 ;; atanh(x) = 1/2*log1p(2*x + 2*x*x/(1-x))
2336 (let ((2x (fptimes* (intofp 2) fp-x)))
2337 (bcons
2338 (fptimes* (cdr bfhalf)
2339 (fplog1p (fpplus 2x
2340 (fpquotient (fptimes* 2x fp-x)
2341 (fpdifference (fpone) fp-x)))))))))))
2343 ;; Stuff which follows is derived from atanh z = (log(1 + z) - log(1 - z))/2
2344 ;; which apparently originates with Kahan's "Much ado" paper.
2346 ;; The formulas for eta and nu below can be easily derived from
2347 ;; rectform(atanh(x+%i*y)) =
2349 ;; 1/4*log(((1+x)^2+y^2)/((1-x)^2+y^2)) + %i/2*(arg(1+x+%i*y)-arg(1-x+%i*(-y)))
2351 ;; Expand the argument of log out and divide it out and we get
2353 ;; log(((1+x)^2+y^2)/((1-x)^2+y^2)) = log(1+4*x/((1-x)^2+y^2))
2355 ;; When y = 0, Im atanh z = 1/2 (arg(1 + x) - arg(1 - x))
2356 ;; = if x < -1 then %pi/2 else if x > 1 then -%pi/2 else <whatever>
2358 ;; Otherwise, arg(1 - x + %i*(-y)) = - arg(1 - x + %i*y),
2359 ;; and Im atanh z = 1/2 (arg(1 + x + %i*y) + arg(1 - x + %i*y)).
2360 ;; Since arg(x)+arg(y) = arg(x*y) (almost), we can simplify the
2361 ;; imaginary part to
2363 ;; arg((1+x+%i*y)*(1-x+%i*y)) = arg((1-x)*(1+x)-y^2+2*y*%i)
2364 ;; = atan2(2*y,((1-x)*(1+x)-y^2))
2366 ;; These are the eta and nu forms below.
2367 (defun complex-atanh (x y)
2368 (let* ((fpx (cdr (bigfloatp x)))
2369 (fpy (cdr (bigfloatp y)))
2370 (beta (if (minusp (car fpx))
2371 (fpminus (fpone))
2372 (fpone)))
2373 (x-lt-minus-1 (mevalp `((mlessp) ,x -1)))
2374 (x-gt-plus-1 (mevalp `((mgreaterp) ,x 1)))
2375 (y-equals-0 (like y '((bigfloat) 0 0)))
2376 (x (fptimes* beta fpx))
2377 (y (fptimes* beta (fpminus fpy)))
2378 ;; Kahan has rho = 4/most-positive-float. What should we do
2379 ;; here about that? Our big floats don't really have a
2380 ;; most-positive float value.
2381 (rho (intofp 0))
2382 (t1 (fpplus (fpabs y) rho))
2383 (t1^2 (fptimes* t1 t1))
2384 (1-x (fpdifference (fpone) x))
2385 ;; eta = log(1+4*x/((1-x)^2+y^2))/4
2386 (eta (fpquotient
2387 (fplog1p (fpquotient (fptimes* (intofp 4) x)
2388 (fpplus (fptimes* 1-x 1-x)
2389 t1^2)))
2390 (intofp 4)))
2391 ;; If y = 0, then Im atanh z = %pi/2 or -%pi/2.
2392 ;; Otherwise nu = 1/2*atan2(2*y,(1-x)*(1+x)-y^2)
2393 (nu (if y-equals-0
2394 ;; EXTRA FPMINUS HERE TO COUNTERACT FPMINUS IN RETURN VALUE
2395 (fpminus (if x-lt-minus-1
2396 (cdr ($bfloat '((mquotient) $%pi 2)))
2397 (if x-gt-plus-1
2398 (cdr ($bfloat '((mminus) ((mquotient) $%pi 2))))
2399 (merror "COMPLEX-ATANH: HOW DID I GET HERE?"))))
2400 (fptimes* (cdr bfhalf)
2401 (fpatan2 (fptimes* (intofp 2) y)
2402 (fpdifference (fptimes* 1-x (fpplus (fpone) x))
2403 t1^2))))))
2404 (values (bcons (fptimes* beta eta))
2405 ;; WTF IS FPMINUS DOING HERE ??
2406 (bcons (fpminus (fptimes* beta nu))))))
2408 (defun big-float-atanh (x &optional y)
2409 (if y
2410 (multiple-value-bind (u v) (complex-atanh x y)
2411 (add u (mul '$%i v)))
2412 (fpatanh x)))
2414 ;; acos(x) for real x. X is a bigfloat, and a maxima number is returned.
2415 (defun fpacos (x)
2416 ;; acos(x) = %pi/2 - asin(x)
2417 ($bfloat (add (div '$%pi 2) (mul -1 (fpasin-core x)))))
2419 (defun complex-acos (x y)
2420 (let ((x (cdr (bigfloatp x)))
2421 (y (cdr (bigfloatp y))))
2422 (multiple-value-bind (re-sqrt-1-z im-sqrt-1-z)
2423 (complex-sqrt (bcons (fpdifference (intofp 1) x))
2424 (bcons (fpminus y)))
2425 (multiple-value-bind (re-sqrt-1+z im-sqrt-1+z)
2426 (complex-sqrt (bcons (fpplus (intofp 1) x))
2427 (bcons y))
2428 (values (bcons
2429 (fptimes* (intofp 2)
2430 (fpatan (fpquotient re-sqrt-1-z re-sqrt-1+z))))
2431 (fpasinh (bcons
2432 (fpdifference
2433 (fptimes* re-sqrt-1+z im-sqrt-1-z)
2434 (fptimes* im-sqrt-1+z re-sqrt-1-z)))))))))
2437 (defun big-float-acos (x &optional y)
2438 (if y
2439 (multiple-value-bind (u v) (complex-acos x y)
2440 (add u (mul '$%i v)))
2441 (fpacos x)))
2443 (defun complex-log (x y)
2444 (let* ((x (cdr (bigfloatp x)))
2445 (y (cdr (bigfloatp y)))
2446 (t1 (let (($float2bf t))
2447 ;; No warning message, please.
2448 (floattofp 1.2)))
2449 (t2 (intofp 3))
2450 (rho (fpplus (fptimes* x x)
2451 (fptimes* y y)))
2452 (abs-x (fpabs x))
2453 (abs-y (fpabs y))
2454 (beta (fpmax abs-x abs-y))
2455 (theta (fpmin abs-x abs-y)))
2456 (values (if (or (fpgreaterp t1 beta)
2457 (fplessp rho t2))
2458 (fpquotient (fplog1p (fpplus (fptimes* (fpdifference beta (fpone))
2459 (fpplus beta (fpone)))
2460 (fptimes* theta theta)))
2461 (intofp 2))
2462 (fpquotient (fplog rho) (intofp 2)))
2463 (fpatan2 y x))))
2465 (defun big-float-log (x &optional y)
2466 (if y
2467 (multiple-value-bind (u v) (complex-log x y)
2468 (add (bcons u) (mul '$%i (bcons v))))
2469 (flet ((%log (x)
2470 ;; x is (mantissa exp), where mantissa = frac*2^fpprec,
2471 ;; with 1/2 < frac <= 1 and x is frac*2^exp. To
2472 ;; compute log(x), use log(x) = log(frac)+ exp*log(2).
2473 (cdr
2474 (let* ((extra 8)
2475 (fpprec (+ fpprec extra))
2476 (log-frac
2477 (fplog #+nil
2478 (cdr ($bfloat
2479 (cl-rat-to-maxima (/ (car x)
2480 (ash 1 (- fpprec 8))))))
2481 (list (ash (car x) extra) 0)))
2482 (log-exp (fptimes* (intofp (second x)) (fplog2)))
2483 (result (bcons (fpplus log-frac log-exp))))
2484 (let ((fpprec (- fpprec extra)))
2485 (bigfloatp result))))))
2486 (let ((fp-x (cdr (bigfloatp x))))
2487 (cond ((onep1 x)
2488 ;; Special case for log(1). See:
2489 ;; https://sourceforge.net/p/maxima/bugs/2240/
2490 (bcons (intofp 0)))
2491 ((fplessp fp-x (intofp 0))
2492 ;; ??? Do we want to return an exact %i*%pi or a float
2493 ;; approximation?
2494 (add (big-float-log (bcons (fpminus fp-x)))
2495 (mul '$%i (bcons (fppi)))))
2497 (bcons (%log fp-x))))))))
2499 (defun big-float-sqrt (x &optional y)
2500 (if y
2501 (multiple-value-bind (u v) (complex-sqrt x y)
2502 (add (bcons u) (mul '$%i (bcons v))))
2503 (let ((fp-x (cdr (bigfloatp x))))
2504 (if (fplessp fp-x (intofp 0))
2505 (mul '$%i (bcons (fproot (bcons (fpminus fp-x)) 2)))
2506 (bcons (fproot x 2))))))
2508 (eval-when
2509 #+gcl (load eval)
2510 #-gcl (:load-toplevel :execute)
2511 (fpprec1 nil $fpprec)) ; Set up user's precision