在Java中如果要开对数,利用API中Math类自带方法有可能满足不了需求,仅能够求以e与以10的对数,如下图所示:
如果我们要求任意底的对数,需要利用到换底公式:
如下,封装一个方法,之后就能够求任意底的对数了:
public class LagarithmTest {
public static double logx(double bottom, double antilogarithm) {
if (bottom <= 0 || bottom == 1) {
System.exit(-1);
}
return Math.log(antilogarithm) / Math.log(bottom);
}
public static void main(String[] args) {
System.out.println(logx(2, 8));
}
}
运行结果如下图所示: