Question

I'm trying to figure out how to write a program to approximate pi with the Leibniz formula. The function takes an error, E, and somehow gives the pi approximation.

I'm not sure at all how to do this. I started writing a helper function but didn't know what to put in it. Any help?

Thanks!

Was it helpful?

Solution 2

The Leibniz formula for PI is a summation. The function will increment n until the summand for n is less than E.

(define (leibniz err)
  (define (summand n)
    (/ (expt -1 n) (+ (* 2.0 n) 1)))
  (let summing ((result 0) (n 0))
    (let ((increment (summand n)))
      (if (< (abs increment) err)
          (* 4 (+ result increment))
          (summing (+ result increment) (+ n 1))))))

OTHER TIPS

Leibniz's formula is a rather inefficient way to calculate π, unless some sort of convergence acceleration technique is used. According to Wikipedia, calculating π to 10 correct decimal places using direct summation of the series requires about 5,000,000,000 terms !

Anyway, here's a direct translation of the formula - with small optimizations including the removal of the exponentiation operation, which makes it slightly faster than @GoZoner's implementation:

(define (leibniz err)
  (let loop ((n 0)
             (prev +nan.0)
             (curr 0.0))
    (if (<= (abs (- curr prev)) err)
        (* 4 curr)
        (loop (add1 n)
              curr
              ((if (even? n) + -) curr (/ 1 (add1 (+ n n))))))))

The procedure keeps iterating until the difference between the current value of the series and the previous one is less than or equal to the error provided. The error should be a small number, say 1e-6. For example:

(leibniz 1e-6)
=> 3.1415946535856922

For reference, in this question there are several very short implementations of Leibniz's formula - including one in Scheme.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top