Last active
May 2, 2023 18:37
-
-
Save nitely/4cc812cda9e2047872607e2342f69aef to your computer and use it in GitHub Desktop.
Square root (sqrt) in JavaScript using a binary search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)