Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computing Square Roots

Similar presentations


Presentation on theme: "Computing Square Roots"— Presentation transcript:

1 Computing Square Roots
= the y such that and y2=x The mathematical definition does not describe a procedure. Declarative : describing properties of things Imperative: describing how to do things (define (sqrt x) (the y (and (>= y 0) (= (square y) x))))

2 Newton’s Method Successive approximation
Guess y for the square root of a number x Get a better guess by averaging y with x/y Guess Quotient Average 1 2/1=2 (1+2)/2=1.5 1.5 2/1.5= ( )/2=1.4167 /1.4167= ( )=1.4142 /1.4142=...

3 (define (sqrt-iter guess x)
(if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) (define (improve guess x) (average guess (/ x guess))) (define (average x y) (/ (+ x y) 2)) (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.001)) (define (sqrt x) (sqrt-iter 1.0 x))

4 Decomposition of sqrt sqrt Sqrt-iter improve Good-enough? square abs
average

5 Procedural Abstraction
Procedures as “black boxes” Each procedure accomplishes an identifiable task. The details can be suppressed at the moment. ;; implementation #1 (define (square x) (* x x)) ;; implementation #2 (define (square x) (exp (double (log x)))) (define (double x) (+ x x))

6 Formal Parameters The meaning of a procedure should be independent of the parameter names (bound variables) used. The meaning of a procedure definition is unchanged if a bound variable is consistently renamed throughout the definition. If a variable is not bound, we say that it is free. In a procedure definition, the formal parameters have the body of the procedure as their scope. (define (square x) (* x x)) (define (square y) (* y y))


Download ppt "Computing Square Roots"

Similar presentations


Ads by Google