Created
January 2, 2021 05:43
-
-
Save nileshtrivedi/bc2bd0d6a6f97239e4675eb12aa6a932 to your computer and use it in GitHub Desktop.
Simulation of Parrondo's Paradox
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Twitter thread about this: https://twitter.com/nileshtrivedi/status/1345230833431429120