1 ;;; -*- Mode: Lisp; Package: Maxima; Syntax: Common-Lisp; Base: 10 -*- ;;;;
2 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3 ;;; The data in this file contains enhancments. ;;;;;
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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
20 ;; August 1980 by CWH to run on Multics and to install
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.
31 #+gcl
(compile load eval
)
32 #-gcl
(:compile-toplevel
:load-toplevel
:execute
)
33 (defconstant +machine-fixnum-precision
+ (integer-length most-positive-fixnum
)))
38 "If TRUE, no MAXIMA-ERROR message is printed when a floating point number is
39 converted to a bigfloat number.")
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.")
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."
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)")
89 ;; Number of bits of precision in the mantissa of newly created bigfloats.
90 ;; FPPREC = ($FPPREC+1)*(Log base 2 of 10)
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.
102 ;; *DECFP = T if the computation is being done in decimal radix. NIL implies
103 ;; base 2. Decimal radix is used only during output.
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)).
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
))
148 (let ((fpprec (+ 4 fpprec
(integer-length exp
)
149 (floor (1+ (* #.
(/ (log 10.0) (log 2.0)) (length lft
))))))
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>) ...).
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
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~%"
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))))
184 (of (bigfloat-prec l
))
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.
)
197 ((effective-printprec (if (or (= $fpprintprec
0) (> $fpprintprec fpprec
)) fpprec $fpprintprec
))
198 (integer-to-explode (round (car l
) (expt 10 (- fpprec effective-printprec
))))
199 (exploded-integer (explodec integer-to-explode
)))
201 (do ((l (nreverse exploded-integer
) (cdr l
)))
202 ((not (eq '|
0|
(car l
))) (nreverse l
)))
204 (nconc (ncons (car l1
)) (ncons '|.|
)
205 (or (cdr l1
) (ncons '|
0|
))
207 (explodec (1- (cadr l
)))))))))
209 ;; NOTE: This is a modified version of FORMAT-EXP-AUX from CMUCL to
210 ;; support printing of bfloats.
211 (defun bfloat-format-e (stream arg colonp atp
212 &optional w d e
(k 1)
213 overflowchar
(padchar #\space
) exponentchar
)
214 (declare (ignore colonp
))
215 (flet ((exponent-value (x)
216 ;; Compute the (decimal exponent) of the bfloat number X.
217 (let* (($fpprintprec
1)
219 (marker (position '|b| f
)))
220 ;; FIXME: do something better than printing and reading
223 (format nil
"~{~A~}" (nthcdr (1+ marker
) f
)))))
224 (bfloat-to-string (x fdigits scale
)
225 ;; Print the bfloat X with FDIGITS after the decimal
226 ;; point. This means, roughtly, FDIGITS+1 significant
228 (let* (($fpprintprec
(if fdigits
233 (f (fpformat (bcons (fpabs (cdr x
)))))
234 (marker (position '|b| f
))
235 (digits (remove '|.|
(subseq f
0 marker
))))
236 ;; Depending on the value of k, move the decimal
237 ;; point. DIGITS was printed assuming the decimal point
238 ;; is after the first digit. But if fdigits = 0, fpformat
239 ;; actually printed out one too many digits, so we need
241 (when (and fdigits
(zerop fdigits
))
242 (setf digits
(butlast digits
)))
246 ;; Put the leading decimal and then some zeroes
251 ;; The number is scaled by 10^k. Do this by
252 ;; putting the decimal point in the right place,
253 ;; appending zeroes if needed.
255 (cond ((> k
(length digits
))
258 (make-list (- k
(length digits
))
259 :initial-element
#\
0)
265 (subseq digits k
)))))))
266 (let* ((str (format nil
"~{~A~}" digits
))
268 (when (and fdigits
(>= fdigits len
))
269 ;; Append some zeroes to get the desired number of digits
270 (setf str
(concatenate 'string str
271 (make-string (+ 1 k
(- fdigits len
))
272 :initial-element
#\
0)))
273 (setf len
(length str
)))
276 (char= (aref str
0) #\.
)
277 (char= (aref str
(1- (length str
))) #\.
)
280 (let* ((num-expt (exponent-value arg
))
281 (expt (if (zerop (second arg
))
283 (1+ (- num-expt k
))))
284 (estr (format nil
"~D" (abs expt
)))
285 (elen (if e
(max (length estr
) e
) (length estr
)))
287 (cond ((and w overflowchar e
(> elen e
))
290 (write-char overflowchar stream
)))
300 (if (or atp
(minusp (second arg
)))
305 (format t
"d, k = ~D ~D~%" d k
)
306 (format t
"fdig = ~D, spaceleft = ~D~%" fdig spaceleft
))
308 (multiple-value-bind (fstr flen lpoint tpoint
)
309 (bfloat-to-string arg fdig
(or k
1))
311 (format t
"fstr flen lpoint tpoint = ~S ~S ~S ~S~%"
312 fstr flen lpoint tpoint
)
313 (when (and d
(zerop d
)) (setq tpoint nil
))
315 (decf spaceleft flen
)
316 ;; See CLHS 22.3.3.2. "If the parameter d is
317 ;; omitted, ... [and] if the fraction to be
318 ;; printed is zero then a single zero digit should
319 ;; appear after the decimal point." So we need to
320 ;; subtract one from here because we're going to
321 ;; add an extra 0 digit later.
322 (when (and (null d
) (char= (aref fstr
(1- flen
)) #\.
))
326 (if (or (> spaceleft
0) tpoint
)
329 (when (and tpoint
(<= spaceleft
0))
332 (format t
"w, spaceleft overflowchar = ~S ~S ~S~%"
333 w spaceleft overflowchar
)
334 (cond ((and w
(< spaceleft
0) overflowchar
)
335 ;; Significand overflow; output the overflow char
337 (write-char overflowchar stream
)))
340 (dotimes (i spaceleft
)
341 (write-char padchar stream
)))
342 (if (minusp (second arg
))
343 (write-char #\- stream
)
344 (when atp
(write-char #\
+ stream
)))
346 (write-char #\
0 stream
))
348 (write-string fstr stream
)
349 ;; Add a zero if we need it. Which means
350 ;; we figured out we need one above, or
351 ;; another condition. Basically, append a
352 ;; zero if there are no width constraints
353 ;; and if the last char to print was a
354 ;; decimal (so the trailing fraction is
358 (char= (aref fstr
(1- flen
)) #\.
)))
359 (write-char #\
0 stream
))
360 (write-char (if exponentchar
364 (write-char (if (minusp expt
) #\-
#\
+) stream
)
366 (dotimes (i (- e
(length estr
)))
367 (write-char #\
0 stream
)))
368 (write-string estr stream
)))))))))
371 ;; NOTE: This is a modified version of FORMAT-FIXED-AUX from CMUCL to
372 ;; support printing of bfloats.
373 (defun bfloat-format-f (stream number colonp atsign
&optional w d
(k 0) ovf
(pad #\space
))
374 (declare (ignore colonp
))
377 ;; Compute the (decimal exponent) of the bfloat number X.
378 (let* (($fpprintprec
1)
380 (marker (position '|b| f
)))
381 ;; FIXME: do something better than printing and reading
384 (format nil
"~{~A~}" (nthcdr (1+ marker
) f
)))))
385 (bfloat-to-string (x fdigits scale spaceleft
)
386 ;; Print the bfloat X with FDIGITS after the decimal
387 ;; point. To do this we need to know the exponent because
388 ;; fpformat always produces exponential output. If the
389 ;; exponent is E, and we want FDIGITS after the decimal
390 ;; point, we need FDIGITS + E digits printed.
391 (flet ((compute-prec (exp spaceleft
)
393 (format t
"compute-prec ~D ~D~%" exp spaceleft
)
397 (max (1- spaceleft
) (1+ exp
)))
400 (let* ((exp (+ k
(exponent-value x
)))
401 ($fpprintprec
(compute-prec exp spaceleft
))
402 (f (let ((maxima::$bftrunc nil
))
404 (format t
"printprec = ~D~%" $fpprintprec
)
405 (fpformat (bcons (fpabs (cdr x
))))))
406 (marker (position '|b| f
))
407 (digits (remove '|.|
(subseq f
0 marker
))))
408 ;; Depending on the value of scale, move the decimal
409 ;; point. DIGITS was printed assuming the decimal point
410 ;; is after the first digit. But if fdigits = 0, fpformat
411 ;; actually printed out one too many digits, so we need
414 (format t
"exp, fdigits = ~D ~D, digits = ~S~%" exp fdigits digits
)
416 (when (and fdigits
(zerop fdigits
))
417 (setf digits
(butlast digits
)))
418 ;; Figure out where the decimal point should go. An
419 ;; exponent of 0 means the decimal is after the first
422 (dotimes (k (1- (abs exp
)))
425 ((< exp
(length digits
))
427 (format t
"exp, len = ~D ~D~%" exp
(length digits
))
428 (setf digits
(concatenate 'list
429 (subseq digits
0 (1+ exp
))
431 (subseq digits
(1+ exp
)))))
433 (setf digits
(append digits
(list '|.|
)))))
434 (let* ((str (format nil
"~{~A~}" digits
))
437 (format t
"str = ~S~%" str
)
438 (when (and fdigits
(>= fdigits len
))
439 ;; Append some zeroes to get the desired number of digits
440 (setf str
(concatenate 'string str
441 (make-string (+ 1 scale
(- fdigits len
))
442 :initial-element
#\
0)))
443 (setf len
(length str
)))
446 (char= (aref str
0) #\.
)
447 (char= (aref str
(1- (length str
))) #\.
)
451 (when (and w
(or atsign
(minusp (second number
))))
453 (multiple-value-bind (str len lpoint tpoint
)
454 (bfloat-to-string number d k spaceleft
)
455 ;;if caller specifically requested no fraction digits, suppress the
456 ;;optional trailing zero
457 (when (and d
(zerop d
)) (setq tpoint nil
))
460 ;;optional leading zero
462 (if (or (> spaceleft
0) tpoint
) ;force at least one digit
465 ;;optional trailing zero
470 (cond ((and w
(< spaceleft
0) ovf
)
471 ;;field width overflow
472 (dotimes (i w
) (write-char ovf stream
))
475 (when w
(dotimes (i spaceleft
) (write-char pad stream
)))
476 (if (minusp (second number
))
477 (write-char #\- stream
)
478 (if atsign
(write-char #\
+ stream
)))
479 (when lpoint
(write-char #\
0 stream
))
480 (write-string str stream
)
481 (when tpoint
(write-char #\
0 stream
))
484 ;; NOTE: This is a modified version of FORMAT-EXP-AUX from CMUCL to
485 ;; support printing of bfloats.
486 (defun bfloat-format-g (stream arg colonp atsign
487 &optional w d e
(k 1)
488 ovf
(pad #\space
) exponentchar
)
489 (declare (ignore colonp
))
490 (flet ((exponent-value (x)
491 ;; Compute the (decimal exponent) of the bfloat number X.
492 (let* (($fpprintprec
1)
494 (marker (position '|b| f
)))
495 ;; FIXME: do something better than printing and reading
498 (format nil
"~{~A~}" (nthcdr (1+ marker
) f
)))))
499 (bfloat-to-string (x fdigits
)
500 ;; Print the bfloat X with FDIGITS after the decimal
501 ;; point. This means, roughtly, FDIGITS+1 significant
503 (let* (($fpprintprec
(if fdigits
508 (f (fpformat (bcons (fpabs (cdr x
)))))
509 (marker (position '|b| f
))
510 (digits (remove '|.|
(subseq f
0 marker
))))
511 ;; Depending on the value of k, move the decimal
512 ;; point. DIGITS was printed assuming the decimal point
513 ;; is after the first digit. But if fdigits = 0, fpformat
514 ;; actually printed out one too many digits, so we need
516 (when (and fdigits
(zerop fdigits
))
517 (setf digits
(butlast digits
)))
521 ;; Put the leading decimal and then some zeroes
526 ;; The number is scaled by 10^k. Do this by
527 ;; putting the decimal point in the right place,
528 ;; appending zeroes if needed.
530 (cond ((> k
(length digits
))
533 (make-list (- k
(length digits
))
534 :initial-element
#\
0)
540 (subseq digits k
)))))))
541 (let* ((str (format nil
"~{~A~}" digits
))
543 (when (and fdigits
(>= fdigits len
))
544 ;; Append some zeroes to get the desired number of digits
545 (setf str
(concatenate 'string str
546 (make-string (+ 1 k
(- fdigits len
))
547 :initial-element
#\
0)))
548 (setf len
(length str
)))
551 (char= (aref str
0) #\.
)
552 (char= (aref str
(1- (length str
))) #\.
)
555 (let* ((n (1+ (exponent-value arg
)))
557 ;; Default d if omitted. The procedure is taken directly from
558 ;; the definition given in the manual (CLHS 22.3.3.3), and is
559 ;; not very efficient, since we generate the digits twice.
560 ;; Future maintainers are encouraged to improve on this.
562 ;; It's also not very clear whether q in the spec is the
563 ;; number of significant digits or not. I (rtoy) think it
564 ;; makes more sense if q is the number of significant digits.
565 ;; That way 1d300 isn't printed as 1 followed by 300 zeroes.
566 ;; Exponential notation would be used instead.
568 (let* ((q (1- (nth-value 1 (bfloat-to-string arg nil
)))))
569 (setq d
(max q
(min n
7)))))
570 (let* ((ee (if e
(+ e
2) 4))
571 (ww (if w
(- w ee
) nil
))
575 (format t
"d = ~A~%" d
)
576 (format t
"ee = ~A~%" ee
)
577 (format t
"ww = ~A~%" ww
)
578 (format t
"dd = ~A~%" dd
)
579 (format t
"n = ~A~%" n
))
581 ;; Use dd fraction digits, even if that would cause
582 ;; the width to be exceeded. We choose accuracy over
583 ;; width in this case.
584 (let* ((fill-char (if (bfloat-format-f stream arg nil atsign
591 (dotimes (i ee
) (write-char fill-char stream
))))
593 (bfloat-format-e stream arg nil atsign
597 ovf pad exponentchar
)))))))
599 ;; Tells you if you have a bigfloat object. BUT, if it is a bigfloat,
600 ;; it will normalize it by making the precision of the bigfloat match
601 ;; the current precision setting in fpprec. And it will also convert
602 ;; bogus zeroes (mantissa is zero, but exponent is not) to a true
605 ;; A bigfloat object looks like '((bigfloat simp <prec>) <mantissa> <exp>)
606 ;; Note bene that the simp flag is optional -- don't count on its presence.
608 (cond ((not ($bfloatp x
)) (return nil
))
609 ((= fpprec
(setq x-prec
(bigfloat-prec x
)))
610 ;; Precision matches. (Should we fix up bogus bigfloat
614 ;; Current precision is higher than bigfloat precision.
615 ;; Scale up mantissa and adjust exponent to get the
616 ;; correct precision.
617 (setq x
(bcons (list (fpshift (cadr x
) (- fpprec x-prec
))
620 ;; Current precision is LOWER than bigfloat precision.
621 ;; Round the number to the desired precision.
622 (setq x
(bcons (list (fpround (cadr x
))
623 (+ (caddr x
) *m fpprec
(- x-prec
)))))))
624 ;; Fix up any bogus zeros that we might have created.
625 (return (if (equal (cadr x
) 0) (bcons (list 0 0)) x
))))
627 (defun bigfloat2rat (x)
628 (setq x
(bigfloatp x
))
633 (setq exp
(cond ((minusp (cadr x
))
635 y
(fpration1 (cons (car x
) (fpabs (cdr x
)))))
636 (rplaca y
(* -
1 (car y
))))
639 (princ "`rat' replaced ")
640 (when sign
(princ "-"))
641 (princ (maknam (fpformat (cons (car x
) (fpabs (cdr x
))))))
647 (setq x
($bfloat
(list '(rat simp
) (car exp
) (cdr exp
))))
648 (when sign
(princ "-"))
649 (princ (maknam (fpformat (cons (car x
) (fpabs (cdr x
))))))
655 (let ((fprateps (cdr ($bfloat
(if $bftorat
656 (list '(rat simp
) 1 (exptrl 2 (1- fpprec
)))
658 (or (and (equal x bigfloatzero
) (cons 0 1))
660 (return (do ((xx x
(setq y
(invertbigfloat
661 (bcons (fpdifference (cdr xx
) (cdr ($bfloat a
)))))))
662 (num (setq a
(fpentier x
))
663 (+ (* (setq a
(fpentier y
)) num
) onum
))
664 (den 1 (+ (* a den
) oden
))
667 ((and (not (zerop den
))
670 (fpdifference (cdr x
)
671 (fpquotient (cdr ($bfloat num
))
672 (cdr ($bfloat den
))))
675 (cons num den
))))))))
677 (defun float-nan-p (x)
678 (and (floatp x
) (not (= x x
))))
680 (defun float-inf-p (x)
681 (and (floatp x
) (not (float-nan-p x
)) (beyond-extreme-values x
)))
683 (defun beyond-extreme-values (x)
684 (multiple-value-bind (most-negative most-positive
) (extreme-float-values x
)
686 ((< x
0) (< x most-negative
))
687 ((> x
0) (> x most-positive
))
690 (defun extreme-float-values (x)
691 ;; BLECHH, I HATE ENUMERATING CASES. IS THERE A BETTER WAY ??
692 (typecase x
;gcl returns an atomic list type with type-of
693 (short-float (values most-negative-short-float most-positive-short-float
))
694 (single-float (values most-negative-single-float most-positive-single-float
))
695 (double-float (values most-negative-double-float most-positive-double-float
))
696 (long-float (values most-negative-long-float most-positive-long-float
))
697 ;; NOT SURE THE FOLLOWING REALLY WORKS
698 ;; #+(and cmu double-double)
699 ;; (kernel:double-double-float
700 ;; (values most-negative-double-double-float most-positive-double-double-float))
703 ;; Convert a floating point number into a bigfloat.
706 (merror (intl:gettext
"bfloat: attempted conversion of floating point NaN (not-a-number).~%")))
708 (merror (intl:gettext
"bfloat: attempted conversion of floating-point infinity.~%")))
710 (let ((p (float-precision x
)))
712 (mtell (intl:gettext
"bfloat: converting float ~S to bigfloat.~%") x
))))
714 ;; Need to check for zero because different lisps return different
715 ;; values for integer-decode-float of a 0. In particular CMUCL
716 ;; returns 0, -1075. A bigfloat zero needs to have an exponent and
720 (multiple-value-bind (frac exp sign
)
721 (integer-decode-float x
)
722 ;; Scale frac to the desired number of bits, and adjust the
723 ;; exponent accordingly.
724 (let ((scale (- fpprec
(integer-length frac
))))
725 (list (ash (* sign frac
) scale
)
726 (+ fpprec
(- exp scale
)))))))
728 ;; Convert a bigfloat into a floating point number.
730 (let ((precision (bigfloat-prec l
))
733 (fpprec machine-mantissa-precision
)
735 ;; Round the mantissa to the number of bits of precision of the
736 ;; machine, and then convert it to a floating point fraction. We
737 ;; have 0.5 <= mantissa < 1
738 (setq mantissa
(quotient (fpround mantissa
) (expt 2.0 machine-mantissa-precision
)))
739 ;; Multiply the mantissa by the exponent portion. I'm not sure
740 ;; why the exponent computation is so complicated.
742 ;; GCL doesn't signal overflow from scale-float if the number
743 ;; would overflow. We have to do it this way. 0.5 <= mantissa <
744 ;; 1. The largest double-float is .999999 * 2^1024. So if the
745 ;; exponent is 1025 or higher, we have an overflow.
746 (let ((e (+ exponent
(- precision
) *m machine-mantissa-precision
)))
748 (merror (intl:gettext
"float: floating point overflow converting ~:M") l
)
749 (scale-float mantissa e
)))))
751 ;; New machine-independent version of FIXFLOAT. This may be buggy. - CWH
752 ;; It is buggy! On the PDP10 it dies on (RATIONALIZE -1.16066076E-7)
753 ;; which calls FLOAT on some rather big numbers. ($RATEPSILON is approx.
757 (let (($ratepsilon
(expt 2.0 (- machine-mantissa-precision
))))
758 (maxima-rationalize x
)))
760 ;; Takes a flonum arg and returns a rational number corresponding to the flonum
761 ;; in the form of a dotted pair of two integers. Since the denominator will
762 ;; always be a positive power of 2, this number will not always be in lowest
766 `((bigfloat simp
,fpprec
) .
,s
))
770 (cond ((bigfloatp x
))
772 (member x
'($%e $%pi $%gamma
) :test
#'eq
))
774 ((or (atom x
) (member 'array
(cdar x
) :test
#'eq
))
776 ($bfloat
'((mtimes simp
)
778 ((mplus simp
) 1 ((mexpt simp
) 5 ((rat simp
) 1 2)))))
780 ((eq (caar x
) 'mexpt
)
781 (if (equal (cadr x
) '$%e
)
782 (*fpexp
($bfloat
(caddr x
)))
783 (exptbigfloat ($bfloat
(cadr x
)) (caddr x
))))
784 ((eq (caar x
) 'mncexpt
)
785 (list '(mncexpt) ($bfloat
(cadr x
)) (caddr x
)))
787 (ratbigfloat (cdr x
)))
788 ((setq y
(safe-get (caar x
) 'floatprog
))
789 (funcall y
(mapcar #'$bfloat
(cdr x
))))
790 ((or (trigp (caar x
)) (arcp (caar x
)) (eq (caar x
) '$entier
))
791 (setq y
($bfloat
(cadr x
)))
793 (cond ((eq (caar x
) '$entier
) ($entier y
))
795 (setq y
($bfloat
(logarc (caar x
) y
)))
797 y
(let ($ratprint
) (fparcsimp ($rectform y
)))))
798 ((member (caar x
) '(%cot %sec %csc
) :test
#'eq
)
800 ($bfloat
(list (ncons (safe-get (caar x
) 'recip
)) y
))))
801 (t ($bfloat
(exponentialize (caar x
) y
))))
802 (subst0 (list (ncons (caar x
)) y
) x
)))
803 (t (recur-apply #'$bfloat x
)))))
805 (defprop mplus addbigfloat floatprog
)
806 (defprop mtimes timesbigfloat floatprog
)
807 (defprop %sin sinbigfloat floatprog
)
808 (defprop %cos cosbigfloat floatprog
)
809 (defprop rat ratbigfloat floatprog
)
810 (defprop %atan atanbigfloat floatprog
)
811 (defprop %tan tanbigfloat floatprog
)
812 (defprop %log logbigfloat floatprog
)
813 (defprop mabs mabsbigfloat floatprog
)
815 (defun addbigfloat (h)
816 (prog (fans tst r nfans
)
817 (setq fans
(setq tst bigfloatzero
) nfans
0)
820 (cond ((setq r
(bigfloatp (car l
)))
821 (setq fans
(bcons (fpplus (cdr r
) (cdr fans
)))))
822 (t (setq nfans
(list '(mplus) (car l
) nfans
)))))
823 (return (cond ((equal nfans
0) fans
)
824 ((equal fans tst
) nfans
)
825 (t (simplify (list '(mplus) fans nfans
)))))))
827 (defun ratbigfloat (r)
828 ;; R is a Maxima ratio, represented as a list of the numerator and
829 ;; denominator. FLOAT-RATIO doesn't like it if the numerator is 0,
830 ;; so handle that here.
833 (bcons (float-ratio r
))))
835 ;; This is borrowed from CMUCL (float-ratio-float), and modified for
836 ;; converting ratios to Maxima's bfloat numbers.
837 (defun float-ratio (x)
838 (let* ((signed-num (first x
))
839 (plusp (plusp signed-num
))
840 (num (if plusp signed-num
(- signed-num
)))
844 (declare (fixnum digits scale
))
846 ;; Strip any trailing zeros from the denominator and move it into the scale
847 ;; factor (to minimize the size of the operands.)
848 (let ((den-twos (1- (integer-length (logxor den
(1- den
))))))
849 (declare (fixnum den-twos
))
850 (decf scale den-twos
)
851 (setq den
(ash den
(- den-twos
))))
853 ;; Guess how much we need to scale by from the magnitudes of the numerator
854 ;; and denominator. We want one extra bit for a guard bit.
855 (let* ((num-len (integer-length num
))
856 (den-len (integer-length den
))
857 (delta (- den-len num-len
))
858 (shift (1+ (the fixnum
(+ delta digits
))))
859 (shifted-num (ash num shift
)))
860 (declare (fixnum delta shift
))
862 (labels ((float-and-scale (bits)
863 (let* ((bits (ash bits -
1))
864 (len (integer-length bits
)))
865 (cond ((> len digits
)
866 (assert (= len
(the fixnum
(1+ digits
))))
867 (multiple-value-bind (f0)
868 (floatit (ash bits -
1))
869 (list (first f0
) (+ (second f0
)
872 (multiple-value-bind (f0)
874 (list (first f0
) (+ (second f0
) scale
)))))))
876 (let ((sign (if plusp
1 -
1)))
877 (list (* sign bits
) 0))))
879 (multiple-value-bind (fraction-and-guard rem
)
880 (truncate shifted-num den
)
881 (let ((extra (- (integer-length fraction-and-guard
) digits
)))
882 (declare (fixnum extra
))
884 (assert (> extra
1)))
885 ((oddp fraction-and-guard
)
889 (if (zerop (logand fraction-and-guard
2))
891 (1+ fraction-and-guard
)))
892 (float-and-scale (1+ fraction-and-guard
)))))
894 (return (float-and-scale fraction-and-guard
)))))
895 (setq shifted-num
(ash shifted-num -
1))
898 (defun decimalsin (x)
899 (do ((i (quotient (* 59. x
) 196.
) (1+ i
))) ;log[10](2)=.301029
901 (when (> (integer-length (expt 10. i
)) x
)
904 (defun atanbigfloat (x)
905 (*fpatan
(car x
) (cdr x
)))
908 (fpend (let ((fpprec (+ 8. fpprec
)))
910 (if ($bfloatp a
) (fpatan (cdr ($bfloat a
)))
912 (fpatan2 (cdr ($bfloat a
)) (cdr ($bfloat
(car y
))))))))
916 (prog (term x2 ans oans one two tmp
)
917 (setq one
(intofp 1) two
(intofp 2))
918 (cond ((fpgreaterp (fpabs x
) one
)
922 ;; atan(x) + acot(x) = +/- pi/2 (+ for x >= 0, - for x < 0)
925 ;; acot(z) = atan(1/z)
926 (setq tmp
(fpquotient (fppi) two
))
927 (setq ans
(fpdifference tmp
(fpatan (fpquotient one x
))))
928 (return (cond ((fplessp x
(intofp 0))
929 (fpdifference ans
(fppi)))
931 ((fpgreaterp (fpabs x
) (fpquotient one two
))
934 ;; Use A&S 4.4.42, third formula:
936 ;; atan(z) = z/(1+z^2)*[1 + 2/3*r + (2*4)/(3*5)*r^2 + ...]
939 (setq tmp
(fpquotient x
(fpplus (fptimes* x x
) one
)))
940 (setq x2
(fptimes* x tmp
) term
(setq ans one
))
944 (fptimes* term
(fptimes* x2
(fpquotient
945 (intofp (+ 2 (* 2 n
)))
946 (intofp (+ (* 2 n
) 3))))))
947 (setq oans ans ans
(fpplus term ans
)))
948 (setq ans
(fptimes* tmp ans
)))
950 ;; |x| <= 1/2. Use Taylor series (A&S 4.4.42, first
952 (setq ans x x2
(fpminus (fptimes* x x
)) term x
)
955 (setq term
(fptimes* term x2
))
957 ans
(fpplus ans
(fpquotient term
(intofp n
)))))))
960 ;; atan(y/x) taking into account the quadrant. (Also equal to
963 (cond ((equal (car x
) 0)
964 ;; atan(y/0) = atan(inf), but what sign?
965 (cond ((equal (car y
) 0)
966 (merror (intl:gettext
"atan2: atan2(0, 0) is undefined.")))
968 ;; We're on the negative imaginary axis, so -pi/2.
969 (fpquotient (fppi) (intofp -
2)))
971 ;; The positive imaginary axis, so +pi/2
972 (fpquotient (fppi) (intofp 2)))))
974 ;; x > 0. atan(y/x) is the correct value.
975 (fpatan (fpquotient y x
)))
977 ;; x < 0, and y > 0. We're in quadrant II, so the angle we
978 ;; want is pi+atan(y/x).
979 (fpplus (fppi) (fpatan (fpquotient y x
))))
981 ;; x <= 0 and y <= 0. We're in quadrant III, so the angle we
982 ;; want is atan(y/x)-pi.
983 (fpdifference (fpatan (fpquotient y x
)) (fppi)))))
985 (defun tanbigfloat (a)
987 (fpend (let ((fpprec (+ 8. fpprec
)))
989 (setq a
(cdr ($bfloat a
)))
990 (fpquotient (fpsin a t
) (fpsin a nil
)))
991 (t (list '(%tan
) a
))))))
993 ;; Returns a list of a mantissa and an exponent.
995 (cond ((not (atom l
)) ($bfloat l
))
996 ((floatp l
) (floattofp l
))
998 ((eq l
'$%pi
) (fppi))
1000 ((eq l
'$%gamma
) (fpgamma))
1001 (t (list (fpround l
) (+ *m fpprec
)))))
1003 ;; It seems to me that this function gets called on an integer
1004 ;; and returns the mantissa portion of the mantissa/exponent pair.
1006 ;; "STICKY BIT" CALCULATION FIXED 10/14/75 --RJF
1007 ;; BASE must not get temporarily bound to NIL by being placed
1008 ;; in a PROG list as this will confuse stepping programs.
1010 (defun fpround (l &aux
(*print-base
* 10.
) *print-radix
*)
1014 ;;*M will be positive if the precision of the argument is greater than
1015 ;;the current precision being used.
1016 (setq *m
(- (integer-length l
) fpprec
))
1020 ;;FPSHIFT is essentially LSH.
1021 (setq adjust
(fpshift 1 (1- *m
)))
1022 (when (minusp l
) (setq adjust
(- adjust
)))
1024 (setq *m
(- (integer-length l
) fpprec
))
1025 (setq *cancelled
(abs *m
))
1026 (cond ((zerop (hipart l
(- *m
)))
1027 ;ONLY ZEROES SHIFTED OFF
1028 (return (fpshift (fpshift l
(- -
1 *m
))
1029 1))) ; ROUND TO MAKE EVEN
1030 (t (return (fpshift l
(- *m
))))))
1032 (setq *m
(- (flatsize (abs l
)) fpprec
))
1033 (setq adjust
(fpshift 1 (1- *m
)))
1034 (when (minusp l
) (setq adjust
(- adjust
)))
1035 (setq adjust
(* 5 adjust
))
1036 (setq *m
(- (flatsize (abs (setq l
(+ l adjust
)))) fpprec
))
1037 (return (fpshift l
(- *m
)))))))
1039 ;; Compute (* L (expt d n)) where D is 2 or 10 depending on
1040 ;; *decfp. Throw away an fractional part by truncating to zero.
1041 (defun fpshift (l n
)
1042 (cond ((null *decfp
)
1043 (cond ((and (minusp n
) (minusp l
))
1044 ;; Left shift of negative number requires some
1045 ;; care. (That is, (truncate l (expt 2 n)), but use
1053 (quotient l
(expt 10.
(- n
))))
1056 ;; Bignum LSH -- N is assumed (and declared above) to be a fixnum.
1057 ;; This isn't really LSH, since the sign bit isn't propagated when
1058 ;; shifting to the right, i.e. (BIGLSH -100 -3) = -40, whereas
1059 ;; (LSH -100 -3) = 777777777770 (on a 36 bit machine).
1060 ;; This actually computes (* X (EXPT 2 N)). As of 12/21/80, this function
1061 ;; was only called by FPSHIFT. I would like to hear an argument as why this
1062 ;; is more efficient than simply writing (* X (EXPT 2 N)). Is the
1063 ;; intermediate result created by (EXPT 2 N) the problem? I assume that
1064 ;; EXPT tries to LSH when possible.
1067 (cond ((and (not (bignump x
))
1068 (< n
#.
(- +machine-fixnum-precision
+)))
1070 ;; Either we are shifting a fixnum to the right, or shifting
1071 ;; a fixnum to the left, but not far enough left for it to become
1073 ((and (not (bignump x
))
1075 (< (+ (integer-length x
) n
) #.
+machine-fixnum-precision
+)))
1076 ;; The form which follows is nearly identical to (ASH X N), however
1077 ;; (ASH -100 -20) = -1, whereas (BIGLSH -100 -20) = 0.
1080 (- (biglsh (- x
) n
)))) ;(- x) may be a bignum even is x is a fixnum.
1081 ;; If we get here, then either X is a bignum or our answer is
1082 ;; going to be a bignum.
1084 (cond ((> (abs n
) (integer-length x
)) 0)
1086 (hipart x
(+ (integer-length x
) n
)))
1087 (t (- (hipart x
(+ (integer-length x
) n
))))))
1089 ;; Isn't this the kind of optimization that compilers are
1090 ;; supposed to make?
1091 ((< n
#.
(1- +machine-fixnum-precision
+)) (* x
(ash 1 n
)))
1092 (t (* x
(expt 2 n
)))))
1097 ;; For negative x, use exp(-x) = 1/exp(x)
1099 ;; For x > 0, exp(x) = exp(r+y) = exp(r) * exp(y), where x = r + y and
1103 (unless (signp ge
(car x
))
1104 (return (fpquotient (fpone) (fpexp (fpabs x
)))))
1105 (setq r
(fpintpart x
:skip-exponent-check-p t
))
1106 (return (cond ((< r
2)
1109 (setq s
(fpexp1 (fpdifference x
(intofp r
))))
1112 (let ((fpprec (+ fpprec
(integer-length r
) -
1))
1114 (bcons (fpexpt (fpe) r
))))))))))) ; patch for full precision %E
1116 ;; exp(x) for small x, using Taylor series.
1118 (prog (term ans oans
)
1119 (setq ans
(setq term
(fpone)))
1122 (setq term
(fpquotient (fptimes* x term
) (intofp n
)))
1124 (setq ans
(fpplus ans term
)))
1127 ;; Does one higher precision to round correctly.
1128 ;; A and B are each a list of a mantissa and an exponent.
1129 (defun fpquotient (a b
)
1130 (cond ((equal (car b
) 0)
1131 (merror (intl:gettext
"pquotient: attempted quotient by zero.")))
1132 ((equal (car a
) 0) '(0 0))
1133 (t (list (fpround (quotient (fpshift (car a
) (+ 3 fpprec
)) (car b
)))
1134 (+ -
3 (- (cadr a
) (cadr b
)) *m
)))))
1136 (defun fpgreaterp (a b
)
1137 (fpposp (fpdifference a b
)))
1139 (defun fplessp (a b
)
1140 (fpposp (fpdifference b a
)))
1145 (defun fpmin (arg1 &rest args
)
1147 (mapc #'(lambda (u) (if (fplessp u min
) (setq min u
))) args
)
1150 (defun fpmax (arg1 &rest args
)
1152 (mapc #'(lambda (u) (if (fpgreaterp u max
) (setq max u
))) args
)
1155 ;; The following functions compute bigfloat values for %e, %pi,
1156 ;; %gamma, and log(2). For each precision, the computed value is
1157 ;; cached in a hash table so it doesn't need to be computed again.
1158 ;; There are functions to return the hash table or clear the hash
1159 ;; table, for debugging.
1161 ;; Note that each of these return a bigfloat number, but without the
1165 ;; https://sourceforge.net/p/maxima/bugs/1842/
1166 ;; for an explanation.
1167 (let ((table (make-hash-table)))
1169 (let ((value (gethash fpprec table
)))
1172 (setf (gethash fpprec table
) (cdr (fpe1))))))
1175 (defun clear_fpe_table ()
1178 (let ((table (make-hash-table)))
1180 (let ((value (gethash fpprec table
)))
1183 (setf (gethash fpprec table
) (cdr (fppi1))))))
1184 (defun fppi-table ()
1186 (defun clear_fppi_table ()
1189 (let ((table (make-hash-table)))
1191 (let ((value (gethash fpprec table
)))
1194 (setf (gethash fpprec table
) (cdr (fpgamma1))))))
1195 (defun fpgamma-table ()
1197 (defun clear_fpgamma_table ()
1200 (let ((table (make-hash-table)))
1202 (let ((value (gethash fpprec table
)))
1205 (setf (gethash fpprec table
) (comp-log2)))))
1206 (defun fplog2-table ()
1208 (defun clear_fplog2_table ()
1211 ;; This doesn't need a hash table because there's never a problem with
1212 ;; using a high precision value and rounding to a lower precision
1213 ;; value because 1 is always an exact bfloat.
1215 (cond (*decfp
(intofp 1))
1216 ((= fpprec
(bigfloat-prec bigfloatone
)) (cdr bigfloatone
))
1219 ;;----------------------------------------------------------------------------;;
1221 ;; The values of %e, %pi, %gamma and log(2) are computed by the technique of
1222 ;; binary splitting. See http://www.ginac.de/CLN/binsplit.pdf for details.
1224 ;; Volker van Nek, Sept. 2014
1230 (let ((e (compe (+ fpprec
12)))) ;; compute additional bits
1231 (bcons (list (fpround (car e
)) (cadr e
))) )) ;; round to fpprec
1233 ;; Taylor: %e = sum(s[i] ,i,0,inf) where s[i] = 1/i!
1236 (let ((fpprec prec
))
1237 (multiple-value-bind (tt qq
) (split-taylor-e 0 (taylor-e-size prec
))
1238 (fpquotient (intofp tt
) (intofp qq
)) )))
1240 ;; binary splitting:
1243 ;; s[i] = ----------------------
1244 ;; q[0]*q[1]*q[2]*..*q[i]
1249 (defun split-taylor-e (i j
)
1252 (setq qq
(if (= i
0) 1 i
)
1254 (let ((m (ash (+ i j
) -
1)))
1255 (multiple-value-bind (tl ql
) (split-taylor-e i m
)
1256 (multiple-value-bind (tr qr
) (split-taylor-e m j
)
1258 tt
(+ (* qr tl
) tr
) )))))
1261 ;; stop when i! > 2^fpprec
1263 ;; log(i!) = sum(log(k), k,1,i) > fpprec * log(2)
1265 (defun taylor-e-size (prec)
1267 (lim (* prec
(log 2))) )
1270 (incf acc
(log i
)) )))
1272 ;;----------------------------------------------------------------------------;;
1277 (let ((pi1 (comppi (+ fpprec
10))))
1278 (bcons (list (fpround (car pi1
)) (cadr pi1
))) ))
1280 ;; Chudnovsky & Chudnovsky:
1282 ;; C^(3/2)/(12*%pi) = sum(s[i], i,0,inf),
1284 ;; where s[i] = (-1)^i*(6*i)!*(A*i+B) / (i!^3*(3*i)!*C^(3*i))
1286 ;; and A = 545140134, B = 13591409, C = 640320
1288 (defun comppi (prec)
1290 nr n d oldn tt qq n
*qq
)
1292 ;; compute n/d = sqrt(10005) :
1294 ;; n[0] n[i+1] = n[i]^2+a*d[i]^2 n[inf]
1295 ;; quadratic Heron: x[0] = ----, , sqrt(a) = ------
1296 ;; d[0] d[i+1] = 2*n[i]*d[i] d[inf]
1298 (multiple-value-setq (nr n d
) (sqrt-10005-constants fpprec
))
1301 n
(+ (* n n
) (* 10005 d d
))
1304 ;; divide C^(3/2)/12 = 3335*2^7*sqrt(10005)
1305 ;; by Chudnovsky-sum = tt/qq :
1307 (setq nr
(ceiling (* fpprec
0.021226729578153))) ;; nr of summands
1308 ;; fpprec*log(2)/log(C^3/(24*6*2*6))
1309 (multiple-value-setq (tt qq
) (split-chudnovsky 0 (1+ nr
)))
1311 n
*qq
(intofp (* n qq
)) )
1312 (fpquotient (list (car n
*qq
) (+ (cadr n
*qq
) 7))
1313 (intofp (* d tt
)) )))
1315 ;; The returned n and d serve as start values for the iteration.
1316 ;; n/d = sqrt(10005) with a precision of p = ceiling(prec/2^nr) bits
1317 ;; where nr is the number of needed iterations.
1319 (defun sqrt-10005-constants (prec)
1320 (let (ilen p nr n d
)
1323 (setq ilen
(integer-length prec
)
1325 p
(ceiling (* prec
(expt 2.0 (- nr
)))) ))
1327 ((<= p
76) (setq n
256192036001 d
2561280120))
1328 ((<= p
89) (setq n
51244811200700 d
512320048001))
1329 ((<= p
102) (setq n
2050048640064001 d
20495363200160))
1330 ((<= p
115) (setq n
410060972824000900 d
4099584960080001))
1331 (t (setq n
16404488961600100001 d
164003893766400200)) )
1334 ;; binary splitting:
1336 ;; a[i] * p[0]*p[1]*p[2]*..*p[i]
1337 ;; s[i] = -----------------------------
1338 ;; q[0]*q[1]*q[2]*..*q[i]
1343 ;; p[i] = - (6*i-5)*(2*i-1)*(6*i-1)
1344 ;; q[i] = C^3/24*i^3
1346 (defun split-chudnovsky (i j
)
1347 (let (aa pp
/qq pp qq tt
)
1350 (setq aa
13591409 pp
1 qq
1 tt aa
)
1351 (setq aa
(+ (* i
545140134) 13591409)
1352 pp
/qq
(/ (* (- 5 (* 6 i
)) (- (* 2 i
) 1) (- (* 6 i
) 1))
1353 10939058860032000 ) ; C^3/24
1354 pp
(numerator pp
/qq
)
1355 qq
(* (denominator pp
/qq
) (expt i
3))
1357 (let ((m (ash (+ i j
) -
1)))
1358 (multiple-value-bind (tl ql pl
) (split-chudnovsky i m
)
1359 (multiple-value-bind (tr qr pr
) (split-chudnovsky m j
)
1362 tt
(+ (* qr tl
) (* pl tr
)) )))))
1363 (values tt qq pp
) ))
1365 ;;----------------------------------------------------------------------------;;
1367 ;; Euler-Mascheroni constant GAMMA
1370 (let ((res (comp-bf%gamma
(+ fpprec
14))))
1371 (bcons (list (fpround (car res
)) (cadr res
))) ))
1373 ;; Brent-McMillan algorithm
1376 ;; alpha = 4.970625759544
1378 ;; n > 0 and N-1 >= alpha*n
1380 ;; H(k) = sum(1/i, i,1,k)
1382 ;; S = sum(H(k)*(n^k/k!)^2, k,0,N-1)
1384 ;; I = sum((n^k/k!)^2, k,0,N-1)
1386 ;; T = 1/(4*n)*sum((2*k)!^3/(k!^4*(16*n)^(2*k)), k,0,2*n-1)
1389 ;; %gamma = S/I - T/I^2 - log(n)
1392 ;; |%gamma - gamma| < 24 * e^(-8*n)
1394 ;; (Corollary 2, Remark 2, Brent/Johansson http://arxiv.org/pdf/1312.0039v1.pdf)
1396 (defun comp-bf%gamma
(prec)
1397 (let* ((fpprec prec
)
1398 (n (ceiling (* 1/8 (+ (* prec
(log 2.0)) (log 24.0)))))
1400 (alpha 4.970625759544)
1401 (lim (ceiling (* alpha n
)))
1403 sumi sumi2
;; I and I^2
1404 sumt
/sumi2
) ;; T/I^2
1405 (multiple-value-bind (vv tt qq dd
) (split-gamma-1 1 (1+ lim
) n2
)
1407 ;; sums = vv/(qq*dd)
1409 ;; sums/sumi = vv/(qq*dd)*qq/tt = vv/(dd*tt)
1411 (setq sums
/sumi
(fpquotient (intofp vv
) (intofp (* dd tt
)))
1412 sumi
(fpquotient (intofp tt
) (intofp qq
))
1413 sumi2
(fptimes* sumi sumi
) )
1415 (multiple-value-bind (ttt qqq
) (split-gamma-2 0 (* 2 n
) (* 32 n2
))
1417 ;; sumt = 1/(4*n)*ttt/qqq
1418 ;; sumt/sumi2 = ttt/(4*n*qqq*sumi2)
1420 (setq sumt
/sumi2
(fpquotient (intofp ttt
)
1421 (fptimes* (intofp (* 4 n qqq
)) sumi2
) ))
1423 (fpdifference sums
/sumi
(fpplus sumt
/sumi2
(log-n n
)) )))))
1425 ;; split S and I simultaneously:
1427 ;; summands I[0] = 1, I[i]/I[i-1] = n^2/i^2
1429 ;; S[0] = 0, S[i]/S[i-1] = n^2/i^2*H(i)/H(i-1)
1431 ;; p[0]*p[1]*p[2]*..*p[i]
1432 ;; I[i] = ----------------------
1433 ;; q[0]*q[1]*q[2]*..*q[i]
1439 ;; c[0] c[1] c[2] c[i]
1440 ;; S[i] = H[i] * I[i], where H[i] = ---- + ---- + ---- + .. + ----
1441 ;; d[0] d[1] d[2] d[i]
1447 (defun split-gamma-1 (i j n2
)
1448 (let (pp cc dd qq tt vv
)
1451 (if (= i
1) ;; S[0] is 0 -> start with i=1 and add I[0]=1 to tt :
1452 (setq pp n2 cc
1 dd
1 qq
1 tt
(1+ n2
) vv n2
)
1453 (setq pp n2 cc
1 dd i qq
(* i i
) tt pp vv tt
) ))
1455 (let* ((m (ash (+ i j
) -
1)) tmp
)
1456 (multiple-value-bind (vl tl ql dl cl pl
) (split-gamma-1 i m n2
)
1457 (multiple-value-bind (vr tr qr dr cr pr
) (split-gamma-1 m j n2
)
1459 cc
(+ (* cl dr
) (* dl cr
))
1463 tt
(+ (* tl qr
) tmp
)
1464 vv
(+ (* dr
(+ (* vl qr
) (* cl tmp
))) (* dl pl vr
)) ))))))
1465 (values vv tt qq dd cc pp
) ))
1469 ;; summands T[0] = 1, T[i]/T[i-1] = (2*i-1)^3/(32*i*n^2)
1471 ;; p[0]*p[1]*p[2]*..*p[i]
1472 ;; T[i] = ----------------------
1473 ;; q[0]*q[1]*q[2]*..*q[i]
1475 ;; where p[0] = q[0] = 1
1479 (defun split-gamma-2 (i j n2
*32)
1484 (setq pp
1 qq
1 tt
1)
1485 (setq pp
(expt (1- (* 2 i
)) 3) qq
(* i n2
*32) tt pp
) ))
1487 (let* ((m (ash (+ i j
) -
1)))
1488 (multiple-value-bind (tl ql pl
) (split-gamma-2 i m n2
*32)
1489 (multiple-value-bind (tr qr pr
) (split-gamma-2 m j n2
*32)
1492 tt
(+ (* tl qr
) (* pl tr
)) ))))))
1493 (values tt qq pp
) ))
1495 ;;----------------------------------------------------------------------------;;
1497 ;; log(2) = 18*L(26) - 2*L(4801) + 8*L(8749)
1499 ;; where L(k) = atanh(1/k)
1501 ;; see http://numbers.computation.free.fr/Constants/constants.html
1503 ;;;(defun $log2 () (bcons (comp-log2))) ;; checked against reference table
1507 (let ((fpprec (+ fpprec
12)))
1509 (fpdifference (n*atanh-1
/k
18 26) (n*atanh-1
/k
2 4801))
1510 (n*atanh-1
/k
8 8749) ))))
1511 (list (fpround (car res
)) (cadr res
)) ))
1513 ;; Taylor: atanh(1/k) = sum(s[i], i,0,inf)
1515 ;; where s[i] = 1/((2*i+1)*k^(2*i+1))
1517 (defun n*atanh-1
/k
(n k
) ;; integer n,k
1519 (nr (ceiling (* fpprec
(/ (log 2) (log k2
))))) )
1520 (multiple-value-bind (tt qq bb
) (split-atanh-1/k
0 (1+ nr
) k k2
)
1521 (fpquotient (intofp (* n tt
)) (intofp (* bb qq
))) )))
1523 ;; binary splitting:
1525 ;; s[i] = -----------------------------
1526 ;; b[i] * q[0]*q[1]*q[2]*..*q[i]
1533 (defun split-atanh-1/k
(i j k k2
)
1537 (setq bb
1 qq k tt
1)
1538 (setq bb
(1+ (* 2 i
)) qq k2 tt
1) )
1539 (let ((m (ash (+ i j
) -
1)))
1540 (multiple-value-bind (tl ql bl
) (split-atanh-1/k i m k k2
)
1541 (multiple-value-bind (tr qr br
) (split-atanh-1/k m j k k2
)
1544 tt
(+ (* br qr tl
) (* bl tr
)) )))))
1545 (values tt qq bb
) ))
1547 ;;----------------------------------------------------------------------------;;
1549 ;; log(n) = log(n/2^k) + k*log(2)
1551 ;;;(defun $log10 () (bcons (log-n 10))) ;; checked against reference table
1553 (defun log-n (n) ;; integer n > 0
1555 ((= 1 n
) (list 0 0))
1556 ((= 2 n
) (comp-log2))
1559 (let ((fpprec (+ fpprec
10))
1560 (k (integer-length n
)) )
1561 ;; choose k so that |n/2^k - 1| is as small as possible:
1562 (when (< n
(* (coerce 2/3 'flonum
) (ash 1 k
))) (decf k
))
1563 ;; now |n/2^k - 1| <= 1/3
1564 (fpplus (log-u/2^k n k fpprec
)
1565 (fptimes* (intofp k
) (comp-log2)) ))))
1566 (list (fpround (car res
)) (cadr res
)) ))))
1568 ;; log(1+u/v) = 2 * sum(s[i], i,0,inf)
1570 ;; where s[i] = (u/(2*v+u))^(2*i+1)/(2*i+1)
1572 (defun log-u/2^k
(u k prec
) ;; integer u k; x = u/2^k; |x - 1| < 1
1573 (setq u
(- u
(ash 1 k
))) ;; x <-- x - 1
1575 ((= 0 u
) (list 0 0))
1577 (while (evenp u
) (setq u
(ash u -
1)) (decf k
))
1581 (nr (ceiling (* prec
(/ (log 2) 2 (log (abs (/ w u
)))))))
1583 (multiple-value-bind (tt qq bb
) (split-log-1+u
/v
0 (1+ nr
) u u2 w w2
)
1584 (setq lg
/2 (fpquotient (intofp tt
) (intofp (* bb qq
)))) ;; sum
1585 (list (car lg
/2) (1+ (cadr lg
/2))) ))))) ;; 2*sum
1587 ;; binary splitting:
1589 ;; p[0]*p[1]*p[2]*..*p[i]
1590 ;; s[i] = -----------------------------
1591 ;; b[i] * q[0]*q[1]*q[2]*..*q[i]
1600 (defun split-log-1+u
/v
(i j u u2 w w2
)
1604 (setq pp u bb
1 qq w tt u
)
1605 (setq pp u2 bb
(1+ (* 2 i
)) qq w2 tt pp
) )
1606 (let ((m (ash (+ i j
) -
1)))
1607 (multiple-value-bind (tl ql bl pl
) (split-log-1+u
/v i m u u2 w w2
)
1608 (multiple-value-bind (tr qr br pr
) (split-log-1+u
/v m j u u2 w w2
)
1612 tt
(+ (* br qr tl
) (* bl pl tr
)) )))))
1613 (values tt qq bb pp
) ))
1615 ;;----------------------------------------------------------------------------;;
1618 (defun fpdifference (a b
)
1619 (fpplus a
(fpminus b
)))
1622 (if (equal (car x
) 0)
1624 (list (- (car x
)) (cadr x
))))
1627 (prog (*m exp man sticky
)
1629 (cond ((equal (car a
) 0) (return b
))
1630 ((equal (car b
) 0) (return a
)))
1631 (setq exp
(- (cadr a
) (cadr b
)))
1632 (setq man
(cond ((equal exp
0)
1634 (fpshift (+ (car a
) (car b
)) 2))
1636 (setq sticky
(hipart (car b
) (- 1 exp
)))
1637 (setq sticky
(cond ((signp e sticky
) 0)
1638 ((signp l
(car b
)) -
1)
1640 ; COMPUTE STICKY BIT
1641 (+ (fpshift (car a
) 2)
1642 ; MAKE ROOM FOR GUARD DIGIT & STICKY BIT
1643 (fpshift (car b
) (- 2 exp
))))
1644 (t (setq sticky
(hipart (car a
) (1+ exp
)))
1645 (setq sticky
(cond ((signp e sticky
) 0)
1646 ((signp l
(car a
)) -
1)
1648 (+ (fpshift (car b
) 2)
1649 (fpshift (car a
) (+ 2 exp
))))))
1650 (setq man
(+ man sticky
))
1651 (return (cond ((equal man
0) '(0 0))
1652 (t (setq man
(fpround man
))
1653 (setq exp
(+ -
2 *m
(max (cadr a
) (cadr b
))))
1656 (defun fptimes* (a b
)
1657 (if (or (zerop (car a
)) (zerop (car b
)))
1659 (list (fpround (* (car a
) (car b
)))
1660 (+ *m
(cadr a
) (cadr b
) (- fpprec
)))))
1662 ;; Don't use the symbol BASE since it is SPECIAL.
1664 (defun fpintexpt (int nn fixprec
) ;INT is integer
1665 (setq fixprec
(truncate fixprec
(1- (integer-length int
)))) ;NN is pos
1666 (let ((bas (intofp (expt int
(min nn fixprec
)))))
1668 (fptimes* (intofp (expt int
(rem nn fixprec
)))
1669 (fpexpt bas
(quotient nn fixprec
)))
1672 ;; NN is positive or negative integer
1674 (defun fpexpt (p nn
)
1675 (cond ((zerop nn
) (fpone))
1677 ((< nn
0) (fpquotient (fpone) (fpexpt p
(- nn
))))
1682 (do ((ii (quotient nn
2) (quotient ii
2)))
1684 (setq p
(fptimes* p p
))
1686 (setq u
(fptimes* u p
))))
1689 (defun exptbigfloat (p n
)
1690 (cond ((equal n
1) p
)
1691 ((equal n
0) ($bfloat
1))
1692 ((not ($bfloatp p
)) (list '(mexpt) p n
))
1693 ((equal (cadr p
) 0) ($bfloat
0))
1694 ((and (< (cadr p
) 0) (ratnump n
))
1695 (mul2 (let ($numer $float $keepfloat $ratprint
)
1697 (exptbigfloat (bcons (fpminus (cdr p
))) n
)))
1698 ((and (< (cadr p
) 0) (not (integerp n
)))
1699 (cond ((or (equal n
0.5) (equal n bfhalf
))
1700 (exptbigfloat p
'((rat simp
) 1 2)))
1701 ((or (equal n -
0.5) (equal n bfmhalf
))
1702 (exptbigfloat p
'((rat simp
) -
1 2)))
1703 (($bfloatp
(setq n
($bfloat n
)))
1704 (cond ((equal n
($bfloat
(fpentier n
)))
1705 (exptbigfloat p
(fpentier n
)))
1706 (t ;; for P<0: P^N = (-P)^N*cos(pi*N) + i*(-P)^N*sin(pi*N)
1707 (setq p
(exptbigfloat (bcons (fpminus (cdr p
))) n
)
1708 n
($bfloat
`((mtimes) $%pi
,n
)))
1709 (add2 ($bfloat
`((mtimes) ,p
,(*fpsin n nil
)))
1710 `((mtimes simp
) ,($bfloat
`((mtimes) ,p
,(*fpsin n t
)))
1712 (t (list '(mexpt) p n
))))
1713 ((and (ratnump n
) (< (caddr n
) 10.
))
1714 (bcons (fpexpt (fproot p
(caddr n
)) (cadr n
))))
1716 (setq n
($bfloat n
))
1718 ((not ($bfloatp n
)) (list '(mexpt) p n
))
1720 (let ((extrabits (max 1 (+ (caddr n
) (integer-length (caddr p
))))))
1722 (let ((fpprec (+ extrabits fpprec
)))
1723 (fpexp (fptimes* (cdr (bigfloatp n
)) (fplog (cdr (bigfloatp p
)))))))
1724 (setq p
(list (fpround (car p
)) (+ (- extrabits
) *m
(cadr p
))))
1726 ;; The number of extra bits required
1727 ((< n
0) (invertbigfloat (exptbigfloat p
(- n
))))
1728 (t (bcons (fpexpt (cdr p
) n
)))))
1730 (defun fproot (a n
) ; computes a^(1/n) see Fitch, SIGSAM Bull Nov 74
1732 ;; Special case for a = 0b0. General algorithm loops endlessly in that case.
1734 ;; Unlike many or maybe all of the other functions named FP-something,
1735 ;; FPROOT assumes it is called with an argument like
1736 ;; '((BIGFLOAT ...) FOO BAR) instead of '(FOO BAR).
1737 ;; However FPROOT does return something like '(FOO BAR).
1739 (if (eql (cadr a
) 0)
1742 (let* ((ofprec fpprec
)
1743 (fpprec (+ fpprec
2)) ;assumes a>0 n>=2
1744 (bk (fpexpt (intofp 2) (1+ (quotient (cadr (setq a
(cdr (bigfloatp a
)))) n
)))))
1745 (do ((x bk
(fpdifference x
1746 (setq bk
(fpquotient (fpdifference
1747 x
(fpquotient a
(fpexpt x n1
))) n
))))
1750 ((or (equal bk
'(0 0))
1751 (> (- (cadr x
) (cadr bk
)) ofprec
))
1753 (list (fpround (car a
)) (+ -
2 *m
(cadr a
))))))
1755 (defun timesbigfloat (h)
1756 (prog (fans r nfans
)
1757 (setq fans
(bcons (fpone)) nfans
1)
1760 (if (setq r
(bigfloatp (car l
)))
1761 (setq fans
(bcons (fptimes* (cdr r
) (cdr fans
))))
1762 (setq nfans
(list '(mtimes) (car l
) nfans
))))
1763 (return (if (equal nfans
1)
1765 (simplify (list '(mtimes) fans nfans
))))))
1767 (defun invertbigfloat (a)
1768 ;; If A is a bigfloat, be sure to round it to the current precision.
1769 ;; (See Bug 2543079 for one of the symptoms.)
1770 (let ((b (bigfloatp a
)))
1772 (bcons (fpquotient (fpone) (cdr b
)))
1773 (simplify (list '(mexpt) a -
1)))))
1776 (fpend (let ((fpprec (+ 8. fpprec
)))
1778 (fpexp (cdr (bigfloatp a
)))
1779 (list '(mexpt) '$%e a
)))))
1781 (defun *fpsin
(a fl
)
1782 (fpend (let ((fpprec (+ 8. fpprec
)))
1783 (cond (($bfloatp a
) (fpsin (cdr ($bfloat a
)) fl
))
1784 (fl (list '(%sin
) a
))
1785 (t (list '(%cos
) a
))))))
1788 (cond ((equal (car a
) 0) (bcons a
))
1790 (setq a
(list (fpround (car a
)) (+ -
8.
*m
(cadr a
))))
1794 (defun fparcsimp (e) ; needed for e.g. ASIN(.123567812345678B0) with
1795 ;; FPPREC 16, to get rid of the miniscule imaginary
1796 ;; part of the a+bi answer.
1797 (if (and (mplusp e
) (null (cdddr e
))
1798 (mtimesp (caddr e
)) (null (cdddr (caddr e
)))
1799 ($bfloatp
(cadr (caddr e
)))
1800 (eq (caddr (caddr e
)) '$%i
)
1801 (< (caddr (cadr (caddr e
))) (+ (- fpprec
) 2)))
1805 (defun sinbigfloat (x)
1808 (defun cosbigfloat (x)
1809 (*fpsin
(car x
) nil
))
1811 ;; THIS VERSION OF FPSIN COMPUTES SIN OR COS TO PRECISION FPPREC,
1812 ;; BUT CHECKS FOR THE POSSIBILITY OF CATASTROPHIC CANCELLATION DURING
1813 ;; ARGUMENT REDUCTION (E.G. SIN(N*%PI+EPSILON))
1814 ;; *FPSINCHECK* WILL CAUSE PRINTOUT OF ADDITIONAL INFO WHEN
1815 ;; EXTRA PRECISION IS NEEDED FOR SIN/COS CALCULATION. KNOWN
1816 ;; BAD FEATURES: IT IS NOT NECESSARY TO USE EXTRA PRECISION FOR, E.G.
1817 ;; SIN(PI/2), WHICH IS NOT NEAR ZERO, BUT EXTRA
1818 ;; PRECISION IS USED SINCE IT IS NEEDED FOR COS(PI/2).
1819 ;; PRECISION SEEMS TO BE 100% SATSIFACTORY FOR LARGE ARGUMENTS, E.G.
1820 ;; SIN(31415926.0B0), BUT LESS SO FOR SIN(3.1415926B0). EXPLANATION
1821 ;; NOT KNOWN. (9/12/75 RJF)
1823 (defvar *fpsincheck
* nil
)
1825 ;; FL is a T for sin and NIL for cos.
1827 (prog (piby2 r sign res k
*cancelled
)
1828 (setq sign
(cond (fl (signp g
(car x
)))
1831 (when (equal (car x
) 0)
1832 (return (if fl
(intofp 0) (intofp 1))))
1836 (let ((fpprec (max fpprec
(+ fpprec
(cadr x
))))
1841 loop
(setq x
(cdr (bigfloatp xt
)))
1842 (setq piby2
(fpquotient (fppi) (intofp 2)))
1843 (setq r
(fpintpart (fpquotient x piby2
) :skip-exponent-check-p t
))
1844 (setq x
(fpplus x
(fptimes* (intofp (- r
)) piby2
)))
1846 (fpplus x
(fpminus piby2
))
1847 (setq *cancelled
(max k
*cancelled
))
1849 (print `(*canc
= ,*cancelled fpprec
= ,fpprec oldprec
= ,oldprec
)))
1850 (cond ((not (> oldprec
(- fpprec
*cancelled
)))
1853 (cond (fl (cond ((= r
0) (fpsin1 x
))
1854 ((= r
1) (fpcos1 x
))
1855 ((= r
2) (fpminus (fpsin1 x
)))
1856 ((= r
3) (fpminus (fpcos1 x
)))))
1857 (t (cond ((= r
0) (fpcos1 x
))
1858 ((= r
1) (fpminus (fpsin1 x
)))
1859 ((= r
2) (fpminus (fpcos1 x
)))
1860 ((= r
3) (fpsin1 x
))))))
1861 (return (bcons (if sign res
(fpminus res
)))))
1863 (incf fpprec
*cancelled
)
1869 ;; Compute SIN or COS in (0,PI/2). FL is T for SIN, NIL for COS.
1871 ;; Use Taylor series
1872 (defun fpsincos1 (x fl
)
1873 (prog (ans term oans x2
)
1874 (setq ans
(if fl x
(intofp 1))
1875 x2
(fpminus(fptimes* x x
)))
1877 (do ((n (if fl
3 2) (+ n
2)))
1879 (setq term
(fptimes* term
(fpquotient x2
(intofp (* n
(1- n
))))))
1881 ans
(fpplus ans term
)))
1888 (if (signp ge
(car x
))
1890 (cons (- (car x
)) (cdr x
))))
1893 (let ((fpprec (bigfloat-prec f
)))
1894 (fpintpart (cdr f
))))
1896 ;; Calculate the integer part of a floating point number that is represented as
1899 ;; (MANTISSA EXPONENT)
1901 ;; The special variable fpprec should be bound to the precision (in bits) of the
1902 ;; number. This encodes how many bits are known of the result and also a right
1903 ;; shift. The pair denotes the number MANTISSA * 2^(EXPONENT - FPPREC), of which
1904 ;; FPPREC bits are known.
1906 ;; If EXPONENT is large and positive then we might not have enough
1907 ;; information to calculate the integer part. Specifically, we only
1908 ;; have enough information if EXPONENT < FPPREC. If that isn't the
1909 ;; case, we signal a Maxima error. However, if SKIP-EXPONENT-CHECK-P
1910 ;; is non-NIL, this check is skipped, and we compute the integer part
1913 ;; For the bigfloat code here, skip-exponent-check-p should be true.
1914 ;; For other uses (see commit 576c7508 and bug #2784), this should be
1915 ;; nil, which is the default.
1916 (defun fpintpart (f &key skip-exponent-check-p
)
1917 (destructuring-bind (mantissa exponent
)
1919 (let ((m (- fpprec exponent
)))
1921 (quotient mantissa
(expt 2 (- fpprec exponent
)))
1922 (if (and (not skip-exponent-check-p
) (< exponent fpprec
))
1923 (merror "~M doesn't have enough precision to compute its integer part"
1924 `((bigfloat ,fpprec
) ,mantissa
,exponent
))
1925 (* mantissa
(expt 2 (- m
))))))))
1927 (defun logbigfloat (a)
1928 (cond (($bfloatp
(car a
))
1929 (big-float-log ($bfloat
(car a
))))
1931 (list '(%log
) (car a
)))))
1934 ;;; Computes the log of a bigfloat number.
1938 ;;; log(1+x) = sum((x/(x+2))^(2*n+1)/(2*n+1),n,0,inf);
1944 ;;; = 2 > --------------
1950 ;;; which converges for x > 0.
1952 ;;; Note that FPLOG is given 1+X, not X.
1954 ;;; However, to aid convergence of the series, we scale 1+x until 1/e
1958 (prog (over two ans oldans term e sum
)
1959 (unless (> (car x
) 0)
1960 (merror (intl:gettext
"fplog: argument must be positive; found: ~M") (car x
)))
1962 over
(fpquotient (fpone) e
)
1964 ;; Scale X until 1/e < X <= E. ANS keeps track of how
1965 ;; many factors of E were used. Set X to NIL if X is E.
1968 (cond ((equal x e
) (setq x nil
) (return nil
))
1969 ((and (fplessp x e
) (fplessp over x
))
1972 (setq x
(fptimes* x e
))
1976 (setq x
(fpquotient x e
)))))
1977 (when (null x
) (return (intofp (1+ ans
))))
1978 ;; Prepare X for the series. The series is for 1 + x, so
1979 ;; get x from our X. TERM is (x/(x+2)). X becomes
1981 (setq x
(fpdifference x
(fpone))
1983 (setq x
(fpexpt (setq term
(fpquotient x
(fpplus x
(setq two
(intofp 2))))) 2))
1984 ;; Sum the series until the sum (in ANS) doesn't change
1986 (setq sum
(intofp 0))
1988 ((equal sum oldans
))
1990 (setq sum
(fpplus sum
(fpquotient term
(intofp n
))))
1991 (setq term
(fptimes* term x
)))
1992 (return (fpplus ans
(fptimes* two sum
)))))
1994 (defun mabsbigfloat (l)
1996 (setq r
(bigfloatp (car l
)))
1997 (return (if (null r
)
1998 (list '(mabs) (car l
))
1999 (bcons (fpabs (cdr r
)))))))
2002 ;;;; Bigfloat implementations of special functions.
2005 ;;; This is still a bit messy. Some functions here take bigfloat
2006 ;;; numbers, represented by ((bigfloat) <mant> <exp>), but others want
2007 ;;; just the FP number, represented by (<mant> <exp>). Likewise, some
2008 ;;; return a bigfloat, some return just the FP.
2010 ;;; This needs to be systemized somehow. It isn't helped by the fact
2011 ;;; that some of the routines above also do the samething.
2013 ;;; The implementation for the special functions for a complex
2014 ;;; argument are mostly taken from W. Kahan, "Branch Cuts for Complex
2015 ;;; Elementary Functions or Much Ado About Nothing's Sign Bit", in
2016 ;;; Iserles and Powell (eds.) "The State of the Art in Numerical
2017 ;;; Analysis", pp 165-211, Clarendon Press, 1987
2019 ;; Compute exp(x) - 1, but do it carefully to preserve precision when
2020 ;; |x| is small. X is a FP number, and a FP number is returned. That
2021 ;; is, no bigfloat stuff.
2023 ;; What is the right breakpoint here? Is 1 ok? Perhaps 1/e is better?
2024 (cond ((fpgreaterp (fpabs x
) (fpone))
2026 (fpdifference (fpexp x
) (fpone)))
2028 ;; Use Taylor series for exp(x) - 1
2034 (setf term
(fpquotient (fptimes* x term
) (intofp n
)))
2036 (setf ans
(fpplus ans term
)))
2039 ;; log(1+x) for small x. X is FP number, and a FP number is returned.
2041 ;; Use the same series as given above for fplog. For small x we use
2042 ;; the series, otherwise fplog is accurate enough.
2043 (cond ((fpgreaterp (fpabs x
) (fpone))
2044 (fplog (fpplus x
(fpone))))
2046 (let* ((sum (intofp 0))
2047 (term (fpquotient x
(fpplus x
(intofp 2))))
2048 (f (fptimes* term term
))
2051 ((equal sum oldans
))
2053 (setq sum
(fpplus sum
(fpquotient term
(intofp n
))))
2054 (setq term
(fptimes* term f
)))
2055 (fptimes* sum
(intofp 2))))))
2057 ;; sinh(x) for real x. X is a bigfloat, and a bigfloat is returned.
2059 ;; X must be a maxima bigfloat
2061 ;; See, for example, Hart et al., Computer Approximations, 6.2.27:
2063 ;; sinh(x) = 1/2*(D(x) + D(x)/(1+D(x)))
2065 ;; where D(x) = exp(x) - 1.
2067 ;; But for negative x, use sinh(x) = -sinh(-x) because D(x)
2068 ;; approaches -1 for large negative x.
2069 (cond ((equal 0 (cadr x
))
2070 ;; Special case: x=0. Return immediately.
2074 (let ((d (fpexpm1 (cdr (bigfloatp x
)))))
2075 (bcons (fpquotient (fpplus d
(fpquotient d
(fpplus d
(fpone))))
2080 (fpminus (cdr (fpsinh (bcons (fpminus (cdr (bigfloatp x
)))))))))))
2082 (defun big-float-sinh (x &optional y
)
2083 ;; The rectform for sinh for complex args should be numerically
2084 ;; accurate, so return nil in that case.
2088 ;; asinh(x) for real x. X is a bigfloat, and a bigfloat is returned.
2090 ;; asinh(x) = sign(x) * log(|x| + sqrt(1+x*x))
2094 ;; asinh(x) = x, if 1+x*x = 1
2095 ;; = sign(x) * (log(2) + log(x)), large |x|
2096 ;; = sign(x) * log(2*|x| + 1/(|x|+sqrt(1+x*x))), if |x| > 2
2097 ;; = sign(x) * log1p(|x|+x^2/(1+sqrt(1+x*x))), otherwise.
2099 ;; But I'm lazy right now and we only implement the last 2 cases.
2100 ;; We should implement all cases.
2101 (let* ((fp-x (cdr (bigfloatp x
)))
2105 (minus (minusp (car fp-x
)))
2107 ;; We only use two formulas here. |x| <= 2 and |x| > 2. Should
2108 ;; we add one for very big x and one for very small x, as given above.
2109 (cond ((fpgreaterp absx two
)
2112 ;; log(2*|x| + 1/(|x|+sqrt(1+x^2)))
2113 (setf result
(fplog (fpplus (fptimes* absx two
)
2116 (fproot (bcons (fpplus one
2117 (fptimes* absx absx
)))
2122 ;; log1p(|x|+x^2/(1+sqrt(1+x^2)))
2123 (let ((x*x
(fptimes* absx absx
)))
2124 (setq result
(fplog1p (fpplus absx
2127 (fproot (bcons (fpplus one x
*x
))
2130 (bcons (fpminus result
))
2133 (defun complex-asinh (x y
)
2134 ;; asinh(z) = -%i * asin(%i*z)
2135 (multiple-value-bind (u v
)
2136 (complex-asin (mul -
1 y
) x
)
2137 (values v
(bcons (fpminus (cdr u
))))))
2139 (defun big-float-asinh (x &optional y
)
2141 (multiple-value-bind (u v
)
2143 (add u
(mul '$%i v
)))
2146 (defun fpasin-core (x)
2147 ;; asin(x) = atan(x/(sqrt(1-x^2))
2148 ;; = sgn(x)*[%pi/2 - atan(sqrt(1-x^2)/abs(x))]
2150 ;; Use the first for 0 <= x < 1/2 and the latter for 1/2 < x <= 1.
2152 ;; If |x| > 1, we need to do something else.
2154 ;; asin(x) = -%i*log(sqrt(1-x^2)+%i*x)
2155 ;; = -%i*log(%i*x + %i*sqrt(x^2-1))
2156 ;; = -%i*[log(|x + sqrt(x^2-1)|) + %i*%pi/2]
2157 ;; = %pi/2 - %i*log(|x+sqrt(x^2-1)|)
2159 (let ((fp-x (cdr (bigfloatp x
))))
2160 (cond ((minusp (car fp-x
))
2161 ;; asin(-x) = -asin(x);
2162 (mul -
1 (fpasin (bcons (fpminus fp-x
)))))
2163 ((fplessp fp-x
(cdr bfhalf
))
2165 ;; asin(x) = atan(x/sqrt(1-x^2))
2167 (fpatan (fpquotient fp-x
2169 (fptimes* (fpdifference (fpone) fp-x
)
2170 (fpplus (fpone) fp-x
)))
2172 ((fpgreaterp fp-x
(fpone))
2174 ;; asin(x) = %pi/2 - %i*log(|x+sqrt(x^2-1)|)
2176 ;; Should we try to do something a little fancier with the
2177 ;; argument to log and use log1p for better accuracy?
2178 (let ((arg (fpplus fp-x
2179 (fproot (bcons (fptimes* (fpdifference fp-x
(fpone))
2180 (fpplus fp-x
(fpone))))
2183 (mul -
1 '$%i
(bcons (fplog arg
))))))
2187 ;; asin(x) = %pi/2 - atan(sqrt(1-x^2)/x)
2192 (fpquotient (fproot (bcons (fptimes* (fpdifference (fpone) fp-x
)
2193 (fpplus (fpone) fp-x
)))
2197 ;; asin(x) for real x. X is a bigfloat, and a maxima number (real or
2198 ;; complex) is returned.
2200 ;; asin(x) = atan(x/(sqrt(1-x^2))
2201 ;; = sgn(x)*[%pi/2 - atan(sqrt(1-x^2)/abs(x))]
2203 ;; Use the first for 0 <= x < 1/2 and the latter for 1/2 < x <= 1.
2205 ;; If |x| > 1, we need to do something else.
2207 ;; asin(x) = -%i*log(sqrt(1-x^2)+%i*x)
2208 ;; = -%i*log(%i*x + %i*sqrt(x^2-1))
2209 ;; = -%i*[log(|x + sqrt(x^2-1)|) + %i*%pi/2]
2210 ;; = %pi/2 - %i*log(|x+sqrt(x^2-1)|)
2212 ($bfloat
(fpasin-core x
)))
2214 ;; Square root of a complex number (xx, yy). Both are bigfloats. FP
2215 ;; (non-bigfloat) numbers are returned.
2216 (defun complex-sqrt (xx yy
)
2217 (let* ((x (cdr (bigfloatp xx
)))
2218 (y (cdr (bigfloatp yy
)))
2219 (rho (fpplus (fptimes* x x
)
2221 (setf rho
(fpplus (fpabs x
) (fproot (bcons rho
) 2)))
2222 (setf rho
(fpplus rho rho
))
2223 (setf rho
(fpquotient (fproot (bcons rho
) 2) (intofp 2)))
2227 (when (fpgreaterp rho
(intofp 0))
2228 (setf nu
(fpquotient (fpquotient nu rho
) (intofp 2)))
2229 (when (fplessp x
(intofp 0))
2230 (setf eta
(fpabs nu
))
2231 (setf nu
(if (minusp (car y
))
2236 ;; asin(z) for complex z = x + %i*y. X and Y are bigfloats. The real
2237 ;; and imaginary parts are returned as bigfloat numbers.
2238 (defun complex-asin (x y
)
2239 (let ((x (cdr (bigfloatp x
)))
2240 (y (cdr (bigfloatp y
))))
2241 (multiple-value-bind (re-sqrt-1-z im-sqrt-1-z
)
2242 (complex-sqrt (bcons (fpdifference (intofp 1) x
))
2243 (bcons (fpminus y
)))
2244 (multiple-value-bind (re-sqrt-1+z im-sqrt-1
+z
)
2245 (complex-sqrt (bcons (fpplus (intofp 1) x
))
2247 ;; Realpart is atan(x/Re(sqrt(1-z)*sqrt(1+z)))
2248 ;; Imagpart is asinh(Im(conj(sqrt(1-z))*sqrt(1+z)))
2250 (let ((d (fpdifference (fptimes* re-sqrt-1-z
2252 (fptimes* im-sqrt-1-z
2254 ;; Check for division by zero. If we would divide
2255 ;; by zero, return pi/2 or -pi/2 according to the
2257 (cond ((equal d
'(0 0))
2258 (if (fplessp x
'(0 0))
2259 (fpminus (fpquotient (fppi) (intofp 2)))
2260 (fpquotient (fppi) (intofp 2))))
2262 (fpatan (fpquotient x d
))))))
2264 (fpdifference (fptimes* re-sqrt-1-z
2266 (fptimes* im-sqrt-1-z
2267 re-sqrt-1
+z
)))))))))
2269 (defun big-float-asin (x &optional y
)
2271 (multiple-value-bind (u v
) (complex-asin x y
)
2272 (add u
(mul '$%i v
)))
2276 ;; tanh(x) for real x. X is a bigfloat, and a bigfloat is returned.
2278 ;; X is Maxima bigfloat
2279 ;; tanh(x) = D(2*x)/(2+D(2*x))
2280 (let* ((two (intofp 2))
2281 (fp (cdr (bigfloatp x
)))
2282 (d (fpexpm1 (fptimes* fp two
))))
2283 (bcons (fpquotient d
(fpplus d two
)))))
2285 ;; tanh(z), z = x + %i*y. X, Y are bigfloats, and a maxima number is
2287 (defun complex-tanh (x y
)
2288 (let* ((tv (cdr (tanbigfloat (list y
))))
2289 (beta (fpplus (fpone) (fptimes* tv tv
)))
2290 (s (cdr (fpsinh x
)))
2291 (s^
2 (fptimes* s s
))
2292 (rho (fproot (bcons (fpplus (fpone) s^
2)) 2))
2293 (den (fpplus (fpone) (fptimes* beta s^
2))))
2294 (values (bcons (fpquotient (fptimes* beta
(fptimes* rho s
)) den
))
2295 (bcons (fpquotient tv den
)))))
2297 (defun big-float-tanh (x &optional y
)
2299 (multiple-value-bind (u v
) (complex-tanh x y
)
2300 (add u
(mul '$%i v
)))
2303 ;; atanh(x) for real x, |x| <= 1. X is a bigfloat, and a bigfloat is
2306 ;; atanh(x) = -atanh(-x)
2307 ;; = 1/2*log1p(2*x/(1-x)), x >= 0.5
2308 ;; = 1/2*log1p(2*x+2*x*x/(1-x)), x <= 0.5
2310 (let* ((fp-x (cdr (bigfloatp x
))))
2311 (cond ((fplessp fp-x
(intofp 0))
2312 ;; atanh(x) = -atanh(-x)
2313 (mul -
1 (fpatanh (bcons (fpminus fp-x
)))))
2314 ((fpgreaterp fp-x
(fpone))
2315 ;; x > 1, so use complex version.
2316 (multiple-value-bind (u v
)
2317 (complex-atanh x
(bcons (intofp 0)))
2318 (add u
(mul '$%i v
))))
2319 ((fpgreaterp fp-x
(cdr bfhalf
))
2320 ;; atanh(x) = 1/2*log1p(2*x/(1-x))
2322 (fptimes* (cdr bfhalf
)
2323 (fplog1p (fpquotient (fptimes* (intofp 2) fp-x
)
2324 (fpdifference (fpone) fp-x
))))))
2326 ;; atanh(x) = 1/2*log1p(2*x + 2*x*x/(1-x))
2327 (let ((2x (fptimes* (intofp 2) fp-x
)))
2329 (fptimes* (cdr bfhalf
)
2331 (fpquotient (fptimes* 2x fp-x
)
2332 (fpdifference (fpone) fp-x
)))))))))))
2334 ;; Stuff which follows is derived from atanh z = (log(1 + z) - log(1 - z))/2
2335 ;; which apparently originates with Kahan's "Much ado" paper.
2337 ;; The formulas for eta and nu below can be easily derived from
2338 ;; rectform(atanh(x+%i*y)) =
2340 ;; 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)))
2342 ;; Expand the argument of log out and divide it out and we get
2344 ;; log(((1+x)^2+y^2)/((1-x)^2+y^2)) = log(1+4*x/((1-x)^2+y^2))
2346 ;; When y = 0, Im atanh z = 1/2 (arg(1 + x) - arg(1 - x))
2347 ;; = if x < -1 then %pi/2 else if x > 1 then -%pi/2 else <whatever>
2349 ;; Otherwise, arg(1 - x + %i*(-y)) = - arg(1 - x + %i*y),
2350 ;; and Im atanh z = 1/2 (arg(1 + x + %i*y) + arg(1 - x + %i*y)).
2351 ;; Since arg(x)+arg(y) = arg(x*y) (almost), we can simplify the
2352 ;; imaginary part to
2354 ;; arg((1+x+%i*y)*(1-x+%i*y)) = arg((1-x)*(1+x)-y^2+2*y*%i)
2355 ;; = atan2(2*y,((1-x)*(1+x)-y^2))
2357 ;; These are the eta and nu forms below.
2358 (defun complex-atanh (x y
)
2359 (let* ((fpx (cdr (bigfloatp x
)))
2360 (fpy (cdr (bigfloatp y
)))
2361 (beta (if (minusp (car fpx
))
2364 (x-lt-minus-1 (mevalp `((mlessp) ,x -
1)))
2365 (x-gt-plus-1 (mevalp `((mgreaterp) ,x
1)))
2366 (y-equals-0 (like y
'((bigfloat) 0 0)))
2367 (x (fptimes* beta fpx
))
2368 (y (fptimes* beta
(fpminus fpy
)))
2369 ;; Kahan has rho = 4/most-positive-float. What should we do
2370 ;; here about that? Our big floats don't really have a
2371 ;; most-positive float value.
2373 (t1 (fpplus (fpabs y
) rho
))
2374 (t1^
2 (fptimes* t1 t1
))
2375 (1-x (fpdifference (fpone) x
))
2376 ;; eta = log(1+4*x/((1-x)^2+y^2))/4
2378 (fplog1p (fpquotient (fptimes* (intofp 4) x
)
2379 (fpplus (fptimes* 1-x
1-x
)
2382 ;; If y = 0, then Im atanh z = %pi/2 or -%pi/2.
2383 ;; Otherwise nu = 1/2*atan2(2*y,(1-x)*(1+x)-y^2)
2385 ;; EXTRA FPMINUS HERE TO COUNTERACT FPMINUS IN RETURN VALUE
2386 (fpminus (if x-lt-minus-1
2387 (cdr ($bfloat
'((mquotient) $%pi
2)))
2389 (cdr ($bfloat
'((mminus) ((mquotient) $%pi
2))))
2390 (merror "COMPLEX-ATANH: HOW DID I GET HERE?"))))
2391 (fptimes* (cdr bfhalf
)
2392 (fpatan2 (fptimes* (intofp 2) y
)
2393 (fpdifference (fptimes* 1-x
(fpplus (fpone) x
))
2395 (values (bcons (fptimes* beta eta
))
2396 ;; WTF IS FPMINUS DOING HERE ??
2397 (bcons (fpminus (fptimes* beta nu
))))))
2399 (defun big-float-atanh (x &optional y
)
2401 (multiple-value-bind (u v
) (complex-atanh x y
)
2402 (add u
(mul '$%i v
)))
2405 ;; acos(x) for real x. X is a bigfloat, and a maxima number is returned.
2407 ;; acos(x) = %pi/2 - asin(x)
2408 ($bfloat
(add (div '$%pi
2) (mul -
1 (fpasin-core x
)))))
2410 (defun complex-acos (x y
)
2411 (let ((x (cdr (bigfloatp x
)))
2412 (y (cdr (bigfloatp y
))))
2413 (multiple-value-bind (re-sqrt-1-z im-sqrt-1-z
)
2414 (complex-sqrt (bcons (fpdifference (intofp 1) x
))
2415 (bcons (fpminus y
)))
2416 (multiple-value-bind (re-sqrt-1+z im-sqrt-1
+z
)
2417 (complex-sqrt (bcons (fpplus (intofp 1) x
))
2420 (fptimes* (intofp 2)
2421 (fpatan (fpquotient re-sqrt-1-z re-sqrt-1
+z
))))
2424 (fptimes* re-sqrt-1
+z im-sqrt-1-z
)
2425 (fptimes* im-sqrt-1
+z re-sqrt-1-z
)))))))))
2428 (defun big-float-acos (x &optional y
)
2430 (multiple-value-bind (u v
) (complex-acos x y
)
2431 (add u
(mul '$%i v
)))
2434 (defun complex-log (x y
)
2435 (let* ((x (cdr (bigfloatp x
)))
2436 (y (cdr (bigfloatp y
)))
2437 (t1 (let (($float2bf t
))
2438 ;; No warning message, please.
2441 (rho (fpplus (fptimes* x x
)
2445 (beta (fpmax abs-x abs-y
))
2446 (theta (fpmin abs-x abs-y
)))
2447 (values (if (or (fpgreaterp t1 beta
)
2449 (fpquotient (fplog1p (fpplus (fptimes* (fpdifference beta
(fpone))
2450 (fpplus beta
(fpone)))
2451 (fptimes* theta theta
)))
2453 (fpquotient (fplog rho
) (intofp 2)))
2456 (defun big-float-log (x &optional y
)
2458 (multiple-value-bind (u v
) (complex-log x y
)
2459 (add (bcons u
) (mul '$%i
(bcons v
))))
2461 ;; x is (mantissa exp), where mantissa = frac*2^fpprec,
2462 ;; with 1/2 < frac <= 1 and x is frac*2^exp. To
2463 ;; compute log(x), use log(x) = log(frac)+ exp*log(2).
2466 (fpprec (+ fpprec extra
))
2470 (cl-rat-to-maxima (/ (car x
)
2471 (ash 1 (- fpprec
8))))))
2472 (list (ash (car x
) extra
) 0)))
2473 (log-exp (fptimes* (intofp (second x
)) (fplog2)))
2474 (result (bcons (fpplus log-frac log-exp
))))
2475 (let ((fpprec (- fpprec extra
)))
2476 (bigfloatp result
))))))
2477 (let ((fp-x (cdr (bigfloatp x
))))
2479 ;; Special case for log(1). See:
2480 ;; https://sourceforge.net/p/maxima/bugs/2240/
2482 ((fplessp fp-x
(intofp 0))
2483 ;; ??? Do we want to return an exact %i*%pi or a float
2485 (add (big-float-log (bcons (fpminus fp-x
)))
2486 (mul '$%i
(bcons (fppi)))))
2488 (bcons (%log fp-x
))))))))
2490 (defun big-float-sqrt (x &optional y
)
2492 (multiple-value-bind (u v
) (complex-sqrt x y
)
2493 (add (bcons u
) (mul '$%i
(bcons v
))))
2494 (let ((fp-x (cdr (bigfloatp x
))))
2495 (if (fplessp fp-x
(intofp 0))
2496 (mul '$%i
(bcons (fproot (bcons (fpminus fp-x
)) 2)))
2497 (bcons (fproot x
2))))))
2501 #-gcl
(:load-toplevel
:execute
)
2502 (fpprec1 nil $fpprec
)) ; Set up user's precision