Hi I am reading the SICP, I am stuck in the Exercise 1.7:
here is my code:
(define (avg x y)
(/ (+ x y) 2))
;;(avg 1 2)
(define (square x)
(* x x))
;;(square 2)
(define (improve guess x)
(avg guess (/ x guess)))
;;(improve 1 2)
(define (good-enough? x guess)
(< (abs (- guess ((avg guess (/ x guess))))) 0.1))
(define (sqrt-iter guess x)
(if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
(define (my-sqrt x)
(sqrt-iter 1.0 x))
(my-sqrt 100)
and the DrRacket gives an error:
function call: expected a function after the open parenthesis, but received 50.005
what's that mean and how to fix the problem?
There are a couple of mistakes in the code, including misplaced parentheses. For starters, good-enough?
as defined for the exercise 1.7, should look like this:
(define (good-enough? guess-old guess-new)
(< (/ (abs (- guess-old guess-new)) guess)
(/ 0.001 guess)))
And sqrt-iter
, as written in your code, will lead to an infinite recursion. Try this instead:
(define (sqrt-iter guess-old guess-new x)
(if (good-enough? guess-old guess-new)
guess-new
(sqrt-iter guess-new (improve guess-new x) x)))
(define (my-sqrt x)
(sqrt-iter 0.0 1.0 x))