Java Math.log() 與 Math.exp()
Math.log() 計算自然對數,Math.exp() 計算指數(e 的次方)。
Math.exp() 指數
// e 的次方
System.out.println(Math.exp(0)); // 1.0(e⁰ = 1)
System.out.println(Math.exp(1)); // 2.7182...(e¹ = e)
System.out.println(Math.exp(2)); // 7.389...(e²)
// 自然常數 e
System.out.println(Math.E); // 2.718281828459045
Math.log() 自然對數
// 自然對數(以 e 為底)
System.out.println(Math.log(1)); // 0.0(ln(1) = 0)
System.out.println(Math.log(Math.E)); // 1.0(ln(e) = 1)
System.out.println(Math.log(10)); // 2.302...
// 特殊情況
System.out.println(Math.log(0)); // -Infinity
System.out.println(Math.log(-1)); // NaN
Math.log10() 常用對數
// 以 10 為底的對數
System.out.println(Math.log10(1)); // 0.0
System.out.println(Math.log10(10)); // 1.0
System.out.println(Math.log10(100)); // 2.0
System.out.println(Math.log10(1000)); // 3.0
Math.log1p() 與 Math.expm1()
// log1p(x) = log(1 + x),對小數更精確
System.out.println(Math.log1p(0.0001)); // 更精確
// expm1(x) = exp(x) - 1,對小數更精確
System.out.println(Math.expm1(0.0001)); // 更精確
計算任意底數的對數
// 換底公式:logₐ(b) = ln(b) / ln(a)
public static double logBase(double base, double value) {
return Math.log(value) / Math.log(base);
}
System.out.println(logBase(2, 8)); // 3.0(log₂(8) = 3)
System.out.println(logBase(2, 16)); // 4.0(log₂(16) = 4)
System.out.println(logBase(10, 100)); // 2.0(log₁₀(100) = 2)
實用範例
計算位數
public static int digitCount(int n) {
if (n == 0) return 1;
return (int) Math.floor(Math.log10(Math.abs(n))) + 1;
}
System.out.println(digitCount(12345)); // 5
System.out.println(digitCount(100)); // 3
複利計算(要幾年翻倍)
public static double yearsToDouble(double annualRate) {
// 使用自然對數:t = ln(2) / ln(1 + r)
return Math.log(2) / Math.log(1 + annualRate);
}
System.out.printf("年利率 7%% 需要 %.1f 年翻倍%n", yearsToDouble(0.07)); // 10.2 年
// 72 法則驗證
System.out.println(72.0 / 7); // 10.3(近似值)
pH 值計算
// pH = -log₁₀[H⁺]
public static double calculatePH(double hydrogenConcentration) {
return -Math.log10(hydrogenConcentration);
}
System.out.println(calculatePH(0.0000001)); // 7.0(中性)
System.out.println(calculatePH(0.001)); // 3.0(酸性)
資訊熵計算
// 二進制熵
public static double binaryEntropy(double p) {
if (p <= 0 || p >= 1) return 0;
return -(p * Math.log(p) + (1 - p) * Math.log(1 - p)) / Math.log(2);
}
System.out.println(binaryEntropy(0.5)); // 1.0(最大熵)
System.out.println(binaryEntropy(0.1)); // 0.469...
重點整理
Math.exp(x)計算 eˣMath.log(x)計算自然對數 ln(x)Math.log10(x)計算常用對數 log₁₀(x)- 任意底數對數使用換底公式
Math.E提供自然常數 elog1p()和expm1()對小數計算更精確