SICP 1.31:Pi 的近似值
我正在独自完成 SICP,所以我没有教练来询问这个问题。这段代码应该近似 pi 但总是返回零。
(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))))
以下是此代码中引用的模组和产品程序。这些似乎不是问题,但我会将它们包括在内以防万一。
(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)))
整个事情是公式的实现:
pi / 4 = (2 * 4 * 4 * 6 ...) / (3 * 3 * 5 * 5 ... )
我的错误显然是相当愚蠢的,但我'我是计划新手,所以我找不到它。 如果有人有任何风格建议,我也非常感激。谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的乘积函数有一个微妙的缺陷:
当正确答案是 20 时,返回 120。
原因是
Your product function has a subtle flaw:
returns 120 when the correct answer is 20.
The reason is
在函数
product
中调用product-iter
时,它会做(* 1 (factor 1))
就在第一次迭代中,其计算结果为 0,因为(factor 1)
为 0。因此,总乘积将为 0,如下所示出色地。In the call to
product-iter
in the functionproduct
, 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.