1.46

Exercise 1.46: Several of the numerical methods described in this chapter are instances of an extremely general computational strategy known as iterative improvement. Iterative improvement says that, to compute something, we start with an initial 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 iterative-improve that takes two procedures as arguments: a method for telling whether a guess is good enough and a method for improving a guess. Iterative-improve 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 sqrt procedure of 1.1.7 and the fixed-point procedure of 1.3.3 in terms of iterative-improve.

iterative-improve

(define (iterative-improve good-enough improve)
    (lambda (x guess)
        (define (try-with guess)
            (if (good-enough guess x)
                guess
                (try-with (improve guess x))
            )
        )

        (try-with guess)
    )
)

sqrt

(define (square x) (* x x))

(define (good-enough? guess x)
  (< (abs (- (square guess) x)) 0.001))

(good-enough? 0.0001 25)

(define (improve guess x)
  (/ (+ guess (/ x guess)) 2))

(improve 1 4)

(define sqrt (iterative-improve good-enough?
                                   improve))

(sqrt 4 1)

fixed-point

fixed-point in 1.3.3
(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 (lambda (x) (/ x 2)) 1.0)
rewritten fixed-point
(define (good-enough? guess f)
  (< (abs (- (f guess) guess)) tolerance))

(define (improve guess f)
  (f guess))

(define fixed-point (iterative-improve good-enough? improve))

(fixed-point (lambda (x) (/ x 2)) 1.0)

results matching ""

    No results matching ""