Random Numbers with Decimals

The rand() function returns a pseudo-random number as a long int value. That value helps your code generate random numbers in the long int range. It can also be manipulated to yield random real number values, but that process involves . . . math.

The rand() function is prototyped in the stdlib.h header file. It generates values in the range of 0 to RAND_MAX, which is also defined in stdlib.h.

On my system, I peeked inside stdlib.h to see how RAND_MAX is defined. Here it is:

#define RAND_MAX        0x7fffffff

The definition might be different on your system, but the constant name is identical.

You can use the RAND_MAX value to help your code generate floating point random values. It makes for a nice, clean equation, as shown in Figure 1.

Figure 1.

Figure 1.

The value returned by rand() is in the range of 0 to RAND_MAX. When its divided by RAND_MAX, the result is in the range of 0.0 to 1.0.

If you leave the division as-is, then the result is a long int value. That means 99 percent of the time the result is 0. Only when the value returned by rand() is close to RAND_MAX would it equal 1. So the equation must be typecast to a float, as is done in the following code at Line 13:

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

int main()
{
    int x;
    float fr;

    srand((unsigned)time(NULL));
    for(x=0;x<10;x++)
    {
        fr = (float)rand()/RAND_MAX;
        printf("%f\n",fr);
    }

    return(0);
}

At Line 13, the value in variable fr ranges between 0.0 and 1.0. Here’s sample output:

0.581146
0.320701
0.013958
0.597070
0.954065
0.965519
0.479583
0.355317
0.810573
0.297443

While these may not be the floating point values your code needs, they do provide a base. You can manipulate the real random numbers to represent values in any range. For example, multiply the values by 100 to have the code generate floating point numbers between 0.0 and 100.0.

Leave a Reply