Reprinted from:http://blog.csdn.net/beyond0824/article/details/6009908

< a >

How to generate random numbers in C/s + +: The rand () function, the Srand () function, and the random (int number) function in the C language/c++ are used here.

(1) If you want to generate random numbers without setting the range, you can just use RAND (): rand () returns a random number, ranging from 0 to Rand_max. Rand_max is defined in stdlib.h with a value of 2147483647.

For example:

#include <stdio.h>

#include <stdlib.h>

void Main ()

{

for (int i=0;i<10;i+)

printf ("%d/n", Rand ());

}

(2) If you want to randomly generate a number in a range, you can define a random (int number) function in the macro definition, and then call the random () function directly inside main ():

For example: Randomly generate 10 0~100 numbers:

#include <stdio.h>

#include <stdlib.h>

#define RANDOM (x) (rand ()%x)

void Main ()

{

for (int x=0;x<10;x++)

printf ("%d/n", Random (100));

}

(3) But the random number generated by the above two examples can only be a one-time, if you run the second time the output will be the same as the first time. This is related to the Srand () function. The Srand () is used to set the random number seed when rand () produces a random number. Before calling the rand () function to produce a random number, the random number seed (seed) must be set with Srand (), and if no random number seed is set, rand () automatically sets the random number seed to 1 when called. The two examples above are that because no random number seed is set, each random number seed is automatically set to the same value of 1, which results in the same random values generated by rand ().

Srand () function definition: void srand (unsigned int seed);

You can usually use the return value of Geypid () or time (0) as the seed

If you use Time (0), add the header file #include<time.h>

For example:

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#define RANDOM (x) (rand ()%x)

void Main ()

{

Srand ((int) time (0));

for (int x=0;x<10;x++)

printf ("%d/n", Random (100));

}

So the results of two runs will be different!!

< two >

The function RAND () in the standard C library can generate a random number between 0~rand_max, where Rand_max is an integer defined in Stdlib.h, which is related to the system.

The rand () function does not have an input parameter and is directly referenced by the expression rand (), for example, you can print two random numbers using the following statement:

printf ("Random numbers is:%i%i/n", Rand (), Rand ());

Because the rand () function produces integers in the order specified, each execution of the above statement prints the same two values, so that the C language is not random in the true sense.

In order for the program to generate random values for a new sequence each time it executes, we usually provide a new random seed for the random number generator. The function Srand () (from stdlib.h) can spread the seed for the random number generator. As long as the seed is different, the rand () function produces a different sequence of random numbers. Srand () is called the initializer of the random number generator.

Routines:

File name: ** rand_srand.c**

/* This program generates and prints ten random integers between 1 and rand_max*/

#include <stdio.h>

#includ <stdlib.h>

int main ()

{

usigned int seed; /* Declare the seed of the initializer, note the usigned int type */

int k;

Pringt ("Enter a positive integer seed value:/n");

scanf ("%u", &seed);

Srand (seed);

printf ("Random Numbers are:/n");

for (k = 1; k <=; k++)

printf ("%i", Rand ());

printf ("/n");

return 0;

}

You will find that when you provide the seed in the same time, the sequence of random numbers is also the same. And when the seed is 1 o'clock, the same as when the Srand () function is not used, that is, the rand () function initializes the seed value to 1 by default;

The prototypes of these two functions in stdlib.h are:

int rand ();

void Srand (unsigned int);

Expand:

x = rand ()%11; /* Generates a random integer between 1~10 */

y = rand ()%51-25; /* Generate a random integer between 25 ~ 25 */

z = (double) rand ()/rand_max) * (B-A) + a;/* generation interval [b] random number */

< three >

1-0:microsoft VC generates a random number principle:

The Srand () and Rand () functions. It is essentially using linear with congruential, Y=ax+b (mod m). where A,b,m are constants. So Rand's production is determined by the x,x called Seed. Seed needs to be set in the program and normally takes the system time as a seed. It produces a small correlation between the random number, the value range is 0-32767 (int), that is, double-byte (16 digits), if the unsigned int double byte is 65535, four bytes is 4294967295, can generally meet the requirements.

1-1: Linear with congruential:

?/p>

where M is the modulus, A is the multiplier, C is the increment, for the initial value, when c=0, called this algorithm is the same as congruential; if c≠0, the algorithm is mixed with congruential, when C is not the appropriate value of zero, there are some advantages, but the advantages are not outstanding, so often take c=0. Modulus m size is the main sign of the generator cycle length, the usual m is the prime number, take A is the original root of M, then cycle t=m-1. For example:

a=1220703125

a=32719 (number of this group in the program)

a=16807

Code:

