Teaching Kids Programming – Recursive Algorithm to Compute the Square Root


Teaching Kids Programming: Videos on Data Structures and Algorithms

We have learned that we can use the binary search algorithm to guess the root – which then converges to the answer we are looking for. We can also use the Recursive algorithm to compute the square root.

Let’s assume the tex_e8c307ed224ab08cb7c3a90c54e5d66d Teaching Kids Programming - Recursive Algorithm to Compute the Square Root where tex_131f3471012d850e7586cd9ded6c16a6 Teaching Kids Programming - Recursive Algorithm to Compute the Square Root is the biggest square number that is less or equal to n.
Then, we can rewrite it as:
tex_28c90a717f86a2f2e5dd248e71a90e1e Teaching Kids Programming - Recursive Algorithm to Compute the Square Root
tex_824b05a595f4733eec76d35906ff19f2 Teaching Kids Programming - Recursive Algorithm to Compute the Square Root
tex_edc661ce1f82b925ffbfc931cace532b Teaching Kids Programming - Recursive Algorithm to Compute the Square Root
tex_11c07f8dfc9a41c10e1b50428ce21805 Teaching Kids Programming - Recursive Algorithm to Compute the Square Root
Recursively replacing the tex_2bfd4eef41f1e5e87e825b8ccb7f9896 Teaching Kids Programming - Recursive Algorithm to Compute the Square Root
tex_261ebc410281dc62e1b209725ded00b9 Teaching Kids Programming - Recursive Algorithm to Compute the Square Root
tex_96342b5ec8bf17f7756b8cccd58ebf77 Teaching Kids Programming - Recursive Algorithm to Compute the Square Root

Thus, we can implement as the following, converging the real root until the Error (EPS) is small enough:

def rSqrt(n, a, EPS = 1e-8):
    b = n - a * a
    x = a + b/a
    t = x
    # while error is still big
    while abs(x*x - n) > EPS:
        x = a + b/(a+t)
        # converge the answer
        t = x
    return x

Test the solution by comparing to Math.sqrt function:

print(rSqrt(150, 12)) # 12.247448713888222
print(sqrt(150))      # 12.24744871391589

This algorithm works for floating numbers as well. This is recursive algorithm however, the implementation is iterative.

–EOF (The Ultimate Computing & Technology Blog) —

629 words
Last Post: How to Sort List by Hamming Weight in C++?
Next Post: Teaching Kids Programming - Ugly Number Detection Algorithm

The Permanent URL is: Teaching Kids Programming – Recursive Algorithm to Compute the Square Root (AMP Version)

Leave a Reply