三门问题简介
奖品随机分布在3扇门后,客户随机选择其中一扇,主持人打开另外两扇中任意没有奖品的一扇,问客户选择以下哪种策略赢面更大:
1.坚持原来的选择
2.改选剩下的那扇未打开的门
测试代码及结果
#include <iostream>
#include <random>
#include <vector>
using namespace std;
int get_random_number(int a, int b)
{
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> distrib(a, b);
int random_number = distrib(gen);
return random_number;
}
int main()
{
int test_time = 0, right_door = 0, right_time = 0, choose_door = 0, open_door = 0;
double sum = 0;
vector<int> wait_open_door;
cout << "请输入测试次数" << endl;
cin >> test_time;
cout << "第一次测试:不更改门";
for (int cptime = 1; cptime <= test_time; cptime++)
{
right_door = get_random_number(1, 3);
choose_door = get_random_number(1, 3);
if (right_door == choose_door)
{
wait_open_door.clear();
for (int ncptime = 1; ncptime <= 3; ncptime++)
{
if (ncptime != choose_door)
{
wait_open_door.push_back(ncptime);
}
}
open_door = wait_open_door[get_random_number(0, wait_open_door.size() - 1)];
right_time++;
}
else if (right_door != choose_door)
{
wait_open_door.clear();
for (int ncptime = 1; ncptime <= 3; ncptime++)
{
if (ncptime != choose_door && ncptime != right_door)
{
open_door = ncptime;
}
}
}
}
sum = static_cast<double>(right_time) / static_cast<double>(test_time);
cout << "测试完毕。" << endl << "测试次数:" << test_time << endl << "概率为:" << sum << endl;
cout << "第二次测试:更改门";
sum = 0, right_door = 0, right_time = 0, choose_door = 0, open_door = 0;
wait_open_door.clear();
for (int cptime = 1; cptime <= test_time; cptime++)
{
right_door = get_random_number(1, 3);
choose_door = get_random_number(1, 3);
if (right_door == choose_door)
{
wait_open_door.clear();
for (int ncptime = 1; ncptime <= 3; ncptime++)
{
if (ncptime != choose_door)
{
wait_open_door.push_back(ncptime);
}
}
open_door = wait_open_door[get_random_number(0, wait_open_door.size() - 1)];
int temp = 0;
for (int ncptime = 1; ncptime <= 3; ncptime++)
{
if (ncptime != choose_door && ncptime != open_door)
{
temp = ncptime;
}
}
choose_door = temp;
}
else if (right_door != choose_door)
{
wait_open_door.clear();
for (int ncptime = 1; ncptime <= 3; ncptime++)
{
if (ncptime != right_door && ncptime != choose_door)
{
open_door = ncptime;
}
}
int temp = 0;
for (int ncptime = 1; ncptime <= 3; ncptime++)
{
if (ncptime != choose_door && ncptime != open_door)
{
temp = ncptime;
}
}
choose_door = temp;
}
if (choose_door == right_door)
{
right_time++;
}
}
sum = static_cast<double>(right_time) / static_cast<double>(test_time);
cout << "测试完毕。" << endl << "测试次数:" << test_time << endl << "概率为:" << sum << endl;
}
请输入测试次数
100000
第一次测试:不更改门测试完毕。
测试次数:100000
概率为:0.33103
第二次测试:更改门测试完毕。
测试次数:100000
概率为:0.66814
请输入测试次数
1000000
第一次测试:不更改门测试完毕。
测试次数:1000000
概率为:0.333417
第二次测试:更改门测试完毕。
测试次数:1000000
概率为:0.666994
请输入测试次数
100000000
第一次测试:不更改门测试完毕。
测试次数:100000000
概率为:0.333328
第二次测试:更改门测试完毕。
测试次数:100000000
概率为:0.66656
剑客云提供云计算支持:https://cloud.swordsman.com.cn/
总结
如果每次不选择更改,那么概率将趋近于三分之一。如果每次都选择更改,那么概率将趋近于三分之二。