Question

I'm working through SICP on my own, so I don't have an instructor to ask about this. This code is supposed to approximate pi but always returns zero instead.

(define (approx-pi acc)
  (define (factors a)
    (define basic-num
         (if (= (mod a 2) 0)
             (/ a 2)
             (/ (- a 1) 2)))
    (if (= (mod basic-num 2) 0)
      basic-num
      (/ 1 basic-num)))
  (* 4 (product factors 5 (* 2 acc))))

Here are the mod and product procedures that are referenced in this code. These don't seem to be the problem but I'll include them just in case.

(define (product func lo hi)
  (define (product-iter i result)
    (if (> i hi)
      result
      (product-iter (+ 1 i) (* result (func i)))))
  (product-iter 1 1))

(define (mod a b)
  (if (< (- a b) 0)
    a
    (mod (- a b) b)))

The whole thing is an implementation of the formula:

pi / 4 = (2 * 4 * 4 * 6 ...) / (3 * 3 * 5 * 5 ... )

My mistake is obviously something pretty stupid, but I'm new to Scheme so I can't find it. If anyone has any stylistic tips, I'd really appreciate that, too. Thanks!

Was it helpful?

Solution

Your product function has a subtle flaw:

(product + 4 5)

returns 120 when the correct answer is 20. The reason is

(product-iter 1 1) should be (product-iter lo 1)

OTHER TIPS

In the call to product-iter in the function product, it will do (* 1 (factor 1)) right in the first iteration, which will evaluate to 0 because (factor 1) is 0. Therefore, the total product will be 0 as well.

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