Skip to content
scipython.com

P2.5.4Hero's method for computing a square root

Hero's method for calculating the square root of a number, \(S\), is as follows: starting with an initial guess, \(x_0\), the sequence of numbers \(x_{n+1} = \frac{1}{2}(x_n + S/x_n)\) are successively better approximations to \(\sqrt{S}\). Implement this algorithm to estimate the square root of 2117519.73 to two decimal places and compare with the "exact" answer provided by the math.sqrt method. For the purpose of this exercise, start with an initial guess, \(x_0 = 2000\).

Show solution

Here's one solution:

TOL = 0.01
S = 2117519.73
x_old = 2000
while True:
    x_new = (x_old + S / x_old) / 2
    if abs(x_new - x_old) < TOL:
        break
    x_old = x_new

print("sqrt({}) by Hero's method: {:.2f}".format(S, x_new))

import math
print('Compare with the "exact" answer:', math.sqrt(S))

The output is:

sqrt(2117519.73) by Hero's method: 1455.17
Compare with the "exact" answer: 1455.1700003779627