Calculating nth root in Java using power method

后端 未结 9 2683
礼貌的吻别
礼貌的吻别 2021-02-18 22:08

I was trying to get a cubic root in java using Math.pow(n, 1.0/3) but because it divides doubles, it doesn\'t return the exact answer. For example, with 125, this g

9条回答
  •  后悔当初
    2021-02-18 22:20

    Here is the solution without using Java's Math.pow function. It will give you nearly nth root

    public class NthRoot {
    
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            int testcases = scanner.nextInt();
            while (testcases-- > 0) {
                int root = scanner.nextInt();
                int number = scanner.nextInt();
                double rootValue = compute(number, root) * 1000.0 / 1000.0;
                System.out.println((int) rootValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static double compute(int number, int root) {
        double xPre = Math.random() % 10;
        double error = 0.0000001;
        double delX = 2147483647;
        double current = 0.0;
    
        while (delX > error) {
            current = ((root - 1.0) * xPre + (double) number / Math.pow(xPre, root - 1)) / (double) root;
            delX = Math.abs(current - xPre);
            xPre = current;
        }
        return current;
    }
    

提交回复
热议问题