The function shown in your listing generates "random" integers that are greater than or equal to *min* and less than or equal to *max*.

Here's the idea:

The standard C library function rand() generates a sequence of integers between 0 and some large value. (The largest value that rand() can generate for a given compiler is given by a constant RAND_MAX, which is defined in <stdlib.h>.) Every time you call rand() you get another number between 0 and RAND_MAX.

Now for non-negative integers, the % operator gives the remainder that is obtained by dividing the first number by the second. So, if you take any int, say Z, and let x = Z % 11, the result in x will always be greater than or equal to zero and less than or equal to 10. (That's how division works: the remainder is greater than or equal to zero and less than the divisor.) This program assumes that the remainders will be "random" also (since they were obtained by dividing a "random" number by a constant).

So if we want to obtain a random number between -5 and 5, we see that there are 11 possible values of integers (count them: -5, -4, ..., 4, 5). The number if integer values between min and max is given by (max - min) + 1.

In other words the value x in the following expression is greater than equal to 0 and less than or equal to 10 (where min = -5, max = 5):

Code:

x = rand() % (max - min + 1);

Then, since we want to find a "random" integer number between min and max, one way is to use the formula

Code:

x = rand() % (max - min + 1) + min;

Note that, although your example calls getrand(5.,5.) the arguments are converted to ints since that's the way the function and its prototype are defined.

If you want to get a floating point number between two given numbers, say fmin and fmax, here's a way

First find a floating point number between 0 and 1. Then perform a scaling function that maps the interval [0,1] to [fmin,fmax].

Here's the function (remember RAND_MAX is the largest possible value that can be returned by rand()).

Code:

double x;
x = (double)rand()/RAND_MAX; /* this makes x between 0 and 1 */
x = x * (fmax - fmin) + fmin;

Of course you can do it in one step:

Code:

x = ((double)rand()/RAND_MAX ) * (fmax - fmin) + fmin;

Here's a function built like the one you had, but the inputs and output are doubles:

Code:

double getfrand(double fmin, double fmax)
{
static int Init=0;
double rc;
if (Init==0)
{
srand(time(NULL));
Init=1;
}
rc= ((double)rand()/RAND_MAX) * (fmax - fmin) + fmin;
return (rc);
}

Regards,

Dave