Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random number range, exclude 0

Tags:

c

I have the following function that generates a random number between -10 and 2:

#include <stdlib.h>
#include <time.h>

static int
getRandomReturnCode(void)
{
    int N = 2,
        M = -10;

    srand(time(NULL));

    r = M + rand() / (RAND_MAX / (N - M + 1) + 1);

    if (r == 0){
        getRandomReturnCode();
    }

    return r;
}

Currently, if a return code of 0 (success) is returned, it will recursively call the function over until a non-zero return code is met and returned. What can I do to improve my code such that 0 is excluded from the range of randomly chosen numbers?

like image 674
ILostMySpoon Avatar asked Jul 01 '15 14:07

ILostMySpoon


1 Answers

Whatever you do, don't redraw if a returned value is 0: that will introduce statistical bias into the result.

The best thing to do here is to draw between -10 and 1 inclusive and add 1 to any non-negative output.

Finally, call srand once else you'll ruin the generator's statistical properties.

(Briefly - since this comment is more for the mathematics site - and restricting the argument to a linear congruential generator, what tends to happen if you omit generated values is that you increase the variance of the resulting distribution so it's no longer uniform. A previously drawn small number will be linearly related to the subsequent drawing as the generator's modulus will have no effect. This autocorrelation - necessary for the resulting distribution to be uniform - of adjacent drawings will be curtailed if drawings are discarded and that increases the sample variance.)

like image 84
Bathsheba Avatar answered Sep 28 '22 11:09

Bathsheba