2

I am attempting to write a function which provides results similar to the JavaScript built-in math.sqrt function. I am using the trial and error method where the function guesses, and then subsequently refines the guess for the square root of the number the user enters into the program, until the correct value is successfully reached.

Currently a recursive function with an if.. else statement is used to perform the calculations, and adjust the guess until it reaches the user defined target number when squared.

The function provides the correct answer for 11, 22, 33, 44, 55, any number where the square root is not a decimal, among others. However it returns an error - too much recursion with other numbers such as 13, although the program gets very close to solving the problem - usually just .00000000000000x above or below the target number.

This function has gone through multiple iterations where I finally settled on using two arrays to store previous guesses, sorted into one or the other depending on whether they were too large or too small, and storing the latest guess from each array in a variable which can be used in calculating the next guess.

Previous iterations were reaching the error of too much recursion much earlier, and were only returning correct results for numbers where the correct answer was arrived at within the first run through of the function, otherwise my browser would crash.

// HTML

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Function library example</title>
  <style>
    input {
      font-size: 2em;
      margin: 10px 1px 0;
    }
  </style>
</head>
<body>

  <input class="numberInput" type="text">
  <p></p>

// JavaScript

  <script>
      var input = document.querySelector('.numberInput');
      var para = document.querySelector('p');

  function findSquareRoot(num){
    function find(guess, square, lastSmallGuess, lastLargeGuess){
      var smallerArray = [];
      var greaterArray = [];

      if(square == num){
        return guess;
      } else if(square > num){
          greaterArray.push(guess);
          console.log('Last Small Guess : ' + lastSmallGuess); // shows guess in developer tools
          console.log(' Last Large Guess : ' + lastLargeGuess); // shows guess in developer tools
          console.log((((guess * 1) + (lastSmallGuess * 1)) / 2), (((guess * 1) + (lastSmallGuess * 1)) / 2) * (((guess * 1) + (lastSmallGuess * 1)) / 2), lastSmallGuess, greaterArray[greaterArray.length-1]); // shows calculation process in dev tools
          return find((((guess * 1) + (lastSmallGuess * 1)) / 2), (((guess * 1) + (lastSmallGuess * 1)) / 2) * (((guess * 1) + (lastSmallGuess * 1)) / 2), lastSmallGuess, greaterArray[greaterArray.length-1]);
      } else if(square < num){
          smallerArray.push(guess);
          console.log('Last Small Guess : ' + lastSmallGuess);  // shows guess in developer tools
          console.log(' Last Large Guess : ' + lastLargeGuess); // shows guess in developer tools
          console.log((((guess * 1) + (lastLargeGuess * 1)) / 2), (((guess * 1) + (lastLargeGuess * 1)) / 2) * (((guess * 1) + (lastLargeGuess * 1)) / 2), smallerArray[smallerArray.length-1], lastLargeGuess); // shows calculation process in dev tools
          return find((((guess * 1) + (lastLargeGuess * 1)) / 2), (((guess * 1) + (lastLargeGuess * 1)) / 2) * (((guess * 1) + (lastLargeGuess * 1)) / 2), smallerArray[smallerArray.length-1], lastLargeGuess);
    } 
  }
  return find((num * 1) / 2, ((num * 1) / 2) * ((num * 1) / 2), 0, 0);
}

  input.onchange = function() {
    var num = input.value;
    if(isNaN(num)) {
      para.textContent = 'You need to enter a number!';
    } else {
      para.textContent = num + ' square root is ' + findSquareRoot(num) + '. ' +
                       num + ' square root is ' + Math.sqrt(num) + '.';
    }
  }
  </script>
</body>
</html>

I expect my function to consistently deliver the same answer as the built in math.sqrt function. Although even when the function causes the browser to crash and therefore does not return the result, it has arrived at an answer very close to the correct one, as shown in the console section of the developer tools. With other numbers it returns precisely the same result as math.sqrt

Thank you for taking the time to read my question.

  • 1
    You are getting an error because you are not restricting the answer to a specif number of decimal places. Numbers like 13 or 2 could have 100's or even an infinite number of decimal points and will overflow the stack causing the " too much recursion" error – GifCo May 27 '19 at 18:44
  • Thank you for your comment, much appreciated. I will look into making this change and get back to you with updated code and results. – HenryKissingerIsAWarCriminal May 28 '19 at 10:23

0 Answers0