[removed] Calculate the nth root of a number

前端 未结 9 1432
长情又很酷
长情又很酷 2020-12-04 20:26

I\'m trying to get the nth root of a number using JavaScript, but I don\'t see a way to do it using the built in Math object. Am I overlooking something?
If

相关标签:
9条回答
  • 2020-12-04 21:25

    The n-th root of x is a number r such that r to the power of 1/n is x.

    In real numbers, there are some subcases:

    • There are two solutions (same value with opposite sign) when x is positive and r is even.
    • There is one positive solution when x is positive and r is odd.
    • There is one negative solution when x is negative and r is odd.
    • There is no solution when x is negative and r is even.

    Since Math.pow doesn't like a negative base with a non-integer exponent, you can use

    function nthRoot(x, n) {
      if(x < 0 && n%2 != 1) return NaN; // Not well defined
      return (x < 0 ? -1 : 1) * Math.pow(Math.abs(x), 1/n);
    }
    

    Examples:

    nthRoot(+4, 2); // 2 (the positive is chosen, but -2 is a solution too)
    nthRoot(+8, 3); // 2 (this is the only solution)
    nthRoot(-8, 3); // -2 (this is the only solution)
    nthRoot(-4, 2); // NaN (there is no solution)
    
    0 讨论(0)
  • 2020-12-04 21:26

    Can you use something like this?

    Math.pow(n, 1/root);
    

    eg.

    Math.pow(25, 1/2) == 5
    
    0 讨论(0)
  • 2020-12-04 21:32

    I have written an algorithm but it is slow when you need many numbers after the point:

    https://github.com/am-trouzine/Arithmetic-algorithms-in-different-numeral-systems

    NRoot(orginal, nthRoot, base, numbersAfterPoint);
    

    The function returns a string.

    E.g.

    var original = 1000;
    var fourthRoot = NRoot(original, 4, 10, 32);
    console.log(fourthRoot); 
    //5.62341325190349080394951039776481
    
    0 讨论(0)
提交回复
热议问题