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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With