def estimate_pi(n_trials): """Sample x,y ~ U(0,1) and test if x^2 + y^2 < 1.""" n_hits_in_circle = 0 for _ in range(n_trials): x, y = unif_rand(), unif_rand() f = circle_func(x, y) if f < 1: n_hits_in_circle += 1 estimate = 4 * n_hits_in_circle / n_trials return estimate
def play_game(): player_amt = -5 # player initially pays 5 units u = unif_rand() success_counter = 0 payout = 1 while u > 0.5: success_counter += 1 payout = 2 * payout player_amt += payout u = unif_rand() return player_amt
def sample_die_from_unif(N=6): """Simulate an N-sided die.""" u = unif_rand() x = u * N for n in range(1, N + 1): if x <= n: return n
def simulate_game(max_iter): """Gambler wins with prob > 0 and the game stops when either: i) the gambler runs out of money, or ii) house runs out of money, or iii) max_iter reached. Params: max_iter (int): upper bound on number of rounds in game. Returns: curr_iter (int): num iterations reached at end of game. Notes: "game" is synonymous with "trial". """ # hardcoded vals to make parallelization easier... gambler_limit=100 house_limit=200 gambler_win_prob=0.5 curr_iter = 0 # simulate game while gambler_limit and house_limit and curr_iter < max_iter: curr_iter += 1 u = unif_rand() payout = 1 if u > gambler_win_prob else -1 gambler_limit += payout house_limit += -payout return curr_iter
def simulate_gambler(max_iter=1e6, gambler_limit=100, house_limit=200, gambler_win_prob=0.5): """Gambler wins with prob > 0 and the game stops when either: i) the gambler runs out of money, or ii) house runs out of money, or iii) max_iter reached. """ curr_iter = 0 gambler_val_path = [gambler_limit] # cumulative win/loss each round while gambler_limit and house_limit and curr_iter < max_iter: curr_iter += 1 u = unif_rand() payout = 1 if u > gambler_win_prob else -1 gambler_limit += payout house_limit += payout gambler_val_path += [gambler_limit] return gambler_val_path, curr_iter
def est_sample(n_bernoulli): bernoulli_sum = np.sum([unif_rand() for _ in range(n_bernoulli)]) s = (bernoulli_sum - (n_bernoulli / 2)) * (1 / (np.sqrt(n_bernoulli / 12))) return s
def estimate(): x, y = unif_rand(), unif_rand() z = x**2 + y**2 return z <= 1
def sample_pt(d=2): """Sample a d-dimensional point in the cube.""" pt = [unif_rand() for _ in range(d)] return pt