LoginSignup
4
5

More than 5 years have passed since last update.

rubyでモンティホールをシミュレートしてみた

Posted at

モンティホール問題とは(wikipdiaより引用)

モンティ・ホール問題(モンティ・ホールもんだい、Monty Hall problem)は確率論の問題で、ベイズの定理における事後確率、あるいは主観確率の例題のひとつとなっている。モンティ・ホール (Monty Hall、本名 Monte Halperin) が司会者を務めるアメリカのゲームショー番組、「Let's make a deal」の中で行われたゲームに関する論争に由来する。 一種の心理トリックになっており、確率論から導かれる結果を説明されても、なお納得しない者が少なくないことから、ジレンマあるいはパラドックスとも称される。「直感で正しいと思える解答と、論理的に正しい解答が異なる問題」の適例とされる。
なお、モンティ・ホール問題と実質的に同型である「3囚人問題」については、かつて日本で精力的に研究された。

ソース

debug = false
num_itr = 10000

[true, false].each do |do_change|
  num_seikai = 0
  num_itr.times.each do |n|

    seikai = rand(3)
    ans = rand(3)
    puts "first select: " +  ans.to_s if debug
    mon = nil
    3.times do | c |
      if c != seikai && c != ans
        mon = c
        break
      end
    end
    puts "mon: " + mon.to_s if debug
    final_ans = ans
    if do_change
      3.times do | c |
        if c != ans && c != mon
          final_ans = c
          break
        end
      end
      puts "change to " + final_ans.to_s if debug
    end

    if final_ans == seikai
      puts "seikai" if debug
      num_seikai += 1
    else
      puts "hazure" if debug
    end
    puts "" if debug
  end
  puts (do_change ? "change" : "no change")
  puts "seikai ritsu: " + (num_seikai.to_f / num_itr * 100) .to_s
end

結果

change
seikai ritsu: 66.32000000000001
no change
seikai ritsu: 33.379999999999995
4
5
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5