Generating a uniform distribution of INTEGERS in C

后端 未结 4 1072
情书的邮戳
情书的邮戳 2020-12-01 09:48

I\'ve written a C function that I think selects integers from a uniform distribution with range [rangeLow, rangeHigh], inclusive. This isn\

4条回答
  •  不思量自难忘°
    2020-12-01 10:22

    A version which corrects the distribution errors (noted by Lior), involves the high-bits returned by rand() and only uses integer math (if that's desirable):

    int uniform_distribution(int rangeLow, int rangeHigh)
    {
        int range = rangeHigh - rangeLow + 1; //+1 makes it [rangeLow, rangeHigh], inclusive.
        int copies=RAND_MAX/range; // we can fit n-copies of [0...range-1] into RAND_MAX
        // Use rejection sampling to avoid distribution errors
        int limit=range*copies;    
        int myRand=-1;
        while( myRand<0 || myRand>=limit){
            myRand=rand();   
        }
        return myRand/copies+rangeLow;    // note that this involves the high-bits
    }
    

    //note: make sure rand() was already initialized using srand()

    This should work well provided that range is much smaller than RAND_MAX, otherwise you'll be back to the problem that rand() isn't a good random number generator in terms of its low-bits.

提交回复
热议问题