Heron's JavaScript Method

The following code should return the square root using the Heron method. I try to find a bug in it, but honestly, I could not find it. I have a question about the instruction var prevGuess = n. How does "n" work for the first time? This is a mistake, and what is a "fix?"

Thanks, I'm a little 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; } 
+6
source share
1 answer

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.

+3
source

Source: https://habr.com/ru/post/951232/


All Articles