A method of generating random numbers

Source: Internet
Author: User
Tags random seed

One, random number test

The rand () functions commonly used in C + + generate random numbers, but only pseudo-random numbers (pseudo-random integral number) are generated in strict terms. When generating random numbers, we need to specify a seed, and if we loop within the program, the next time we generate a random number, we call the last result as a seed. However, if the program is executed two times, the resulting "random number" is the same as the seed.

In engineering applications, we generally use the current time of the System (Unix time) as a seed, so that the random number generated is closer to the actual random number. Give the following example:

<span style= "FONT-SIZE:12PX;" > #include <iostream> #include <ctime> #include <cstdlib>using namespace Std;int main () {    Double random (double,double);    Srand (Unsigned (time (0)));    for (int icnt = 0; icnt! = ++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);} </span>

/* Run Results
* 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 get a random number in full sense? It seems that 9 is a little bit more oh? But no 1,4,7?!. Let's do a probabilistic experiment, generate 10 million random numbers, and see if 0-9 of these 10 numbers appear to be roughly the same frequency. 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]++; 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! = ++icnt) cout << icnt << ":" << setw (6) << Setiosfla        GS (ios::fixed) << setprecision (2) << double (a[icnt])/gen_max*100 << "%" << Endl; return 0;} Double random (double start, double end) {returnstart+ (End-start) *rand ()/(Rand_max + 1.0);} 

/* Run Results
* 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 satisfies the statistic law.
Another: Using the GCC compiler under Linux, even if I perform 1 million operations, whether the random function defines the inline function does not seem to have any effect on the program, there is reason to believe that GCC has been optimized for us. But I remember to do the inline optimization to add O3 ...
No, so we change the number of cycles to 1 billion times and use the time command to see the execution times:
[Email protected] ~/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.768s
User 2m4.405s
SYS 0m0.038s
[Email protected] ~/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.269s
User 2m4.077s
SYS 0m0.025s
The previous time for the inline optimization case, the latter is not for the optimization of the situation, two times the result is not small, even the indicators of the second better, I do not know why ...
B. Random number under C + +
The random function is not an ANSI C standard and cannot be compiled under a compiler such as GCC,VC. You can use the RAND function under C + + to implement it.
1. The C + + standard function library provides a random number generator RAND, which returns a pseudo-random integer evenly distributed between 0-rand_max. The Rand_max must be at least 32767. The rand () function does not accept parameters and defaults to 1 as the seed (that is, the starting value). The random number generator always starts with the same seed, so the pseudo-random sequence is the same and loses its random meaning. (But this is easy for the program to debug)

2, another function Srand () in C + +, you can specify a different number (unsigned integer variable) to seed. But if the seed is the same, the pseudo-random sequence is the same. One way is to let the user enter the seed, but still not ideal.
3, the ideal is to use the number of changes, such as time to be a random number generator seed. The value of time is different every moment. So the seed is different, so the random number produced is different.
//C + + random function (VC program)
#include <stdio.h>
#include <iostream>
#include <time.h>
using namespace std;
#define MAX
int main (int argc, char* argv[])
{srand (unsigned) time (NULL)); the//srand () function produces a random seed that starts at the current moment. It should be in front of the for-waiting loop, or it'll 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;

usage of rand ()
RAND () does not require arguments, it returns an arbitrary integer from 0 to the maximum random number, and the maximum random number size is usually a fixed large integer. This way, if you want to produce a 0~10 of 10 integers, you can express it as:
int N = rand ()% 11;
Thus, the value of n is a random number of 0~10, and if it is to produce 1~10, this is the case:
int N = 1 + rand ()% 10;
In summary, it can be expressed as:
A + rand ()% n
Where a is the starting value and N is the range of integers. A + rand ()% (b-a+1) represents a random number between a~b to 0~1 decimal, you can get the 0~10 integer, and then divide by 10 to obtain a random decimal to a very bit of 10 random decimals, you need to get a random decimal to the percentile of the first 0~ 100 of 10 integers, then all divided by 100, and so on.
Usually rand () generates random numbers that are the same as the last time they were run, and this is intentionally designed to facilitate debugging of the program. To produce a different random number each time, you can use the Srand (seed) function to randomize, and with different seed, you can produce different random numbers.
As you may say, you can also include the time.h header file, and then use Srand (Time (0)) to randomize the random number generator using the current times, which guarantees that a different sequence of random numbers can be obtained every two runs (as long as the two runs are more than 1 seconds apart).

A method of generating 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.