Skip to content
Merged
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
38 changes: 33 additions & 5 deletions math_modules/newton_raphson.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,39 @@

/*global module:true*/

// Calculating nth root of 'a'
// Calculate the nth root of `a` using the Newton–Raphson method.
//
// The function returns a string representing the result rounded to six
// significant digits to preserve the behaviour expected by callers of the
// previous implementation.
let nthRoot = (n, a) => {
if (n === 2)
// Basic validation – n must be a positive integer.
if (!Number.isInteger(n) || n <= 0) {
return NaN;
}

// Special cases for zero and common roots.
if (a === 0) {
return '0';
}
if (n === 2) {
return Math.sqrt(a).toPrecision(6);
else if (n === 3)
} else if (n === 3) {
return Math.cbrt(a).toPrecision(6);
}

// Even roots of negative numbers do not have a real solution.
if (a < 0 && n % 2 === 0) {
return NaN;
}

// Keep track of the sign so that odd roots of negative numbers are handled
// correctly while the iterative algorithm works on a positive value.
let sign = 1;
if (a < 0) {
sign = -1;
a = Math.abs(a);
}

// Use a deterministic initial guess instead of a random one for
// improved stability. `a / n` generally brings us closer to the
Expand All @@ -22,13 +49,14 @@ let nthRoot = (n, a) => {
// Limit the number of iterations to avoid potential infinite loops
// when provided with invalid input.
while (delX > eps && iterations < 1000) {
result = ((n - 1.0) * preResult + a/Math.pow(preResult, n-1)) / n;
result = ((n - 1) * preResult + a / Math.pow(preResult, n - 1)) / n;
delX = Math.abs(result - preResult);
preResult = result;
iterations += 1;
}

return result.toPrecision(6);
result *= sign;
return Number(result.toPrecision(6)).toString();
Copy link

Copilot AI Jun 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Consider simplifying the conversion chain by either directly returning result.toPrecision(6) for consistency with the earlier branches or clearly documenting the need for converting to a Number then back to a String.

Suggested change
return Number(result.toPrecision(6)).toString();
return result.toPrecision(6);

Copilot uses AI. Check for mistakes.
};

module.exports = {
Expand Down