sicp习题试解 (1.46)

类别:编程语言 点击:0 评论:0 推荐:

; ======================================================================
;
; Structure and Interpretation of Computer Programs
; (trial answer to excercises)
;
; 计算机程序的构造和解释(习题试解)
;
; created: code17 03/06/05
; modified:
; (保持内容完整不变前提下,可以任意转载)
; ======================================================================


;; SICP No.1.46

(define (iterative-improve good-enough? improve)
(define (try-it x)
(if (good-enough? x) x (try-it (improve x))))
(lambda (x) (try-it x)))

;; sqrt,采用1-1-7节中原来的good-enough?和improve函数定义
(define (sqrt x)
(define (good-enough? guess)
(< (abs (- (square guess) x)) 0.001))
(define (improve guess)
(average guess (/ x guess)))
((iterative-improve good-enough? improve) 1.0))

;; fixed-point
(define (fixed-point f first-guess)
(define tolerance 0.00001)
(define (good-enough? guess)
(< (abs (- guess (f guess))) tolerance))
(define (improve guess) (f guess))
((iterative-improve good-enough? improve) first-guess))


;; Test-it
;; Welcome to MzScheme version 209, Copyright (c) 2004 PLT Scheme, Inc.
;; ;; 新的sqrt的测试结果与课本中原始版本的结果完全一致
;; > (sqrt 9)
;; 3.00009155413138
;; > (sqrt (+ (sqrt 2) (sqrt 3)))
;; 1.7739279023207892
;; > (square (sqrt 1000))
;; 1000.000369924366
;;
;; ;; 新的fixed-point的测试结果与课本中原始版本非常接近,但不完全一致。原因是
;; ;; 课本中采用的close-enough?函数取guess 和(f guess)两个参数,如果满足条
;; ;; 件,主函数取(f guess)为最后结果;而在使用iterative-improve模式时,
;; ;; 按照一般形式,good-enough?只能取一个参数,那么只能是guess,通过判断
;; ;; guess满足条件(guess与(f guess)差值小于tolerance),iterative-improve
;; ;; 的定义是取guess为最后结果而不是(f guess)。这是造成微小数值的差异的原因。
;; > (fixed-point cos 1.0)
;; 0.7390893414033927
;; > (fixed-point (lambda (y) (+ (sin y) (cos y))) 1.0)
;; 1.2587228743052672
;; >

本文地址:http://com.8s8s.com/it/it23016.htm