Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #For a binomial distribution you can input the number of experiments , trials and the probability of success
- #Binomial_chart_matplotlib coded by Ken Adams
- #The probability of success p_prob. the number of experiments and the number of trials are set.
- #The code is run and a bar chart is displayed using matplotlib
- import matplotlib.pyplot as plot
- import random
- print("This program makes a graph of a binonial distribution for a given probability of success 'p'")
- print("Each experiment consists of a set number of trials and the total number of successes that occoured are recorded")
- print("After running a set number of experiments a graph is plotted\n")
- #These are the default values
- experiments = 1000000
- trials = 4
- p_prob = 0.2
- #random.seed(30)# for testing
- print("The program will run on default values")
- print(str(experiments) + " experiments, with " + str(trials) + " trials " + " and a probability of success of " +str(p_prob))
- decision = input("do you want to change the parameters 'Y' or 'N' ? ")
- if decision.lower() == "y":
- experiments = int(input("How many experiments to run " ))
- trials = int(input("How many trials of each experiment? "))
- p_prob = float(input(" What probability for success do you want? enter a number betwen 0 ans 1 "))
- else:
- print("OK we run on default paramenter")
- results = [ ]
- for y in range (experiments):
- p_count = 0
- for x in range(trials):
- raw = random.randint(0, 1000)
- #print(str(raw))
- if raw < 1000*p_prob:
- p_count = p_count +1
- results.append(p_count)
- # for testing ##print("results") #print(results) #print("p_count is: " + str(p_count))
- def score_freq(scores_list):
- freq = []
- for x in range(trials+1):
- score_x = scores_list.count(x)
- freq.append(score_x)
- return freq
- performance = score_freq(results)
- print("performance")
- print(performance)
- # The rest of the code is for plotting
- plot.bar(range(trials+1), performance, align='center', alpha=0.5)
- plot.xticks(range(trials+1))
- plot.ylabel('Number of successes')
- plot.title("Binomial distribution over " +str(experiments) + " experiments of " + str(trials) + " trials with p = " + str(p_prob))
- plot.show()
- #plot.savefig(fname="2.10(102) binomial.png") # can save if you wish
- print("bye")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement