. seed- seed-:
const unsigned long maxshort = 65536;
const unsigned long multiplier = 1194211693;
const unsigned long adder = 12345;
randSeed. (seeding) .
seed- - time. , time <time.h>. 0 time (32-) , , . 1- 1970 1- 1904 . , :
// seed-
RandomNumber::RandomNumber (unsigned long s)
{
if (s == 0)
randSeed = time(0); // time
else
randSeed = s; // seed-
}
seed-:
randSeed=multiplier*randSeed+adder;
16 32- randSeed (" ") . 0 65535, 16 . 0n-1, n. Random(n).
// 0<=value<=n-1<65536
unsigned short RandomNumber::Random (unsigned long n)
{
randSeed=multiplier*randSeed+adder;
return (unsigned short) ((randSeed)>>16)%n);
}
Random(maxshort), 0 maxshort-1. double(maxshort) 0<=fRandom() < 1.0.
double RandomNumber::fRandom (void)
{
return Random(maxshort)/double(maxshort);
}
RandomNumber "random.h".
: . RandomNumber 10 . (head)1 , - . 0-10. , 0 10 10 - . , . - 0-10, , 4-6. (50 0000) . head , 0,1,,10.
|
|
head[i] (0<=i<=10) - 50 000 , i 10 .
3.
10 . Random 2 , 0 , 1 . TossCoins coinToss Random-Number, seed-. , TossCoins . 10 , CoinToss.Random(2). .
. (occurences) y , . i , i ,
heads[i]/float(NTOSSES)
* 1- 72- . .
#include <iostream.h>
#include <iomanip.h>
#include "random.h" //
// "" numberCoins
//
int TossCoins(int numberCoins)
{
static RandomNumber coinToss;
int if tosses = 0;
for (i=0;i<numberCoins;i++)
// Random (2)=1
tosses += coinToss.Random(2);
return tosses;
}
void main (void)
{
//
const int NCOINS = 10;
const long NTOSSES = 50000;
// heads [0]=
// heads [1]= ..
long i, heads [NCOINS+1];
int j, position;
// heads
for (j=0;j<=NCOINS+1; j++)
heads [j] = 0;
//"" NTOSSES
// heads
for (i=0;i<NTOSSES; i++)
heads [TossCoins(NCOINS)] ++;
//
for (i=0;i < NCOINS+1;I++)
{
position=int(float(heads[i])/float(NTOSSES)*72);
cout << setw(6) << i << " ";
for (j=0;j<position-1; j++)
cout << " ";
// ' *' i
cout << ' *' << endl;
}
}