2.8

练习 2.8 通过类似于 Alyssa 的推理,说明两个区间的差应该怎样计算。请定义出相应的减法过程 sub-interval。


两个区间相减,相当于第一个区间加上第二个区间的“负区间”。

(define (make-interval a b) (cons a b))
(define upper-bound cdr)
(define lower-bound car)

(define (add-interval x y) 
    (make-interval (+ (lower-bound x) (lower-bound y))
                    (+ (upper-bound x) (upper-bound y))))
(define (sub-interval x y) (add-interval x (make-interval (- 0 (upper-bound y)) (- 0 (lower-bound y)))))
(define int1 (make-interval 2 4))
(lower-bound int1)
(upper-bound int1)
(define int2 (make-interval 1 3))
(lower-bound int2)
(upper-bound int2)
(define int3 (make-interval (- 0 (upper-bound int2)) (- 0 (lower-bound int2))))
(lower-bound int3)
(upper-bound int3)
int1
int2
(sub-interval int1 int2)

或者,使用和区间乘法类似的方法:

(define (subtract-interval x y)
    (define p1 (- (lower-bound x) (lower-bound y)))
    (define p2 (- (lower-bound x) (upper-bound y)))
    (define p3 (- (upper-bound x) (lower-bound y)))
    (define p4 (- (upper-bound x) (upper-bound y)))

    (make-interval (min p1 p2 p3 p4) (max p1 p2 p3 p4)))

(subtract-interval int1 int2)

results matching ""

    No results matching ""