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