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

Mathematical Functions ใน Python: โมดูล math และ cmath

โมดูล math ให้ฟังก์ชันคณิตศาสตร์มาตรฐานสำหรับจำนวนจริง ส่วน cmath สำหรับจำนวนเชิงซ้อน (Complex Numbers)

Import และ Constants

import math

math.pi      # 3.141592653589793
math.e       # 2.718281828459045
math.tau     # 6.283185307179586 (2π)
math.inf     # Infinity
math.nan     # Not a Number

ฟังก์ชันตัวเลขและการแทนค่า

Functionคำอธิบาย
ceil(x)ปัดขึ้น (น้อยที่สุด ≥ x)
floor(x)ปัดลง (มากที่สุด ≤ x)
fabs(x)ค่าสัมบูรณ์
factorial(x)แฟกทอเรียล (x ≥ 0)
fsum(iterable)ผลรวมแม่นยำสูง
gcd(x, y)ตัวหารร่วมมาก
copysign(x, y)ค่า x พร้อมเครื่องหมายของ y
isfinite/inf/nan(x)ตรวจสอบค่าพิเศษ
remainder(x, y)เศษจากการหาร
import math

print(math.ceil(9.45), math.floor(9.45))    # 10 9
print(math.copysign(94, -27))               # -94.0
print(math.fabs(-94), math.fabs(54))        # 94.0 54.0
print(math.fsum([12, 9.25, 89, 3.02, -75.23, -7.2, 6.3]))  # 37.14
print(math.gcd(24, 48))                     # 24

print(math.isnan(float('nan')))   # True
print(math.isinf(float('inf')))   # True
print(math.isfinite(float('inf'))) # False
print(math.isfinite(54))           # True

Power & Logarithmic Functions

Functionคำอธิบาย
pow(x, y)xʸ
sqrt(x)รากที่ 2
exp(x)eˣ
log(x[, base])ลอการิทึม (base default = e)
log2(x)ลอค base 2
log10(x)ลอค base 10
print(math.pow(2, 5))      # 32.0
print(math.sqrt(625))      # 25.0
print(math.exp(5))         # 148.413...
print(math.log(625, 5))    # 4.0
print(math.log10(1024))    # 3.0103
print(math.log2(1024))     # 10.0

Trigonometric & Angular Conversion

Functionคำอธิบาย
sin/cos/tan(x)ตรีโกณมิติ (radian)
asin/acos/atan(x)Inverse trig
degrees(x)Radian → Degree
radians(x)Degree → Radian
print(math.sin(math.radians(45)))   # 0.7071
print(math.cos(math.pi))            # -1.0
print(math.tan(math.pi/4))          # 1.0 (ไม่ใช่ pi/2!)
print(math.degrees(math.asin(1)))   # 90.0

cmath: Complex Math

import cmath
c = 1 + 2j

print(cmath.exp(c))      # eᶜ
print(cmath.log(c, 2))   # log₂(c)
print(cmath.sqrt(c))     # √c
print(cmath.phase(c))    # Phase angle (radian)
print(cmath.polar(c))    # (r, φ)

ค่าคงที่ cmath: pi, e, tau, inf, infj, nan, nanj