Share
Explore BrainMass

# Heron method to locate sqaure root of a number

The Heron Method for approximating the square root of a number states that if x is a guess for the square root of n then a better guess x' is:

x' = [x + (n/x)] / 2

Naturally this process can be repeated using x' in place of x the next time through the loop. The loop can stop when the difference between the previous and next guesses is small enough.

A programmer wrote the following code to implement the Heron Method to locate the square root of any number:

function heronSqrt(n)
{
var DELTA = 1.0E-10;
var nextGuess;
var prevGuess = n;
do
{
nextGuess = (prevGuess + (n/prevGuess))/2.0;
prevGuess = nextGuess;
} while (nextGuess-prevGuess > DELTA)
return nextGuess;
}

However, the code does not work properly. Fix the program so that it works. Also list a set of test cases that will thoroughly exercise the Heron Method code above.

#### Solution Preview

Correct function should be as follows.

function heronSqrt(n)
{
var DELTA = 1.0E-10;
var nextGuess = n;
var prevGuess;
do
{
prevGuess = nextGuess;
nextGuess = (prevGuess + (n/prevGuess))/2.0;
} while (nextGuess-prevGuess > DELTA)
return nextGuess;
}

If assignment order in do-while loop is other way round (as in your original function definition), it always sets prevGuess and nextGuess to same value at the end ...

#### Solution Summary

Solution not only gives the fixed code but it also explains why the given buggy code will not work as desired. It also provides the guidance regarding how the test space can be divided into various categories to generate test cases for the given function. It is more of a guidance than ready-to-consume solution.

\$2.19