Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ฟังก์ชันลอการิทึม (Log Functions) ใน Python math Module

โมดูล math ใน Python มีฟังก์ชันลอการิทึม 4 รูปแบบ ครอบคลุมฐานที่ใช้บ่อยทั้งหมด

1. math.log(x, [base])

ลอการิทึมฐานใดก็ได้ (default ฐาน e = natural log)

import math
print(math.log(15, 7))   # log₇(15) = 1.3917
print(math.log(15))      # ln(15) = 2.7081
# math.log(-15)  # ValueError: math domain error

2. math.log2(x)

ลอการิทึมฐาน 2 (ใช้ใน Computer Science บ่อย)

print(math.log2(15))   # 3.9069
# math.log2(-15)  # ValueError

3. math.log10(x)

ลอการิทึมฐาน 10 (Common logarithm)

print(math.log10(15))  # 1.1761
# math.log10(-15)  # ValueError

4. math.log1p(x)

คำนวณ ln(1 + x)แม่นยำสำหรับ x ใกล้ 0

print(math.log1p(15))  # ln(16) = 2.7726
# math.log1p(-15)  # ValueError (1+x ≤ 0)

สรุปการใช้งาน

ฟังก์ชันฐานใช้เมื่อไหร่
math.log(x, base)ใดก็ได้ทั่วไป, ฐาน e (default)
math.log2(x)2CS, Information Theory
math.log10(x)10วิทยาศาสตร์, Engineering
math.log1p(x)ex ใกล้ 0 (Preserve precision)

ข้อจำกัด: ทุกฟังก์ชัน error ถ้า argument ≤ 0 (ยกเว้น log1p ต้อง > -1)