python正態分布隨機數生成的三種方式
方法1:內置庫random
使用方式:詳見 https://docs.python.org/zh-cn/3/library/random.html
1 import random 2 # 返回整數 3 a=random.randint(min,max) 4 # 返回指定范圍內的小數 5 a=random.uniform(min,max) 6 # 返回0-1之間的小數 7 a=random.seed() 8 # 返回指定數學期望和標准差的高斯分布隨機數 9 a=random.gauss(miu,sigma) 10 # 從序列seq中有放回采樣 11 a=random.choice(seq) 12 # 從序列seq中無放回采樣 13 a=random.sample(seq)
優點:快
缺點:每次只能生成一個,生成一組需要加循環。只支持正態分布等八種分布。
方法2:numpy函數random
使用方法:https://numpy.org/devdocs/reference/random/index.html?highlight=random#module-numpy.random
1 from numpy.random import default_rng 2 rng = default_rng() 3 vals = rng.standard_normal(100)
優點:較快,更准確,可以同時生成很多,但是需要先定義生成器
方法3:scipy統計學函數stats
使用方法:https://docs.scipy.org/doc/scipy/reference/stats.html
1 from scipy import stats 2 a=stats.norm.rvs(miu,sigma,size=500)
優點:支持絕大部分數學分布,不僅可以生成隨機數,還可以生成概率密度函數,累計概率密度函數及其對數函數。
缺點:慢