diff --git a/DIRECTORY.md b/DIRECTORY.md index 3237c4e5..8934c233 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -124,6 +124,7 @@ * [Hexagonal Numbers.Test](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/series/test/hexagonal_numbers.test.ts) * [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/sieve_of_eratosthenes.ts) * [Signum](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/signum.ts) + * [Square Root](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/square_root.ts) * [Ugly Numbers](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/ugly_numbers.ts) * [Zellers Congruence](https://github.com/TheAlgorithms/TypeScript/blob/HEAD/maths/zellers_congruence.ts) diff --git a/maths/square_root.ts b/maths/square_root.ts new file mode 100644 index 00000000..04a8eda0 --- /dev/null +++ b/maths/square_root.ts @@ -0,0 +1,26 @@ +/** + * @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"); + 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) { + return sqrt; + } + sqrt = curr; + } +}; diff --git a/maths/test/square_root.test.ts b/maths/test/square_root.test.ts new file mode 100644 index 00000000..3dbd8658 --- /dev/null +++ b/maths/test/square_root.test.ts @@ -0,0 +1,28 @@ +import { squareRoot } from "../square_root"; + +describe("squareRoot", () => { + test.each([-1, -10, -2.4])( + "should throw an error for negative numbers", + (n: number) => { + expect(() => squareRoot(n)).toThrow("number must be non-negative number"); + } + ); + + test.each([0, 1, 4, 9, 16, 25])( + "should return correct rational square root value", + () => { + (n: number) => { + expect(() => squareRoot(n)).toBeCloseTo(Math.sqrt(n)); + }; + } + ); + + test.each([2, 15, 20, 40, 99, 10032])( + "should return correct irrational square root value", + () => { + (n: number) => { + expect(() => squareRoot(n)).toBeCloseTo(Math.sqrt(n)); + }; + } + ); +});