void Main ()

{

const int n=100;

Double a=32719,m=1,f[n+1],g[n],seed;

M=pow (2,31);

cout<< "Set m value to" <<m-1<<endl;

cout<< "Input Seed" <<endl; Input seed

cin>>seed;

F[0]=seed;

for (int i=1;i<=n;i++)//linear with congruential generate random number

{

F[i]=fmod ((A*f[i-1]), (m-1));

g[i-1]=f[i]/(m-1);

COUT.SETF (ios::fixed); cout.precision (6); Setting output precision

cout<<i<< "" << "/n" <<g[i-1]<<endl;

}

}

Results analysis: The average of statistical data is: 0.485653

The variance of statistical data is: 0.320576

1-2: Man-word mapping

Recursive formulas

?/p>

It is known as "man-word mapping" or "tent mapping" in chaotic mapping, and its distribution density function of non-periodic orbital points: The combination of herringbone mapping and linear congruential can produce homogeneous random numbers with good statistical properties.

for (int i=1;i<=n;i++)//linear with congruential generate random number

{

F[i]=fmod ((A*f[i-1]), m);

if (F[I]<=M/2)//Combined with a human-character map to generate random numbers

{

F[i]=2*f[i];

}

Else

{

f[i]=2* (M-f[i]) +1;

}

1-3: The square Take the middle method--Von Neumann

Around 1946, proposed by von Neumann, his approach was to go to the square of the preceding random number and extract the middle number. For example, to generate a 10-bit number, and the previous value is 5772156649, the square is 33317792380594909201, so the next number is 7923805949.

for (j=1;j<=n;j++)

{

I[J]=I[J-1]*I[J-1];

I[j]=i[j]/pow (10,5);

I[j]=fmod (I[j],pow (10,10));

G[j]=i[j]/pow (10,10);

COUT.SETF (ios::fixed); cout.precision (6); Setting output precision

cout<<j<< '/t ' <<g[j]<<endl;

}

Second: generation of random numbers with arbitrary distributions

Random numbers with uniformly distributed (0,1) can be used to generate random numbers of arbitrary distributions. The main methods are inverse function method, house selection method, discrete approximation method, limit approximation method and random variable function method. This paper mainly discusses the inverse function method, of course, for the specific distribution function can be used in different ways.

Set the random variable x has the distribution function f (x), the value of x for a given distribution function value is

Where inv represents an inverse function. Now assume that R is a value of the random variable R (0,1) that is evenly distributed, and that the distribution function of R is known as

Therefore, if R is a value of R, then X has a probability

That is, if (R1,R2,..., RN) is a set of values for R, a corresponding set of values can be obtained

Have a distribution. Thus, if we have known the inverse function of the distribution function, we can get the random number of the desired distribution from the uniformly distributed random number (0,1) distribution.

1-4: Exponential distribution:

The distribution function of the exponential distribution is:

X<0, f (x) =0;, f (x) =1-exp

Using the inverse function method described above, it can be obtained: x= ln (1-y), where it is advisable to take a constant of 1.

for (int j=0;j<n;j++)

{

I=rand ()%100;//generates any value from 0-32767

A[j]=double (i)/double (100);

A[j]=-log (A[j]);//constant greater than 0, here take 1

、、、、、、、

1-5: Normal Distribution:

The probability density of a normal distribution is:

The distribution functions of the normal distribution are:

For normal distribution, it is obviously troublesome to use the inverse function method to get the normal distribution sequence, which involves complex calculus calculus, and for convenience, we take the standard normal distribution. So here are two kinds of algorithms:

The first type:

Box and Muller the algorithm for generating a random variable of normal distribution from a uniformly distributed random variable in 1958 years. U1, U2 is a random variable distributed evenly on the interval (0, 1) and is independent of each other. Make

X1=sqrt ( -2*log (U1)) * cos (2*PI*U2);

X2=sqrt ( -2*log (U1)) * sin (2*PI*U2);

So X1, X2 obey N (0,1) distribution, and are independent of each other.

P=rand ()%100;//generates any value from 0-32767

B[j]=double (P)/double (100);

A[j]=sqrt ( -2*log (a[j)) *cos (2*3.1415926*b[j]);

The second type:

Approximate generation of standard normal distribution, independent of the distribution of multiple random variables and distributions towards the normal distribution, take k uniformly distributed (0,1) random variables, ..., their and approximate obey normal distribution.

In practice, take k=12, (because D () =1/12), then the new random variable y=x1+x2+...+x12-6, you can find the mathematical expectation e (y) = 0, Variance d (y) =12*1/12=1, so can be approximated to describe the standard normal distribution.

Generate random numbers in C/