my attempt to do the exercises in sicp.

Tuesday, July 1, 2008

sicp exercise 1.44

;  Exercise 1.44.  The idea of smoothing a function is an important concept in signal processing. If f is
;  a function and dx is some small number, then the smoothed version of f is the function whose value at a
;  point x is the average of f(x - dx), f(x), and f(x + dx). Write a procedure smooth that takes as input
;  a procedure that computes f and returns a procedure that computes the smoothed f. It is sometimes
;  valuable to repeatedly smooth a function (that is, smooth the smoothed function, and so on) to obtained
;  the n-fold smoothed function. Show how to generate the n-fold smoothed function of any given function
;  using smooth and repeated from exercise 1.43.

(define (compose f g)
    (f (g x))))

(define (repeated f n)
  (define (iter i res)
    (if (>= i n)
        (iter (+ i 1) (compose f res))))
  (iter 1 f))

(define dx 0.00001)

(define (avg3 x y z) (/ (+ x y z) 3))

(define (smooth f)
  (lambda (x)
    (avg3 (f (- x dx)) (f x) (f (+ x dx)))))

(define (smooth-n f n)
  (repeated smooth n) f)

(define (cube x) (* x x x))

(display ((smooth cube) 3.9999999)) (newline)
(display ((smooth-n cube 5) 3.9999999)) (newline)

No comments: