Dan's Thoughts Thinking somewhat carefully

26Jul/090

Exercise 2.10 of SICP

Exercise 2.10: Ben Bitdiddle, an expert systems programmer, looks over Alyssa's shoulder and comments that it is not clear what it means to divide by an interval that spans zero. Modify Alyssa's code to check for this condition and to signal an error if it occurs.

If an interval I = [-2,2] spans 0, the inverse, I-1=[0.5,-0.5] which is wrong since the lower limit cannot be greater than the upper limit.

(define (div-interval x y)
  (define (spans-zero? i)
    (and 
      (not (> (lower-bound i) 0)) 
      (not (< (upper-bound i) 0)))) 
  (if (spans-zero? y)
    (error "The dividing interval cannot span 0.")
    (mul-interval x 
                  (make-interval (/ 1.0 (upper-bound y))
                                 (/ 1.0 (lower-bound y))))))

> (div-interval (make-interval 1 1) (make-interval -2 2))
*** ERROR IN (console)@76.1 -- The dividing interval cannot span 0.

Filed under: lisp, SICP Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

Spam protection by WP Captcha-Free

No trackbacks yet.