Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
26 changes: 26 additions & 0 deletions maths/square_root.ts
Original file line number Diff line number Diff line change
@@ -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;
}
};
28 changes: 28 additions & 0 deletions maths/test/square_root.test.ts
Original file line number Diff line number Diff line change
@@ -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));
};
}
);
});