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

ฟังก์ชันทางคณิตศาสตร์ใน Python - Special Functions และ Constants

ในบทความนี้ เราจะเรียนรู้ฟังก์ชันพิเศษ (special functions) และค่าคงที่ (constants) ที่มีอยู่ในโมดูล math ของ Python Standard Library

ที่นี่เราจะพูดถึงค่าคงที่บางอย่าง เช่น:

  • pi — ค่า π (พาย)
  • e — ค่าคงที่ออยเลอร์
  • inf — ค่าอนันต์ (infinity)
  • nan — Not a Number
  • tau — ค่า τ (ทาว) = 2π

และฟังก์ชันบางอย่าง เช่น:

  • gamma — คืนค่า gamma(n)
  • isinf — ตรวจสอบว่าค่าเป็นอนันต์หรือไม่
  • isnan — ตรวจสอบว่าค่าไม่ใช่ตัวเลขหรือไม่
  • isfinite — คืนค่า True หากค่าไม่ใช่อนันต์และไม่ใช่ nan
  • erf — คืนค่า error function ของ x

ตารางค่าคงที่และค่าของพวกมัน:

pi 3.141592...
e 2.718281...
tau 6.283185...
inf Infinity
nan Not a Number

ตอนนี้มาเปลี่ยนดูฟังก์ชันพิเศษบางอย่างและการนำไปใช้:

  • Gamma — คืนค่า gamma(n)
  • Isinf — ตรวจสอบว่าค่าของฟังก์ชันเป็นอนันต์หรือไม่
  • Isnan — ตรวจสอบว่าค่าที่คืนเป็นตัวเลขหรือไม่
  • Isfinite — คืนค่า True หากค่าไม่ใช่อนันต์และไม่ใช่ nan มิฉะนั้น False
  • Erf — คืนค่า error function ของ x

มาเปลี่ยนดูตัวอย่าง:

ตัวอย่าง

import math
num = 10
print(math.gamma(num))
if (math.isnan(math.nan)):
    print("The number is not a number")
else:
    print("The number is a number")
if (math.isinf(math.inf)):
    print("The number is positive infinity")
else:
    print("The number is not positive infinity")
print(math.isfinite(math.inf))

ผลลัพธ์

362880.0
The number is not a number
The number is positive infinity
False

สรุป

ในบทความนี้ เราได้เรียนรู้เกี่ยวกับ Mathematical Functions in Python - Special Functions and Constants