1.1.35 simulate the dice. The following code calculates the accurate probability distribution of the sum of every two dice:
Public class test
{
Public static void main (string [] ARGs)
{
Int sides = 6;
Double [] Dist = new double [2 * sides + 1];
For (INT I = 1; I <= sides; I ++)
For (Int J = 1; j <= sides; j ++)
Dist [I + J] + = 1.0;
For (int K = 2; k <= 2 * sides; k ++)
Dist [k]/= 36.0;
}
}
The value of DIST [I] is the sum of two dice and the probability of I. Use an experiment to simulate n times of throwing dice, and calculate the occurrence frequency of a random integer between two 1 and six and record each value to verify their probability. N how big is it to ensure that your experience data and accurate data are consistent to three digits after the decimal point?
Solution: About 10 ^ 8 times
Public class test
{
Public static void main (string [] ARGs)
{
Int sides = 6;
// A two-dimensional array. The first dimension uses the number of points and two dice. The first dimension stores the theoretical probability of the first element, and the second dimension stores the number of times that the second element has been thrown, actual probability of element 3 stored in the second dimension
Double [] [] Dist = new double [2 * sides + 1] [3];
For (INT I = 1; I <= sides; I ++)
For (Int J = 1; j <= sides; j ++)
Dist [I + J] [0] + = 1.0;
//
For (int K = 2; k <= 2 * sides; k ++)
Dist [k] [0]/= 36.0;
//
Int n = 0;
Int dist1;
Int dist2;
// If isok = true, it indicates that the actual probability meets the precision requirement.
Boolean isok = false;
While (! Isok)
{
N ++;
Dist1 = stdrandom. Uniform (1, sides + 1 );
Dist2 = stdrandom. Uniform (1, sides + 1 );
Dist [dist1 + dist2] [1] ++;
Dist [dist1 + dist2] [2] = DIST [dist1 + dist2] [1]/n;
//
Isok = true;
// The accuracy is deemed to be satisfied only when the actual probability of all points and values meet the precision.
For (INT I = 2; I <= 2 * sides; I ++)
{
If (math. Abs (Dist [I] [0]-Dist [I] [2])> = 0.0001)
{
Isok = false;
Break;
}
} // End
} // End while
Stdout. printf ("limt times is % d", N );
}
}
Algs4-1.1.35 simulated dice