Deriving Square Roots

Five Square

Five Square

Square Root

The Square of a number, X2, is any number multiplied by its self. 2= 4, 42 = 16, 6= 36 etc. The square root of a number is the derived by reducing a number so that the √36 = 6, √16 = 4, √4 = 2. Deriving the square root of a number is often considered a computationally expensive operation, with most programming languages offering function for finding the square root of a number as part of its standard library.

C has sqrt() and sqrtf() in math.h and thus C++ in <cmath>. Perl, Swift, and Java all have their own square root functions. But what makes this such an expensive operation? Lets take a closer look at how we calculate square root.

Implementing a Square Root function

A popular algorithm for deriving roots is called “Newton’s method”, named for fame mathematician and astronomer Sir Isaac Newton. It lends itsself nicely to a very simple iterative implementation. We use the double data type, as most numbers are not perfect squares.

If we want to test if a number is a perfect square, we use the following equation:

f(x) = n / √n, 
if x == √n then x is a perfect square.

So if we wanted to find all the perfect squares from 1 to 100:

When compiled and ran:

[maxs-MacBook-Pro:~/]% ./squareroot 
Square root of 1 is 1.000000
Square root of 4 is 2.000000
Square root of 9 is 3.000000
Square root of 16 is 4.000000
Square root of 25 is 5.000000
Square root of 36 is 6.000000
Square root of 49 is 7.000000
Square root of 64 is 8.000000
Square root of 81 is 9.000000
Square root of 100 is 10.000000

 

Leave a Reply

Your email address will not be published. Required fields are marked *