[removed] Calculate the nth root of a number

前端 未结 9 1430
长情又很酷
长情又很酷 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:19

    Use Math.pow()

    Note that it does not handle negative nicely - here is a discussion and some code that does

    http://cwestblog.com/2011/05/06/cube-root-an-beyond/

    function nthroot(x, n) {
      try {
        var negate = n % 2 == 1 && x < 0;
        if(negate)
          x = -x;
        var possible = Math.pow(x, 1 / n);
        n = Math.pow(possible, n);
        if(Math.abs(x - n) < 1 && (x > 0 == n > 0))
          return negate ? -possible : possible;
      } catch(e){}
    }
    

提交回复
热议问题