0
0

More than 1 year has passed since last update.

【python】モンティホール問題

Posted at

モンティホール問題とは

プレーヤーの前に閉じた3つのドアがあって、1つのドアの後ろには景品の新車が、2つのドアの後ろには、はずれを意味するヤギがいる。プレーヤーは新車のドアを当てると新車がもらえる。プレーヤーが1つのドアを選択した後、司会のモンティが残りのドアのうちヤギがいるドアを開けてヤギを見せる。

ここでプレーヤーは、最初に選んだドアを、残っている開けられていないドアに変更してもよいと言われる。
ここでプレーヤーはドアを変更すべきだろうか?

wikipediaより引用
https://ja.wikipedia.org/wiki/%E3%83%A2%E3%83%B3%E3%83%86%E3%82%A3%E3%83%BB%E3%83%9B%E3%83%BC%E3%83%AB%E5%95%8F%E9%A1%8C

pythonによるシミュレーション

monty_hall.py
import random

def monty_hall(n_trial=1000, change_door=True):
  n_wins = 0
  for i in range(n_trial):
    doors = [0, 0, 0]
    win_place = random.randint(0, 2)
    doors[win_place] = 1
    choice = random.randint(0, 2)

    # ハズレドアの1つを公開
    if doors[choice] == 0:
      revealed = 3 - choice - win_place
    else:
      revealed = (choice + random.randint(1, 2)) % len(doors)

    # ドアを変えたければ変える
    if change_door:
      choice = 3 - revealed - choice

    if doors[choice] == 1:
      n_wins += 1

  return n_wins

n = 1000
print("ドアを変えた場合 : {} 回中勝ち {} 回。".format(n, monty_hall(n_trial=n, change_door=True)))
print("ドアを変えない場合 : {} 回中勝ち {} 回。".format(n, monty_hall(n_trial=n, change_door=False)))

ドアが3つしかないのでドアインデックスの和を利用することで少し簡潔に書くことができる。

結果

ドアを変えた場合 : 1000 回中勝ち 668 回。
ドアを変えない場合 : 1000 回中勝ち 354 回。
0
0
0

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
0
0