# 练习 1.46¶

(define (iterative-improve close-enough? improve)
(lambda (first-guess)
; ...
))


;;; p46-fixed-point.scm

(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))


fixed-point 函数不仅仅和 iterative-improve 非常相似，事实上， iterative-improve 就隐藏在 fixed-point 当中！

fixed-point 中， close-enough? 负责检查猜测是否足够好，而函数 f 负责改进猜测，如果我们将 close-enough? 函数抽取出来，成为额外的参数，那么 fixed-point 的定义就变成了：

(define (fixed-point f first-guess close-enough?)
(define (try guess)
(let ((next (f guess)))
(if (close-enough? guess next)
next
(try next))))
(try first-guess))

(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))

(define tolerance 0.00001)


(define (fixed-point f close-enough?)
(lambda (first-guess)
(define (try guess)
(let ((next (f guess)))
(if (close-enough? guess next)
next
(try next))))
(try first-guess)))

(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))

(define tolerance 0.00001)


;;; 46-iterative-improve.scm

(define (iterative-improve close-enough? improve)
(lambda (first-guess)
(define (try guess)
(let ((next (improve guess)))
(if (close-enough? guess next)
next
(try next))))
(try first-guess)))


## 用 iterative-improve 重定义 fixed-point¶

;;; 46-fixed-point.scm

(define (fixed-point f first-guess)
(define tolerance 0.00001)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(define (improve guess)
(f guess))
((iterative-improve close-enough? improve) first-guess))


1 ]=> (load "46-fixed-point.scm")

;... done
;Value: fixed-point

1 ]=> (fixed-point cos 1.0)

;Value: .7390822985224024


## 用 iterative-improve 重定义 sqrt¶

;;; 46-sqrt.scm

(define (sqrt x)
(define dx 0.00001)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) dx))
(define (improve guess)
(average guess (/ x guess)))
(define (average x y)
(/ (+ x y) 2))
((iterative-improve close-enough? improve) 1.0))


1 ]=> (load "46-sqrt.scm")