Skip to content

Instantly share code, notes, and snippets.

@trevor-atlas
Forked from joelpt/squirt.js
Last active October 2, 2017 18:55
Show Gist options
  • Save trevor-atlas/44b1f4d767cd21be43afc9d78edb4f86 to your computer and use it in GitHub Desktop.
Save trevor-atlas/44b1f4d767cd21be43afc9d78edb4f86 to your computer and use it in GitHub Desktop.
Manually calculate the square root of a number with Javascript
// The Babylonian Method
// http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
// @param n - the number to compute the square root of
// @param guess - the best guess so far (can omit from initial call)
function squirt(n, guess) {
if (!guess) {
guess = n / 2.0; // Take an initial guess at the square root
}
const divided = n / guess; // Divide our guess into the number
const newGuess = (divided + guess) / 2.0; // Use average of guess and divided as our new guess
if (guess == newGuess) {
// The new guess is the same as the old guess; further guesses can get no more accurate so we return this guess
return guess;
}
return squirt(n, newGuess); // Recursively solve for closer and closer approximations of the square root
}
console.log(squirt(42)); // 6.48074069840786
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment