Some experiences on the use of rand and srand Functions

Source: Internet
Author: User
Tags random seed

In the C language, two functions are included in the <stdlib. h> header file, C ++, and the standard library <cstdlib> (included in <iostream> ).

The srand function is the initialization function of the random number generator.

Prototype: void srand (unsigned seed );

The rand function is used to generate random numbers, of coursePseudo-Random Number.

Prototype: int rand (void)

The role of seed: The srand function is to set a random starting point based on the seed parameter, and the rand function generates a random number sequence based on this starting point. The default Random Seed is 1. If the random seed is the same, the random sequence generated by the rand function is the same.
ThereforeGenerate different random sequences, Each timeDifferent seed Parameters.


Description:

Because the internal implementation of Rand is made by the linear same remainder method, itNoA real random number is only generated because the cycle is particularly long.ScopeRand () returns a random value in the range0 to RAND_MAX. Before calling this function to generate a random number, you must use srand () to set the random number seed. If no random number seed is set, Rand () will automatically set the random number seed to 1. Rand () generates false random numbers, which are the same during each execution. To be different, initialize it with different values. The initialized function is srand ().

Return Value:
Returns a random integer between 0 and rand_max. The range of rand_max is at least 32767 (INT), that is, double byte (16 digits ). If unsigned int is used, the dual-byte value is 65535, and the four-byte value is an integer range of 4294967295.

0 ~ The probability that rand_max is selected for each number isSame.

Example:

// Obtain 0 ~ Random integer between 6 # include <iostream> int main () {for (INT I = 0; I <10; I ++) {ran_num = rand () % 6; cout <ran_num <";} return 0;} // because the seed value is 1 by default, the output is: 5 5 4 4 5 0 4 2


When seed is set to 1:

// Obtain 0 ~ Random integer between 6 # include <iostream> int main () {srand (1); For (INT I = 0; I <10; I ++) {ran_num = rand () % 6; cout <ran_num <"";} return 0;} // The output will be output at each run because the seed is not changed: 5 5 4 4 5 4 0 4 2

Specify seed as the value 6:

// Obtain 0 ~ Random integer between 6 # include <iostream> int main () {srand (6); for (int I = 0; I <10; I ++) {ran_num = rand () % 6; cout <ran_num <"";} return 0;} // The output will be output at each run because the seed is not changed: output after each operation: 4 1 5 1 4 3 4 2 2

So how do we generate a pseudo-random seed? Generally, the specified seed is the time elapsed by the current system (unit: seconds): time_t time (0 ):

// Obtain 0 ~ Random integer between 6 # include <iostream> # include <ctime> // time function int main () {srand (unsigned) time (0 )); for (int I = 0; I <10; I ++) {ran_num = rand () % 6; cout <ran_num <"" ;}return 0 ;}

Output at first run: 0 1 5 4 5 0 2 3 4 2

Second: 3 2 3 0 3 5 5 2 2 3
In short, each running result will be different, because every time the program is started is different (the interval must be greater than 1 second? See ).

About time_t time (0 ):
Time_t is defined as a long integer. It returns the time elapsed since 00:00:00, January 1, January 1, 1970, in seconds. For example, assume that the output is:
Cout <time (0 );
The value is about 1169174701, which is equal to 37 (year) multiplied by 365 (days) multiplied by 24 (hours) multiplied by 3600 (seconds) (months and days are not counted ).


In addition, regarding ran_num = rand () % 6, it is necessary to evaluate the modulo between the return value of rand () and 6 so as to ensure that the random number of the target falls between [0, 6). Otherwise, rand () the returned value may be huge.
A general formula is:
To obtain a random integer between [a, B), use(Rand () % (B-a) +
(The result value will contain a and B ). If a is 0, it is abbreviatedRand () % B.

There is also a common function for generating random seeds:

Srand (time (NULL ));// The current time is used as the seed to generate random numbers. Here, time (NULL) is used to obtain the current time. In essence, it is a large integer, and then a random number is used.


Finally, the pseudo-random Floating Point Number:

UseRand ()/double (RAND_MAX)0 ~ The floating point between 1 (note that, unlike the integer formula, it is divided by, not the modulo), for example:

# Include <iostream> # include <ctime> // time function int main () {double ran_numf = 0.0; srand (unsigned) time (0 )); for (int I = 0; I <10; I ++) {ran_numf = rand ()/(double) (RAND_MAX); cout <ran_numf <"";} return 0 ;}

Running result: 0.716636, 0.457725 ,... And so on ~ The floating point number between 1 and the result is different each time.

If you want to get a larger range of random floating point numbers, such as 1 ~ 10. You can change rand ()/(double) (RAND_MAX)Rand ()/(double) (RAND_MAX/10)
Running result: 7.19362, 6.45775 ,... And so on ~ The floating point number between 10 and the result is different each time.
As for, and so on.
The above is not the best implementation method for pseudo-random floating-point numbers, but it can be used...


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.