1 #coding:utf-8 2 import random 3 4 # random.randint(1,10)產生1,10的隨機整數 5 for i in range(1,5): 6 ranint = random.randint(1,10) 7 print(ranint, end=" ") 8 print() 9 10 #random.random()產生0,1之間的隨機數 11 for j in range(1,5): 12 ran_1 = random.random() 13 print(ran_1,end=" ") 14 print() 15 #random.uniform(10,20)產生指定區間的隨機符點數 16 for a in range(1,5): 17 ran_2 = random.uniform(10,20) 18 print(ran_2,end=" ") 19 print() 20 21 #random.randrange(10,20,2)在指定區間上以特定步長產生隨機數 22 for b in range(1,5): 23 ran_3 = random.randrange(10,20,2) 24 print(ran_3,end=" ") 25 print() 26 for c in range(1,5): 27 ran_4 = random.choice(range(10,20,2)) 28 print(ran_4,end=" ") 29 print() 30 31 #random.choice從序列中獲取一個隨機元素 32 ran_5 = random.choice(['a','b','c','d']) 33 print(ran_5) 34 35 #random.shuffle(x[, random]),用於將一個列表中的元素打亂 36 p = ['I','love','you','and','do','you','hate','me'] 37 ran_6 = random.shuffle(p) 38 print(p) 39 40 #random.sample(sequence, k),從指定序列中隨機獲取指定長度的片段。sample函數不會修改原有序列。 41 42 list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 43 slice = random.sample(list, 5) #從list中隨機獲取5個元素,做爲一個片段返回 44 print(slice) 45 print(list) #原有序列並無改變。 46 47 #random.sample(population, k)產生指定序列的指定長度的隨機數,可利用此方法產生10位隨機密碼 48 #列表轉字符串方法:「」.join(list) 49 #字符串轉列表方法:list(str) 50 ran_7 = random.sample('abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*():"?><',10) 51 print("".join(ran_7)) 52 53 #random.triangular(low, high, mode) 54 # random.triangular(低,高,模式) 55 # 返回一個隨機浮點數N,以便在這些邊界之間使用指定的模式。該低和高界默認的0和1。 56 # 所述模式參數默認爲邊界之間的中點,給人一種對稱分佈。low <= N <= high 57 ran_8 = random.triangular(10,20) 58 print(ran_8) 59 60 # random.betavariate(alpha,beta ) 61 # Beta分發。參數的條件是和 。返回值的範圍介於0和1之間。alpha > 0beta > 0 62 ran_9 = random.betavariate(2,9) 63 print(ran_9) 64 65 # random.expovariate(lambd ) 66 # 指數分佈。 lambd是1.0除以所需的平均值。它應該是非零的。 67 # (該參數將被稱爲「拉姆達」,可是這是在Python保留字。) 68 # 返回值的範圍從0到正無窮大若是lambd爲正,且從負無窮大到0,若是lambd爲負。 69 for i in [0.01,0.2,1,33,-0.02,-0.99,-22,-88]: 70 ran_10 = random.expovariate(i) 71 print(ran_10,end=" ") 72 73 # random.gammavariate(alpha,beta ) 74 # Gamma分佈。(不是伽瑪函數!)參數的條件是和。alpha > 0beta > 0 75 # 76 # 機率分佈函數是: 77 # 78 # x ** (alpha - 1) * math.exp(-x / beta) 79 # pdf(x) = -------------------------------------- 80 # math.gamma(alpha) * beta ** alpha 81 # random.gauss(mu,sigma ) 82 # 高斯分佈。 mu是平均值,sigma是標準誤差。這比normalvariate()下面定義的函數稍快。 83 # 84 # random.lognormvariate(mu,sigma ) 85 # 記錄正態分佈。若是你採用這個分佈的天然對數,你將得到具備平均μ和標準誤差西格瑪的正態分佈。 mu能夠有任何值,sigma必須大於零。 86 # 87 # random.normalvariate(mu,sigma ) 88 # 正態分佈。 mu是平均值,sigma是標準誤差。 89 # 90 # random.vonmisesvariate(mu,kappa ) 91 # mu是平均角度,以弧度表示,介於0和2 * pi之間,kappa 是濃度參數,必須大於或等於零。若是 kappa等於零,則該分佈在0到2 * pi的範圍內減少到均勻的隨機角度。 92 # 93 # random.paretovariate(alpha ) 94 # 帕累託分佈。 alpha是形狀參數。 95 # 96 # random.weibullvariate(alpha,beta ) 97 # 威布爾分佈。 alpha是scale參數,beta是shape參數。 98 99 # 基本示例: 100 # 101 # >>> 102 # >>> random() # Random float: 0.0 <= x < 1.0 103 # 0.37444887175646646 104 # 105 # >>> uniform(2.5, 10.0) # Random float: 2.5 <= x < 10.0 106 # 3.1800146073117523 107 # 108 # >>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds 109 # 5.148957571865031 110 # 111 # >>> randrange(10) # Integer from 0 to 9 inclusive 112 # 7 113 # 114 # >>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive 115 # 26 116 # 117 # >>> choice(['win', 'lose', 'draw']) # Single random element from a sequence 118 # 'draw' 119 # 120 # >>> deck = 'ace two three four'.split() 121 # >>> shuffle(deck) # Shuffle a list 122 # >>> deck 123 # ['four', 'two', 'ace', 'three'] 124 # 125 # >>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement 126 # [40, 10, 50, 30] 127 # 模擬: 128 # 129 # >>> 130 # >>> # Six roulette wheel spins (weighted sampling with replacement) 131 # >>> choices(['red', 'black', 'green'], [18, 18, 2], k=6) 132 # ['red', 'green', 'black', 'black', 'red', 'black'] 133 # 134 # >>> # Deal 20 cards without replacement from a deck of 52 playing cards 135 # >>> # and determine the proportion of cards with a ten-value 136 # >>> # (a ten, jack, queen, or king). 137 # >>> deck = collections.Counter(tens=16, low_cards=36) 138 # >>> seen = sample(list(deck.elements()), k=20) 139 # >>> seen.count('tens') / 20 140 # 0.15 141 # 142 # >>> # Estimate the probability of getting 5 or more heads from 7 spins 143 # >>> # of a biased coin that settles on heads 60% of the time. 144 # >>> trial = lambda: choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5 145 # >>> sum(trial() for i in range(10000)) / 10000 146 # 0.4169 147 # 148 # >>> # Probability of the median of 5 samples being in middle two quartiles 149 # >>> trial = lambda : 2500 <= sorted(choices(range(10000), k=5))[2] < 7500 150 # >>> sum(trial() for i in range(10000)) / 10000 151 # 0.7958 152 # 使用從新取樣和替換來估計大小爲5的樣本的均值的置信區間的統計自舉的示例: 153 # 154 # # http://statistics.about.com/od/Applications/a/Example-Of-Bootstrapping.htm 155 # from statistics import mean 156 # from random import choices 157 # 158 # data = 1, 2, 4, 4, 10 159 # means = sorted(mean(choices(data, k=5)) for i in range(20)) 160 # print(f'The sample mean of {mean(data):.1f} has a 90% confidence ' 161 # f'interval from {means[1]:.1f} to {means[-2]:.1f}') 162 # 從新採樣置換測試的示例, 以肯定藥物與安慰劑的效果之間觀察到的差別的統計顯着性或p值: 163 # 164 # # Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson 165 # from statistics import mean 166 # from random import shuffle 167 # 168 # drug = [54, 73, 53, 70, 73, 68, 52, 65, 65] 169 # placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46] 170 # observed_diff = mean(drug) - mean(placebo) 171 # 172 # n = 10000 173 # count = 0 174 # combined = drug + placebo 175 # for i in range(n): 176 # shuffle(combined) 177 # new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):]) 178 # count += (new_diff >= observed_diff) 179 # 180 # print(f'{n} label reshufflings produced only {count} instances with a difference') 181 # print(f'at least as extreme as the observed difference of {observed_diff:.1f}.') 182 # print(f'The one-sided p-value of {count / n:.4f} leads us to reject the null') 183 # print(f'hypothesis that there is no difference between the drug and the placebo.') 184 # 模擬單個服務器隊列中的到達時間和服務交付: 185 # 186 # from random import expovariate, gauss 187 # from statistics import mean, median, stdev 188 # 189 # average_arrival_interval = 5.6 190 # average_service_time = 5.0 191 # stdev_service_time = 0.5 192 # 193 # num_waiting = 0 194 # arrivals = [] 195 # starts = [] 196 # arrival = service_end = 0.0 197 # for i in range(20000): 198 # if arrival <= service_end: 199 # num_waiting += 1 200 # arrival += expovariate(1.0 / average_arrival_interval) 201 # arrivals.append(arrival) 202 # else: 203 # num_waiting -= 1 204 # service_start = service_end if num_waiting else arrival 205 # service_time = gauss(average_service_time, stdev_service_time) 206 # service_end = service_start + service_time 207 # starts.append(service_start) 208 # 209 # waits = [start - arrival for arrival, start in zip(arrivals, starts)] 210 # print(f'Mean wait: {mean(waits):.1f}. Stdev wait: {stdev(waits):.1f}.') 211 # print(f'Median wait: {median(waits):.1f}. Max wait: {max(waits):.1f}.') 212 # 也能夠看看 「黑客統計」 是Jake Vanderplas 關於統計分析的視頻教程, 僅使用了一些基本概念,包括模擬,抽樣,改組和交叉驗證。 213 # 經濟模擬Peter Norvig對 市場的模擬 ,顯示了該模塊提供的許多工具和分佈的有效使用(高斯,均勻,樣本,beta變量,選擇,三角和randrange)。 214 # 215 # 具體的機率介紹(使用Python)Peter Norvig 的教程,涵蓋了機率論的基礎知識,如何編寫模擬,以及如何使用Python進行數據分析。 216 217 218