C + + generates random number __c++

Source: Internet
Author: User
Tags cos function definition modulus pow rand random seed setf

< a >

How C + + generates random numbers: Here is the rand () function, the Srand () function, and the C language/c++ does not have its own random (int number) function.
(1) If you want to generate random numbers without setting a range, you can just use RAND (): rand () returns a random value ranging from 0 to Rand_max. Rand_max is defined in Stdlib.h, and its value is 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 within a certain range, you can define a random (int number) function in the macro definition, and then call the random () function directly in main ():

For example: randomly generated number of 10 0~100:
#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 numbers generated by the above two examples can only be one-time, if you run the second time the output is still the same as the first time. This is related to the Srand () function. Srand () is used to set the random number seed for rand () to produce random numbers. Before you can invoke the rand () function to generate random numbers, you must first use Srand () to set up the random number seed (seed), and if no random number seed is set, rand () automatically sets the random number seed to 1 when it is called. The above two examples are because no random number seed is set, and each random number seed is automatically set to the same value of 1, which results in the same random values produced by Rand ().

Srand () function definition: void srand (unsigned int seed);
You can usually use the return value of Geypid () or time (0) as a 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));
}

The results of this two-time operation 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 input parameters and is referenced directly by the expression rand (), for example, you can print two random numbers with the following statement:

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

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

In order to generate a random value for a new sequence every time the program executes, we usually provide a new random seed for the random number generator. function Srand () (from stdlib.h) can disseminate seeds for random number generators. As long as the seed is different from the rand () function, a different sequence of random numbers is produced. Srand () is called the initialization of a random number generator.

Routines:

FileName: 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 when 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 supply the seeds at 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 a seed value of 1 by default;

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

int rand ();

void Srand (unsigned int);

Expand:

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

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

z = ((double) The random number on the generation interval [a,b] of Rand ()/rand_max) * (b-a) + a;/*

< three >

1-0:microsoft VC + + produces the principle of random number:

Srand () and Rand () functions. It is essentially the use of linear with congruential, Y=ax+b (mod m). Where the a,b,m are constant. So Rand's production is determined by the x,x known as seed. Seed needs to be set in the program and generally take the system time as a seed. It produces a small correlation between the random number, the 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 modulus, A is the multiplier, C is the increment, for the initial value, when c=0, call this algorithm to multiply the same congruential, if the c≠0, the algorithm is mixed with congruential, when the C to take the appropriate value of zero, there are some advantages, but the advantages are not prominent, so often take c=0. The modulus m size is the main symbol of the generator cycle length, it is common to have m as prime number, take a as the original root of M, then the cycle t=m-1. For example:

a=1220703125

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

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 congruential generation 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); Set Output precision

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

}

}

Result Analysis: The average of statistic data is: 0.485653

The variance of the statistic data is: 0.320576

1-2: The Human word map

Recursive formula

?/p>

is known as the "human Character Map" or "tent map" in the chaotic map, and its distribution density function of the aperiodic orbital points: The combination of herringbone mapping and linear congruential can produce homogeneous random numbers with excellent statistical properties.

for (int i=1;i<=n;i++)//Linear congruential generation random number

{

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

if (F[I]<=M/2)//To generate random numbers in combination with human character mappings

{

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

}

Else

{

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

}

1-3: Square Method--Neumann

Before and after 1946, proposed by Neumann, his approach was to go to the front of the random number of squares and extract the middle number. For example, to generate a 10-digit 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); Set Output precision

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

}

Generation of random numbers of arbitrary distribution

Random numbers with arbitrary distributions can be produced by using (0,1) uniform 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, we can use different methods for the specific distribution function.

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

Where inv represents the inverse function. It is assumed that R is (0,1) a value of the uniformly distributed random variable r, and the distribution function of the known R is

So, 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, then a corresponding set of values can be obtained

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

1-4: Exponential distribution:

The distribution function of exponential distribution is:

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

Using the inverse function method mentioned above, we can get: x= ln (1-y), where it is possible to take a constant of 1.

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

{

I=rand ()%100;//produces any one of the values from 0-32767

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

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

、、、、、、、

1-5: Normal Distribution:

The probability density of a normal distribution is:

The distribution function of the normal distribution is:

For normal distribution, using the inverse function method to obtain the normal distribution sequence is very troublesome, involving a very complex integro-differential operation, at the same time for convenience, we take, that is, the standard normal distribution. So here are a couple of algorithms:

First type:

Box and Muller in 1958 years, the algorithm for generating the random variable of normal distribution by the uniformly distributed random variable is given. Set U1, U2 is a uniformly distributed random variable 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);

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

P=rand ()%100;//produces any one of the values 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 distribution of multiple random variables and distribution tends to the normal distribution, take k uniformly distributed (0,1) random variables, ..., then their and approximate obeys the normal distribution.

In practice, by taking k=12, (because of D () =1/12), the new random variable y=x1+x2+...+x12-6 can find the mathematical expectation e (y) = 0, Variance d (y) =12*1/12=1, so the standard normal distribution can be approximately described.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.