Q:用实验模拟N 次掷骰子,并在计算两个1 到 6 之间的随机整数之和时记录每个值的出现频率以验证它们的概率。N 要多大才能够保证你的经验数据和准确数据的吻合程度达到小数点后三位。
A:C++代码:
int MinmunDiceRollingTimesForGivenAccurancy(int accurancy)
{
int SIDES = 6;
double *dist = new double[2 * SIDES + 1];
double *hist = new double[2 * SIDES + 1];
double *sum = new double[2 * SIDES + 1];
double N=0.0f;
for (int t = 0; t < 2 * SIDES + 1;t++)
{
dist[t] = 0.0f;
hist[t] = 0.0f;
sum[t] = 0.0f;
}
//概率计算;
for (int i = 1; i < SIDES+1;i++)
{
for (int j = 1; j < SIDES+1;j++)
{
dist[i + j] += 1.0;
}
}
for (int k = 2; k < 2 * SIDES + 1;k++)
{
dist[k] /= 36.0;//理论上的每种结果的概率计算;
}
//频率计算;
srand((unsigned)time(NULL));
int m1, m2;
do
{
m1 = (rand() % SIDES) + 1;
m2 = (rand() % SIDES) + 1;
cout << m1 << " , " << m2<<endl;
sum[m1 + m2] +=1.0;
N+=1.0;
for (int p = 2; p < 2 * SIDES + 1; p++)
{
hist[p] =sum[p]/N;
cout << hist[p] << "; ";
}
} while ((!(floor(hist[2]*1000)==floor(dist[2]*1000)))||
(!(floor(hist[3] * 1000) == floor(dist[3] * 1000))) ||
(!(floor(hist[4] * 1000) == floor(dist[4] * 1000)))||
(!(floor(hist[5] * 1000) == floor(dist[5] * 1000)))||
(!(floor(hist[6] * 1000) == floor(dist[6] * 1000)))||
(!(floor(hist[7] * 1000) == floor(dist[7] * 1000)))||
(!(floor(hist[8] * 1000) == floor(dist[8] * 1000)))||
(!(floor(hist[9] * 1000) == floor(dist[9] * 1000)))||
(!(floor(hist[10] * 1000) == floor(dist[10] * 1000))) ||
(!(floor(hist[11] * 1000) == floor(dist[11] * 1000))) ||
(!(floor(hist[12] * 1000) == floor(dist[12] * 1000))) );
return N;
}
Q:用实验模拟N 次掷骰子,并在计算两个1 到 6 之间的随机整数之和时记录每个值的出现频率以验证它们的概率。N 要多大才能够保证你的经验数据和准确数据的吻合程度达到小数点后三位。
A:C++代码:
output:N=306341=0.3e+06;