Skip to content

Instantly share code, notes, and snippets.

@wengzilla
Created May 25, 2019 14:24
Show Gist options
  • Save wengzilla/3c99bd7947a2aa4bb9eab6aed9a57cdc to your computer and use it in GitHub Desktop.
Save wengzilla/3c99bd7947a2aa4bb9eab6aed9a57cdc to your computer and use it in GitHub Desktop.
class RandomWalk
attr_accessor :outcome, :step_count
def initialize(upper_bound, lower_bound, step_size, win_probability)
@step_count = 0
@current_position = 0
@upper_bound = upper_bound
@lower_bound = lower_bound
@step_size = step_size
@win_probability = win_probability
simulate
end
def simulate
while outcome.nil?
@step_count += 1
if rand(0) < @win_probability
@current_position += @step_size
else
@current_position -= @step_size
end
end
end
def outcome
if @current_position >= @upper_bound
:win
elsif @current_position <= @lower_bound
:loss
end
end
def win?
outcome == :win
end
end
class MonteCarlo
def initialize(trials, params)
@trials = trials
@trial_count = 0
@step_count = 0
@win_count = 0
@params = params
run
end
def run
while(@trial_count < @trials)
random_walk = RandomWalk.new(*@params.values)
@step_count += random_walk.step_count
@win_count += 1 if random_walk.win?
@trial_count += 1
end
end
def avg_steps
@step_count / @trials
end
def win_walkaway_probability
@win_count * 1.0 / @trials
end
def loss_walkaway_probability
1 - win_walkaway_probability
end
def print_results
puts "Average steps: #{avg_steps}"
puts "Probability to walkaway with win: #{win_walkaway_probability}"
puts "Probability to walkaway with loss: #{loss_walkaway_probability}"
end
end
params = {win_walkaway: 333, loss_walkaway: -1000, bet_size: 1, win_probability: 0.50}
m = MonteCarlo.new(1000, params)
m.print_results
# r = RandomWalk.new(win_walkaway, loss_walkaway, bet_size, win_probability)
# puts r.outcome
# puts r.step_count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment