sicp 2.11

Exercise 2.11.  In passing, Ben also cryptically comments: ``By testing the signs of the endpoints of the intervals, it is possible to break mul-interval into nine cases, only one of which requires more than two multiplications.'' Rewrite this procedure using Ben's suggestion.

 

 

根据interval的两个值的范围(大于等于或小于0),分情况计算mul-interval

 

(define (mul-interval x y)
  (cond ((and (>= (lower-bound x) 0) (>= (lower-bound y) 0))
         (make-interval (* (lower-bound x) (lower-bound y))
                        (* (upper-bound x) (upper-bound y))))
        ((and (< (lower-bound x) 0) (>= (upper-bound x) 0) (>= (lower-bound y) 0))
         (make-interval (* (lower-bound x) (upper-bound y))
                        (* (upper-bound x) (upper-bound y))))
        ((and (< (upper-bound x) 0) (>= (lower-bound y) 0))
         (make-interval (* (lower-bound x) (upper-bound y))
                        (* (upper-bound x) (lower-bound y))))
        ((and (>= (lower-bound x) 0) (< (lower-bound y) 0) (>= (upper-bound y) 0))
         (make-interval (* (upper-bound x) (lower-bound y))
                        (* (upper-bound x) (upper-bound y))))
        ((and (< (lower-bound x) 0) (>= (upper-bound x) 0)
              (< (lower-bound y) 0) (>= (upper-bound y) 0))
         (make-interval (min (* (lower-bound x) (upper-bound y))
                             (* (upper-bound x) (lower-bound y)))
                        (max (* (lower-bound x) (lower-bound y))
                             (* (upper-bound x) (upper-bound y)))))
        ((and (< (upper-bound x) 0) (< (lower-bound y) 0) (>= (upper-bound y) 0))
         (make-interval (* (lower-bound x) (upper-bound y))
                        (* (lower-bound x) (lower-bound y))))
        ((and (>= (lower-bound x) 0) (< (upper-bound y) 0))
         (make-interval (* (upper-bound x) (lower-bound y))
                        (* (lower-bound x) (upper-bound y))))
        ((and (< (lower-bound x) 0) (>= (upper-bound x) 0) (< (upper-bound y) 0))
         (make-interval (* (upper-bound x) (lower-bound y))
                        (* (lower-bound x) (lower-bound y))))
        ((and (< (upper-bound x) 0) (< (upper-bound y) 0))
         (make-interval (* (upper-bound x) (upper-bound y))
                        (* (lower-bound x) (lower-bound y))))))
 

你可能感兴趣的:(SICP)