Search code examples
mathschemepi

Write program to approximate pi with Leibniz formula in Scheme?


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!


Solution

  • 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))))))