Exercise 1.8.  Newton’s method for cube roots is based on the fact that if y is an approximation to the cube root of x, then a better approximation is given by the value

Use this formula to implement a cube-root procedure analogous to the square-root procedure. (In section 1.3.4 we will see how to implement Newton’s method in general as an abstraction of these square-root and cube-root procedures.)

Solution


(define (square x) (* x x))
(define (cube x) (* (* x x) x))
(define
(average x y)
(/
(+ x y)
2))
(define
(good-enough?
x
guess)
(<
(abs
(-
x
(square guess)))
0.00001))
(define
(good-enough2?
x
guess)
(<
(abs
(-
x
guess))
0.00001))
(define (abs x)
(cond ((> x 0) x)
((= x 0) 0)
((< x 0) (- x))))
(define
(improve-guess
x
guess)
(/
(+
(/
x
(square guess))
(* 2 guess))
3))
(define
(cube-iter x guess)
(if
(or
(good-enough?
x
guess)
(good-enough2?
guess
(improve-guess
x
guess)))
guess
(cube-iter
x
(improve-guess
x
guess)))))
(define (cube-root x) (cube-iter x 1.0))

view raw

Cuberoot.scm

hosted with ❤ by GitHub

 


Comments

Leave a Reply

Discover more from Gaurav Sharma's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading