my attempt to do the exercises in sicp.

Saturday, July 12, 2008

sicp exercise 2.12

; Exercise 2.12.  Define a constructor make-center-percent that takes a center and a percentage tolerance and produces the desired interval. You must also define a selector percent that produces the percentage tolerance for a given interval. The center selector is the same as the one shown above.

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

(define (make-center-percent center percent-tolerance)
  (let ((d (/ (* center percent-tolerance) 100.0)))
  (make-interval (- center d) (+ center d))))

(define (center i)
  (/ (+ (lower-bound i) (upper-bound i)) 2))
(define (width i)
  (/ (- (upper-bound i) (lower-bound i)) 2))

(define (percent interval)
  (let ((u (upper-bound interval))
        (c (center interval)))
  (* (/ (- u c) c) 100.0)))

(display (make-center-percent 100 10)) (newline)
(display (make-center-percent 29 11)) (newline)
(display (percent (make-center-percent 100 10))) (newline)

No comments: