File tree Expand file tree Collapse file tree 1 file changed +10
-3
lines changed
Expand file tree Collapse file tree 1 file changed +10
-3
lines changed Original file line number Diff line number Diff 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 ) ;
You can’t perform that action at this time.
0 commit comments