2021-05-06 10:46:27 +05:30
|
|
|
/*
|
|
|
|
|
* Author: Rak Laptudirm
|
|
|
|
|
*
|
|
|
|
|
* https://en.wikipedia.org/wiki/Newton%27s_method
|
|
|
|
|
*
|
|
|
|
|
* Finding the square root of a number using Newton's method.
|
|
|
|
|
*/
|
|
|
|
|
|
2021-05-30 17:04:24 +05:30
|
|
|
function sqrt (num, precision = 4) {
|
2021-05-13 13:18:51 +05:30
|
|
|
if (!Number.isFinite(num)) { throw new TypeError(`Expected a number, received ${typeof num}`) }
|
|
|
|
|
if (!Number.isFinite(precision)) { throw new TypeError(`Expected a number, received ${typeof precision}`) }
|
2021-05-13 12:46:01 +05:30
|
|
|
let sqrt = 1
|
|
|
|
|
for (let i = 0; i < precision; i++) {
|
|
|
|
|
sqrt -= (sqrt * sqrt - num) / (2 * sqrt)
|
|
|
|
|
}
|
|
|
|
|
return sqrt
|
2021-05-06 10:46:27 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export { sqrt }
|