Calculating nth root in Java using power method

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

    It's a pretty ugly hack, but you could reach a few of them through indenting.

    System.out.println(Math.sqrt(Math.sqrt(256)));
        System.out.println(Math.pow(4, 4));
        System.out.println(Math.pow(4, 9));
        System.out.println(Math.cbrt(Math.cbrt(262144)));
    Result:
    4.0
    256.0
    262144.0 
    4.0
    

    Which will give you every n^3th cube and every n^2th root.

提交回复
热议问题