nth root implementation

后端 未结 8 1841
说谎
说谎 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;
    }
    

提交回复
热议问题