def Simulate(self, number_of_flips, number_of_realizations): self.number_of_flips = number_of_flips self.number_of_realizations = number_of_realizations gamecost = -250 # cost of playing the game totalwinnings = 0 # initialize total winnings winningslist = [] # empty list to place each game's winnging into and then graph losecount = 0 # keep track of any time you lose money for j in range(0, self.number_of_realizations): fliplist = "" # create an empty string for i in range(0, self.number_of_flips): # iterate through 20 flips, treating 1's as heads and 0's as tails fliplist = fliplist + str((numpy.random.binomial(1, self.flip_probability))) #per https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html, add each flip to fliplist winnings = gamecost+(100*(fliplist.count("001"))) # find the number of Tails, Tails, Heads, multiply by fifty, add to cost of game to find winnings winningslist.append(winnings) # append winningslist with each games winnings if winnings < 0: losecount = losecount +1 # if winnings are less than 0, add to losecount totalwinnings = totalwinnings + winnings # add all the realizations of winnings together averagewinnings = '${:,.2f}'.format((totalwinnings/self.number_of_realizations)) # find the average winnings # print("Expected reward: ", averagewinnings) # print the average winnings # Problem 1 FigureSupport.graph_histogram( observations=winningslist, title='Histogram of Game Winnings (1000 Games)', x_label='Game Winnings (Dollars)', y_label='Count') print("Problem 1: It appears that the minimum award is approximately $ -250 while the maximum award is approximately $ 250") # Problem 2 loseprob = losecount/self.number_of_realizations print("Problem 2: Probability of Losing Money: ",loseprob)
import CalibrationClassesTT as Cls import CalibrationSettingsTT as CalibSets import scr.FigureSupport as Fig # create a calibration object calibration = Cls.Calibration() # sample the posterior of the mortality probability calibration.sample_posterior() # create the histogram of the resampled mortality probabilities Fig.graph_histogram(data=calibration.get_mortality_resamples(), title='Histogram of Resampled Mortality Probabilities', x_label='Mortality Probability', y_label='Counts', x_range=[CalibSets.POST_L, CalibSets.POST_U]) # Estimate of mortality probability and the posterior interval print( 'Estimate of mortality probability ({:.{prec}%} credible interval):'. format(1 - CalibSets.ALPHA, prec=0), calibration.get_mortality_estimate_credible_interval(CalibSets.ALPHA, 4)) # effective sample size txtEff = 'Effective sample size: {:.1f}'.format( calibration.get_effective_sample_size()) print(txtEff)
""" returns the average reward from all games""" return sum(self._gameRewards) / len(self._gameRewards) def prob_lose(self): tlr = 0 # the times that you lose money for everyreward in self._gameRewards: if everyreward < 0: tlr += 1 return tlr / len(self._gameRewards) # run trail of 1000 games to calculate expected reward games = SetOfGames(prob_head=0.5, n_games=1000) # print all rewards print('All reward:', games.get_all_reward()) # print the average reward print('Expected reward when the probability of head is 0.5:', games.get_ave_reward()) #Problem 1:Draw the histogram of rewards in 1000 games with a fair coin Fig.graph_histogram(observations=games.get_all_reward(), title='Histogram of Game Reward', x_label='Reward($)', y_label='Count') # Answer for problem 1: #the minimum and maximum reward that I expect to see is $-250 and $250 # Problem 2:Estimate the probability of losing money in this game print('The probability of losing money in this game:', games.prob_lose())
import HW6.Classes as Cls import scr.FigureSupport as figureLibrary # create a multiple game sets multipleGameSets = Cls.MultipleGameSets(ids=range(1000), prob_head=0.5, n_games_in_a_set=10) # simulate all game sets multipleGameSets.simulation() # print projected mean reward print('Projected mean reward', multipleGameSets.get_mean_total_reward()) # print projection interval print('95% projection interval of average rewards', multipleGameSets.get_PI_total_reward(0.05)) # plot figureLibrary.graph_histogram( data=multipleGameSets.get_all_total_rewards(), title="Histogram of gambler's total reward from playing the gam 10 times", x_label='Mean Rewards', y_label='Count') print('We need a transient-state simulation for this perspective.') print( 'We are not able to rely on the Law of Large Numbers to make inference because our data is very limited.' ) print( 'Therefore, we must use the sample mean and projection intervals for interpretation.' )
import scr.FigureSupport as Figs print("Hmwk Qs 3-5") # create and simulate cohort cohort = MarkovCls.Cohort(id=1, therapy=P.Therapies.ANTICOAG) simOutputs = cohort.simulate() # graph survival curve PathCls.graph_sample_path(sample_path=simOutputs.get_survival_curve(), title='Survival curve', x_label='Simulation time step', y_label='Number of alive patients') # graph histogram of survival times Figs.graph_histogram(data=simOutputs.get_survival_times(), title='Survival times of patients with Stroke', x_label='Survival time (years)', y_label='Counts', bin_width=1) # graph histogram of number of strokes Figs.graph_histogram(data=simOutputs.get_if_developed_stroke(), title='Number of Strokes per Patient', x_label='Strokes', y_label='Counts', bin_width=1) # print outcomes (means and CIs) SupportMarkov.print_outcomes(simOutputs, 'Treatment:')
therapy=P.Therapies.ANNUAL) simOutputs = cohort.simulate() # graph infection curve PathCls.graph_sample_path( sample_path=simOutputs.get_infection_curve(), title='infection curve', x_label='Simulation time step', y_label='Number of infected patients') # graph histogram of infection durations Figs.graph_histogram( data=simOutputs.get_infection_durations(), #data=[1, 2, 4, 4, 2], title='infection times of patients', x_label='infection time (years)', y_label='Counts', bin_width=2 ) # graph histogram of number of infections Figs.graph_histogram( data=simOutputs.get_if_developed_infection(), #data=[1, 5, 2, 3, 5], title='Number of infections per Patient', x_label='infections', y_label='Counts', bin_width=1 ) Figs.graph_histogram(
self._minValue = 0 for h in self._gameRewards: if h < self._minValue: self._minValue = h return self._minValue def get_max(self): self._maxValue = 0 for l in self._gameRewards: if l > self._maxValue: self._maxValue = l return self._maxValue # run trail of 1000 games to calculate expected reward games = SetOfGames(prob_head=0.5, n_games=1000) # print the average reward print('Expected reward when the probability of head is 0.5:', games.get_ave_reward()) print('The minimum reward you can expect to see while playing this game is:', games.get_min()) print('The maximum reward you can expect to see while playing this game is:', games.get_max()) # plot the histogram Fig.graph_histogram(observations=games.get_list(), title='Histogram of 1,000 games', x_label='Reward', y_label='Frequency')
# simulate the game with 20 flips game.simulate(20) # store the reward self._gameRewards.append(game.get_reward()) def get_ave_reward(self): """ returns the average reward from all games""" return sum(self._gameRewards) / len(self._gameRewards) def n_neg_reward(self): n_neg = sum(1 for i in self._gameRewards if i < 0) return float(n_neg) / self.nGames # run trail of 1000 games to calculate expected reward games = SetOfGames(prob_head=0.5, n_games=1000) # print the average reward print('Expected reward when the probability of head is 0.5:', games.get_ave_reward()) FigSupport.graph_histogram(observations=games._gameRewards, title='Rewards over 1,000 games', x_label='Reward ($)', y_label='Count') print('The minimum reward in a trial of 1,000 games with a fair coin is', min(games._gameRewards)) print('The maximum reward in a trial of 1,000 games with a fair coin is', max(games._gameRewards)) print('The probability of losing money is', games.n_neg_reward())
# store the reward self._gameRewards.append(game.get_reward()) def get_ave_reward(self): """ returns the average reward from all games""" return sum(self._gameRewards) / len(self._gameRewards) def get_reward_histogram(self): return self._gameRewards def get_loss(self): count_loss = 0 for value in self._gameRewards: if 0 > value: count_loss += 1 return count_loss / len(self._gameRewards) # run trail of 1000 games to calculate expected reward games = SetOfGames(prob_head=0.5, n_games=1000) # print the average reward print('Expected reward when the probability of head is 0.5:', games.get_ave_reward()) figure.graph_histogram(observations=trial.get_reward_histogram(), title="Histogram of Rewards", x_axis="Reward ($)", Y_axis="number of games") print games.get_loss()
for k in range(0, self.repeat_time): L = Game(self.id, self.repeat_time, self.head_prop) m = L.simulate() if m <= 0: self.loss += 1 self.id += 1 self.loss = self.loss / self.repeat_time return self.loss Q = Game(1, 1000, 0.5) obs = Q.plot() max_reward = max(obs) min_reward = min(obs) print('The expected reward:', Q.repeat()) print('The minimum reward: ', min_reward) print('The maximum reward: ', max_reward) print('The probability of losing money: ', Q.prop()) obs = Q.plot() mygraph = Fig.graph_histogram(observations=obs, title='Histogram of Reward', x_label='Reward', y_label='Count', x_range=[-350, 350])
import ParameterClasses as P import MarkovModelClasses as MarkovCls import SupportMarkovModel as SupportMarkov import scr.SamplePathClasses as PathCls import scr.FigureSupport as Figs # create a cohort cohort = MarkovCls.Cohort(id=0, therapy=P.Therapies.ANTICOAGULATION) # simulate the cohort simOutputs = cohort.simulate() # graph histogram of survival times Figs.graph_histogram( data=simOutputs.get_survival_times(), title='Number of Strokes for patients with anticoagulation', x_label='Number of strokes', y_label='Counts, individuals', bin_width=1) # create a cohort cohort2 = MarkovCls.Cohort(id=0, therapy=P.Therapies.NO_DRUG) # simulate the cohort simOutputs2 = cohort2.simulate() # graph histogram of survival times Figs.graph_histogram(data=simOutputs2.get_survival_times(), title='Number of Strokes for patients without therepy', x_label='Number of strokes', y_label='Counts, individuals', bin_width=1)
def get_ave_reward(self): """ returns the average reward from all games""" return sum(self._gameRewards) / len(self._gameRewards) def get_game_times(self): return self._gametimes def get_game_rewards(self): return self._gameRewards games = SetOfGames(prob_head=0.5, n_games=1000) # print the average reward print('Expected reward when the probability of head is 0.5:', games.get_ave_reward()) print min(games.get_game_rewards()), max(games.get_game_rewards()) # create a histogram of patient survival time FigSupport.graph_histogram( observations= games.get_game_rewards(), title="Histogram of Rewards Distribution", x_label="The amount of money we win(dollar)", y_label="Count", x_range=[min(games.get_game_rewards()),max(games.get_game_rewards())]) # In 20 times filp, we would expect the maximum money we won achieved at 6 time all win "TTH": # So the maximum reward should be 6*100-250=350 # and the mininum reward shoule be 6*0-250 = -250
#Problem 7: Number of strokes (Weight 2): Estimate the mean and show the histogram of the number of stokes # that an individual who start in state “Well” may experience under both alternatives. #get mean number of strokes stroke_mean_CI_text = F.format_estimate_interval( estimate=simOutputs.get_sumState_stroketimes().get_mean(), interval=simOutputs.get_sumState_stroketimes().get_t_CI(alpha=Data.ALPHA), deci=2) print( " Estimate of mean times of stroke and {:.{prec}%} confidence interval if no drug is used:" .format(1 - Data.ALPHA, prec=0), stroke_mean_CI_text) # graph histogram of the number of strokes Figs.graph_histogram(data=simOutputs.get_stroke_times(), title='Times of Stroke if the patient takes no drug', x_label='Survival time (years)', y_label='Counts', bin_width=1) #get mean number of strokes stroke_mean_CI_text2 = F.format_estimate_interval( estimate=simOutputs2.get_sumState_stroketimes().get_mean(), interval=simOutputs2.get_sumState_stroketimes().get_t_CI(alpha=Data.ALPHA), deci=2) print( " Estimate of mean times of stroke and {:.{prec}%} confidence interval if anticoagulation is used:" .format(1 - Data.ALPHA, prec=0), stroke_mean_CI_text2) # graph histogram of the number of strokes Figs.graph_histogram( data=simOutputs2.get_stroke_times(),
import HW6.Classes as Cls import scr.FigureSupport as figureLibrary # expected rewards from 1000 games setOfGames = Cls.SetOfGames(id=1, prob_head=0.5, n_games=1000) outcomes = setOfGames.simulation() ##### Problem 1 ##### print("Estimated expected reward:", outcomes.get_ave_reward()) print("The 95% CI of expected reward:", outcomes.get_CI_reward(0.05)) print("Probability of loss in a single game:", outcomes.get_prob_loss()) print("The 95% CI of loss probability:", outcomes.get_CI_probLoss(0.05)) ##### Problem 2 ##### print( "If we run our simulation many times, " "on average 95% of the confidence intervals generated will capture the true mean." ) # plot figureLibrary.graph_histogram(data=outcomes.get_rewards(), title="Histogram of rewards", x_label='Rewards', y_label='Count')
MORTALITY_PROB = 0.1 # annual probability of mortality TIME_STEPS = 100 # simulation length REAL_POP_SIZE = 100 # size of the real cohort to make the projections for NUM_SIM_COHORTS = 1000 # number of simulated cohorts used for making projections ALPHA = 0.05 # significance level # calculating prediction interval for mean survival time # create multiple cohorts multiCohort = Cls.MultiCohort( ids=range(NUM_SIM_COHORTS), # [0, 1, 2 ..., NUM_SIM_COHORTS-1] pop_sizes=[REAL_POP_SIZE] * NUM_SIM_COHORTS, # [REAL_POP_SIZE, REAL_POP_SIZE, ..., REAL_POP_SIZE] mortality_probs=[MORTALITY_PROB] * NUM_SIM_COHORTS # [p, p, ....] ) # simulate all cohorts multiCohort.simulate(TIME_STEPS) # plot the histogram of average survival time Fig.graph_histogram(data=multiCohort.get_all_mean_survival(), title='Histogram of Mean Survival Time', x_label='Mean Survival Time (Year)', y_label='Count') # print projected mean survival time (years) print('Projected mean survival time (years)', multiCohort.get_overall_mean_survival()) # print projection interval print('95% projection interval of average survival time (years)', multiCohort.get_PI_mean_survival(ALPHA))
MORTALITY_PROB = 0.1 # annual probability of mortality TIME_STEPS = 100 # simulation length SIM_POP_SIZE = 1000 # population size of the simulated cohort ALPHA = 0.05 # significance level # create a cohort of patients myCohort = Cls.Cohort(id=1, pop_size=SIM_POP_SIZE, mortality_prob=MORTALITY_PROB) # simulate the cohort cohortOutcome = myCohort.simulate(TIME_STEPS) # plot the sample path SamplePathSupport.graph_sample_path( sample_path=cohortOutcome.get_sample_path_alive_patients(), title='Survival Curve', x_label='Time-Step (Year)', y_label='Number Survived') # plot the histogram Fig.graph_histogram(observations=myCohort.get_survival_times(), title='Histogram of Patient Survival Time', x_label='Survival Time (Year)', y_label='Count') # print the patient survival time print('Average survival time (years):', cohortOutcome.get_ave_survival_time()) print('95% CI of average survival time (years)', cohortOutcome.get_CI_survival_time(ALPHA))
# create a cohort without treatment cohort = MarkovCls.Cohort(id=0, therapy=P.Therapies.WITHOUT) # simulate the cohort simOutputs = cohort.simulate() # graph survival curve PathCls.graph_sample_path(sample_path=simOutputs.get_survival_curve(), title='Survival curve', x_label='Simulation time step', y_label='Number of alive patients') # graph histogram of survival times Figs.graph_histogram(data=simOutputs.get_survival_times(), title='Survival times of patients with Stroke', x_label='Survival time (years)', y_label='Counts', bin_width=1) # print the outcomes of this simulated cohort SupportMarkov.print_outcomes(simOutputs, 'Without therapy:') ######################################################## # create a cohort with treatment cohortwith = MarkovCls.Cohort(id=0, therapy=P.Therapies.WITH) # simulate the cohort simOutputswith = cohortwith.simulate() # graph survival curve PathCls.graph_sample_path(sample_path=simOutputswith.get_survival_curve(),
MORTALITY_PROB = 0.1 # annual probability of mortality TIME_STEPS = 100 # simulation length REAL_POP_SIZE = 100 # size of the real cohort to make the projections for NUM_SIM_COHORTS = 1000 # number of simulated cohorts used for making projections ALPHA = 0.05 # significance level # calculating prediction interval for mean survival time # create multiple cohort multiCohort = Cls.MultiCohort( ids=range(NUM_SIM_COHORTS), pop_sizes=[REAL_POP_SIZE] * NUM_SIM_COHORTS, #list of real pop sizes for length of simulations mortality_probs=[MORTALITY_PROB] * NUM_SIM_COHORTS) #Simualte all multiCohort.simulate(TIME_STEPS) #plot the histogram Fig.graph_histogram(observations=multiCohort.get_all_mean_survival(), title='Histogram of Mean Survival Time', x_label='Mean Survival Time (Year)', y_label='Count', x_range=(0, 13)) # print projected mean survival time (years) print('Projected mean survival time (years)', multiCohort.get_overall_mean_survival()) # print projection interval print('95% projection interval of average survival time (years)', multiCohort.get_PI_mean_survival(ALPHA))
import CalibrationClassesTT as Cls import CalibrationSettingsTT as P import scr.FigureSupport as Fig # initialize a calibrated model calibrated_model = Cls.CalibratedModel('CalibrationResults.csv') # simulate the calibrated model calibrated_model.simulate(P.NUM_SIM_COHORTS, P.SIM_POP_SIZE, P.TIME_STEPS) # plot the histogram of mean survival time Fig.graph_histogram( data=calibrated_model.get_all_mean_survival(), title='Histogram of Mean Survival Time', x_label='Mean Survival Time (Year)', y_label='Count', x_range=[7, 13]) # report mean and projection interval print('Mean survival time and {:.{prec}%} projection interval:'.format(1 - P.ALPHA, prec=0), calibrated_model.get_mean_survival_time_proj_interval(P.ALPHA, deci=4))
import ParameterClasses as P import MarkovModelClasses as MarkovCls import SupportMarkovModel as SupportMarkov import scr.SamplePathClasses as PathCls import scr.FigureSupport as Figs # create a cohort cohort = MarkovCls.Cohort(id=0, therapy=P.Therapies.COMBO) # simulate the cohort simOutputs = cohort.simulate() # graph survival curve PathCls.graph_sample_path(sample_path=simOutputs.get_survival_curve(), title='Survival curve', x_label='Simulation time step', y_label='Number of alive patients') # graph histogram of survival times Figs.graph_histogram(data=simOutputs.get_survival_times(), title='Survival times of patients with HIV', x_label='Survival time (years)', y_label='Counts', bin_width=1) # print the outcomes of this simulated cohort SupportMarkov.print_outcomes(simOutputs, 'Mono therapy:')
headProb = 0.5 timeSteps = 20 cohortNumber = 1000 myCohort = Model.Cohort(id=2, cohort_number=cohortNumber, head_prob=headProb) myCohort.simulate(timeSteps) print( "The probablity of flipping a head is 0.5, we flip 20 times as one game and we undergo the game 1000 times" ) print('Average expected reward (dollors):', myCohort.get_ave_value()) print('The maximum reward is:', max(myCohort.get_exp_value()), "dollars", "and the minimum reward is:", min(myCohort.get_exp_value()), 'dollars.') # plot the histogram Fig.graph_histogram(observations=myCohort.get_exp_value(), title='Histogram of Rewards', x_label='Reward', y_label='Count') #estimate the prob of losing money in this game probLoss = myCohort.get_loss_number() print('The probability of losing money in this game is:', probLoss)
self._gameRewards = [ ] # create an empty list where rewards will be stored # simulate the games for n in range(n_games): # create a new game game = Game(id=n, prob_head=prob_head) # simulate the game with 20 flips game.simulate(20) # store the reward self._gameRewards.append(game.get_reward()) def get_ave_reward(self): """ returns the average reward from all games""" return sum(self._gameRewards) / len(self._gameRewards) def get_list(self): return self._gameRewards # run trail of 1000 games to calculate expected reward games = SetOfGames(prob_head=0.5, n_games=1000) # print the average reward print('Expected reward when the probability of head is 0.5:', games.get_ave_reward()) # plot the histogram fig.graph_histogram(observations=games.get_list(), title='Histogram of Games average reward', x_label='Reward', y_label='Count')
print("Problem6") # graph survival curve PathCls.graph_sample_path(sample_path=simOutputs.get_survival_curve(), title='Survival curve-No anticoagulation', x_label='Simulation time step', y_label='Number of alive patients') PathCls.graph_sample_path(sample_path=simOutputs2.get_survival_curve(), title='Survival curve-anticoagulation', x_label='Simulation time step', y_label='Number of alive patients') #Problem7 print("Problem7") print("Estimate of mean storke times of not using anticoagulation:", simOutputs.get_stroke_range().get_mean()) print("Estimate of mean storke times of not using anticoagulation:", simOutputs2.get_stroke_range().get_mean()) Figs.graph_histogram(data=simOutputs.get_stroke_total(), title='Stroke Number of No ANTI', x_label='Number of Strokes', y_label='Counts', bin_width=1) Figs.graph_histogram(data=simOutputs2.get_stroke_total(), title='Stroke Number of WITH ANTI', x_label='Number of Strokes', y_label='Counts', bin_width=1)
) # graph survival curve PathCls.graph_sample_path( sample_path=simOutputs_ac.get_survival_curve(), title='Survival curve for anti-coagulant', x_label='Simulation time step', y_label='Number of alive patients' ) # graph histogram of number of strokes Figs.graph_histogram( data=simOutputs_no.get_nums_of_stroke(), title='Number of strokes a patient may experience without anti-coagulant', x_label='Number of strokes', y_label='Counts', bin_width=1 ) # graph histogram of number of strokes Figs.graph_histogram( data=simOutputs_ac.get_nums_of_stroke(), title='Number of strokes a patient may experience with anti-coagulant', x_label='Number of strokes', y_label='Counts', bin_width=1 ) # print the outcomes of this simulated cohort print('Problems 1 and 2: please see MarkovDiagrams.pdf')
import scr.FigureSupport as Figs # create and cohort cohort = MarkovCls.Cohort(id=1, therapy=P.Therapies.NONE) simOutputs = cohort.simulate() # graph survival curve PathCls.graph_sample_path( sample_path=simOutputs.get_survival_curve(), title='Survival Curve of Women Screened via Digital Mammography', x_label='Simulation time step', y_label='Number of alive patients') # graph histogram of survival times Figs.graph_histogram( data=simOutputs.get_survival_times(), title='Survival Times of Women Screened via Digital Mammography', x_label='Survival time (years)', y_label='Counts', bin_width=2) # graph histogram of number of strokes # Figs.graph_histogram( # data=simOutputs.get_if_developed_stroke(), # title='Number of Strokes per Patient', # x_label='Strokes', # y_label='Counts', # bin_width=1 # )
population = Cohort(id=1, therapy=Therapies.POPULATION) # simulate the cohorts standardOutputs = standard.simulate() populationOutputs = population.simulate() # graph survival curve PathCls.graph_sample_path(sample_path=standardOutputs.get_survival_curve(), title='Survival curve for standard testing', x_label='Simulation time step', y_label='Number of alive patients') # graph histogram of survival times Figs.graph_histogram(data=standardOutputs.get_survival_times(), title='Survival times of patients for standard testing', x_label='Survival time (years)', y_label='Counts', bin_width=1) # graph survival curve PathCls.graph_sample_path(sample_path=populationOutputs.get_survival_curve(), title='Survival curve for population testing', x_label='Simulation time step', y_label='Number of alive patients') # graph histogram of survival times Figs.graph_histogram(data=populationOutputs.get_survival_times(), title='Survival times of patients for population testing', x_label='Survival time (years)', y_label='Counts', bin_width=1)
# simulate all game sets multipleGameSets.simulation() print("") print("Checking against the output from HW6 code:") # print projected mean reward print(' Predicted mean game reward when the coin is fair, P(head)=0.50:', multipleGameSets.get_mean_total_reward()) # print projection interval print(' 95% prediction interval of the average game reward:', multipleGameSets.get_PI_total_reward(0.05)) # plot figureLibrary.graph_histogram( data=multipleGameSets.get_all_total_rewards(), title="Histogram of the Gambler's Total Game Rewards from 10 Games", x_label='Mean Game Rewards', y_label='Count') # Trial 2 # # create a multiple game sets multipleGameSets=Cls.MultipleGameSets(ids=range(1000, 2000), prob_head=0.45, n_games_in_a_set=10) # simulate all game sets multipleGameSets.simulation() # print projected mean reward print(' Predicted mean game reward when the coin is unfair, P(head)=0.45:', multipleGameSets.get_mean_total_reward()) # print projection interval print(' 95% prediction interval of the average game reward:', multipleGameSets.get_PI_total_reward(0.05))
count_loss = 0 for value in self._gameRewards: if value < 0: count_loss += 1 return count_loss / len(self._gameRewards) # Calculate expected reward of 1000 games trial = SetOfGames(prob_head=0.5, n_games=1000) print("The average expected reward is:", trial.get_ave_reward()) # Problem 1: Create histogram of winnings figureLibrary.graph_histogram( observations=trial.get_reward_list(), title="Histogram of Rewards from 1000 Games", x_label="Game Rewards", y_label="Frequency") # minimum reward is -$250 if {T, T, H} never occurs. # maximum reward is $350 if {T, T, H} occurs 6 times (if you increase the number of games you might see this outcome). # find minimum and maximum reward in trial print("In our trial, the maximum reward is:", trial.get_max()) print("In our trial, the minimum reward is:", trial.get_min()) # Problem 2: Find the probability of a loss print("The probability of a single game yielding a loss is:", trial.get_probability_loss()) LOSS_PROB = 0.609 # annual probability of mortality SIM_POP_SIZE = 1000 # the population size of the simulated cohort
import HW5 import scr.FigureSupport as Fig MySimulation = HW5.AllGames(odds_heads=.5, num_games=1000) y = MySimulation.simulate() #SamplePathSupport.graph_sample_path( # sample_path=cohortoutcomes.get_sample_path(), # title="Winnings Curve", # x_label="Amount Won", #y_label="Number of Times Won") Fig.graph_histogram(observations=y, title="Histogram of Patients", x_label="Amount Won", y_label="Number of Times Won") print(MySimulation.get_max()) print(MySimulation.get_min()) ##ANSWER TO QUESTION ONE: #The minimum is -250 because that's what you pay to play. So if you win 0 times, you get $-250 #The theoretical maximum is $350 because the max times you can get the winning combination for # 20 flips is 6 times so you can win $600 - $250 to play = $350. In this case, however, #we saw that the maximum is $250 for our observed games. ##Answer to QUESTION TWO: print(MySimulation.LoseMoney() / 1000) #Based on this, there is a 60.7% chance of losing money with this game.
print ("The next realization of the expected value") print ("will fall in the projection interval", myRounds.get_expected_value_PI(ALPHA)) print ("with probability 0.95.") print() print ("The next realization of the probability of loss") print ("will fall in the projection interval", myRounds.get_expected_loss_PI(ALPHA)) print ("with probability 0.95.") print() print("Minimum value:", myRounds.get_min_tally()) print("Minimum possible value:", -entry_fee) print("Maximum value:", myRounds.get_max_tally()) print("Maximum possible value: 350") print() print("Based on a coin toss game with the following parameters:") print("Probability of getting Heads:", head_prob) print("Number of coin tosses per game:", n_tosses) print("Number of rounds of games:", num_rounds) print("Entry fee to play each game:", entry_fee) print("Reward for each winning sequence:", reward) print("Alpha=",ALPHA) print("Winning sequence:", winning_sequence) # plot the histogram Fig.graph_histogram( observations=myRounds.get_total_tally1(), title='Histogram of Rewards', x_label='Rewards ($)', y_label='Rounds')
#get list of game rewards (NOT the average), because histogram requires just the list def get_list_of_game_rewards(self): return self._list_of_game_rewards def get_loss_probability(self): for game_result in self._list_of_game_rewards: if game_result < 0: self._overall_lost_money_counter += 1 return self._overall_lost_money_counter/1000 * 100 myCohortofGames = cohort_of_games(number_of_games=1000, number_of_flips=20, prob_of_heads=0.4) myCohortofGames.simulate() print(myCohortofGames.get_average_reward_amount()) #PROBLEM 1 #create histogram of reward amounts, note the input requires the list of rewards FigSupport.graph_histogram( observations=myCohortofGames.get_list_of_game_rewards(), title="Histogram of reward amounts", x_label="reward amount", y_label="number of trials" ) #PROBLEM 2 #In 1000 trials, what's the probability of losing money? #formula is prob = # of trials with reward <0 / 1000 print(myCohortofGames.get_loss_probability(),"% chance of losing money")
import HW4Solution as La import scr.FigureSupport as Fig myGame = La.SetOfGames(prob_head=0.5, n_games=1000) print(myGame.get_maximum()) print(myGame.get_minimum()) print(myGame.get_set_rewards()) # plot the histogram Fig.graph_histogram(observations=myGame.get_set_rewards(), title='Histogram of Rewards', x_label='Rewards', y_label='Count')
return sum(self._CountTotalLoss)/sum(self._CountTotalWin) class SetOfGamesOutcomes: def __init__(self, simulated_set_outcomes): # extracts outcomes of the simulated set of games self._simulated_set_outcomes = simulated_set_outcomes #not sure if I should move forward with this piece # run trail of 1000 games to calculate expected reward games = SetOfGames(prob_head=0.5, n_games=1000) # print the average reward print('Expected reward when the probability of head is 0.5:', games.get_ave_reward()) # print the prob of loss print ('Probability of losing money', games.get_prob_loss()) # Histogram of rewards for 1000 games FigSupport.graph_histogram( observations= SetOfGames.get_reward(games), title='Histogram of Rewards', x_label='Reward', y_label='Count') # Answer 1: min is -150, max is 250 # Answer 2: Prob of losing money is 100%