  asked on

# How to limit numbers returned by a random number generator to multiples of .25?

I'm randomly assigning individuals in a simulation ages and I need to limit the ages to numbers that are multiples of .25 (i.e. you can be 22.75 yrs. old).

Here's the code that pulls a number from a uniform distribution between 2 numbers a and b.

inline int DiscreteUniformDeviate(const int a, const int b){ return nag_random_discrete_uniform(a, b);}
int nag_random_discrete_uniform (const int a, const int b)
{
double f = nag_random_continuous_uniform();
f = f * (b-a+1);
int rval = a + f;
return rval;
}

Here's the line that calls DiscreteUniformDeviate...

g_cIndividual[iThisID].SetAge(DiscreteUniformDeviate (0, 65))

...I'd like to wrap the discreteUniformDeviate(0,65) call in something like static_cast<int>(DiscreteUniformDeviate(0,65)) only instead of an int, it has to be a mult of .25. Other solutions are welcome too.

Daniel
C++ Last Comment
CDirenzi

8/22/2022 - Mon
CDirenzi

multiply the returned random number by 4 and store the result as an integer.  It has to be an integer so it cuts off the decimal.  Then divide the integer by 4 and store it as a float.

int n = randomNum* 4;
randomNum=(float)n/4;
CDirenzi

Or this might make it easier, include this function:

float RoundToNearestQuarter (float num) {
int n = num * 4;
return (float)n/4;
}
ltdanp22

If I take num and mult it by 4 and then divide the prod by 4 don't I just get the original number?
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Infinity08

The idea is to generate a random integer value between 0 and MAX_AGE*4. If the maximum age is 65, then between 0 and 260 for example.

This integer value is then divided by 4 (floating number division) to get the final age, which will be a multiple of 0.25 between 0 and MAX_AGE.
CDirenzi

>> int n = randomNum* 4;
>> randomNum=(float)n/4;

The first line multiplies the random decimal by 4 and then saves it as an integer n, which truncates the decimal portion of the number.  Then the second line divides the integer by 4 and saves the new decimal portion in the randomNum variable.

For example,
if the random age is 40.372:

>> int n = randomNum* 4;

randomNum = 40.372 and n = 161, because 40.372*4=161.488 and the integer portion is 161

randomNum=(float)n/4;

161/4=40.25, which is 40.372 rounded to the nearest 0.25

>> randomNum=(float)n/4;
ltdanp22

what does the float in parentheses do? forgive my complete ingnorance. i didn't write this code. i just have to make some mods.
Get an unlimited membership to EE for less than \$4 a week.
Unlimited question asking, solutions, articles and more.
ltdanp22

would this do the trick?

(note 0.75 is the upper limit on the first age group)

g_cIndividual[iThisID].SetAge(float((static_cast<int>(DiscreteUniformDeviate (0, 4*0.75))))/4)
SOLUTION
Infinity08