Python การใช้งานโมดูล math

โมดูล math ใน Python เป็นโมดูลที่มีฟังก์ชันทางคณิตศาสตร์มากมายที่สามารถใช้ได้ในการประมวลผลตัวเลขเชิงคณิตศาสตร์ ซึ่งรองรับการคำนวณที่ซับซ้อน เช่น ฟังก์ชันตรีโกณมิติ ฟังก์ชันลอการิทึม และการคำนวณค่าคงที่ทางคณิตศาสตร์ เช่น ค่าพาย (π)

การใช้งานทั่วไปของ math โมดูล

ก่อนที่จะใช้งานฟังก์ชันต่าง ๆ ใน math โมดูล เราต้องนำเข้ามาก่อนด้วยคำสั่ง

Python
import math

ฟังก์ชันพื้นฐาน

  • math.ceil(x): ปัดเศษขึ้นค่าของ x ให้เป็นจำนวนเต็มที่ใกล้เคียงที่สุด
  • math.floor(x): ปัดเศษลงค่าของ x ให้เป็นจำนวนเต็มที่ใกล้เคียงที่สุด
  • math.factorial(x): คำนวณค่า factorial ของ x (เช่น 5! = 5 * 4 * 3 * 2 * 1 = 120)
  • math.sqrt(x): หาค่ารากที่สองของ x

ตัวอย่าง

Python
import math

x = 4.7
print(math.ceil(x))   # Output: 5
print(math.floor(x))  # Output: 4
print(math.factorial(5))  # Output: 120
print(math.sqrt(16))  # Output: 4.0

ฟังก์ชันตรีโกณมิติ

math โมดูลรองรับการคำนวณทางตรีโกณมิติหลายอย่าง

  • math.sin(x): หาค่า sine ของ x โดยที่ x มีหน่วยเป็นเรเดียน
  • math.cos(x): หาค่า cosine ของ x
  • math.tan(x): หาค่า tangent ของ x
  • math.radians(x): แปลงค่ามุมจากองศาเป็นเรเดียน
  • math.degrees(x): แปลงค่ามุมจากเรเดียนเป็นองศา

ตัวอย่าง

Python
import math

angle_deg = 45
angle_rad = math.radians(angle_deg)

print(math.sin(angle_rad))  # Output: 0.7071067811865475
print(math.cos(angle_rad))  # Output: 0.7071067811865476
print(math.tan(angle_rad))  # Output: 1.0

ลอการิทึมและเลขยกกำลัง

  • math.log(x, base): หาค่าลอการิทึมของ x ในฐาน base (ถ้าไม่ระบุ base จะใช้ฐาน e)
  • math.exp(x): หาค่าของ e^x (ค่าของเลขฐาน e ยกกำลัง x)
  • math.pow(x, y): หาค่า x ยกกำลัง y

ตัวอย่าง

Python
import math

print(math.log(10))      # Output: 2.302585092994046 (ฐาน e)
print(math.log(100, 10)) # Output: 2.0 (ฐาน 10)
print(math.exp(2))       # Output: 7.38905609893065
print(math.pow(2, 3))    # Output: 8.0

ค่าคงที่ทางคณิตศาสตร์

  • math.pi: ค่าของพาย (π) ≈ 3.14159
  • math.e: ค่าของ e (ฐานของลอการิทึมธรรมชาติ) ≈ 2.71828

ตัวอย่าง

Python
import math

print(math.pi)  # Output: 3.141592653589793
print(math.e)   # Output: 2.718281828459045

ฟังก์ชันอื่น ๆ ที่มีประโยชน์

  • math.fabs(x): หาค่าสัมบูรณ์ของ x
  • math.gcd(a, b): หาค่าตัวหารร่วมมาก (GCD) ของ a และ b
  • math.isqrt(x): หาค่ารากที่สองแบบจำนวนเต็ม (integer square root)

ตัวอย่าง

Python
import math

print(math.fabs(-10))   # Output: 10.0
print(math.gcd(60, 48)) # Output: 12
print(math.isqrt(10))   # Output: 3

การคำนวณมุมพิเศษ

นอกจากนี้ยังมีฟังก์ชันเฉพาะสำหรับการคำนวณมุม:

  • math.asin(x): หา arcsine ของ x
  • math.acos(x): หา arccosine ของ x
  • math.atan(x): หา arctangent ของ x

ตัวอย่าง

Python
import math

print(math.asin(1))  # Output: 1.5707963267948966 (π/2)
print(math.acos(1))  # Output: 0.0
print(math.atan(1))  # Output: 0.7853981633974483 (π/4)
แชร์เรื่องนี้