Calculating nth root in Java using power method

后端 未结 9 2675
礼貌的吻别
礼貌的吻别 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:28

    Find nth root Using binary search method. Here is the way to find nth root with any precision according to your requirements.

    import java.util.Scanner;
    
    public class FindRoot {
    
        public static void main(String[] args) {
            try (Scanner scanner = new Scanner(System.in)) {
                int testCase = scanner.nextInt();
                while (testCase-- > 0) {
                    double number = scanner.nextDouble();
                    int root = scanner.nextInt();
                    double precision = scanner.nextDouble();
                    double result = findRoot(number, root, precision);
                    System.out.println(result);
                }
            }
        }
    
        private static double findRoot(double number, int root, double precision) {
            double start = 0;
            double end = number / 2;
            double mid = end;
            while (true) {
                if (precision >= diff(number, mid, root)) {
                    return mid;
                }
                if (pow(mid, root) > number) {
                    end = mid;
                } else {
                    start = mid;
                }
                mid = (start + end) / 2;
            }
        }
    
        private static double diff(double number, double mid, int n) {
            double power = pow(mid, n);
            return number > power ? number - power : power - number;
        }
    
        private static double pow(double number, int pow) {
            double result = number;
            while (pow-- > 1) {
                result *= number;
            }
            return result;
        }
    }
    

提交回复
热议问题