def vote(n, p, w): n1 = stdrandom.binomial(n, 1 - w) #n次投票,不错误的次数为n1 na = stdrandom.binomial(n1, p) + stdrandom.binomial( n - n1, 1 - p) #正常的N1次p概率投给A;错误的N-N1次,票数记反,相当于A,B概率对调。返回na为A获得的票数 print('A获得:', na) if na > n / 2: return 'A获胜' else: return 'A失败'
def main(): n = int(sys.argv[1]) # number of biased coin flips per trial p = float(sys.argv[2]) # heads with probability p trialCount = int(sys.argv[3]) # number of trials histogram = Histogram(n + 1) for trial in range(trialCount): heads = stdrandom.binomial(n, p) histogram.addDataPoint(heads) stddraw.setCanvasSize(500, 200) stddraw.clear(stddraw.LIGHT_GRAY) histogram.draw() stddraw.show()
#----------------------------------------------------------------------- # Accept integers n and trials as command-line arguments. # Perform trials experiments, each of which counts the number # of heads found when a fair coin is flipped n times. Then # draw the results to standard draw. Also draw the predicted Gaussian # distribution function, thereby allowing easy comparison of the # experimental results to the theoretically predicted results. n = int(sys.argv[1]) trials = int(sys.argv[2]) freq = stdarray.create1D(n + 1, 0) for t in range(trials): heads = stdrandom.binomial(n, 0.5) freq[heads] += 1 norm = stdarray.create1D(n + 1, 0.0) for i in range(n + 1): norm[i] = 1.0 * freq[i] / trials phi = stdarray.create1D(n + 1, 0.0) stddev = math.sqrt(n) / 2.0 for i in range(n + 1): phi[i] = gaussian.pdf(i, n / 2.0, stddev) stddraw.setCanvasSize(1000, 400) stddraw.setYscale(0, 1.1 * max(max(norm), max(phi))) stdstats.plotBars(norm) stdstats.plotLines(phi)
import stdrandom t = 10000 s = 0 for i in range(t): if stdrandom.binomial(12,0.05) > 0: s += 1 print(s/t)
#----------------------------------------------------------------------- # Accept integers n and trials as command-line arguments. # Perform trials experiments, each of which counts the number # of heads found when a fair coin is flipped n times. Then # draw the results to standard draw. Also draw the predicted Gaussian # distribution function, thereby allowing easy comparison of the # experimental results to the theoretically predicted results. n = int(sys.argv[1]) trials = int(sys.argv[2]) freq = stdarray.create1D(n+1, 0) for t in range(trials): heads = stdrandom.binomial(n, 0.5) freq[heads] += 1 norm = stdarray.create1D(n+1, 0.0) for i in range(n+1): norm[i] = 1.0 * freq[i] / trials phi = stdarray.create1D(n+1, 0.0) stddev = math.sqrt(n)/2.0 for i in range(n+1): phi[i] = gaussian.pdf(i, n/2.0, stddev) stddraw.setCanvasSize(1000, 400) stddraw.setYscale(0, 1.1 * max(max(norm), max(phi))) stdstats.plotBars(norm) stdstats.plotLines(phi)