2.12

练习 2.12 请定义一个构造函数 make-center-percent,它以一个中心点和一个百分比为参数,产生出所需要的区间。你还需要定义选择函数 percent,通过它可以得到给定区间的百分数误差,选择函数 center 与前面定义的一样。


(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 int1 (make-interval 2 4))
(define int2 (make-interval 3 6))
(mul-interval int1 int2)

在之前定义过的函数的基础上,很容易写出:

(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 (percent x)
  (/ (width x) (center x)))

(define int (make-center-percent 2 0.5))
int
(center int)
(define (width x) (/ (- (upper-bound x) (lower-bound x)) 2))
(percent int)

results matching ""

    No results matching ""