Calculate Square Root

From Software Engineers Wiki
Jump to: navigation, search

Calculate square root of a number.


Using Newton's square root approximation, we can repeat the A = (N/A + A) / 2 until we see a value that is very close to the square root value. I picked the initialize value of A as N/2.

def my_sqrt(num):
        '''sqrt(N) `==` (N/A + A)/2'''
        sqrt = num / 2
        err_limit = 0.000000001
        while True:
                new_sqrt = (num / sqrt + sqrt) / 2
                if abs(new_sqrt - sqrt) < err_limit:
                        return new_sqrt
                sqrt = new_sqrt

Test program:

import math

def main():
        while True:
                number = float(raw_input("Enter a number: "))
                if number == 0:
                print("Using math library: sqrt({}) is {}".format(number, math.sqrt(number)))
                print("Using own impelementation: sqrt({}) is {}".format(number, my_sqrt(number)))


Test result:

Enter a number: 2
Using math library: sqrt(2.0) is 1.41421356237
Using own impelementation: sqrt(2.0) is 1.41421356237
Enter a number: 3
Using math library: sqrt(3.0) is 1.73205080757
Using own impelementation: sqrt(3.0) is 1.73205080757
Enter a number: 5
Using math library: sqrt(5.0) is 2.2360679775
Using own impelementation: sqrt(5.0) is 2.2360679775
Enter a number: 7
Using math library: sqrt(7.0) is 2.64575131106
Using own impelementation: sqrt(7.0) is 2.64575131106
Enter a number: 8
Using math library: sqrt(8.0) is 2.82842712475
Using own impelementation: sqrt(8.0) is 2.82842712475
Enter a number: 0


Personal tools