Merge pull request #600 from raklaptudirm/master

Added `sqrt()` function. Changes Approved by @marsonya
This commit is contained in:
Rak Laptudirm
2021-05-21 10:26:33 +05:30
committed by GitHub

19
Maths/SquareRoot.js Normal file
View File

@ -0,0 +1,19 @@
/*
* Author: Rak Laptudirm
*
* https://en.wikipedia.org/wiki/Newton%27s_method
*
* Finding the square root of a number using Newton's method.
*/
function sqrt (num, precision = 10) {
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}`) }
let sqrt = 1
for (let i = 0; i < precision; i++) {
sqrt -= (sqrt * sqrt - num) / (2 * sqrt)
}
return sqrt
}
export { sqrt }