Purchase Solution

Heron method to locate sqaure root of a number

Not what you're looking for?

Ask Custom Question

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.

Purchase this Solution

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.

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 ...

Purchase this Solution


Free BrainMass Quizzes
Basic Networking Questions

This quiz consists of some basic networking questions.

Basic UNIX commands

Use this quiz to check your knowledge of a few common UNIX commands. The quiz covers some of the most essential UNIX commands and their basic usage. If you can pass this quiz then you are clearly on your way to becoming an effective UNIX command line user.

Excel Introductory Quiz

This quiz tests your knowledge of basics of MS-Excel.

Java loops

This quiz checks your knowledge of for and while loops in Java. For and while loops are essential building blocks for all Java programs. Having a solid understanding of these constructs is critical for success in programming Java.

Word 2010: Table of Contents

Ever wondered where a Table of Contents in a Word document comes from? Maybe you need a refresher on the topic? This quiz will remind you of the keywords and options used when working with a T.O.C. in Word 2010.