Cube Root - LISP(Scheme)
Let us program similarly for finding the cube root of which just 1 thing changes. i.e, how the next improve guess is defined i.e: if we make a guess, g then the improved guess would be
g' = (x/(y^2) + 2y)/3
So , we will mainly have to make changes in improve which would look as:
(define (improve guess x)(/ (+ (/ x (* guess guess)) (* 2 guess)) 3))
Now our other functions are similar, just in checking of good guess we need to check the difference between the cube of the guess and x instead of square of the guess and x. Hence the procedure goodGuess changes to:
(define (goodGuess guess x)(<(abs(- (cube guess) x)) 0.001))
Now we need to define something else, instead of the function square, i.e: cube.
(define (cube x)(* x x x))
Now let us define the main function cuberoot, its much similar to square root function we defined earlier.
(define (cuberoot guess x)(if(goodGuess guess x)guess (cuberoot (improve guess x) x)))
Now our total code will look in interpreter like:
>(define (cuberoot guess x)(if(goodGuess guess x)guess (cuberoot (improve guess x) x)))
>(define (goodGuess guess x)(<(abs(- (cube guess) x)) 0.001))
>(define (cube x)(* x x x))
>(define (improve guess x)(/ (+ (/ x (* guess guess)) (* 2 guess)) 3))
Now let us see the code in action ,
>(cuberoot 1.0 8)
2.000004911675504
Written By,
Sarvesh Bhatnagar