Advertisement
Guest User

Birthday paradox

a guest
Jun 8th, 2018
979
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.12 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import random
  4. import subprocess
  5.  
  6. def ratio_bdays(n):
  7.     mult = 1
  8.     for i in range(365, 365 - n , -1):
  9.         mult = mult * i / 365
  10.     return (1 - mult) * 100
  11.  
  12. def create_matrix_ratio(num_of_sims, num_days_random):
  13.     sim_with_coinc = 0
  14.  
  15.     #Creates a 12x31 blue matrix
  16.     list_calendar = np.zeros((12,31))
  17.     for i in range(0,12):
  18.         for j in range(0,31):
  19.             list_calendar[i][j] = 0
  20.  
  21.     #Creates the non-existing days at the end of the month
  22.     ##Months with 30 days
  23.     for i in [3, 5, 8, 10]:
  24.         list_calendar[i][30] = 100
  25.     #February
  26.     for i in [28, 29, 30]:
  27.         list_calendar[1][i] = 100
  28.  
  29.     #Creates random bdays and draw them and the coincidences
  30.     sum_days_random = 0
  31.     coincidences = 0
  32.    
  33.     while sum_days_random < num_days_random:
  34.         i = random.randint(0,11)
  35.         j = random.randint(0,30)
  36.        
  37.         if list_calendar[i][j] == 30:  #If there is already a birthday (orange) -> green
  38.             list_calendar[i][j] = 45
  39.             coincidences = coincidences + 1
  40.             sum_days_random = sum_days_random + 1
  41.  
  42.         elif list_calendar[i][j] != 100: #If day exists and not a bday already
  43.             list_calendar[i][j] = 30
  44.             sum_days_random = sum_days_random + 1
  45.  
  46.     if coincidences != 0:
  47.         sim_with_coinc = sim_with_coinc + 1
  48.  
  49.     ax = plt.gca()
  50.    
  51.     for i in range(0,11):
  52.         ax.axhline(y= i + 0.45, linewidth=0.5, color='k')
  53.     for i in range(0,30):
  54.         ax.axvline(x= i + 0.45, linewidth=0.5, color='k')
  55.  
  56.     ax.set_title("Random birthdays (orange): " + str(num_days_random) + "\n"
  57.                 "Coincidences / Shared birthdays (green): " +
  58.                 str(coincidences) + "\n" +
  59.                 "Simulation number " + str(num_of_sims) + "\n")
  60.  
  61.     return list_calendar, num_of_sims, sim_with_coinc, coincidences
  62.  
  63.  
  64. def creates_graph(simus_user, num_days_random):
  65.     list_simu_0 = []
  66.     list_simu_1 = []
  67.  
  68.     list_ratio_0 = []
  69.     list_ratio_sum_0 = []
  70.    
  71.     list_ratio_1 = []
  72.     list_ratio_sum_1 = []
  73.    
  74.     list_num_coinc_0 = []
  75.     list_num_coinc_1 = []
  76.  
  77.     for num_of_sims in range(1, simus_user):
  78.         #Creates and saves the graph
  79.         plt.figure(figsize=(12,8))
  80.  
  81.         ###### First matrix [0,0]###
  82.         ax1 = plt.subplot(221)
  83.         list_calendar, simu_with_coinc_0, ratio_0, num_coinc_0 = create_matrix_ratio(num_of_sims, num_days_random[0])
  84.         list_simu_0.append( simu_with_coinc_0 )
  85.         list_ratio_0.append( ratio_0 )
  86.         list_ratio_sum_0.append( 100 * sum(list_ratio_0) / num_of_sims )
  87.         list_num_coinc_0.append(num_coinc_0)
  88.  
  89.         #Turns the list into an array and colours it
  90.         array_calendar = np.asarray(list_calendar)
  91.         array_calendar = array_calendar.reshape((12, 31))
  92.         ax1.matshow(array_calendar, cmap="tab20c", interpolation='none')
  93.        
  94.         col_labels = range(1,32)
  95.         ax1.set_xticks(range(31))
  96.         ax1.set_xticklabels(col_labels, fontsize=7)
  97.         row_labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dic" ]
  98.         ax1.set_yticks(range(12))
  99.         ax1.set_yticklabels(row_labels, fontsize=8)
  100.  
  101.         ###### First ratio [1,0]###
  102.         ax1 = plt.subplot(223)
  103.         ratio_obj = round( ratio_bdays( num_days_random[0]) , 1)
  104.         ax1.axhline(y= ratio_obj, linewidth=0.5, color='g')
  105.         ax1.set_xlim( [0, simus_user] )
  106.         plt.title("Ratio of simulations with shared birthdays (%)" + "\n"
  107.                         + "Expected ratio: " + str(ratio_obj) + "%" + "\n"
  108.                         + "Average of shared birthdays: " +
  109.                         str( round(np.mean(list_num_coinc_0), 2) ) + "\n")
  110.         ax1.plot(list_simu_0, list_ratio_sum_0, "-ro", linewidth=1, markersize=2)
  111.  
  112.  
  113.         ###### Second matrix [0,1]###
  114.         ax1 = plt.subplot(222)
  115.        
  116.         list_calendar, simu_with_coinc_1, ratio_1, num_coinc_1 = create_matrix_ratio(num_of_sims, num_days_random[1])
  117.         list_simu_1.append( simu_with_coinc_1 )
  118.         list_ratio_1.append( ratio_1 )
  119.         list_ratio_sum_1.append( 100 * sum(list_ratio_1) / num_of_sims )
  120.         list_num_coinc_1.append(num_coinc_1)
  121.  
  122.         #Turns the list into an array and colours it
  123.         array_calendar = np.asarray(list_calendar)
  124.         array_calendar = array_calendar.reshape((12, 31))
  125.         ax1.matshow(array_calendar, cmap="tab20c", interpolation='none')
  126.        
  127.         col_labels = range(1,32)
  128.         ax1.set_xticks(range(31))
  129.         ax1.set_xticklabels(col_labels, fontsize=7)
  130.         row_labels = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dic" ]
  131.         ax1.set_yticks(range(12))
  132.         ax1.set_yticklabels(row_labels, fontsize=8)
  133.  
  134.  
  135.         ###### Second ratio [1,1]###
  136.         plt.subplot(224)
  137.         ratio_obj = round( ratio_bdays( num_days_random[1]) , 1)
  138.         plt.axhline(y= ratio_obj, linewidth=0.5, color='g')
  139.         plt.xlim( [0, simus_user] )
  140.         plt.title("Ratio of simulations with shared birthdays (%)" + "\n"
  141.                         + "Expected ratio: " + str(ratio_obj) + "%" + "\n"
  142.                         + "Average of shared birthdays: " +
  143.                         str( round(np.mean(list_num_coinc_1), 2) ) + "\n")
  144.         plt.plot(list_simu_1, list_ratio_sum_1, "-ro", linewidth=1, markersize=2)
  145.  
  146.         if len(str(num_of_sims)) == 1:
  147.             zeros = "00"
  148.         elif len(str(num_of_sims)) == 2:
  149.             zeros = "0"
  150.         else:
  151.             zeros = ""
  152.  
  153.         plt.savefig(zeros + str(num_of_sims) + ".png", bbox_inches='tight')
  154.         plt.close()
  155.         plt.close('all')
  156.  
  157.  
  158. number_of_sims_to_run = 150
  159. random_days = [23, 41]
  160. creates_graph(number_of_sims_to_run, random_days)
  161.  
  162. delay = 6
  163. subprocess.run(["convert", "-delay", str(delay), "-loop", "0", "*.png", "ZZZ.gif"])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement