C ++ library study notes -- generate a set of random numbers

Source: Internet
Author: User

When trying to use

Srand (time (0 ))

Rand ()

When a random number is generated, many of the generated numbers are "same ".

Tested: srand (seed); rand () generates a random number. When seed is the same, the random number is the same.

Therefore, the above "same" problem should be caused by time (0)

So the final method is: sleep + high-precision timing, + srand (gettime_function) + rand ()

However,

[Cpp] view plaincopyprint? Changing gettimeofday to higher precision may result in better results

Changing gettimeofday to higher precision may result in better results

 

The Code is as follows (in Linux)


 

 include <stdlib.h> // for srand  #include <limits>  #include <time.h>   // for nanosleep  #include <sys/time.h>   // for gettimeofday #include <stdlib.h> // for srand#include <limits>#include <time.h>   // for nanosleep#include <sys/time.h>   // for gettimeofday

 

generate random number between 0~1  inline float randf(void) {     struct timespec tim;     tim.tv_sec=0; tim.tv_nsec=1e4;     nanosleep(&tim, 0);     struct timeval cur;     gettimeofday(&cur, 0);     srand(cur.tv_usec);     return rand()/float(RAND_MAX); }  inline int randi(int max=1e6) {     struct timespec tim;     tim.tv_sec=0; tim.tv_nsec=1e4     nanosleep(&tim, 0);     struct timeval cur;     gettimeofday(&cur, 0);     srand(cur.tv_usec);      return rand()%(max+1); } /// generate random number between 0~1inline float randf(void){    struct timespec tim;    tim.tv_sec=0; tim.tv_nsec=1e4;    nanosleep(&tim, 0);    struct timeval cur;    gettimeofday(&cur, 0);    srand(cur.tv_usec);    return rand()/float(RAND_MAX);}inline int randi(int max=1e6){    struct timespec tim;    tim.tv_sec=0; tim.tv_nsec=1e4    nanosleep(&tim, 0);    struct timeval cur;    gettimeofday(&cur, 0);    srand(cur.tv_usec);    return rand()%(max+1);}

Result:

 

 


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.