Skip to content

Commit 194e26f

Browse files
authored
Merge pull request #71 from pugulist/codex/improve-newton_raphson-method
Improve Newton-Raphson implementation
2 parents 0364011 + cb54867 commit 194e26f

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

math_modules/newton_raphson.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,23 @@ let nthRoot = (n, a) => {
99
else if (n === 3)
1010
return Math.cbrt(a).toPrecision(6);
1111

12-
let preResult = Math.random() % 10; // Initial guess
12+
// Use a deterministic initial guess instead of a random one for
13+
// improved stability. `a / n` generally brings us closer to the
14+
// final answer than an arbitrary random value.
15+
let preResult = a / n;
16+
1317
let eps = Math.pow(10, -6); // Lesser the eps value, more the accuracy
1418

1519
let delX = Number.MAX_SAFE_INTEGER;
1620
let result;
17-
18-
while (delX > eps) {
21+
let iterations = 0;
22+
// Limit the number of iterations to avoid potential infinite loops
23+
// when provided with invalid input.
24+
while (delX > eps && iterations < 1000) {
1925
result = ((n - 1.0) * preResult + a/Math.pow(preResult, n-1)) / n;
2026
delX = Math.abs(result - preResult);
2127
preResult = result;
28+
iterations += 1;
2229
}
2330

2431
return result.toPrecision(6);

0 commit comments

Comments
 (0)