Python math 與 random 數學及隨機數
Python 提供了豐富的內建模組來處理數字運算。如果你需要進行精確的數學計算、生成隨機樣本,或者是進行基本的數據統計分析,math、random 與 statistics 就是你的最佳工具。
math 模組:科學運算
math 模組提供了對 C 標準庫中數學函數的存取,適合開發科學運算與工程相關應用。
常用常數與函數
import math
# 常數
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
# 無條件進位與捨去
print(math.ceil(4.2)) # 5
print(math.floor(4.8)) # 4
# 四捨五入 (注意:Python 內建有 round(),math 則提供更精確的操作)
# math.trunc() 直接截斷小數點
print(math.trunc(4.9)) # 4
# 次方與開根號
print(math.pow(2, 3)) # 8.0
print(math.sqrt(16)) # 4.0
# 對數
print(math.log(100, 10)) # 2.0 (以 10 為底)
三角函數
import math
# 注意:三角函數使用的參數是「弧度」(Radians)
angle_deg = 90
angle_rad = math.radians(angle_deg) # 角度轉弧度
print(math.sin(angle_rad)) # 1.0
print(math.cos(angle_rad)) # 接近 0 的極小值
random 模組:隨機數產生
random 模組用於生成虛擬隨機數。它適合用於抽獎、模擬、打亂順序等場景。
生成隨機數
import random
# 0.0 到 1.0 之間的隨機浮點數
print(random.random())
# 指定範圍內的隨機浮點數
print(random.uniform(1.5, 9.5))
# 指定範圍內的隨機整數 (包含 1 與 10)
print(random.randint(1, 10))
# 類似 range() 的隨機選擇 (例如 0, 2, 4, 6, 8)
print(random.randrange(0, 10, 2))
序列操作
items = ['蘋果', '香蕉', '橘子', '葡萄']
# 隨機選擇一個
print(random.choice(items))
# 隨機選擇 N 個 (可重複)
print(random.choices(items, k=2))
# 隨機抽樣 N 個 (不重複)
print(random.sample(items, 2))
# 原地打亂列表順序 (會改變原列表)
random.shuffle(items)
print(items)
statistics 模組:數據統計 (精簡介紹)
如果你只是需要基本的敘述統計(平均數、中位數、標準差),不需要動用到大型的 Pandas 庫:
import statistics
data = [1, 2, 3, 4, 100, 2, 3]
print(statistics.mean(data)) # 平均數
print(statistics.median(data)) # 中位數
print(statistics.mode(data)) # 眾數
print(statistics.stdev(data)) # 標準差
總結
math:處理確定性的數學計算(如三角函數、開方等)。random:處理隨機性的生成與選擇。statistics:處理數據集的統計分析。
這些模組共同構成了 Python 強大的數值處理基礎,讓開發者在不依賴外部套件的情況下,也能完成大多數常用的數字運算任務。