【发布时间】:2017-11-03 21:46:48
【问题描述】:
我收到了一道关于概率的数学题。它是这样的:
有 1000 张彩票,每张有 1000 张彩票。您决定每张彩票购买 1 张彩票。您至少赢得一个彩票的概率是多少?
我能够在纸上进行数学运算(到达 1 - (999/1000)^1000),但是我想到了在我的计算机上进行随机实验的大规模迭代。所以,我输入了一些代码——确切地说是两个版本,而且都发生了故障。
代码1:
#include<iostream>
#include <stdlib.h>
using namespace std;
int main() {
int p2 = 0;
int p1 = 0;
srand(time(NULL));
for (int i = 0; i<100000; i++){
for(int j = 0; j<1000; j++){
int s = 0;
int x = rand()%1000;
int y = rand()%1000;
if(x == y)
s = 1;
p1 += s;
}
if(p1>0)
p2++;
}
cout<<"The final probability is = "<< (p2/100000);
return 0;
}
代码 2:
#include<iostream>
#include <stdlib.h>
using namespace std;
int main() {
int p2 = 0;
int p1 = 0;
for (int i = 0; i<100000; i++){
for(int j = 0; j<1000; j++){
int s = 0;
srand(time(NULL));
int x = rand()%1000;
srand(time(NULL));
int y = rand()%1000;
if(x == y)
s = 1;
p1 += s;
}
if(p1>0)
p2++;
}
cout<<"The final probability is = "<< (p2/100000);
return 0;
}
代码3(参考了一些进阶的文字,但大部分没看懂):
#include<iostream>
#include <random>
using namespace std;
int main() {
int p2 = 0;
int p1 = 0;
random_device rd;
mt19937 gen(rd());
for (int i = 0; i<100000; i++){
for(int j = 0; j<1000; j++){
uniform_int_distribution<> dis(1, 1000);
int s = 0;
int x = dis(gen);
int y = dis(gen);
if(x == y)
s = 1;
p1 += s;
}
if(p1>0)
p2++;
}
cout<<"The final probability is = "<< (p2/100000);
return 0;
}
现在,所有这些代码都输出相同的文本:
最终概率为=1 进程以退出代码 0 结束
似乎 rand() 函数在循环的所有 100000 次迭代中一直在输出相同的值。我无法解决这个问题。
我也尝试使用 randomize() 函数而不是 srand() 函数,但它似乎不起作用并给出了奇怪的错误,例如:
error: ‘randomize’ was not declared in this scope
randomize();
^
我认为 randomize() 在 C++ 的更高版本中已经停止使用。
我知道我在很多方面都错了。如果您能耐心地解释我的错误并告诉我一些可能的更正,我将不胜感激。
【问题讨论】:
标签: c++ random probability discrete-mathematics