(define (sqrt x y z) (define (half m n) (/ (+ m n) 2)) (define (square m) (* m m)) (cond ((and ( < (- (square (half x y)) z) 0.0001) ( > (- (square (half x y)) z) (- 0.0001))) (half x y)) ((> (- (square (half x y)) z) 0.0001) (sqrt x (half x y) z)) ((< (- (square (half x y)) z) (- 0.0001)) (sqrt (half x y) y z))))
x 區間開始spa
y 區間結束code
z求的開平方數blog
調用ci
(sqrt 0 2 2)class
1 ]=> (sqrt 0 2 2)
;Value: 11585/8192di
牛頓法co
x(n+1) = (x(n)*x(n) + b)/(2*x(n))gif
(define (sqrt x s) (define (square z) (* z z)) (define (temp x s) (/ (+ s (/ x s)) 2)) (cond ((and (> (- ( square (temp x s) ) x) (- 0.0001)) (< (- (square (temp x s)) x) 0.0001)) (temp x s)) (else (sqrt x (temp x s)))))
]=> (sqrt 2 1) ;Value: 577/408