nth root implementation

后端 未结 8 1786
说谎
说谎 2020-12-30 01:16

I am working on a way to calculate the nth root of a number. However, I am having problems with the nth root of negative numbers.

Most people s

相关标签:
8条回答
  • 2020-12-30 02:07

    I use the method below. Maybe it's not the most accurate, but it works well in my case.

    public double root(double num, double root) {
        double d = Math.pow(num, 1.0 / root);
        long rounded = Math.round(d);
        return Math.abs(rounded - d) < 0.00000000000001 ? rounded : d;
    }
    
    0 讨论(0)
  • 2020-12-30 02:07
        public double root(double num, double root) {
            double y=1;
            double x;
            while(Math.pow(x, root) != num) {
                if(Math.pow(x, root) > num) {
                    x=x-y;
                    y=y/10;
                } else {
                    x=x+y;
                }
            }
            return x;
        }   
    

    This should work fine for you, although it isn't compact it uses as little math functions as possible.

    0 讨论(0)
提交回复
热议问题