Skip to content

Commit 80ed495

Browse files
authored
Merge pull request #600 from raklaptudirm/master
Added `sqrt()` function. Changes Approved by @marsonya
2 parents 712d428 + 054622c commit 80ed495

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

Maths/SquareRoot.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/*
2+
* Author: Rak Laptudirm
3+
*
4+
* https://en.wikipedia.org/wiki/Newton%27s_method
5+
*
6+
* Finding the square root of a number using Newton's method.
7+
*/
8+
9+
function sqrt (num, precision = 10) {
10+
if (!Number.isFinite(num)) { throw new TypeError(`Expected a number, received ${typeof num}`) }
11+
if (!Number.isFinite(precision)) { throw new TypeError(`Expected a number, received ${typeof precision}`) }
12+
let sqrt = 1
13+
for (let i = 0; i < precision; i++) {
14+
sqrt -= (sqrt * sqrt - num) / (2 * sqrt)
15+
}
16+
return sqrt
17+
}
18+
19+
export { sqrt }

0 commit comments

Comments
 (0)