top | item 755905

(no title)

flambard | 16 years ago

This is kind of situation where LOOP really shines.

    (defun machin-pi (digits)
      "Accurately calculates PI digits using Machin's formula
       with fixed point arithmetic and variable digit guarding."
      (flet ((arccot (x unity)
	       (loop
	          with xsq = (* x x)
	          for positive = t then (not positive)
	          for n upfrom 1 by 2
	          for xpow = (floor (/ unity x)) then (floor xpow xsq)
	          for term = (floor xpow n)
	          until (= 0 term)
	          sum (if positive term (- term)))))
        (when (> digits 0)
          (let* ((guard (floor (* 10 (log digits 10))))
	         (unity (expt 10 (+ digits guard)))
	         (thispi (* 4 (- (* 4 (arccot 5 unity)) (arccot 239 unity)))))
	    (floor thispi (expt 10 guard))))))

discuss

order

No comments yet.