How to get a larger random number from the c function rand()

前端 未结 4 1966
孤独总比滥情好
孤独总比滥情好 2021-01-19 21:19

I am in a coding environment where I only have access to some most basic c functions. #include\'ing other lib is not feasible.

In this environment, I can call rand()

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-19 21:58

    Besides the other excellent solutions proposed here, you can also do a power expansion in RAND_MAX, truncate at a user defined MY_RAND_MAX, and discard solutions which would cause uniformity to be destroyed.

    int myrand(int MY_RAND_MAX)
    {
        int j = 0, num = 0;
    
        // Generate digits for expansion in powers of RAND_MAX, up to acceptable range.
        while (pow(RAND_MAX + 1, j) <= MY_RAND_MAX){
            num = num + rand() * (int)pow(RAND_MAX + 1, j);
            j++; 
        } 
    
        //compute remainder to determine truncation 
        int remainder = ((int)pow(RAND_MAX + 1, j)) % (MY_RAND_MAX + 1); 
    
        // If number is within accepted bounds, mod and return
        if (num <= (  (int)pow(RAND_MAX + 1, j) - remainder ) ){
            return (num % (MY_RAND_MAX + 1)); 
    
        // Else, if number generated exceeds allowed bounds, rerun method.
        }else if (num > (  (int)pow(RAND_MAX + 1, j) - remainder ) ){
            return myrand(MY_RAND_MAX);
    
        }else{
            exit(-1);
        }
    }
    

    You can check empirically that this method gives you a statistically uniform output in the given range.

    I've done so for several trials with different ranges, each with a sample size of 100000, and got an agreement between the variance of the sample and the expected variance to at least 3 sig. fig.s each time.

    p.s. I am not a coder, but a mathematician/physicist who has recently learnt to code, so any and all feedback on the quality of my code would be appreciated.

提交回复
热议问题