Calculating nth root in Java using power method

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

    The Math.round function will round to the nearest long value that can be stored to a double. You could compare the 2 results to see if the number has an integer cubic root.

    double dres = Math.pow(125, 1.0 / 3.0);
    double ires = Math.round(dres);
    double diff = Math.abs(dres - ires);
    if (diff < Math.ulp(10.0)) {
        // has cubic root
    }
    

    If that's inadequate you can try implementing this algorithm and stop early if the result doesn't seem to be an integer.

提交回复
热议问题