forked from TheAlgorithms/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsquare_root.ts
27 lines (24 loc) · 838 Bytes
/
square_root.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* @function SquareRoot
* @description Finding the square root of a number using Newton's method.
* @param {number} num - A number.
* @param {number} precision - Precision of square root, 1e-15 by default.
* @returns {number} - Square root of the given number.
* @see https://www.geeksforgeeks.org/find-root-of-a-number-using-newtons-method/
* @example SquareRoot(36) = 6
* @example SquareRoot(50) = 7.0710678118654755
*/
export const SquareRoot = (num: number, precision: number = 1e-15): number => {
if (num < 0) throw new Error("number must be non-negative number > 0");
if (num === 0) return 0;
let sqrt: number = num;
let curr: number;
while (true) {
curr = 0.5 * (sqrt + num / sqrt);
if (Math.abs(curr - sqrt) < precision) {
console.log(sqrt);
return sqrt;
}
sqrt = curr;
}
};