C + + generates random numbers

Source: Internet
Author: User

Random number

The random number of a computer is generated by a pseudo-random number, which is a sequence of small m-polynomial, in which each small sequence has an initial value, that is, a random seed. (Note: The period of the small m polynomial sequence is 65535, that is, the period of the random number generated by each random seed is 65535, and when you get 65,535 random numbers, they repeat.) )

We know that the rand () function can be used to generate random numbers, but this is not really a random number, it's a pseudo-random number, a series of numbers that are based on a recursive formula as a basis for a number (which we can call a seed), and when the series is large, it conforms to the normal publication, This is equivalent to generating a random number, but this is not a true random number, and the value of this seed is fixed when the computer is booted properly, unless you destroy the system.

1.rand ()

Function: Random number generator

Usage: int rand (void)

Header file: stdlib.h

The internal implementation of RAND () is made with linear congruential, which is not a true random number, because its period is particularly long, so it can be seen as random in a certain range.

RAND () returns the range of a random number between 0 and Rand_max. The range of Rand_max is at least between 32767 (int). With unsigned int DWORD is 65535, four bytes is an integer range of 4294967295. 0~rand_max the odds of each number being selected are the same.

When the user does not set a random number seed, the system default random number seed is 1.

RAND () produces pseudo-random numbers that are the same each time they are executed, and to be different, initialize it with the function srand ().

2.srand ()

Function: Initialize random number generator

Usage: void srand (unsigned int seed)

Header file: stdlib.h

The Srand () is used to set the random number seed when rand () produces a random number. The parameter seed must be an integer, and if each seed has the same value, the random number generated by RAND () will be the same every time.

3. Use the current clock as a random number seed

The random number generated by rand () is the same as the last time it was run. To be different, initialize it with the function srand (). You can use the Srand ((unsigned int) (Time (NULL)) method to produce different random number seeds, because each time you run the program is different.

4. Use of random number generation

1) provide a seed to Srand (), which is a unsigned int type;
2) call Rand (), which returns a random number (between 0 and Rand_max) based on the seed value provided to Srand ();
3) Call Rand () as many times as necessary to obtain a new random number without interruption;
4) Whenever possible, a new seed can be given to Srand () to further "Randomize" the output of rand ().

A random number program between 0~rand_max

 #include <iostream> #include  <stdlib.h>  #include  <time.h> using  namespace   STD;  int   main () {Srand ((unsigned) time (NULL));  for  (int  i = 0 ; i < 10 ; I++) cout  << rand () << 
   
     " 
    \t  
    "  Span style= "COLOR: #000000" >; cout  <<
     Endl;  
    return  
    0  
    ;}  
   
5. General expression formula for generating a certain range of random numbers

To obtain a random integer [A, b], use (rand ()% (b-a)) + A;
To obtain a random integer [A, b], use (rand ()% (b-a+1)) + A;
To obtain a random integer (A, b], use (rand ()% (b-a)) + A + 1;
General formula: A + rand ()% n; where a is the starting value and N is the range of integers.
To get a random integer between A and B, another representation: A + (int) b * rand ()/(Rand_max + 1).
To obtain a floating-point number between 0~1, you can use RAND ()/double (Rand_max).

Random number 1 is not repeated. Method One

The original idea is to generate a random number for each of the preceding random numbers to compare, if there are duplicates, then do not, re-select. However, this method is time-consuming and can cause huge problems when the volume of data is huge and there are some limitations. For example, to generate 10,000 random numbers, with a range of 0-9999 and no repetition, the last few random numbers can take a long time to filter out.

Here we think from another angle, assuming that we have an array length of 10000 arrays, which store data 0-9999, I now do is to find a way to make 10,000 numbers randomly arranged, then got such a random sequence, if I only have 100 of them, Then take 100 out of the front. Here, we use a function inside the algorithm.h to do simple processing.

template<class randomaccessiterator>      void  random_shuffle (      Randomaccessiterator _first,       randomaccessiterator _last);

The object of this function is the iterator of the container, that is, we need to change the storage data from the array to the container, the following code is implemented:

#include <algorithm>#include<iostream>#include<vector>using namespacestd;voidRandperm (intNum) {Vector<int>temp;  for(inti =0; i < Num; ++i) {temp.push_back (i+1);    } random_shuffle (Temp.begin (), Temp.end ());  for(inti =0; I < temp.size (); i++) {cout<< Temp[i] <<" "; }}cout<< Endl;
2. Method Two

These numbers are generated sequentially, but their positions are randomly generated. For example, below is a 100 code that does not repeat random numbers within 100:

int a[];  for (i=0; i<=; ++i) a[i]=i;  for (i=; i>=1;--) Swap (A[i], A[rand ()%i]);

The above code only needs to traverse once to produce these 100 non-repeating random numbers, how is it done? First, the second line fills the entire array with 0 to 99, and the third row is randomly generated from 0 to m-2, and the element value of the subscript is followed by the m-1.

The element value Exchange, which continues to the subscript 1. So it only needs to traverse once to produce all the random numbers.

Look at the following code, the principle is similar to the above example, but more efficient than the above, but still a good way to:

int a[]={0}; int I, M;  for (i=1; i<=, + +i) {        while (A[m=rand ()%]);          = i;}

This code is also randomly generated position, but it pre-initialized the entire array to 0, and then randomly generated one of the positions, if the value of the element is 0, indicating that the position has not been used, I gave it to it, otherwise, re-randomly generated another position, until the entire array

Be filled. This way, the more you go back, the more likely you are to encounter an element that has been used, the more repetitions it is, the less the first method, but overall, the efficiency is good.

References:

[1]. How to efficiently produce non-repeating random numbers within m n ranges

[2]. Generate random numbers (Rand,srand usage) in C + +

[3]. Random numbers and non-repeating random numbers in C + +

C + + generates random numbers

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.