Generate random numbers in C/

Source: Internet
Author: User
Tags cos modulus random seed setf

< 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 just want to generate random numbers without setting the range, you just have to use rand () to be able to: rand () will return a random number, ranging from 0 to Rand_max. Rand_max is defined in stdlib.h with a value of 2147483647.
Like what:

#include <stdio.h>
#include <stdlib.h>
void Main ()
for (int i=0;i<10;i+)
printf ("%d/n", Rand ());

(2) Suppose 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:
#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 one-time, assuming that the output will be the same as the first time you execute the second. 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 (), assuming that the random number seed is not set, and Rand () will voluntarily set the random number seed to 1 upon invocation. The two examples above are that because no random number seed is set, each random number seed is itself set to the same value 1, which causes rand () to produce the same random values.

Srand () function definition: void srand (unsigned int seed);
It is usually possible to use the return value of Geypid () or time (0) as the seed
Suppose you use time (0) to add a header file #include<time.h>

Like what:
#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 executions 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, which is directly referenced by the expression rand (), such as the ability to print two random numbers using the following statement:

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

Since the rand () function produces integers in the order specified, each run 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 is run, we usually provide a new random seed for the random number generator. The function Srand () (from stdlib.h) can spread the seed to the random number generator. The rand () function produces different sequences of random numbers only if the seed is different. Srand () is called the initializer of the random number generator.


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 same seed, the random number sequence is also the same. And when the seed is 1 o'clock, the same as not using the Srand () function, which means that 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);


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). The a,b,m are constant. So Rand's production is determined by the x,x called Seed. Seed needs to be set in the program, and the system time is normally taken as seed. It produces a very small correlation between random numbers, the range is 0-32767 (int), that is, double-byte (16-digit), if the unsigned int DWORD is 65535, four bytes is 4294967295, generally can meet the requirements.

1-1: Linear with congruential:


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. Like what:


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



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



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


F[i]=fmod ((A*f[i-1]), (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


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* (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, the following number is 7923805949.

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



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: Randomly distributed random number generation

Random numbers that are randomly distributed can be generated by using (0,1) an evenly distributed stochastic number. The basic 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 detailed 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

In which inv represents an inverse function. Now if R is a value of (0,1) evenly distributed random variable r, the distribution function known as R is

So, assuming that R is a value of R, then X has a probability

That is, assuming (R1,R2,..., RN) is a set of values for r, corresponding to the resulting set of values

Have a distribution. Thus, assuming we know the inverse of the distribution function, we are able to 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, can be obtained: x= ln (1-y), it is best to take a constant of 1.

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


I=rand ()%100;//generates a random 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 very troublesome to use the inverse function method to get the normal distribution sequence, which involves very complex integral differential operations, and at the same time, we take the standard normal distribution for convenience. 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 a random value from 0-32767

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

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

Another type of:

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, taking k=12, (due to 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 can approximate descriptive description of the standard normal distribution.

Generate random numbers in C/

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: 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.