Here is the 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 update "prevGuess" before performing a limit check. Secondly, you need to check the absolute value of the difference between guesses. I changed the initialization so that it "nextGuess", initialized by the input value, transferred the update to "prevGuess" in the first line of the loop, and I added a call to Math.abs() .
To make this work for a wider range of values, I think you need the "DELTA" value to be proportional to the "n" value. If you try this with huge numbers, it probably doesn't converge.
source share