sicp每日一题[1.46]

41 篇文章 0 订阅
14 篇文章 0 订阅

Exercise 1.46

Several of the numerical methods described in this chapter are instances of an extremely general computational strategy known as i t e r a t i v e i m p r o v e m e n t iterative improvement iterativeimprovement. Iterative improvement says that to compute something, we start with aninitial guess for the answer, test if the guess is good enough, and otherwise improve the guess and continue the process using the improved guess as the new guess. Write a procedure i t e r a t i v e − i m p r o v e iterative-improve iterativeimprove that takes two procedures as arguments: a method for telling whether a guess is good enough and a method for improving a guess. i t e r a t i v e − i m p r o v e iterative-improve iterativeimprove should return as its value a procedure that takes a guess as argument and keeps improving the guess until it is good enough. Rewrite the s q r t sqrt sqrt procedure of Section 1.1.7 and the f i x e d − p o i n t fixed-point fixedpoint procedure of Section 1.3.3 in terms of i t e r a t i v e − i m p r o v e iterative-improve iterativeimprove.


(define tolerance 0.00001)

(define (good-enough? guess target tolerance)
  (< (abs (- guess target)) tolerance))

; 注意:这个函数的两个参数以及返回值都是函数,所以调用的语句外还要传一个参数作为 first-guess
(define (iterative-improve good-enough? improve-guess)
  (lambda (first-guess)
    (define (iter guess)
      (if (good-enough? guess)
          guess
          (iter (improve-guess guess))))
    (iter first-guess)))

; Rewrite Version
; 1.1.7 Square Roots by Newton's Method
(define (sqrt x)
  ((iterative-improve (lambda (guess) (good-enough? (square guess) x tolerance))
                      (lambda (guess) (average guess (/ x guess))))
   1.0))

; 1.3.3 Procedures as General Methods
(define (fixed-point f first-guess)
  ((iterative-improve (lambda (guess) (good-enough? guess (f guess) tolerance))
                      f)
   first-guess))


(sqrt 2)
(sqrt 10)

(fixed-point cos 1.0)
(fixed-point (lambda (x) (+ (sin x) (cos x))) 1.0)


; 执行结果
1.4142156862745097
3.162277665175675
0.7390893414033927
1.2587228743052672
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值