math.log(x[, base]) 是 Python 標準庫 math 模組提供的對數函數,預設計算自然對數(底數為 e),也可指定任意底數。本文詳細說明語法、參數、回傳值、多種底數用法、定義域限制與實務範例。
import math
math.log(x) # 自然對數 ln(x)
math.log(x, base) # 指定底數對數 log_base(x)
| 參數 | 說明 |
|---|---|
x | 數值運算式,必須 > 0,否則拋出 ValueError |
base (可選) | 底數,預設 math.e(自然對數),必須 > 0 且 ≠ 1 |
| 回傳 | float:對數結果 |
import math
print(math.log(1)) # 0.0
print(math.log(math.e)) # 1.0
print(math.log(100)) # 4.605170185988092 (ln 100)
print(math.log(100, 10)) # 2.0 (log10 100)
print(math.log(8, 2)) # 3.0 (log2 8)
print(math.log(0.5)) # -0.6931471805599453
math.log10(x) # 底數 10,等同 math.log(x, 10) 但更快、精度更高
math.log2(x) # 底數 2,等同 math.log(x, 2)
math.log1p(x) # 計算 ln(1 + x),針對極小 x (|x| << 1) 保持高精度
try:
math.log(0)
except ValueError as e:
print(e) # math domain error
try:
math.log(-5)
except ValueError as e:
print(e) # math domain error
-sum(p * math.log2(p) for p in probs)t_half = math.log(2) / decay_ratemath.log2(n)A = P * math.e ** (r * t) 或 t = math.log(A/P) / rdB = 20 * math.log10(amplitude_ratio)log2、log10、log(無 base 參數),避免額外除法運算。numpy.log、numpy.log2、numpy.log10,向量化速度快數十倍。math.log(100) 是底數 10 → 實為自然對數,底數 10 請用 math.log10(100) 或 math.log(100, 10)。if x > 0。math.log(1 + 1e-15) 精度損失大,改用 math.log1p(1e-15)。掌握 math.log 及其姊妹函數,能在科學計算、資料分析、演算法實作中精準高效地處理對數運算。