tags:

views:

173

answers:

2

Hello- 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!

A: 

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.

carnieri
You're right- I really just forgot to implement the lower starting range in the product function.
gregsabo
+3  A: 

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)
Timothy Pratley
Ah, that was the problem exactly. I should have known that it's a bad sign when I don't use all of my formal parameters. Now everything works, thanks!
gregsabo