home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1994 November / macformat-018.iso / Utility Spectacular / Developer / macgambit-20-compiler-src-p1 / Examples / pi.scm < prev    next >
Encoding:
Text File  |  1994-07-26  |  916 b   |  35 lines  |  [TEXT/gamI]

  1. ; Compute pi
  2.  
  3. (define (square x) (* x x))
  4.  
  5. (define (partial-sum i n e ee base)
  6.   (- (quotient base (* i e))
  7.      (quotient base (* (+ 2 i) ee))))
  8.  
  9. (define (a n base)  ; atan(1/n)
  10.   (do ((i 1 (+ 4 i))
  11.        (delta 1 (partial-sum i n e (* e n n) base))
  12.        (e n (* e n n n n))
  13.        (sum 0 (+ sum delta)))
  14.       ((zero? delta) sum)))
  15.  
  16. (define (calc-pi base)
  17.   (- (* 32 (a  10 base))
  18.      (* 16 (a 515 base))
  19.      (*  4 (a 239 base))))
  20.  
  21. (define (run)
  22.   (display "How many digits of pi do you want (0 to exit): ")
  23.   (let ((num (read)))
  24.     (if (and (not (eof-object? num)) (integer? num) (positive? num))
  25.       (let* ((extra (+ 5 (truncate (inexact->exact (log num)))))
  26.              (base (expt 10 (+ num extra)))
  27.              (pi (calc-pi base)))
  28.         (display (quotient pi base))
  29.         (display ".")
  30.         (display (quotient (remainder pi base) (expt 10 extra)))
  31.         (newline)
  32.         (run)))))
  33.  
  34. (run)
  35.