sicp每日一題[1.45]

再思即可發表於2024-09-05

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

相關文章