I am playing around with Lisp (Scheme dialect in this case), so I decided to write some square root algorithms.
Here’s the first naive version I wrote. As you can see it only works with perfect squares (the first argument should always be 1, as it starts looking with it; the second argument is the number you want to find the square root of):
(define (squareRoot start x)
(if (= (* start start) x)
start
(squareRoot (+ start 1) x)
) )
(display (squareRoot 1 9))
(display "\n")
The second algorithm I wrote uses Newton’s method. The idea is simple: take a guess for the square root, y, and then iteratively improve it by averaging y with x/y (every time you do this average you move guess toward the square root). You can see a similar algorithm on the Structure and Interpretation of Computer Programs (SICP) book:
(define (abso x) (if (< x 0) (* -1 x) x))
(define (squareRoot guess x)
(if (< (abso(- (* guess guess) x)) 0.01)
guess
(squareRoot (/ (+ guess (/ x guess)) 2) x))
)
(display (squareRoot 1 10))
(display "\n")