考虑这两种稍微不同的计算第五根的方法:
(define (fifth-root-right x)
(fixed-point-of-transform (lambda (y) (/ x (expt y 4)))
(repeated average-damp 2)
1.0))
(define (fifth-root-wrong x)
(fixed-point (repeated
(average-damp (lambda (y) (/ x (expt y 4))))
2)
1.0))
两者都试图通过对固定点的平均衰减搜索来计算第五个根,因为 x 的第五个根是映射 y -> x/(y^4) 的一个固定点。我已经定义
(define (average-damp f)
(lambda (x) (average x (f x))))
(define tolerance 0.00001)
(define (fixed-point f first-guess)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(define (try guess)
(let ((next (f guess)))
(if (close-enough? guess next)
next
(try next))))
(try first-guess))
(define (fixed-point-of-transform g transform guess)
(fixed-point (transform g) guess))
(define (repeated f n)
(if (= n 1)
f
(compose f (repeated f (- n 1)))))
(define (compose f g) (lambda (x) (f (g x))))
尝试这两种方法,我们得到
> (fifth-root-right 32)
2.000001512995761
> (fifth-root-wrong 32)
2.8804315666156364
为什么第二种方法无法正确计算第五个根?更奇怪的是,如果我们在第四或第三根上尝试这种错误的方法,它会正常工作:
(define (fourth-root x)
(fixed-point (repeated
(average-damp (lambda (y) (/ x (expt y 3))))
2)
1.0))
(define (cube-root x)
(fixed-point (repeated
(average-damp (lambda (y) (/ x (expt y 2))))
2)
1.0))
> (fourth-root 16)
1.982985155172348
> (cube-root 8)
2.0000009087630515
作为参考,此代码尝试解决计算机程序的结构和解释中的练习 1.45。现在我有了正确的方法,我的代码可以工作,但我不明白为什么我的错误方法是错误的。