Skip to content

Instantly share code, notes, and snippets.

@nitely
Last active May 2, 2023 18:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nitely/4cc812cda9e2047872607e2342f69aef to your computer and use it in GitHub Desktop.
Save nitely/4cc812cda9e2047872607e2342f69aef to your computer and use it in GitHub Desktop.
Square root (sqrt) in JavaScript using a binary search
/*
sqrt(8)
(0 + 8) / 2 = 4
4 * 4 = 16
(0 + 4) / 2 = 2
2 * 2 = 4
(2 + 4) / 2 = 3
3 * 3 = 9
(2 + 3) / 2 = 2.5
2.5 * 2.5 = 6.25
...
*/
function _sqrt(number, low_bound, high_bound) {
let guess = (low_bound + high_bound) / 2;
let aproximation = guess * guess;
if (Math.abs(number - aproximation) < 0.01)
return guess;
if (aproximation > number)
high_bound = guess;
else
low_bound = guess;
return _sqrt(number, low_bound, high_bound);
}
function sqrt(number) {
if (number < 0)
return -1;
return _sqrt(number, 0, number);
}
console.log(sqrt(8));
// 2.828125
@imranhossainemi
Copy link

if (Math.abs(number - aproximation) < 0.01) - this will not give you accurate result
use tolerance = 1e-8 or tolerance = 1e-14 for accurate result
if (Math.abs(number - aproximation) < tolerance)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment