3

I've spent some time looking at the questions about this on here and throughout the internet but I can't really find anything that makes sense to me. Basically I need help on realizing a function in scheme that evaluates Leibniz's formula when you give it a value k. The value you input lets the function know how many values in the series it should compute. This is what I have so far, I'm not sure what way I need to write this program to make it work. Thanks!

(define (fin-alt-series k)
  (cond ((= k 1)4)
        ((> k 1)(+ (/ (expt -1 k) (+(* 2.0 k) 1.0)) (fin-alt-series (- k 1.0))))))
Lawrence
  • 31
  • 3

1 Answers1

3

The base case is incorrect. And we can clean-up the code a bit:

(define (fin-alt-series k)
  (cond ((= k 0) 1)
        (else
         (+ (/ (expt -1.0 k)
               (+ (* 2 k) 1))
            (fin-alt-series (- k 1))))))

Even better, we can rewrite the procedure to use tail recursion, it'll be faster this way:

(define (fin-alt-series k)
  (let loop ((k k) (sum 0))
    (if (< k 0)
        sum
        (loop (- k 1)
              (+ sum (/ (expt -1.0 k) (+ (* 2 k) 1)))))))

For example:

(fin-alt-series 1000000)
=> 0.7853984133971936

(/ pi 4)
=> 0.7853981633974483
Óscar López
  • 232,561
  • 37
  • 312
  • 386