Heron's method JavaScript
The following code is supposed to return the square root using Heron's
method. I am trying to find a "bug" in it, but to be honest, I haven't
been able to spot it. I have a question about the "var prevGuess = n"
statement. How does "n" work the first time? Is that the bug, and what's
the "fix?"
Thanks, I am a bit confused at the moment......
function heronSqrt(n)
{
var DELTA = 1.0E-10;
var nextGuess;
var prevGuess = n;
do
{
nextGuess = (prevGuess + (n/prevGuess))/2;
prevGuess = nextGuess;
} while (nextGuess-prevGuess > DELTA)
return nextGuess;
}
No comments:
Post a Comment