- 牛顿法求平方根:用需要求平方根的数x与猜测值做商,得到的商值与x相加取平均值。用x再次与该平均值做商,商值与x相加求平均值。重复上面步骤。
(define (sqrt-iter guess x)
(if (good-enough? guess x) guess (sqrt-iter (improve guess x) x)));Value: sqrt-iter
(define (improve guess x)
(average guess (/ x guess)));Value: improve
(define (average x y)
(/ (+ x y) 2));Value: average
(define (good-enough? guess x)
(< (abs (- (square guess) x)) 0.001));Value: good-enough?
(define (abs x)
(if (< x 0) (- x) x));Value: abs
(define (square x) (* x x))
;Value: square
(define (sqrt x) (sqrt-iter 1.0 x))
;Value: sqrt
(sqrt 9)
;Value: 3.00009155413138
(sqrt (+ 100 37))
;Value: 11.704699917758145
- 习题1.6与1.7在与得到了很好的解释。习题1.6中的问题出在应用序求值时,将表达式带入new-if中时,已经对所有分支进行了求值,而不像if中,只有条件表达式为真时,才求分支。习题1.7因为其精度不够,可以采用猜测值比例的方式判断。
- 习题1.8
(define (tri-iter guess x)
(if (good-enough? guess x) guess (tri-iter (improve guess x) x))) (define (improve guess x) (/ (+ (/ x (square guess)) (* 2 guess)) 3))(define (good-enough? guess x)
(< (abs (- (tripple guess) x)) 0.001)) (define (abs x) (if (< x 0) (- x) x))(define (tripple x) (* x x x))
(define (square x) (* x x)) (define (tri x) (tri-iter 1.0 x))