Skip to content

Instantly share code, notes, and snippets.

@nileshtrivedi
Created January 2, 2021 05:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nileshtrivedi/bc2bd0d6a6f97239e4675eb12aa6a932 to your computer and use it in GitHub Desktop.
Save nileshtrivedi/bc2bd0d6a6f97239e4675eb12aa6a932 to your computer and use it in GitHub Desktop.
Simulation of Parrondo's Paradox
def coin(win) = rand(1000) > (1000 - win) ? 1 : -1
def a(capital) = coin(495) # 49.5% chance of winning
def b(capital) = (capital % 3 != 0) ? coin(745) : coin(95)
def simulate(strategy, count)
(strategy * count).reduce(100) do |capital,game|
capital + send(game, capital)
end
end
# Simulate [:a] 100 times
result = 100.times.map { |i| simulate([:a], 10_000) }.sum / 100
puts "Average remaining capital after playing A: #{result}"
result = 100.times.map { |i| simulate([:b], 10_000) }.sum / 100
puts "Average remaining capital after playing B: #{result}"
result = 100.times.map { |i| simulate([:a, :b], 5_000) }.sum / 100
puts "Average remaining capital after playing A,B: #{result}"
result = 100.times.map { |i| simulate([:a, :a, :b, :b], 2_500) }.sum / 100
puts "Average remaining capital after playing A,A,B,B: #{result}"
result = 100.times.map { |i| simulate([:a, :a, :a, :b, :b, :b], 1667) }.sum / 100
puts "Average remaining capital after playing A,A,A,B,B,B: #{result}"
=begin
Sample run
$ ruby parrondo.rb
Average remaining capital after playing A: -21
Average remaining capital after playing B: -15
Average remaining capital after playing A,B: 32
Average remaining capital after playing A,A,B,B: 245
Average remaining capital after playing A,A,A,B,B,B: 86
=end
@nileshtrivedi
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment