sicp逐日一题[1.45]

打印 上一主题 下一主题

主题 930|帖子 930|积分 2790

Exercise 1.45

We saw in Section 1.3.3 that attempting to compute square roots by naively finding a fixed point of y->x/y does not converge, and that this can be fixed by  average damping. The same method works for finding cube roots as fixed points of the average-dampedy x/y^2. Unfortunately, the process does not work for fourth roots—a single average damp is not enough to make a fixed-point search for y->x/y3 converge. On the other hand, if we average damp twice (i.e., use the average damp of the average damp of y->x/y3) the fixed-point search does converge. Do some experiments to determine how many average damps are required to compute nth roots as a fixed point search based upon repeated average damping of y->x/y^(n-1). Use this to implement a simple procedure for computing nth roots using fixed-point, average-damp,and the repeated procedure of Exercise1.43. Assume that any arithmetic operations you need are available as primitives.
这道题难度太难了,我最后也没能靠本身做出来。一个是怎么找到要执行频频average-damp,我一开始以为是 n-2,试了几个发现明显不是,又猜测是不是 n/2,结果还是不对,最后上网搜了一下才知道是 log 2(n),感爱好的可以参考知乎的这个回答;知道了重复执行的次数,在编写代码的时候再次遇到了问题,我对于“把一个过程作为另一个过程的返回值”这个概念明白的还是不到位,没有明白(repeated average-damp n)之后还要给它传一个过程作为 average-damp 的参数,最后上网看了别人的答案才明白过来。下面是我的答案:
  1. ; 求 x 和 f(x) 的平均值
  2. (define (average-damp f)
  3.   (lambda (x) (average x (f x))))
  4. ; 对于任意正整数 n,求使得 2^k < n 的最大 k 值
  5. (define (max-expt n)
  6.   (define (iter k pre)
  7.     (if (< n pre)
  8.         (- k 1)
  9.         (iter (+ k 1) (* 2 pre))))
  10.   (iter 1 2))
  11. (define (nth-root x n)
  12.   (fixed-point ((repeated average-damp (max-expt n))
  13.                 (lambda (y) (/ x (expt y (- n 1)))))
  14.                1.0))
  15. (display (nth-root 2 2))
  16. (newline)
  17. (display (nth-root 32 5))
  18. (newline)
  19. ; 结果
  20. 1.4142135623746899
  21. 2.000001512995761
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

种地

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表