Python math 庫教學指南
一、概述
math 庫是 Python 標準庫中用于數學運算的核心模塊,提供以下主要功能:
- 數學常數(如 π 和 e)
- 基本數學函數(絕對值、取整等)
- 冪與對數運算
- 三角函數
- 雙曲函數
- 特殊函數(伽馬函數等)
與內置運算符的區別:
- 提供更專業的數學函數實現
- 包含高等數學運算方法
- 支持浮點數特殊處理
二、使用詳解
1. 基礎使用
import math# 基本運算
print(math.sqrt(25)) # 5.0(平方根)
print(math.fabs(-3.14)) # 3.14(絕對值)
print(math.factorial(5)) # 120(階乘)# 取整函數
print(math.ceil(3.2)) # 4(向上取整)
print(math.floor(3.9)) # 3(向下取整)
print(math.trunc(-3.7)) # -3(截斷小數)
2. 指數與對數
# 指數運算
print(math.pow(2, 3)) # 8.0
print(math.exp(2)) # e2 ≈ 7.389# 對數運算
print(math.log(100, 10)) # 2.0
print(math.log10(1000)) # 3.0
print(math.log2(1024)) # 10.0
3. 三角函數(弧度制)
angle = math.radians(60) # 角度轉弧度
print(math.sin(angle)) # ≈0.866(正弦值)
print(math.cos(math.pi/4)) # ≈0.707(余弦值)
print(math.degrees(math.pi)) # 180.0(弧度轉角度)
4. 數學常數
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print(math.inf) # 無窮大
print(math.nan) # 非數字
5. 進階函數
# 伽馬函數
print(math.gamma(5)) # 24.0(等價于4!)# 距離計算
print(math.hypot(3, 4)) # 5.0(直角三角形斜邊)# 組合函數
print(math.comb(10, 3)) # 120(組合數C(10,3))
三、綜合應用案例
案例1:計算圓相關參數
def circle_calculations(r):circumference = 2 * math.pi * rarea = math.pi * r**2return circumference, areaprint(circle_calculations(5))
# 輸出:(31.41592653589793, 78.53981633974483)
案例2:二次方程求解
def solve_quadratic(a, b, c):discriminant = b**2 - 4*a*cif discriminant < 0:return Nonesqrt_disc = math.sqrt(discriminant)x1 = (-b + sqrt_disc) / (2*a)x2 = (-b - sqrt_disc) / (2*a)return x1, x2print(solve_quadratic(1, -5, 6)) # (3.0, 2.0)
案例3:三角函數應用
def triangle_height(angle_deg, base):angle_rad = math.radians(angle_deg)return base * math.tan(angle_rad)print(f"{triangle_height(30, 10):.2f}米") # 輸出:5.77米
四、注意事項
-
輸入值范圍限制:
- 負數平方根會引發 ValueError
- 非數值輸入會引發 TypeError
-
精度問題:
print(0.1 + 0.2 == 0.3) # False print(math.isclose(0.1+0.2, 0.3)) # True
-
與內置函數的區別:
- math.sqrt() 比 **0.5 更準確
- math.pow() 處理浮點指數更專業
五、總結建議
- 優先使用 math 庫進行復雜數學運算
- 注意角度與弧度的轉換
- 處理邊界值時使用 math.isclose() 代替直接比較
- 需要更高精度時考慮使用 decimal 模塊
建議學習者通過以下方式加深理解:
- 嘗試實現自己的數學函數并與 math 庫對比
- 解決Project Euler等平臺的數學編程問題
- 結合matplotlib進行函數可視化