Advertisement
kenadams53

Binomial Distribution chart

Sep 6th, 2019
406
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. #For a binomial distribution you can input the number of experiments , trials and the probability of success
  2. #Binomial_chart_matplotlib coded by Ken Adams
  3. #The probability of success p_prob. the number of experiments and the number of trials are set.
  4. #The code is run and a bar chart is displayed using matplotlib
  5.  
  6. import matplotlib.pyplot as plot
  7. import random
  8. print("This program makes a graph of a binonial distribution for a given probability of success 'p'")
  9. print("Each experiment consists of a set number of trials and the total number of successes that occoured are recorded")
  10. print("After running a set number of experiments a graph is plotted\n")
  11.  
  12. #These are the default values
  13. experiments = 1000000
  14. trials = 4
  15. p_prob = 0.2
  16. #random.seed(30)# for testing
  17.  
  18. print("The program will run on default values")
  19. print(str(experiments) + " experiments, with " + str(trials) + " trials " + " and a probability of success of " +str(p_prob))
  20.  
  21.  
  22.  
  23.  
  24. decision = input("do you want to change the parameters 'Y' or 'N' ? ")
  25. if decision.lower() == "y":
  26. experiments = int(input("How many experiments to run " ))
  27. trials = int(input("How many trials of each experiment? "))
  28. p_prob = float(input(" What probability for success do you want? enter a number betwen 0 ans 1 "))
  29. else:
  30. print("OK we run on default paramenter")
  31.  
  32.  
  33. results = [ ]
  34. for y in range (experiments):
  35. p_count = 0
  36. for x in range(trials):
  37.  
  38. raw = random.randint(0, 1000)
  39. #print(str(raw))
  40. if raw < 1000*p_prob:
  41. p_count = p_count +1
  42. results.append(p_count)
  43. # for testing ##print("results") #print(results) #print("p_count is: " + str(p_count))
  44.  
  45.  
  46. def score_freq(scores_list):
  47. freq = []
  48. for x in range(trials+1):
  49. score_x = scores_list.count(x)
  50. freq.append(score_x)
  51. return freq
  52.  
  53. performance = score_freq(results)
  54. print("performance")
  55. print(performance)
  56.  
  57.  
  58. # The rest of the code is for plotting
  59. plot.bar(range(trials+1), performance, align='center', alpha=0.5)
  60.  
  61. plot.xticks(range(trials+1))
  62. plot.ylabel('Number of successes')
  63. plot.title("Binomial distribution over " +str(experiments) + " experiments of " + str(trials) + " trials with p = " + str(p_prob))
  64.  
  65. plot.show()
  66. #plot.savefig(fname="2.10(102) binomial.png") # can save if you wish
  67.  
  68. print("bye")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement