2.10

练习 2.10 Ben Bitdiddle 是个专业程序员,他看了 Alyssa 工作后评论说,除以一个跨过横跨0的区间的意义不清楚。请修改 Alyssa 的代码,检查这种情况并在出现这一错误时报错。


(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 (width x) (/ (- (upper-bound x) (lower-bound x)) 2))
(define int1 (make-interval 1 2))
(define int2 (make-interval 1 2))

(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 x (make-interval 2 4))
(define y (make-interval 1 2))
(define z (make-interval -1 1))

(div-interval x y)
(div-interval x z)

JavaScript 版本的区间算术

results matching ""

    No results matching ""