SICP 1.31: Approximation Pi

I work through SICP myself, so I don’t have an instructor to ask about this. This code should approximate pi, but always returns zero.

(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 mods and product procedures that are listed in this code. This is not a problem, but I will 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)))

It's all about implementing the formula:

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

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

+5
source share
2 answers

Your product function has a subtle flaw:

(product + 4 5)

120, 20. ,

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

product-iter product (* 1 (factor 1)) , 0, (factor 1) 0. , 0.

0

All Articles