## **Note: this wiki is now retired and will no longer be updated!**

**The static final versions of the pages are left as a convenience for readers. Note that meta-pages such as "discussion," "history," etc., will not work.**

# SICP exercise 2.10

## Problem

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 from section 2.1.4 of the text to check for this condition and to signal an error if it occurs.

## Solution

Let's signal an error by returning zero. Here are the unmodified procedures from Alyssa's original code in section 2.1.4 of the text:

(define (make-interval a b) (cons a b)) (define (lower-bound i) (car i)) (define (upper-bound i) (cdr i)) (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))))

Here's the modified `div-interval` procedure and a helper procedure
that finds intervals that span zero (which may be useful to other
procedure, so it's not an internal procedure to `div-interval`):

(define (spans-zero? x) (and (> 0 (lower-bound x)) (< 0 (upper-bound x)))) (define (div-interval x y) (if (spans-zero? y) 0 (mul-interval x (make-interval (/ 1.0 (upper-bound y)) (/ 1.0 (lower-bound y))))))

Test:

(define x (make-interval 2 8)) (define y (make-interval 4 8)) (lower-bound (div-interval x y))

*Output:*

`
`

0.25

(upper-bound (div-interval x y))

*Output:*

`
`

2.0

(define ybad (make-interval -1 4)) (div-interval x ybad)

*Output:*

`
`

0