Java普通对数(log)计算方法

Java给我提供的数学计算的工具类Math计算对数的函数有两个:

    /**
     * Returns the natural logarithm (base <i>e</i>) of a {@code double}
     * value.  Special cases:
     * <ul><li>If the argument is NaN or less than zero, then the result
     * is NaN.
     * <li>If the argument is positive infinity, then the result is
     * positive infinity.
     * <li>If the argument is positive zero or negative zero, then the
     * result is negative infinity.</ul>
     *
     * <p>The computed result must be within 1 ulp of the exact result.
     * Results must be semi-monotonic.
     *
     * @param   a   a value
     * @return  the value ln&nbsp;{@code a}, the natural logarithm of
     *          {@code a}.
     */
    public static double log(double a) {
        return StrictMath.log(a); // default impl. delegates to StrictMath
    }

    /**
     * Returns the base 10 logarithm of a {@code double} value.
     * Special cases:
     *
     * <ul><li>If the argument is NaN or less than zero, then the result
     * is NaN.
     * <li>If the argument is positive infinity, then the result is
     * positive infinity.
     * <li>If the argument is positive zero or negative zero, then the
     * result is negative infinity.
     * <li> If the argument is equal to 10<sup><i>n</i></sup> for
     * integer <i>n</i>, then the result is <i>n</i>.
     * </ul>
     *
     * <p>The computed result must be within 1 ulp of the exact result.
     * Results must be semi-monotonic.
     *
     * @param   a   a value
     * @return  the base 10 logarithm of  {@code a}.
     * @since 1.5
     */
    public static double log10(double a) {
        return StrictMath.log10(a); // default impl. delegates to StrictMath
    }

log(double a),log10(double a)从源码doc注释我们可以看到分别是计算自然对数和以10为底的对数。

如下代码:

double x = Math.log(10);

等价于:x = ln10 或 x = loge(10),即以e为底的自然对数。

问题来了,如果我们要计算非常规底数的对数怎么办呢?比如我们要计算以33为底27的对数(也就是33的多少次方运算结果为27)?

这个就需要使用数学的换底公式:logx(y)=ln(y)/ln(x);

代码实现以x为底y的对数计算工具类:

public class Logarithm {
    public static double log(double value, double base) {
        return Math.log(value) / Math.log(base);
    }
}

这样我们计算以33为底27的对数:

    public static void main(String[] args) {
        double log = log(27, 33);
        System.out.println(log);
    }

    private static double log(double value, double base) {
        return Logarithm.log(value) / Math.log(base);
    }

计算结果:0.9426082478202944

本demo使用log以及换底公式,也可以使用log10和换底公式计算,结果是一样的。

如:

public static double log(double value, double base) {
        return Math.log10(value) / Math.log10(base);
}

普通底对数计算的关键点在于使用换底公式转换为工具类提供的特殊对数进行计算即可。

微信扫码更精彩
发布了142 篇原创文章 · 获赞 258 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/conconbenben/article/details/103112593
今日推荐