SICP Exercise 2.10
Question
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.
Answer
For this, we have to check whether the upper and lower bounds of \(y\) have the same sign. We can achieve this by checking if \(\frac{y_{upper}}{\lvert y_{upper}\rvert}=\frac{y_{lower}}{\lvert y_{lower}\rvert}\).
(define (div-interval x y)
(if (= (/ (lower-bound y) (abs (lower-bound y)))
(/ (upper-bound y) (abs (upper-bound y)))))
(mul-interval x
(make-interval
(/ 1.0 (upper-bound y))
(/ 1.0 (lower-bound y))))
(error "ERROR: Interval spans zero")))
So let’s test it:
(define i1 (make-interval 3 5))
(define i2 (make-interval -2 2))
(div-interval i1 i2)
And we receive the expected error message:
ERROR: Interval spans zero