Use time to make seeds to generate random numbers

Source: Internet
Author: User
Tags rand repetition

We know that the rand () function can generate random numbers, actually making some kind of transformation based on the seed and returning the generated random number. By default, the seed is 1. Write a small program to test.

Main () {int i,j; for (i=0;i<10;i++) {j=1+ (int) (10.0*rand ()/(rand_max+1.0)), cout<<j<<endl;}} Execute: 9 4 8 8 10 2 4 8 3 6

Each execution result is 9 4 8 8 10 2 4 8 3 6. Without modifying the seed, each run of the program produces the same set of random numbers.

You can invoke Srand (unsigned seed) to modify the seed, so that programs that run two of times will produce a different random number. Time is usually used as a seed, for example:

Srand ((unsigned) time (NULL));

The seeds will change over time, and the probability of random numbers being duplicated is small. But here's a problem: Time returns the number of seconds from 1970.01.01, and if the RAND function is called multiple times within 1s, the resulting data is the same. You can test with the following code.

for (int i = 0;i<1000;++i) std::cout<<randselectquestion (1,1000) << '/t ';

int randselectquestion (int from,int to) {//Select a numeric Srand ((unsigned) time (NULL) between from and to); int span = 0; if (to>from) { span = To-from; Return From+rand ()%span; else {span = from-to; return To+rand ()%span}}

Running the above program, you will find that random numbers are very repetitive. Based on the principle of random number generation, we can make the seed change a bit faster to reduce the repetition probability: Replace time () with clock (), clock----

Calculates the wall-clock time used by the calling process.

Returns the time it takes for a processor to invoke a process or function, in one of the 1-second clocks_per_sec, where Clocks_per_ The SEC's definition in the vs2008 version of the time.h is 1000, which makes seed changes faster and reduces random number repetition probabilities.

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.