mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-18 17:49:40 +08:00
22 lines
523 B
JavaScript
22 lines
523 B
JavaScript
/*
|
|
* 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 }
|