my attempt to do the exercises in sicp.

Saturday, July 12, 2008

sicp exercise 2.14

; Exercise 2.14.  Demonstrate that Lem is right. Investigate the behavior of the system on a variety of arithmetic expressions. Make some intervals A and B, and use them in computing the expressions A/A and A/B. You will get the most insight by using intervals whose width is a small percentage of the center value. Examine the results of the computation in center-percent form (see exercise 2.12).

(define (mul-interval x y)
  (let ((p1 (* (lower-bound x) (lower-bound y)))
        (p2 (* (lower-bound x) (upper-bound y)))
        (p3 (* (upper-bound x) (lower-bound y)))
        (p4 (* (upper-bound x) (upper-bound y))))
    (make-interval (min p1 p2 p3 p4)
                   (max p1 p2 p3 p4))))

(define (make-interval a b) (cons a b))
(define (upper-bound interval) (car interval))
(define (lower-bound interval) (cdr interval))

(define (width interval)
  (/ (- (upper-bound interval) (lower-bound interval)) 2))

(define (div-interval x y)
  (mul-interval x
                (make-interval (/ 1.0 (lower-bound y))
                               (/ 1.0 (upper-bound y)))))

(define (make-center-percent center percent-tolerance)
  (let ((d (/ (* center percent-tolerance) 100.0)))
  (make-interval (- center d) (+ center d))))

(define X (make-interval 10 20))
(define Y (make-interval 1000 100000))
(display (div-interval X X)) (newline)
(display (div-interval X Y)) (newline)

(define P (make-center-percent 100 50))
(define Q (make-center-percent 1000000 10))
(display (div-interval P P)) (newline)
(display (div-interval P Q)) (newline)

(define A (make-center-percent 100 0.01))
(define B (make-center-percent 1000000 0.01))
(display (div-interval A B)) (newline)
(display (div-interval A B)) (newline)

No comments: