Helping a friend do a job in graduate management is a simulation of the inventory system, where the retailer's demand is a random number with Poisson distribution. We need to use C language to generate random numbers with Poisson distribution. By looking for materials and programming practices, a simple program is written as follows for your reference.

The code is as follows:

Algorithm poisson random number (Knuth ):

Init:
Let L & larr; exp (& minus; & lambda;), k & larr; 0 and p & larr; 1.
Do:
K & larr; k + 1.
Generate uniform. random number u in [0, 1] and let p & larr; p × u.
While p> = L.
Return (k & minus; 1 ).

The code for the Poisson distribution random number in C language is as follows:

​The code is as follows:

# Include <stdio. h>
# Include <math. h>
# Include <time. h>

Double U_Random ();
Int possion ();


Void main ()
{
Double u = U_Random ();
Int p = possion ();
Printf ("% fn", u );
Printf ("% dn", p );

}

Int possion ()/* generates a random number with a Poisson distribution. Lamda is the average number */
{
Int Lambda = 20, k = 0;
Long double p = 1.0;
Long double l = exp (-Lambda);/* it is defined as long double for precision, and exp (-Lambda) is a decimal near 0 */
Printf ("%. 15Lfn", l );
While (p> = l)
{
Double u = U_Random ();
P * = u;
K ++;
}
Return K-1;
}

Double U_Random ()/* generates a 0 ~ Random number between 1 */
{
Double f;
Srand (unsigned) time (NULL ));
F = (float) (rand () % 100 );
/* Printf ("% fn", f );*/
Return f/100;
}

Related Artilce:Curl_easy_perform problem in Libcurl in C + +​​