C + + generates random numbers

Source: Internet
Author: User
Tags generator random seed

Stand on the shoulders of giants!

C + + random number generation function rand (), essentially generating pseudo-random sequence numbers.

To generate a more random sequence, srand (unsigned num) is required to sow. Common ways Srand ((unsigned) time (NULL));//Add a header file <time.h> generate a random integer between [b]: 1, rand ()% (b-a+1) +a;2, A+b*rand ()/rand_ MAX; Two citations: the first one tells the basic method, the second one says some restrictions. In fact, for the second case, in the case of a limited range of random numbers, the effects of unequal probabilities can be negligible, but when the interval length of random numbers is very large, the above problems become more meaningful. Especially when the interval length is more than half of the Rand_max, this situation needs to be dealt with carefully. Daisy ' s blogc/c++ generating random number function introduction and usage    the random numbers from the:http://zhangjunhd.blog.51cto.com/113473/197020  computer are all pseudo-random numbers, This is generated by a small m polynomial sequence 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 a real random number, it's a pseudo-random number, a series of numbers that are based on a number (which we can call a seed) as a reference to a recursive formula, and when the number is large, is a normal announcement, which is equivalent to generating a random number, but this is not a true random number, and when the computer boots up, the value of the seed is fixed unless you destroy the system.  1.rand () function: Random number generator   usage: int rand (void)   header file: The internal implementation of Stdlib.h rand () is done with a linear congruential, which is not a true random number, because its period is particularly long, Therefore, in a certain range can be seen as random.  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 () generates pseudo-random numbers that are the same each time they are executed;Initialize it with the function srand ().  2.srand () Function: Initialize random number generator   usage: void srand (unsigned int seed)   header file: Stdlib.h srand () to set rand () Random number seed When a random number is generated. 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. The random number produced by using the current clock as a random number seed 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. The use of generating random numbers
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 (). Random number program between 0~rand_max # # <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 ';
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). Happiness of programing

Http://hi.baidu.com/silyt/blog/item/f1a0bf03e0784ce809fa9309.html

What would you do if you had to use C + + to generate a random number between 0--n-1? You might say, very simply, look:

Srand ((unsigned) time (NULL));
Rand ()% N;

Think about it, is the result random (of course, we don't consider the pseudo-randomness of the rand () function)?

No, because the upper limit of RAND () is Rand_max, and in general, Rand_max is not an integer multiple of N, then if Rand_max% = R, then the probability of the value between 0--r will be larger, and the probability of the value between r+1--n-1 will be smaller. And if n > Rand_max, what should I do?

A more appropriate scheme is given to generate the equal probability random number result in any range. Finally, there is an easier way.

1, if n<rand_max+1, then to remove the mantissa,

R = rand_max-(rand_max+1)%N; Remove Mantissa
t = rand ();
while (T > R) t = rand ();
result = t% N; Random numbers that meet the requirements


2, if N>rand_max, may consider the segmented sampling, divides into [n/(RNAD_MAX+1)] The paragraph, first waits for the probability obtains the paragraph to obtain each paragraph again some element, thus the fragment similarly has a mantissa question, not each time is exactly divides into the integer paragraph, must have more or less a remainder paragraph, How is the value of this part selected?

Select the remainder segment of the data to choose, first to select the remainder of the probability of the event occurred, and then a separate selection:

R = N (rand_max+1); Remainder
If (happened (double) r/n)//probability of selection to remainder segment
result = N-r+myrandom (r); Myrandom can be implemented with the code in case 1
Else
result = rand () +myrandom (n/(rand_max+1)) * (rand_max+1); If the remainder segment is not selected, then the segment selection

The complete code:
#include <iostream.h>
#include <time.h>
#include <stdlib.h>
Const double minprob=1.0/(rand_max+1);
BOOL happened (double probability)//probability 0~1
{
if (probability<=0)
{
return false;
}
if (Probability<minprob)
{
return rand () ==0&&happened (probability* (rand_max+1));
}
if (rand () <=probability* (rand_max+1))
{
return true;
}
return false;
}

Long Myrandom (long N)//Generate equal probability random number between 0~n-1
{
t=0;
if (N<=rand_max)
{
Long r=rand_max-(rand_max+1)%n;//mantissa
t = rand ();
while (T > R)
{
t = rand ();
}
return t% n;
}
Else
{
Long R = n% (rand_max+1);//remainder
If (happened (double) r/n)//probability of taking to remainder
{
return N-r+myrandom (R);
}
Else
{
return rand () +myrandom (n/(rand_max+1)) * (rand_max+1);
}
}
}

There is another very simple way to use

Random_shuffle (Randomaccessiterator _first, Randomaccessiterator _last).

For example, to generate a random number between 0--n-1, you can write this

#include <algorithm>
#include <vector>

Long Myrandom (Long N)
{
Std::vector<long> VL (N); Defines a vector of size n
for (long i=0; i<n; ++i)
{
Vl[i] = i;
}

Std::random_shuffle (Vl.begin (), Vl.end ());

Return (*vl.begin ());
}

Random_shuffle also has a three-parameter overloaded version

Random_shuffle (Randomaccessiterator _first, Randomaccessiterator _last, randomnumbergenerator& _Rand)

The third parameter can accept a custom random number generator to randomize the elements between the first two parameters.

The drawback of this method is that if you just need a random number, when n is large, the space consumption is great!

C + + generates random numbers

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.