sicp每日一题[1.45]

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 的参数,最后上网看了别人的答案才明白过来。下面是我的答案:

复制代码
; 求 x 和 f(x) 的平均值
(define (average-damp f)
  (lambda (x) (average x (f x))))

; 对于任意正整数 n,求使得 2^k < n 的最大 k 值
(define (max-expt n)
  (define (iter k pre)
    (if (< n pre)
        (- k 1)
        (iter (+ k 1) (* 2 pre))))
  (iter 1 2))

(define (nth-root x n)
  (fixed-point ((repeated average-damp (max-expt n))
                (lambda (y) (/ x (expt y (- n 1)))))
               1.0))


(display (nth-root 2 2))
(newline)
(display (nth-root 32 5))
(newline)

; 结果
1.4142135623746899
2.000001512995761
相关推荐
xinxiyinhe2 天前
github免费编程类工具汇总与评估(二)
前端·后端·编程
HyperAI超神经6 天前
【TVM教程】使用自定义调度规则(Sketch Rule)在 CPU 上自动调度稀疏矩阵乘法
人工智能·深度学习·矩阵·编程·cpu·计算机语言·tvm
skywalk81637 天前
DrRacket是一款专为Scheme和Racket编程语言设计的集成开发环境(IDE)
ide·lisp·drracket
大模型铲屎官9 天前
玩转C#函数:参数、返回值与游戏中的攻击逻辑封装
开发语言·游戏·c#·编程·参数·函数·返回值
网络研究院11 天前
Oracle 公布 Java 的五大新功能
java·oracle·编程·更新·功能
大模型铲屎官18 天前
Python 科学计算与机器学习入门:NumPy + Scikit-Learn 实战指南
开发语言·人工智能·python·机器学习·numpy·编程·scikit-learn
大模型铲屎官23 天前
Python 性能优化:从入门到精通的实用指南
开发语言·人工智能·pytorch·python·性能优化·llm·编程
漫谈网络1 个月前
序列化选型:字节流抑或字符串
python·编程
程序猿看视界1 个月前
「读书计划」《啊哈!算法》7日结构化学习规划
数据结构·编程·算法竞赛·学习计划·算法学习
charlie1145141911 个月前
从单片机的启动说起一个单片机到点灯发生了什么下——使用GPIO点一个灯
单片机·嵌入式硬件·学习·编程·教程·gpio