Home‎ > ‎ProgComp‎ > ‎

Trial Task

Task 0

The first consumer calculators provided four arithmetic operators and square root, the latter using an iterative algorithm based on the Newton-Raphson method for finding roots of equations.

To determine the square root of a positive real number k, given any approximation xi > 0 calculate


to obtain a value closer to the root. 

Keep applying the formula to obtain better approximations. 

Stop when successive approximations differ by 1e–10.

Write a program that calculates the square root of a number read from input. 

The initial approximation can be 1 or k, as the algorithm converges quite quickly.

Step 1

Run your program on the following three test cases:

Test Input
2
9.8696044010893586188344909998762
1000000














# My program for the Trial ProgComp competition.

# import SQRT function to compare the calculated result with the computer result
from math import sqrt

testdata = [
2,
9.8696044010893586188344909998762,
1000000
]

#Function to calculate each iteration of the sqrt calculation

def calc(x1):
    xi2 = x1 ** 2;
    _2xi = 2 * xi

    xi1 = xi - (((xi2) - k)/(_2xi))
    print(xi1);
    return xi1;

# ===========================================================

print ("Newton Raphson Method");
# process each entry in test data list as "k" - the number to find sqrt of
for k in testdata:
    xi = float(k);
    xi1 = float(0);

    while True:
        xi1 = calc(xi);
        if (abs(xi1 - xi) < 1E-10) :
            break; # repeat until the diff is minimal
        xi = xi1

    print ('Input K = {} -> Calculated SQRT is xi1 = {}, Computer Sqrt = {}'.format(k, xi1, sqrt(k)));










Comments