Lisp - Square Root
Lets take a look at the program to find square root of a number by newtons method
It involves 2 main steps :
1. Check if current guess is a good one
2. If 1 returns false, improve the guess by guess + (x/guess) / 2 and re-apply the method to find square root.
so some basic functions which we might require are:
Average:
(define (average x y) (/ (+ x y) 2))
Improve Guess:
(define (improveGuess guess x) ( average guess (/ x guess )))
goodGuess? :
(define (goodGuess? guess x) (< (abs (- (square guess) x)) 0.001))
Average: Takes in 2 arguments x and y , adds them and then divides the sum by 2
Improve Guess: does what is mentioned in step 2
goodGuess: Calculates | guess^2 - x | and checks if the magnitude is more than 0.001, if it is then the guess needs to be improved , else the guess is good. 0.001 is the amount of error which is acceptable in calculation of square root.
now let us define square root:
(define (sqrt guess x) ( if(goodGuess? guess x) guess (sqrt (improveGuess guess x) x)))
Let us see total program in interpreter
>(define (average x y) (/ (+ x y) 2))
>(define (improveGuess guess x) ( average guess (/ x guess )))
>(define (goodGuess? guess x) (< (abs (- (square guess) x)) 0.001))
>(define (sqrt guess x) ( if(goodGuess? guess x) guess (sqrt (improveGuess guess x) x)))
Now let us use our defined function sqrt in action, Note that the initial guess value is required to be seeded, in this case we are initializing it as 1.0
>(sqrt 1.0 4)
2.0000000929222947
No comments:
Post a Comment