SICP exercise 2.12
From Drewiki
Problem
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 given in the text in section 2.1.4.
Solution
Here are the center selector and the make-center-width constructor given in the text, along with the code from previous exercises for representing intervals.
(define (make-interval a b) (cons a b)) (define (lower-bound i) (car i)) (define (upper-bound i) (cdr i)) (define (interval-width i) (/ (- (upper-bound i) (lower-bound i)) 2)) (define (center i) (/ (+ (lower-bound i) (upper-bound i)) 2)) (define (make-center-width c w) (make-interval (- c w) (+ c w)))
Here are the requested procedures. Note that the percentage tolerance specifies the width of the interval. For example, using the resistor example given in the text, "6.8 ohms with 10% tolerance" gives a width of 0.68 and an interval of [6.12, 7.48].
(define (make-center-percent center percent) (let ((width (* center ( / percent 100.0)))) (make-center-width center width))) (define (percent i) (* (/ (interval-width i) (center i)) 100.0))
Test:
(define x (make-center-percent 2.5 15)) (lower-bound x)
Output:
2.125
(upper-bound x)
Output:
2.875
(percent x)
Output:
15.0

