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;
}
Heron's formula is used to find the area of a triangle when we know the length of all its sides. It is also termed as Hero's Formula.
var s = (side1 + side2 + side3) / 2; var area = Math. sqrt(s * ((s - side1) * (s - side2) * (s - side3))); Example: HTML.
Hence, area of a triangle by heron's formula is A=s(s−a)(s−b)(s−c) . Was this answer helpful?
Here is a working version:
function heronSqrt(n)
{
var DELTA = 1.0E-10;
var nextGuess = n;
var prevGuess;
do
{
prevGuess = nextGuess;
nextGuess = (prevGuess + (n/prevGuess))/2;
} while (Math.abs(nextGuess-prevGuess) > DELTA)
return nextGuess;
}
There were two problems. First, you were updating "prevGuess" before doing the limit check. Second, you need to check the absolute value of the difference between the guesses. I altered the initialization so that it's "nextGuess" that's initialized to the input value, moved the update to "prevGuess" to the first line of the loop, and I added the call to Math.abs()
.
To make this work for a greater range of values, I think you need to have the value of "DELTA" be proportional to the magnitude of "n". If you try this with huge numbers, it probably won't converge.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With