Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heron's method JavaScript

Tags:

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;
}
like image 617
Christopher Lewis Avatar asked Aug 07 '13 16:08

Christopher Lewis


People also ask

Is it Hero's formula or Heron's formula?

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.

How do you find the area of a triangle in Javascript?

var s = (side1 + side2 + side3) / 2; var area = Math. sqrt(s * ((s - side1) * (s - side2) * (s - side3))); Example: HTML.

What is Heron's ABC formula?

Hence, area of a triangle by heron's formula is A=s(s−a)(s−b)(s−c) . Was this answer helpful?


1 Answers

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.

like image 71
Pointy Avatar answered Nov 05 '22 04:11

Pointy