萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python random 與 math 模組核心功能速查筆記

系統整理 math 數學常數與函數、random 偽隨機數生成、常用分佈、排序與取樣方法,附帶可直接執行的互動式範例。

math 模組

常數

math.pi   # 3.141592653589793
math.e    # 2.718281828459045

常用函數

函數說明範例
ceil(x)向上取整ceil(pi) == 4
floor(x)向下取整floor(pi) == 3
pow(x, y)x 的 y 次方pow(2, 3) == 8.0
log(x[, base])對數,預設自然對數log(8, 2) == 3.0
sqrt(x)平方根sqrt(4) == 2.0
fabs(x)絕對值(浮點數)fabs(-3.5) == 3.5
factorial(x)階乘factorial(5) == 120
exp(x)e 的 x 次方exp(1) == e

三角函數(弧度制)

sin(x), cos(x), tan(x)
asin(x), acos(x), atan(x), atan2(y, x)
degrees(rad)   # 弧度轉角度
radians(deg)   # 角度轉弧度

雙曲函數

sinh, cosh, tanh, asinh, acosh, atanh

random 模組

基本函數

函數說明範例
seed(x)設定種子(可為任何可哈希物件)seed(42)
randint(a, b)返回 [a, b] 間整數randint(1, 6)
randrange(start, stop[, step])等價 choice(range(...))randrange(0, 100, 2)

隨機取樣與排序

choice(seq)          # 從序列隨機取一元素
sample(seq, k)       # 不重複取樣 k 個元素(不修改原序列)
shuffle(list)        # 原地打亂列表

實數分佈

函數分佈參數
random()均勻 [0, 1)無
uniform(a, b)均勻 [a, b]a, b
gauss(mu, sigma)高斯/常態μ, σ
expovariate(lambd)指數分佈λ

進階提示

  • 複雜科學計算建議改用 numpy/scipy(陣列運算、統計分佈、線性代數)。
  • random 非加密安全,密碼學用途請用 secrets 模組(Python 3.6+)。
copyright © 萬盛學電腦網 all rights reserved