網頁

2018年3月18日 星期日

LISP Programming 1062_ex2

exercise 2: improving the good-enough?
Refer to exercise 1.7

解答:
;exercise 2: improving the good-enough?
(define (average x y)
    (/ (+ x y) 2))
(define (improve guess x)
    (average guess (/ x guess))
)
(define (good-enough? old-guess new-guess)
    ;(> 0.01 (/ (abs (- new-guess old-guess)) old-guess))
    (< (/ (abs (- new-guess old-guess)) old-guess) 0.01)
)
(define (sqrt-iter guess x)
    (if (good-enough? guess (improve guess x))  ;調用新的good-enough?
        (improve guess x)
        (sqrt-iter (improve guess x) x)
    )
)
(define (sqrt x)
    (sqrt-iter 1.0 x))


執行結果:

沒有留言:

張貼留言