#input
Table = #table#
# retrive data
Output = [];
Prob = [];
for vr in Table:
Output += [vr[0]]
Prob += [vr[1]]
# normalize probabilities
sum = 0;
for value in Prob:
sum += value;
Prob = vector(Prob) / sum
Prob = list(Prob)
#end
#show table of input probabilties
show("The Possible output and normalized probabilties are following:")
Table1 = [["Output","Probabilty"]]
for i in range(len(Prob)):
Table1 += [[Output[i],Prob[i]]]
show(table(Table1))
# calculate cumulative probabilites
Cum_Prob = [Prob[0]];
for i in range(len(Prob) - 1):
Cum_Prob += [Cum_Prob[i] + Prob[i+1]]
# show cumulative probabilites
show("Calmulative Probabilites are calculated.")
Table2 = [["Output","Probabilty","Cumulative Probabilty"]]
for i in range(len(Prob)):
Table2 += [[Output[i],Prob[i],Cum_Prob[i]]]
show(table(Table2))
# determine accept range of random number
Cum_Prob_Round3 = []
for vl in Cum_Prob:
Cum_Prob_Round3 += [floor(vl * 100)]
RN_low = [0]*len(Prob)
RN_high = [0]*len(Prob)
for i in range(len(Prob)):
RN_high[i] = Cum_Prob_Round3[i] - 1
for i in range(len(Prob) - 1):
RN_low[i+1] = Cum_Prob_Round3[i]
#show random number range
show("Random number range are assigned.")
Table3 = [["Output","Probabilty","Cumulative Probabilty","Random Number Range"]]
for i in range(len(Prob)):
Table3 += [[Output[i] , Prob[i] , Cum_Prob[i] , str(RN_low[i]) + "-" + str(RN_high[i])]]
show(table(Table3))
show("Click 'Generate' to generate the result")
#draw random number and assign output
def Generate():
#draw 3 digit random number
rand_num = randint(0, 99)
show(html("Random number genertated: " + str(rand_num)))
#assign output
assign_index = 0
for i in range(len(Prob)):
if (RN_low[i] <= rand_num <= RN_high[i]):
assign_index = i
show(html("Corresponding output is: " + str(Output[assign_index])))
@interact
def _(action=selector(['Generate'],buttons=True)):
action = eval(action + "()")