SHARE
TWEET

Untitled

a guest Sep 20th, 2019 78 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import random
  2.  
  3. import matplotlib.pyplot as plt;
  4.  
  5. plt.rcdefaults()
  6. import numpy as np
  7. import matplotlib.pyplot as plt
  8.  
  9. # funtion in order to save figures.
  10. def saveFig(plt, num_sample):
  11.     import os
  12.  
  13.     script_dir = os.path.dirname(__file__)
  14.     results_dir = os.path.join(script_dir, 'Distribution/')
  15.     file_name = "3_Coin_Toss_numSample:"+str(num_sample)+".png"
  16.  
  17.     # in case the directory does not exist, create a directory for saving figures.
  18.     if not os.path.isdir(results_dir):
  19.         os.makedirs(results_dir)
  20.  
  21.     plt.savefig(results_dir + file_name)
  22.  
  23.  
  24.  
  25. # number of sampling
  26. num_sample = 100000
  27.  
  28. # 0:tail, 1:head
  29. samples = [[random.randint(0, 1), random.randint(0, 1), random.randint(0, 1)] for i in range(num_sample)]
  30.  
  31. # random variable 'X': total number of heads, possible values of X is from 0 to 3
  32. X_values_cnt = [0, 0, 0, 0]
  33.  
  34.  
  35. for sample in samples:
  36.     X_values_cnt[sum(sample)] = X_values_cnt[sum(sample)] + 1
  37.  
  38. print(X_values_cnt)
  39.  
  40. # all possible values of random variable X
  41. X_values = ('0', '1', '2', '3')
  42.  
  43. # number of possible values of X
  44. num_X_values = np.arange(len(X_values))
  45.  
  46. # probabilities of occuring each outcome
  47. val_probs = [x / num_sample for x in X_values_cnt]
  48.  
  49.  
  50. # plotting the bar chart of the probability distribution of random variable 'X'
  51. plt.bar(num_X_values, val_probs, align='center', alpha=0.5)
  52. plt.xticks(num_X_values, X_values)
  53. plt.ylabel('Probability')
  54. plt.title('3_Coin_Toss, Number of Sampling:{}'.format(num_sample))
  55. saveFig(plt,num_sample)
  56. plt.show()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top