mardi 3 février 2015

how to generate random values with uniform intervals in c within a set range

So far I have a function which generates a random integer value within a fixed range (Min, Max) and it seems to work. But how can I make it so that if my range was (0,100), the random values returned is always a multiple of 8? (that is uniform intervals)



int generate_rand(int Min, int Max)
{
// Generates random number between min and max, inclusive.

int range, result, cutoff;

if (Min >= Max)
return Min; // only one outcome possible, or invalid parameters
range = Max-Min+1;
cutoff = (RAND_MAX / range) * range;

// Rejection method, to be statistically unbiased.
do {
result = rand();
} while (result >= cutoff);

return result % range + Min;
}


The same for the code below. How can I make the RANDOM_NUM variable to always be a multiple of 20/3 every time I call it? This one generates a random float value between 0 and 1. (that is uniform intervals)



RANDOM_NUM = ((float)rand()/(float)(RAND_MAX+1));




Aucun commentaire:

Enregistrer un commentaire