You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
975 B
38 lines
975 B
(define (square x) (* x x)) |
|
|
|
(define (average x y) |
|
(/ (+ x y) 2)) |
|
|
|
(define (improve guess x) |
|
(average guess (/ x guess))) |
|
|
|
(define (good-enough? guess x) |
|
(< (abs (- (square guess) x)) 0.001)) |
|
|
|
(define (sqrt-iter guess x) |
|
(if (good-enough? guess x) |
|
guess |
|
(sqrt-iter (improve guess x) x))) |
|
|
|
(define (sqrt x) |
|
(sqrt-iter 1.0 x)) |
|
|
|
;;; this is where things begin fucking up |
|
;;; it doesn't work because if is a special case |
|
;;; that uses lazy evaluation, thus it doesn't have to |
|
;;; evaluate its parameters. |
|
;;; |
|
;;; when testing, i found that in guile, it caused a stack overflow; |
|
;;; whereas in chicken, it caused an infinite loop (maybe). |
|
|
|
(define (new-if predicate then-clause else-clause) |
|
(cond (predicate then-clause) |
|
(else else-clause))) |
|
|
|
(define (new-sqrt-iter guess x) |
|
(new-if (good-enough? guess x) |
|
guess |
|
(new-sqrt-iter (improve guess x) x))) |
|
|
|
(display (sqrt 3)) |
|
;;(display (new-sqrt-iter 1.0 2))
|
|
|