Extend laplace(t^z,t,s) to complex z
[maxima.git] / src / float.lisp
blobe3e8875a2e49bfa1c4ea70ae913553ae4c4d1bec
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 (l1 nil))
196 (setq l1 (let*
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)))
200 (if $bftrunc
201 (do ((l (nreverse exploded-integer) (cdr l)))
202 ((not (eq '|0| (car l))) (nreverse l)))
203 exploded-integer)))
204 (nconc (ncons (car l1)) (ncons '|.|)
205 (or (cdr l1) (ncons '|0|))
206 (ncons '|b|)
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)
218 (f (fpformat x))
219 (marker (position '|b| f)))
220 ;; FIXME: do something better than printing and reading
221 ;; the result.
222 (read-from-string
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
227 ;; digits.
228 (let* (($fpprintprec (if fdigits
229 (if (zerop fdigits)
231 (+ fdigits scale))
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
240 ;; to remove that.
241 (when (and fdigits (zerop fdigits))
242 (setf digits (butlast digits)))
243 (cond ((zerop k)
244 (push '|.| digits))
245 ((minusp k)
246 ;; Put the leading decimal and then some zeroes
247 (dotimes (i (abs k))
248 (push #\0 digits))
249 (push '|.| digits))
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.
254 (setf digits
255 (cond ((> k (length digits))
256 (concatenate 'list
257 digits
258 (make-list (- k (length digits))
259 :initial-element #\0)
260 (list '|.|)))
262 (concatenate 'list
263 (subseq digits 0 k)
264 (list '|.|)
265 (subseq digits k)))))))
266 (let* ((str (format nil "~{~A~}" digits))
267 (len (length str)))
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)))
274 (values str
276 (char= (aref str 0) #\.)
277 (char= (aref str (1- (length str))) #\.)
279 0)))))
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)))
286 (add-zero-p nil))
287 (cond ((and w overflowchar e (> elen e))
288 ;; Exponent overflow
289 (dotimes (i w)
290 (write-char overflowchar stream)))
292 ;; The hairy case
293 (let* ((fdig (if d
294 (if (plusp k)
295 (1+ (- d k))
297 nil))
298 (spaceleft (if w
299 (- w 2 elen
300 (if (or atp (minusp (second arg)))
301 1 0))
302 nil)))
303 #+(or)
304 (progn
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))
310 #+(or)
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))
314 (when w
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)) #\.))
323 (setf add-zero-p t)
324 (decf spaceleft))
325 (when lpoint
326 (if (or (> spaceleft 0) tpoint)
327 (decf spaceleft)
328 (setq lpoint nil)))
329 (when (and tpoint (<= spaceleft 0))
330 (setq tpoint nil)))
331 #+(or)
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
336 (dotimes (i w)
337 (write-char overflowchar stream)))
339 (when w
340 (dotimes (i spaceleft)
341 (write-char padchar stream)))
342 (if (minusp (second arg))
343 (write-char #\- stream)
344 (when atp (write-char #\+ stream)))
345 (when lpoint
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
355 ;; zero.)
356 (when (or add-zero-p
357 (and (null w)
358 (char= (aref fstr (1- flen)) #\.)))
359 (write-char #\0 stream))
360 (write-char (if exponentchar
361 exponentchar
362 #\b)
363 stream)
364 (write-char (if (minusp expt) #\- #\+) stream)
365 (when e
366 (dotimes (i (- e (length estr)))
367 (write-char #\0 stream)))
368 (write-string estr stream)))))))))
369 (values))
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))
375 (labels
376 ((exponent-value (x)
377 ;; Compute the (decimal exponent) of the bfloat number X.
378 (let* (($fpprintprec 1)
379 (f (fpformat x))
380 (marker (position '|b| f)))
381 ;; FIXME: do something better than printing and reading
382 ;; the result.
383 (read-from-string
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)
392 #+nil
393 (format t "compute-prec ~D ~D~%" exp spaceleft)
394 (cond (fdigits
395 (+ fdigits exp 1))
396 (spaceleft
397 (max (1- spaceleft) (1+ exp)))
399 (max (1+ exp) 0)))))
400 (let* ((exp (+ k (exponent-value x)))
401 ($fpprintprec (compute-prec exp spaceleft))
402 (f (let ((maxima::$bftrunc nil))
403 #+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
412 ;; to remove that.
413 #+nil
414 (format t "exp, fdigits = ~D ~D, digits = ~S~%" exp fdigits digits)
415 #+nil
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
420 ;; digit.
421 (cond ((minusp exp)
422 (dotimes (k (1- (abs exp)))
423 (push '|0| digits))
424 (push '|.| digits))
425 ((< exp (length digits))
426 #+nil
427 (format t "exp, len = ~D ~D~%" exp (length digits))
428 (setf digits (concatenate 'list
429 (subseq digits 0 (1+ exp))
430 (list '|.|)
431 (subseq digits (1+ exp)))))
433 (setf digits (append digits (list '|.|)))))
434 (let* ((str (format nil "~{~A~}" digits))
435 (len (length str)))
436 #+nil
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)))
444 (values str
446 (char= (aref str 0) #\.)
447 (char= (aref str (1- (length str))) #\.)
449 0))))))
450 (let ((spaceleft w))
451 (when (and w (or atsign (minusp (second number))))
452 (decf spaceleft))
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))
458 (when w
459 (decf spaceleft len)
460 ;;optional leading zero
461 (when lpoint
462 (if (or (> spaceleft 0) tpoint) ;force at least one digit
463 (decf spaceleft)
464 (setq lpoint nil)))
465 ;;optional trailing zero
466 (when tpoint
467 (if (> spaceleft 0)
468 (decf spaceleft)
469 (setq tpoint nil))))
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))
482 nil))))))
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)
493 (f (fpformat x))
494 (marker (position '|b| f)))
495 ;; FIXME: do something better than printing and reading
496 ;; the result.
497 (read-from-string
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
502 ;; digits.
503 (let* (($fpprintprec (if fdigits
504 (if (zerop fdigits)
506 (1+ 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
515 ;; to remove that.
516 (when (and fdigits (zerop fdigits))
517 (setf digits (butlast digits)))
518 (cond ((zerop k)
519 (push '|.| digits))
520 ((minusp k)
521 ;; Put the leading decimal and then some zeroes
522 (dotimes (i (abs k))
523 (push #\0 digits))
524 (push '|.| digits))
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.
529 (setf digits
530 (cond ((> k (length digits))
531 (concatenate 'list
532 digits
533 (make-list (- k (length digits))
534 :initial-element #\0)
535 (list '|.|)))
537 (concatenate 'list
538 (subseq digits 0 k)
539 (list '|.|)
540 (subseq digits k)))))))
541 (let* ((str (format nil "~{~A~}" digits))
542 (len (length str)))
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)))
549 (values str
551 (char= (aref str 0) #\.)
552 (char= (aref str (1- (length str))) #\.)
554 0)))))
555 (let* ((n (1+ (exponent-value arg)))
556 (orig-d d))
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.
567 (unless d
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))
572 (dd (- d n)))
573 #+(or)
574 (progn
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))
580 (cond ((<= 0 dd d)
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
588 ovf pad)
590 #\space)))
591 (dotimes (i ee) (write-char fill-char stream))))
593 (bfloat-format-e stream arg nil atsign
595 orig-d
596 e (or k 1)
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
603 ;; zero.
604 (defun bigfloatp (x)
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.
607 (prog (x-prec)
608 (cond ((not ($bfloatp x)) (return nil))
609 ((= fpprec (setq x-prec (bigfloat-prec x)))
610 ;; Precision matches. (Should we fix up bogus bigfloat
611 ;; zeros?)
612 (return x))
613 ((> fpprec x-prec)
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))
618 (caddr x)))))
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))
629 (let (($float2bf t)
630 (exp nil)
631 (y nil)
632 (sign nil))
633 (setq exp (cond ((minusp (cadr x))
634 (setq sign t
635 y (fpration1 (cons (car x) (fpabs (cdr x)))))
636 (rplaca y (* -1 (car y))))
637 (t (fpration1 x))))
638 (when $ratprint
639 (princ "`rat' replaced ")
640 (when sign (princ "-"))
641 (princ (maknam (fpformat (cons (car x) (fpabs (cdr x))))))
642 (princ " by ")
643 (princ (car exp))
644 (write-char #\/)
645 (princ (cdr exp))
646 (princ " = ")
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))))))
650 (terpri)
651 (finish-output))
652 exp))
654 (defun fpration1 (x)
655 (let ((fprateps (cdr ($bfloat (if $bftorat
656 (list '(rat simp) 1 (exptrl 2 (1- fpprec)))
657 $ratepsilon)))))
658 (or (and (equal x bigfloatzero) (cons 0 1))
659 (prog (y a)
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))
665 (onum 1 num)
666 (oden 0 den))
667 ((and (not (zerop den))
668 (not (fpgreaterp
669 (fpabs (fpquotient
670 (fpdifference (cdr x)
671 (fpquotient (cdr ($bfloat num))
672 (cdr ($bfloat den))))
673 (cdr x)))
674 fprateps)))
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)
685 (cond
686 ((< x 0) (< x most-negative))
687 ((> x 0) (> x most-positive))
688 (t nil))))
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.
704 (defun floattofp (x)
705 (if (float-nan-p x)
706 (merror (intl:gettext "bfloat: attempted conversion of floating point NaN (not-a-number).~%")))
707 (if (float-inf-p x)
708 (merror (intl:gettext "bfloat: attempted conversion of floating-point infinity.~%")))
709 (unless $float2bf
710 (let ((p (float-precision x)))
711 (if (< fpprec p)
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
717 ;; mantissa of zero.
718 (if (zerop x)
719 (list 0 0)
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.
729 (defun fp2flo (l)
730 (let ((precision (bigfloat-prec l))
731 (mantissa (cadr l))
732 (exponent (caddr l))
733 (fpprec machine-mantissa-precision)
734 (*m 0))
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)))
747 (if (>= e 1025)
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.
754 ;; 7.45E-9) - JPG
756 (defun fixfloat (x)
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
763 ;; terms.
765 (defun bcons (s)
766 `((bigfloat simp ,fpprec) . ,s))
768 (defmfun $bfloat (x)
769 (let (y)
770 (cond ((bigfloatp x))
771 ((or (numberp x)
772 (member x '($%e $%pi $%gamma) :test #'eq))
773 (bcons (intofp x)))
774 ((or (atom x) (member 'array (cdar x) :test #'eq))
775 (if (eq x '$%phi)
776 ($bfloat '((mtimes simp)
777 ((rat simp) 1 2)
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)))
786 ((eq (caar x) 'rat)
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)))
792 (if ($bfloatp y)
793 (cond ((eq (caar x) '$entier) ($entier y))
794 ((arcp (caar x))
795 (setq y ($bfloat (logarc (caar x) y)))
796 (if (free y '$%i)
797 y (let ($ratprint) (fparcsimp ($rectform y)))))
798 ((member (caar x) '(%cot %sec %csc) :test #'eq)
799 (invertbigfloat
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)
818 (do ((l h (cdr l)))
819 ((null l))
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.
831 (if (zerop (car r))
832 (bcons (list 0 0))
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)))
841 (den (second x))
842 (digits fpprec)
843 (scale 0))
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))
861 (decf scale delta)
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)
870 (1+ scale)))))
872 (multiple-value-bind (f0)
873 (floatit bits)
874 (list (first f0) (+ (second f0) scale)))))))
875 (floatit (bits)
876 (let ((sign (if plusp 1 -1)))
877 (list (* sign bits) 0))))
878 (loop
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))
883 (cond ((/= extra 1)
884 (assert (> extra 1)))
885 ((oddp fraction-and-guard)
886 (return
887 (if (zerop rem)
888 (float-and-scale
889 (if (zerop (logand fraction-and-guard 2))
890 fraction-and-guard
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))
896 (incf scale)))))))
898 (defun decimalsin (x)
899 (do ((i (quotient (* 59. x) 196.) (1+ i))) ;log[10](2)=.301029
900 (nil)
901 (when (> (integer-length (expt 10. i)) x)
902 (return (1- i)))))
904 (defun atanbigfloat (x)
905 (*fpatan (car x) (cdr x)))
907 (defun *fpatan (a y)
908 (fpend (let ((fpprec (+ 8. fpprec)))
909 (if (null y)
910 (if ($bfloatp a) (fpatan (cdr ($bfloat a)))
911 (list '(%atan) a))
912 (fpatan2 (cdr ($bfloat a)) (cdr ($bfloat (car y))))))))
914 ;; Bigfloat atan
915 (defun fpatan (x)
916 (prog (term x2 ans oans one two tmp)
917 (setq one (intofp 1) two (intofp 2))
918 (cond ((fpgreaterp (fpabs x) one)
919 ;; |x| > 1.
921 ;; Use A&S 4.4.5:
922 ;; atan(x) + acot(x) = +/- pi/2 (+ for x >= 0, - for x < 0)
924 ;; and A&S 4.4.8
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)))
930 (t ans))))
931 ((fpgreaterp (fpabs x) (fpquotient one two))
932 ;; |x| > 1/2
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 + ...]
938 ;; r = z^2/(1+z^2)
939 (setq tmp (fpquotient x (fpplus (fptimes* x x) one)))
940 (setq x2 (fptimes* x tmp) term (setq ans one))
941 (do ((n 0 (1+ n)))
942 ((equal ans oans))
943 (setq term
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
951 ;; formula).
952 (setq ans x x2 (fpminus (fptimes* x x)) term x)
953 (do ((n 3 (+ n 2)))
954 ((equal ans oans))
955 (setq term (fptimes* term x2))
956 (setq oans ans
957 ans (fpplus ans (fpquotient term (intofp n)))))))
958 (return ans)))
960 ;; atan(y/x) taking into account the quadrant. (Also equal to
961 ;; arg(x+%i*y).)
962 (defun fpatan2 (y x)
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.")))
967 ((minusp (car y))
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)))))
973 ((signp g (car x))
974 ;; x > 0. atan(y/x) is the correct value.
975 (fpatan (fpquotient y x)))
976 ((signp g (car y))
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)
986 (setq a (car a))
987 (fpend (let ((fpprec (+ 8. fpprec)))
988 (cond (($bfloatp a)
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.
994 (defun intofp (l)
995 (cond ((not (atom l)) ($bfloat l))
996 ((floatp l) (floattofp l))
997 ((equal 0 l) '(0 0))
998 ((eq l '$%pi) (fppi))
999 ((eq l '$%e) (fpe))
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*)
1011 (prog (adjust)
1012 (cond
1013 ((null *decfp)
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))
1017 (when (= *m 0)
1018 (setq *cancelled 0)
1019 (return l))
1020 ;;FPSHIFT is essentially LSH.
1021 (setq adjust (fpshift 1 (1- *m)))
1022 (when (minusp l) (setq adjust (- adjust)))
1023 (incf l 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
1046 ;; shifts instead.)
1047 (- (ash (- l) n)))
1049 (ash l n))))
1050 ((> n 0)
1051 (* l (expt 10. n)))
1052 ((< n 0.)
1053 (quotient l (expt 10. (- n))))
1054 (t l)))
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.
1066 (defun biglsh (x n)
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
1072 ;; a bignum.
1073 ((and (not (bignump x))
1074 (or (<= n 0)
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.
1078 (if (>= x 0)
1079 (ash x n)
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.
1083 ((< n 0)
1084 (cond ((> (abs n) (integer-length x)) 0)
1085 ((> x 0)
1086 (hipart x (+ (integer-length x) n)))
1087 (t (- (hipart x (+ (integer-length x) n))))))
1088 ((= n 0) x)
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)))))
1095 ;; exp(x)
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
1100 ;; r = floor(x).
1101 (defun fpexp (x)
1102 (prog (r s)
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)
1107 (fpexp1 x))
1109 (setq s (fpexp1 (fpdifference x (intofp r))))
1110 (fptimes* s
1111 (cdr (bigfloatp
1112 (let ((fpprec (+ fpprec (integer-length r) -1))
1113 (r r))
1114 (bcons (fpexpt (fpe) r))))))))))) ; patch for full precision %E
1116 ;; exp(x) for small x, using Taylor series.
1117 (defun fpexp1 (x)
1118 (prog (term ans oans)
1119 (setq ans (setq term (fpone)))
1120 (do ((n 1 (1+ n)))
1121 ((equal ans oans))
1122 (setq term (fpquotient (fptimes* x term) (intofp n)))
1123 (setq oans ans)
1124 (setq ans (fpplus ans term)))
1125 (return ans)))
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)))
1142 (defun fpposp (x)
1143 (> (car x) 0))
1145 (defun fpmin (arg1 &rest args)
1146 (let ((min arg1))
1147 (mapc #'(lambda (u) (if (fplessp u min) (setq min u))) args)
1148 min))
1150 (defun fpmax (arg1 &rest args)
1151 (let ((max arg1))
1152 (mapc #'(lambda (u) (if (fpgreaterp u max) (setq max u))) args)
1153 max))
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
1162 ;; bigfloat tag.
1164 ;; See
1165 ;; https://sourceforge.net/p/maxima/bugs/1842/
1166 ;; for an explanation.
1167 (let ((table (make-hash-table)))
1168 (defun fpe ()
1169 (let ((value (gethash fpprec table)))
1170 (if value
1171 value
1172 (setf (gethash fpprec table) (cdr (fpe1))))))
1173 (defun fpe-table ()
1174 table)
1175 (defun clear_fpe_table ()
1176 (clrhash table)))
1178 (let ((table (make-hash-table)))
1179 (defun fppi ()
1180 (let ((value (gethash fpprec table)))
1181 (if value
1182 value
1183 (setf (gethash fpprec table) (cdr (fppi1))))))
1184 (defun fppi-table ()
1185 table)
1186 (defun clear_fppi_table ()
1187 (clrhash table)))
1189 (let ((table (make-hash-table)))
1190 (defun fpgamma ()
1191 (let ((value (gethash fpprec table)))
1192 (if value
1193 value
1194 (setf (gethash fpprec table) (cdr (fpgamma1))))))
1195 (defun fpgamma-table ()
1196 table)
1197 (defun clear_fpgamma_table ()
1198 (clrhash table)))
1200 (let ((table (make-hash-table)))
1201 (defun fplog2 ()
1202 (let ((value (gethash fpprec table)))
1203 (if value
1204 value
1205 (setf (gethash fpprec table) (comp-log2)))))
1206 (defun fplog2-table ()
1207 table)
1208 (defun clear_fplog2_table ()
1209 (clrhash 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.
1214 (defun fpone ()
1215 (cond (*decfp (intofp 1))
1216 ((= fpprec (bigfloat-prec bigfloatone)) (cdr bigfloatone))
1217 (t (intofp 1))))
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
1227 ;; Euler's number E
1229 (defun fpe1 ()
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!
1235 (defun compe (prec)
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:
1242 ;; 1
1243 ;; s[i] = ----------------------
1244 ;; q[0]*q[1]*q[2]*..*q[i]
1246 ;; where q[0] = 1
1247 ;; q[i] = i
1249 (defun split-taylor-e (i j)
1250 (let (qq tt)
1251 (if (= (- j i) 1)
1252 (setq qq (if (= i 0) 1 i)
1253 tt 1 )
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)
1257 (setq qq (* ql qr)
1258 tt (+ (* qr tl) tr) )))))
1259 (values tt qq) ))
1261 ;; stop when i! > 2^fpprec
1263 ;; log(i!) = sum(log(k), k,1,i) > fpprec * log(2)
1265 (defun taylor-e-size (prec)
1266 (let ((acc 0)
1267 (lim (* prec (log 2))) )
1268 (do ((i 1 (1+ i)))
1269 ((> acc lim) i)
1270 (incf acc (log i)) )))
1272 ;;----------------------------------------------------------------------------;;
1274 ;; PI
1276 (defun fppi1 ()
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)
1289 (let ((fpprec prec)
1290 nr n d oldn tt qq n*qq )
1291 ;; STEP 1:
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))
1299 (dotimes (i nr)
1300 (setq oldn n
1301 n (+ (* n n) (* 10005 d d))
1302 d (* 2 oldn d) ))
1303 ;; STEP 2:
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)))
1310 (setq n (* 3335 n)
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)
1321 (if (< prec 128)
1322 (setq nr 0 p prec)
1323 (setq ilen (integer-length prec)
1324 nr (- ilen 7)
1325 p (ceiling (* prec (expt 2.0 (- nr)))) ))
1326 (cond
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)) )
1332 (values nr n d) ))
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]
1340 ;; where a[0] = B
1341 ;; p[0] = q[0] = 1
1342 ;; a[i] = A*i+B
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)
1348 (if (= (- j i) 1)
1349 (if (= i 0)
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))
1356 tt (* aa pp) ))
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)
1360 (setq pp (* pl pr)
1361 qq (* ql qr)
1362 tt (+ (* qr tl) (* pl tr)) )))))
1363 (values tt qq pp) ))
1365 ;;----------------------------------------------------------------------------;;
1367 ;; Euler-Mascheroni constant GAMMA
1369 (defun fpgamma1 ()
1370 (let ((res (comp-bf%gamma (+ fpprec 14))))
1371 (bcons (list (fpround (car res)) (cadr res))) ))
1373 ;; Brent-McMillan algorithm
1375 ;; Let
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)
1388 ;; and
1389 ;; %gamma = S/I - T/I^2 - log(n)
1391 ;; Then
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)))))
1399 (n2 (* n n))
1400 (alpha 4.970625759544)
1401 (lim (ceiling (* alpha n)))
1402 sums/sumi ;; S/I
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)
1408 ;; sumi = tt/qq
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) ))
1422 ;; %gamma :
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]
1435 ;; where p[0] = n^2
1436 ;; q[0] = 1
1437 ;; p[i] = n^2
1438 ;; q[i] = i^2
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]
1442 ;; and c[0] = 0
1443 ;; d[0] = 1
1444 ;; c[i] = 1
1445 ;; d[i] = i
1447 (defun split-gamma-1 (i j n2)
1448 (let (pp cc dd qq tt vv)
1449 (cond
1450 ((= (- j i) 1)
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)
1458 (setq pp (* pl pr)
1459 cc (+ (* cl dr) (* dl cr))
1460 dd (* dl dr)
1461 qq (* ql qr)
1462 tmp (* pl tr)
1463 tt (+ (* tl qr) tmp)
1464 vv (+ (* dr (+ (* vl qr) (* cl tmp))) (* dl pl vr)) ))))))
1465 (values vv tt qq dd cc pp) ))
1467 ;; split 4*n*T:
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
1476 ;; p[i] = (2*i-1)^3
1477 ;; q[i] = 32*i*n^2
1479 (defun split-gamma-2 (i j n2*32)
1480 (let (pp qq tt)
1481 (cond
1482 ((= (- j i) 1)
1483 (if (= i 0)
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)
1490 (setq pp (* pl pr)
1491 qq (* ql qr)
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
1505 (defun comp-log2 ()
1506 (let ((res
1507 (let ((fpprec (+ fpprec 12)))
1508 (fpplus
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
1518 (let* ((k2 (* k 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:
1524 ;; 1
1525 ;; s[i] = -----------------------------
1526 ;; b[i] * q[0]*q[1]*q[2]*..*q[i]
1528 ;; where b[0] = 1
1529 ;; q[0] = k
1530 ;; b[i] = 2*i+1
1531 ;; q[i] = k^2
1533 (defun split-atanh-1/k (i j k k2)
1534 (let (bb qq tt)
1535 (if (= (- j i) 1)
1536 (if (= i 0)
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)
1542 (setq bb (* bl br)
1543 qq (* ql qr)
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
1554 (cond
1555 ((= 1 n) (list 0 0))
1556 ((= 2 n) (comp-log2))
1558 (let ((res
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
1574 (cond
1575 ((= 0 u) (list 0 0))
1577 (while (evenp u) (setq u (ash u -1)) (decf k))
1578 (let* ((u2 (* u u))
1579 (w (+ u (ash 2 k)))
1580 (w2 (* w w))
1581 (nr (ceiling (* prec (/ (log 2) 2 (log (abs (/ w u)))))))
1582 lg/2 )
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]
1593 ;; where b[0] = 1
1594 ;; p[0] = u
1595 ;; q[0] = w = 2*v+u
1596 ;; b[i] = 2*i+1
1597 ;; p[i] = u^2
1598 ;; q[i] = w^2
1600 (defun split-log-1+u/v (i j u u2 w w2)
1601 (let (pp bb qq tt)
1602 (if (= (- j i) 1)
1603 (if (= i 0)
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)
1609 (setq bb (* bl br)
1610 pp (* pl pr)
1611 qq (* ql qr)
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)))
1621 (defun fpminus (x)
1622 (if (equal (car x) 0)
1624 (list (- (car x)) (cadr x))))
1626 (defun fpplus (a b)
1627 (prog (*m exp man sticky)
1628 (setq *cancelled 0)
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)
1633 (setq sticky 0)
1634 (fpshift (+ (car a) (car b)) 2))
1635 ((> exp 0)
1636 (setq sticky (hipart (car b) (- 1 exp)))
1637 (setq sticky (cond ((signp e sticky) 0)
1638 ((signp l (car b)) -1)
1639 (t 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)
1647 (t 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))))
1654 (list man exp))))))
1656 (defun fptimes* (a b)
1657 (if (or (zerop (car a)) (zerop (car b)))
1658 '(0 0)
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)))))
1667 (if (> nn fixprec)
1668 (fptimes* (intofp (expt int (rem nn fixprec)))
1669 (fpexpt bas (quotient nn fixprec)))
1670 bas)))
1672 ;; NN is positive or negative integer
1674 (defun fpexpt (p nn)
1675 (cond ((zerop nn) (fpone))
1676 ((eql nn 1) p)
1677 ((< nn 0) (fpquotient (fpone) (fpexpt p (- nn))))
1678 (t (prog (u)
1679 (if (oddp nn)
1680 (setq u p)
1681 (setq u (fpone)))
1682 (do ((ii (quotient nn 2) (quotient ii 2)))
1683 ((zerop ii))
1684 (setq p (fptimes* p p))
1685 (when (oddp ii)
1686 (setq u (fptimes* u p))))
1687 (return u)))))
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)
1696 (power -1 n))
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)))
1711 $%i)))))
1712 (t (list '(mexpt) p n))))
1713 ((and (ratnump n) (< (caddr n) 10.))
1714 (bcons (fpexpt (fproot p (caddr n)) (cadr n))))
1715 ((not (integerp n))
1716 (setq n ($bfloat n))
1717 (cond
1718 ((not ($bfloatp n)) (list '(mexpt) p n))
1720 (let ((extrabits (max 1 (+ (caddr n) (integer-length (caddr p))))))
1721 (setq 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))))
1725 (bcons 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)
1740 '(0 0)
1741 (progn
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))))
1748 (n1 (1- n))
1749 (n (intofp n)))
1750 ((or (equal bk '(0 0))
1751 (> (- (cadr x) (cadr bk)) ofprec))
1752 (setq a x))))
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)
1758 (do ((l h (cdr l)))
1759 ((null l))
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)
1764 fans
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)))
1771 (if b
1772 (bcons (fpquotient (fpone) (cdr b)))
1773 (simplify (list '(mexpt) a -1)))))
1775 (defun *fpexp (a)
1776 (fpend (let ((fpprec (+ 8. fpprec)))
1777 (if ($bfloatp a)
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))))))
1787 (defun fpend (a)
1788 (cond ((equal (car a) 0) (bcons a))
1789 ((numberp (car a))
1790 (setq a (list (fpround (car a)) (+ -8. *m (cadr a))))
1791 (bcons a))
1792 (t 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)))
1802 (cadr e)
1805 (defun sinbigfloat (x)
1806 (*fpsin (car x) t))
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.
1826 (defun fpsin (x fl)
1827 (prog (piby2 r sign res k *cancelled)
1828 (setq sign (cond (fl (signp g (car x)))
1829 (t))
1830 x (fpabs x))
1831 (when (equal (car x) 0)
1832 (return (if fl (intofp 0) (intofp 1))))
1833 (return
1834 (cdr
1835 (bigfloatp
1836 (let ((fpprec (max fpprec (+ fpprec (cadr x))))
1837 (xt (bcons x))
1838 (*cancelled 0)
1839 (oldprec fpprec))
1840 (prog (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)))
1845 (setq k *cancelled)
1846 (fpplus x (fpminus piby2))
1847 (setq *cancelled (max k *cancelled))
1848 (when *fpsincheck*
1849 (print `(*canc= ,*cancelled fpprec= ,fpprec oldprec= ,oldprec)))
1850 (cond ((not (> oldprec (- fpprec *cancelled)))
1851 (setq r (rem r 4))
1852 (setq res
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)
1864 (go loop))))))))))
1866 (defun fpcos1 (x)
1867 (fpsincos1 x nil))
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)))
1876 (setq term ans)
1877 (do ((n (if fl 3 2) (+ n 2)))
1878 ((equal ans oans))
1879 (setq term (fptimes* term (fpquotient x2 (intofp (* n (1- n))))))
1880 (setq oans ans
1881 ans (fpplus ans term)))
1882 (return ans)))
1884 (defun fpsin1(x)
1885 (fpsincos1 x t))
1887 (defun fpabs (x)
1888 (if (signp ge (car x))
1890 (cons (- (car x)) (cdr x))))
1892 (defun fpentier (f)
1893 (let ((fpprec (bigfloat-prec f)))
1894 (fpintpart (cdr f))))
1896 ;; Calculate the integer part of a floating point number that is represented as
1897 ;; a list
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
1911 ;; as requested.
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)))
1920 (if (plusp m)
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.
1936 ;;; Uses the series
1938 ;;; log(1+x) = sum((x/(x+2))^(2*n+1)/(2*n+1),n,0,inf);
1941 ;;; INF x 2 n + 1
1942 ;;; ==== (-----)
1943 ;;; \ x + 2
1944 ;;; = 2 > --------------
1945 ;;; / 2 n + 1
1946 ;;; ====
1947 ;;; n = 0
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
1955 ;;; < 1+x <= e.
1957 (defun fplog (x)
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)))
1961 (setq e (fpe)
1962 over (fpquotient (fpone) e)
1963 ans 0)
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.
1966 (do ()
1967 (nil)
1968 (cond ((equal x e) (setq x nil) (return nil))
1969 ((and (fplessp x e) (fplessp over x))
1970 (return nil))
1971 ((fplessp x over)
1972 (setq x (fptimes* x e))
1973 (decf ans))
1975 (incf ans)
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
1980 ;; (x/(x+2))^2.
1981 (setq x (fpdifference x (fpone))
1982 ans (intofp ans))
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
1985 ;; anymore.
1986 (setq sum (intofp 0))
1987 (do ((n 1 (+ n 2)))
1988 ((equal sum oldans))
1989 (setq oldans sum)
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)
1995 (prog (r)
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.
2003 ;;;;
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.
2022 (defun fpexpm1 (x)
2023 ;; What is the right breakpoint here? Is 1 ok? Perhaps 1/e is better?
2024 (cond ((fpgreaterp (fpabs x) (fpone))
2025 ;; exp(x) - 1
2026 (fpdifference (fpexp x) (fpone)))
2028 ;; Use Taylor series for exp(x) - 1
2029 (let ((ans x)
2030 (oans nil)
2031 (term x))
2032 (do ((n 2 (1+ n)))
2033 ((equal ans oans))
2034 (setf term (fpquotient (fptimes* x term) (intofp n)))
2035 (setf oans ans)
2036 (setf ans (fpplus ans term)))
2037 ans))))
2039 ;; log(1+x) for small x. X is FP number, and a FP number is returned.
2040 (defun fplog1p (x)
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))
2049 (oldans nil))
2050 (do ((n 1 (+ n 2)))
2051 ((equal sum oldans))
2052 (setq oldans sum)
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.
2058 (defun fpsinh (x)
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.
2071 (bigfloatp x))
2072 ((fpposp (cdr x))
2073 ;; x is positive.
2074 (let ((d (fpexpm1 (cdr (bigfloatp x)))))
2075 (bcons (fpquotient (fpplus d (fpquotient d (fpplus d (fpone))))
2076 (intofp 2)))))
2078 ;; x is negative.
2079 (bcons
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.
2085 (unless y
2086 (fpsinh x)))
2088 ;; asinh(x) for real x. X is a bigfloat, and a bigfloat is returned.
2089 (defun fpasinh (x)
2090 ;; asinh(x) = sign(x) * log(|x| + sqrt(1+x*x))
2092 ;; And
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)))
2102 (absx (fpabs fp-x))
2103 (one (fpone))
2104 (two (intofp 2))
2105 (minus (minusp (car fp-x)))
2106 result)
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)
2110 ;; |x| > 2
2112 ;; log(2*|x| + 1/(|x|+sqrt(1+x^2)))
2113 (setf result (fplog (fpplus (fptimes* absx two)
2114 (fpquotient one
2115 (fpplus absx
2116 (fproot (bcons (fpplus one
2117 (fptimes* absx absx)))
2118 2)))))))
2120 ;; |x| <= 2
2122 ;; log1p(|x|+x^2/(1+sqrt(1+x^2)))
2123 (let ((x*x (fptimes* absx absx)))
2124 (setq result (fplog1p (fpplus absx
2125 (fpquotient x*x
2126 (fpplus one
2127 (fproot (bcons (fpplus one x*x))
2128 2)))))))))
2129 (if minus
2130 (bcons (fpminus result))
2131 (bcons 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)
2140 (if y
2141 (multiple-value-bind (u v)
2142 (complex-asinh x y)
2143 (add u (mul '$%i v)))
2144 (fpasinh x)))
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))
2164 ;; 0 <= x < 1/2
2165 ;; asin(x) = atan(x/sqrt(1-x^2))
2166 (bcons
2167 (fpatan (fpquotient fp-x
2168 (fproot (bcons
2169 (fptimes* (fpdifference (fpone) fp-x)
2170 (fpplus (fpone) fp-x)))
2171 2)))))
2172 ((fpgreaterp fp-x (fpone))
2173 ;; x > 1
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))))
2181 2))))
2182 (add (div '$%pi 2)
2183 (mul -1 '$%i (bcons (fplog arg))))))
2186 ;; 1/2 <= x <= 1
2187 ;; asin(x) = %pi/2 - atan(sqrt(1-x^2)/x)
2188 (add (div '$%pi 2)
2189 (mul -1
2190 (bcons
2191 (fpatan
2192 (fpquotient (fproot (bcons (fptimes* (fpdifference (fpone) fp-x)
2193 (fpplus (fpone) fp-x)))
2195 fp-x)))))))))
2197 ;; asin(x) for real x. X is a bigfloat, and a maxima number (real or
2198 ;; complex) is returned.
2199 (defun fpasin (x)
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)
2220 (fptimes* y y))))
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)))
2225 (let ((eta rho)
2226 (nu y))
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))
2232 (fpminus rho)
2233 rho))))
2234 (values eta nu))))
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))
2246 (bcons y))
2247 ;; Realpart is atan(x/Re(sqrt(1-z)*sqrt(1+z)))
2248 ;; Imagpart is asinh(Im(conj(sqrt(1-z))*sqrt(1+z)))
2249 (values (bcons
2250 (let ((d (fpdifference (fptimes* re-sqrt-1-z
2251 re-sqrt-1+z)
2252 (fptimes* im-sqrt-1-z
2253 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
2256 ;; sign of X.
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))))))
2263 (fpasinh (bcons
2264 (fpdifference (fptimes* re-sqrt-1-z
2265 im-sqrt-1+z)
2266 (fptimes* im-sqrt-1-z
2267 re-sqrt-1+z)))))))))
2269 (defun big-float-asin (x &optional y)
2270 (if y
2271 (multiple-value-bind (u v) (complex-asin x y)
2272 (add u (mul '$%i v)))
2273 (fpasin x)))
2276 ;; tanh(x) for real x. X is a bigfloat, and a bigfloat is returned.
2277 (defun fptanh (x)
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
2286 ;; returned.
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)
2298 (if y
2299 (multiple-value-bind (u v) (complex-tanh x y)
2300 (add u (mul '$%i v)))
2301 (fptanh x)))
2303 ;; atanh(x) for real x, |x| <= 1. X is a bigfloat, and a bigfloat is
2304 ;; returned.
2305 (defun fpatanh (x)
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))
2321 (bcons
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)))
2328 (bcons
2329 (fptimes* (cdr bfhalf)
2330 (fplog1p (fpplus 2x
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))
2362 (fpminus (fpone))
2363 (fpone)))
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.
2372 (rho (intofp 0))
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
2377 (eta (fpquotient
2378 (fplog1p (fpquotient (fptimes* (intofp 4) x)
2379 (fpplus (fptimes* 1-x 1-x)
2380 t1^2)))
2381 (intofp 4)))
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)
2384 (nu (if y-equals-0
2385 ;; EXTRA FPMINUS HERE TO COUNTERACT FPMINUS IN RETURN VALUE
2386 (fpminus (if x-lt-minus-1
2387 (cdr ($bfloat '((mquotient) $%pi 2)))
2388 (if x-gt-plus-1
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))
2394 t1^2))))))
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)
2400 (if y
2401 (multiple-value-bind (u v) (complex-atanh x y)
2402 (add u (mul '$%i v)))
2403 (fpatanh x)))
2405 ;; acos(x) for real x. X is a bigfloat, and a maxima number is returned.
2406 (defun fpacos (x)
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))
2418 (bcons y))
2419 (values (bcons
2420 (fptimes* (intofp 2)
2421 (fpatan (fpquotient re-sqrt-1-z re-sqrt-1+z))))
2422 (fpasinh (bcons
2423 (fpdifference
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)
2429 (if y
2430 (multiple-value-bind (u v) (complex-acos x y)
2431 (add u (mul '$%i v)))
2432 (fpacos x)))
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.
2439 (floattofp 1.2)))
2440 (t2 (intofp 3))
2441 (rho (fpplus (fptimes* x x)
2442 (fptimes* y y)))
2443 (abs-x (fpabs x))
2444 (abs-y (fpabs y))
2445 (beta (fpmax abs-x abs-y))
2446 (theta (fpmin abs-x abs-y)))
2447 (values (if (or (fpgreaterp t1 beta)
2448 (fplessp rho t2))
2449 (fpquotient (fplog1p (fpplus (fptimes* (fpdifference beta (fpone))
2450 (fpplus beta (fpone)))
2451 (fptimes* theta theta)))
2452 (intofp 2))
2453 (fpquotient (fplog rho) (intofp 2)))
2454 (fpatan2 y x))))
2456 (defun big-float-log (x &optional y)
2457 (if y
2458 (multiple-value-bind (u v) (complex-log x y)
2459 (add (bcons u) (mul '$%i (bcons v))))
2460 (flet ((%log (x)
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).
2464 (cdr
2465 (let* ((extra 8)
2466 (fpprec (+ fpprec extra))
2467 (log-frac
2468 (fplog #+nil
2469 (cdr ($bfloat
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))))
2478 (cond ((onep1 x)
2479 ;; Special case for log(1). See:
2480 ;; https://sourceforge.net/p/maxima/bugs/2240/
2481 (bcons (intofp 0)))
2482 ((fplessp fp-x (intofp 0))
2483 ;; ??? Do we want to return an exact %i*%pi or a float
2484 ;; approximation?
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)
2491 (if 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))))))
2499 (eval-when
2500 #+gcl (load eval)
2501 #-gcl (:load-toplevel :execute)
2502 (fpprec1 nil $fpprec)) ; Set up user's precision