Square Root using Newton’s Method in scheme
Scheme is a new language for me. I came across Scheme from the book Structure and Interpretation of Computer Programs(SICP).
Scheme is a pure functional programming language. Scheme is a dialect of Lisp. My first program in scheme is the implentation of square root using Newton’s method.
Newton’s method of finding square root is based on the continuous refininig of guessed square root. We can almost avoid usage of loops in scheme by using the concept of recursion. In Newton’s method first we have to guess a square root, say 1. Then we must refine the guess by making the new guess value as average of guess and the number divided by guess.
guess = (guess + x / guess) / 2
The one important thing to remember in scheme is to make sure all the mathematical expressions given are in the prefix form.
Starting from the squareroot() method, we call the method sqrot with parameters 1.0 and x where 1.0 is the guess. In the sqrot method we check whether our guess is good enough, in this case if the difference between square of guess and x is less than or equal to 0.001 its good enough. If the guess in good enough the guess is returned else the guess is refined further using the average equation.
In the above code, everything is method. There is no need of explicit return statement. It will automatically return to the called method with a return value.
We can use the square root method by just running the command (squareroot 10) in the drscheme command line.