SICP 1.31:Pi 的近似值

发布于 2024-08-09 21:54:10 字数 798 浏览 3 评论 0原文

我正在独自完成 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

天赋异禀 2024-08-16 21:54:10

你的乘积函数有一个微妙的缺陷:

(product + 4 5)

当正确答案是 20 时,返回 120。
原因是

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

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)
じ违心 2024-08-16 21:54:10

在函数 product 中调用 product-iter 时,它会做
(* 1 (factor 1)) 就在第一次迭代中,其计算结果为 0,因为 (factor 1) 为 0。因此,总乘积将为 0,如下所示出色地。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文