C ++ Random Number Generation Method)

Source: Internet
Author: User
Tags random seed

1. the random () function cannot be used in C ++.

========================================================== ========================================================== =

This article was originally issued by qingsong and in accordance with the GPL-V2 and its subsequent versions, please indicate the source and should contain the statement of the bank.

In C ++, the Rand () function is often used to generate random numbers, but strictly speaking, only pseudo random numbers (pseudo-random integral number) are generated ). When generating a random number, we need to specify a seed.ProgramThe next time a random number is generated, the result is called as a seed. However, if the program is executed twice, the generated "random number" is the same because the seeds are the same.

In engineering applications, we generally use the current system time (UNIX time) as the seed, so that the generated random number is closer to the actual random number. The example is as follows:

# Include <iostream>
# Include <ctime>
# Include <cstdlib>
Using namespace STD;

Int main ()
{
Double random (double, double );
Srand (unsigned (time (0 )));
For (INT icnt = 0; icnt! = 10; ++ icnt)
Cout <"no." <icnt + 1 <":" <int (random (0, 10) <Endl;
Return 0;
}

Double random (double start, double end)
{
Return start + (end-Start) * rand ()/(rand_max + 1.0 );
}
/* Running result
* No.1: 3
* No. 2: 9
* No. 3: 0
* No. 4: 9
* No. 5: 5
* No. 6: 6
* No. 7: 9
* No. 8: 2
* No. 9: 9
* No. 10: 6
*/
Can we use this method to obtain a random number in the full sense? It seems that there are more than nine? But there are no, 7 ?! Let's do a probability experiment to generate 10 million random numbers. Check whether the frequencies of the 10 numbers 0-9 are roughly the same. The procedure is as follows:
# Include <iostream>
# Include <ctime>
# Include <cstdlib>
# Include <iomanip>
Using namespace STD;

Int main ()
{
Double random (double, double );
Int A [10] = {0 };
Const int gen_max= 10000000;
Srand (unsigned (time (0 )));

For (INT icnt = 0; icnt! = Gen_max; ++ icnt)
Switch (INT (random (0, 10 )))
{
Case 0: A [0] ++; break;
Case 1: A [1] ++; break;
Case 2: A [2] ++; break;
Case 3: A [3] ++; break;
Case 4: A [4] ++; break;
Case 5: A [5] ++; break;
Case 6: A [6] ++; break;
Case 7: A [7] ++; break;
Case 8: A [8] ++; break;
Case 9: A [9] ++; break;
Default: cerr <"error! "<Endl; exit (-1 );
}

For (INT icnt = 0; icnt! = 10; ++ icnt)
Cout <icnt <":" <SETW (6) <setiosflags (IOs: fixed) <setprecision (2) <double (A [icnt]) /gen_max x 100 <"%" <Endl;

Return 0;
}

Double random (double start, double end)
{
Return start + (end-Start) * rand ()/(rand_max + 1.0 );
}
/* Running result
* 0: 10.01%
* 1: 9.99%
* 2: 9.99%
* 3: 9.99%
* 4: 9.98%
* 5: 10.01%
* 6: 10.02%
* 7: 10.01%
* 8: 10.01%
* 9: 9.99%
*/
It is known that the random number obtained by this method meets the statistical rule.

In addition, in Linux, if GCC is used to compile a program, even if I perform 1000000 operations, it seems that the definition of the inline function of the random function has no effect on the program. I believe that, GCC has been optimized for us. But in the dark, I remember to add O3 to the inline optimization...

No, So we change the number of cycles to 1 billion. Run the time command to view the execution time:
Chinstrap @ Gentoo ~ /Workspace/test/debug $ time./test
0: 10.00%
1: 10.00%
2: 10.00%
3: 10.00%
4: 10.00%
5: 10.00%
6: 10.00%
7: 10.00%
8: 10.00%
9: 10.00%

Real 2m7. 768 s
User 2m4. 405 s
Sys 0m0. 038 s
Chinstrap @ Gentoo ~ /Workspace/test/debug $ time./test
0: 10.00%
1: 10.00%
2: 10.00%
3: 10.00%
4: 10.00%
5: 10.00%
6: 10.00%
7: 10.00%
8: 10.00%
9: 10.00%

Real 2m7. 269 s
User 2m4. 077 s
Sys 0m0. 025 s

The previous one was for inline optimization, and the last one was not for inline optimization. The two results were slightly different, and the latter was even better, I don't know why...

========================================================== ========================================================== =

Random functions are not ansi c standards and cannot be compiled by GCC, Vc, or other compilers. You can use the rand function in C ++. 1. The C ++ standard function library provides a random number generator Rand, which returns a pseudo random integer evenly distributed between 0 and rand_max. Rand_max must be 32767 at least. The rand () function does not accept parameters. The default value is 1 (the start value ). The random number generator always starts with the same seed, so the pseudo-random sequence is also the same, without the random meaning. (But this facilitates program debugging)
2. In C ++, another function srand () can specify different numbers (unsigned integer yuan) as seeds. However, if the seeds are the same, the pseudo-random sequence is also the same. One way is to let the user input seeds, but it is still not ideal.
3. It is ideal to use a variable number, such as time, as the seed of the random number generator. The value of time varies every moment. So the seeds are different, so the random numbers are also different.
// C ++ random function (VC Program)
# Include <stdio. h>
# Include <iostream>
# Include <time. h>
Using namespace STD;
# Deprecision max 100
Int main (INT argc, char * argv [])
{Srand (unsigned) Time (null); // The srand () function generates a Random Seed starting from the current time. It should be placed before loop statements such as for. Otherwise it will take a long time to wait.
For (INT I = 0; I <10; I ++)
Cout <rand () % max <Endl; // Max is the maximum value, and its random field is 0 ~ MAX-1
Return 0;
}
Ii. Rand () Usage
Rand () does not require a parameter. It returns an arbitrary integer from 0 to the maximum random number. The maximum random number is usually a fixed large integer. In this way, if you want to generate 0 ~ 10 integers, which can be expressed:
Int n = rand () % 11;
In this way, the value of N is a 0 ~ A random number of 10 ~ 10, it is like this:
Int n = 1 + rand () % 10;
In summary, it can be expressed:
A + rand () % N
Where a is the starting value and N is the range of integers. A + rand () % (B-A + 1) indicates ~ If a random number between B is 0 ~ 1 decimal point, you can first get 0 ~ Then, divide all the values by 10 to get the 10 random decimal places from random to very. To get the random decimal places from random to percentile, you must first get 0 ~ The 10 Integers of 100 are all divided by 100. In other cases, this is the case.
Generally, the random numbers generated by rand () are the same as the previous one during each operation. This design is intended to facilitate program debugging. To generate different random numbers each time, you can use the srand (SEED) function for randomization. Different random numbers can be generated as the seed varies.
As you said, it can also contain time. h header file, and then use srand (time (0) to use the current time to randomize the random number generator, in this way, different random number sequences can be obtained every two runs (as long as the interval between two runs exceeds 1 second ).

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.