2.14
练习 2.14 请确认 Len 是对的。请你用各种不同的算术表达式来检查这一系统的行为。请做出两个区间 A 和 B,并用它们计算表达式 A/A 和 A/B。如果所用区间的宽度相对于中心值取很小百分数,你将会得到更多的认识。请检查对于中心-百分比形式(见练习2.12)进行计算的结果。
先做个实验:
(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 (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)))
(define (mul-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))
)
(define (div-interval x y)
(if (<= (* (lower-bound y) (upper-bound y)) 0) "Not allowed!"
(mul-interval x
(make-interval (/ 1.0 (upper-bound y))
(/ 1.0 (lower-bound y))))))
(define int1 (make-interval 2 4))
(define int2 (make-interval 3 6))
int1
int2
(define (par1 r1 r2)
(div-interval (mul-interval r1 r2) (add-interval r1 r2)))
(define (par2 r1 r2)
(define one (make-interval 1 1))
(div-interval one (add-interval (div-interval one r1) (div-interval one r2))))
(par1 int1 int2)
(par2 int1 int2)
果然,结果相差甚远。再看一下 A/A 和 A/B 的结果。
(define A int1)
(define B int2)
(div-interval A A)
(div-interval A B)
然后,看一下对于宽度相对于区间中心值取很小的百分数的计算结果。
(define AA (make-interval 99 100))
(define BB (make-interval 999 1000))
(div-interval AA AA)
(div-interval AA BB)
下面再看一下使用中心-百分比的形式来计算的结果。
(define (make-center-percent center percent)
(make-interval (- center (* center percent))
(+ center (* center percent))))
(define (center x) (/ (+ (lower-bound x) (upper-bound x)) 2))
(define (width x) (/ (- (upper-bound x) (lower-bound x)) 2))
(define (percent x)
(/ (width x) (center x)))
(define AAAA (make-center-percent (center A) (percent A)))
(define BBBB (make-center-percent (center B) (percent B)))
(div-interval AAAA AAAA)
(div-interval AAAA BBBB)
结果和 (make-interval) 生成的区间计算的结果一致。
再看一下另一种中心-百分比的形式计算的结果。
(define make-c-p cons)
(define c car)
(define p cdr)
(define (w x) (* (c x) (p x)))
(define (center x) (/ (+ (lower-bound x) (upper-bound x)) 2))
(define (width x) (/ (- (upper-bound x) (lower-bound x)) 2))
(define (percent x) (/ (width x) (center x)))
(define AAA (make-c-p (center A) (percent A)))
AAA
(define BBB (make-c-p (center B) (percent B)))
BBB
(div-interval AAA AAA)
(div-interval AAA BBB)