SICP exercise 2.08

From Drewiki

Jump to: navigation, search

Problem

Using reasoning analogous to Alyssa's in section 2.1.4 of the text, describe how the difference of two intervals may be computed. Define a corresponding subtraction procedure, called sub-interval.

Solution

Here is the definition of add-interval as given in the text, along with the constructor and selectors we defined in exercise 2.7:

 

Let's think about the difference between two intervals. Consider the difference z = xy of two intervals x and y, where

x : \left [x_1, x_2 \right ], x_1 \le x_2

y : \left [y_1, y_2 \right ], y_1 \le y_2.

The bounds of interval z must be chosen from the set of differences

\left \{x_1 - y_1, x_1 - y_2, x_2 - y_1, x_2 - y_2 \right \}

Is one of these differences guaranteed always to be the minimum value of the set? The maximum value of the set?

Using some simple algebra on the inequalities, we can figure this out. For the minimum value, we know that x_1 \le x_2. Subtracting y1 from both sides of the inequality, we get

x_1 - y_1 \le x_2 - y_1

So we can eliminate x2y1 from the set of possible minimum values.

Repeat for y2:

x_1 \le x_2

x_1 - y_2 \le x_2 - y_2

and now we can eliminate x2y2 from the set of possible minimum values.

We also know that y_1 \le y_2. Subtracting y1 from both sides, we get

0 \le y_2 - y_1

Then, subtracting y2 from both sides yields

-y_2 \le -y_1

Now add x1 to both sides:

x_1 - y_2 \le x_1 - y_1

So now we can eliminate x1y1 from the set of possible minimum values, leaving only x1y2. x1y2 is always the lower bound of the interval.

We already showed that

x_1 - y_1 \le x_2 - y_1,

so x1y1 is not the maximum value, nor is x1y2, since that's the minimum value. We also showed that

-y_2 \le - y_1,

so by adding x2 to both sides, we get

x_2 - y_2 \le x_2 - y_1

Therefore x2y1 must always be the upper bound of the interval.

Now we can define sub-interval:

 

Test it:

 

The value of the expression (sub-interval i2 i1) should be the interval [0, 2], since if both values are at 2, the difference is 0 (the minimum value), and if i2 is at 3 and i1 is at 1, the difference is 2 (the maximum value). Let's check the procedure against our reasoning:

 

Output:

0
 

Output:

2


That looks good.

Now let's reverse the calculation: what is the value of (sub-interval i1 i2)? The minimum value in this case occurs when i1 is 1 and i2 is 3: then the value is -2. And the maximum value occurs when i1 is 2 and i2 is 2: then the value is 0.

Check again:

 

Output:

-2
 

Output:

0


Let's try two new intervals, one of which contains the other:

 

Subtracting interval i3 from interval i4, we should get the interval [-2, 3]. Let's check:

 

Output:

-2
 

Output:

3


Subtracting i4 from i3, we should get [-3, 2]:

 

Output:

-3
 

Output:

2
Personal tools