gpt4 book ai didi

方案 : recursive process much faster than iterative

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:57 26 4
gpt4 key购买 nike

我正在研究 SICP 并编写了两个程序来计算 1/n^2 的和,第一个生成递归过程,第二个生成迭代过程:

(define (sum-rec a b)
(if (> a b)
0
(exact->inexact (+ (/ 1 (* a a)) (sum-rec (1+ a) b)))))

(define (sum-it a b)
(define (sum_iter a tot)
(if (> a b)
tot
(sum_iter (1+ a) (+ (/ 1 (* a a)) tot))))
(exact->inexact (sum_iter a 0)))

我测试了当使用较小的 b 值调用时,这两个过程给出了完全相同的结果,并且结果接近 $pi^2/6$ 作为 b正如预期的那样变大。

但令人惊讶的是,调用 (sum-rec 1 250000) 几乎是瞬时的,而调用 (sum-it 1 250000) 则需要很长时间。

有解释吗?

最佳答案

正如评论中提到的,sum-it 目前的形式是使用精确算术加法,这比 sum-rec 中使用的不精确算术慢>。要进行等效比较,您应该如何实现它:

(define (sum-it a b)
(define (sum_iter a tot)
(if (> a b)
tot
(sum_iter (1+ a) (+ (/ 1.0 (* a a)) tot))))
(sum_iter a 0))

请注意,将 1 替换为 1.0 会强制解释器使用不精确的算术。现在这将立即返回:

(sum-it 1 250000)
=> 1.6449300668562465

关于方案 : recursive process much faster than iterative,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57543932/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com