I am trying to understand this code from the generate.c program:

for (int i = 0; i < n; i++)
    printf("%i\n", (int) (drand48() * LIMIT));

I see that the drand48 function returns a nonnegative double-precision floating-point values uniformly distributed between [0.0, 1.0).Then this is multiplied by the upper limit on the range of integers. Can someone explain what is going on here?


You essentially explained it in your question. drand48() returns a random float between 0 and 1. It isn't designed to return a different range, so you then need to expand that range. By multiplying the result by LIMIT, the possible range becomes 0 * LIMIT at minimum and 1 * LIMIT as a maximum.

Say you wanted a number between 0 and 37. drand48() * 37 would do it. It would return a float between 0.0 and 37.0

I assume that you understand the loop.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .