• Home
  • Contents
  • About
​​​​​​​​​​​​​​​​

Thursday 6 September 2012

Writing a Square Root function from scratch





Most of the modern programming languages we use today have built in libraries to handle mathematical functions.Every language ships with a rich math library that can easily handle most of the mathematical tasks.Finding square root is one. Calculating square roots is so prevalent,that most of us have the square roots memorized up to certain extent.System.Math.Sqrt() is the .Net's answer to this widely used function.It takes a double datatype as a single parameter and returns the square root(as double).Well before programming languages it was the handheld calculators that made this function a household among users.In all my years i have never manually calculated the square root of any number until  recently i read about a method called Newton-Raphson's method.There are few other methods like the Babylonian and indian bakshali approximation,which i suggest to have a look at.
How it works?


To find the square root of a Given Number N
   Maintain a variable called G,with a initial value of 1.//G=1;
   Maintain a variable called Q
   Maintain a variable called AVG

STEP 1: Divide N by G  (N/G) and store the result in a variable  Q
STEP 2: Calculate the Average of Q and G and store in AVG
STEP 3: Check if AVG = = G
                  If AVG != G 
                      Assign the value of AVG to G and repeat STEP 1 through 3
                  If AVG == G
                      Exit as Square root found.(Current value in AVG and G is the square root)


Complete Iteration for getting the square root of 9


G=1  ;  N=9   ;  Square root = 3


On the last row both the variable G's value and the Average(step 2) equals and that is where you get your square root.So when your value stored in G equals the Average calculated you can stop and come out.




How it works?



    using System; namespace SquareRoot { class Program { static double inputNumber; static double guess = 1; static double quotient = 0; static double avg = 0; static bool exit = false; static void Main(string[] args) { Console.WriteLine("Please enter the number:"); if (double.TryParse(Console.ReadLine(), out inputNumber)) { while (!exit) { quotient = inputNumber / guess; avg = (guess + quotient) / 2; if (avg == guess) exit = true; else guess = avg; } Console.WriteLine("The Square root of " + inputNumber + " is: " +guess); } else Console.WriteLine("Your input doesn't seem to be numeric"); Console.ReadLine(); } } }

A short implementation of the same in python.
number=float(169)
guess=float(1)
exitLoop=False

while not exitLoop:
    quot=number/guess
    avg=(guess+quot)/2
    if avg == guess:
        exitLoop=True
    else:
        guess=avg
        
print("Square root {0} is {1}.".format(number,guess))


No comments:

Post a Comment