Cube Root - LISP(Scheme)
Using Block Structure
Let us try the same we did for finding out cube root using block structure in LISP(Scheme dialect).
First we should define some common functions which can be safely named globally such as cube:
(define (cube x)(* x x x))
Now let us start by defining cuberoot function:
(define (cuberoot guess x)
(define (goodGuess)(<(abs (- (cube guess) x)) 0.001))
(define (improve)(/(+ (/ x (* guess guess)) (* 2 guess)) 3))
(if(goodGuess) guess (cuberoot (improve) x)))
1. (define (cuberoot guess x)
in this step we simply define a block for cuberoot block ( main block ) and we know that we will require goodGuess procedure and an improve procedure both taking guess and x as a parameter but since both are already in lexical scope we can safely omit the parameters since we already know its value.
hence following (define (cuberoot guess x) we define goodGuess and improve :
(define (goodGuess)(<(abs (- (cube guess) x)) 0.001))
(define (improve)(/(+ (/ x (* guess guess)) (* 2 guess)) 3))
inside the main block.
Then we implement the actual cuberoot function by checking if the current guess is a good one, if it is a goodGuess then we simply output the guess else we improve it and call cuberoot again.
So now in interpreter , the function's will look like:
>(define (cube x)(* x x x))
>(define (cuberoot guess x)
(define (goodGuess)(<(abs (- (cube guess) x)) 0.001))
(define (improve)(/(+ (/ x (* guess guess)) (* 2 guess)) 3))
(if(goodGuess) guess (cuberoot (improve) x)))
Now let us test the made program by running it in interpreter, it will look like:
>(cuberoot 1.0 8)
2.000004911675504
where 1.0 is the initial guess and 8 is the number of which we are interested to find cuberoot of.
Written By,
Sarvesh Bhatnagar
No comments:
Post a Comment