What is the best way to generate a random number in C?

What is the best way to generate random numbers?
if and only if:

>You are not looking for “perfect uniform Sex” or
>you don’t have C 11 support, or even TR1 (so you have no other choice)

Then you can consider using the following C-style solutions, (for the reputation of this community~ see rand() Considered Harmful) is written in perspective font:

This is a simple C-style function that generates random numbers from the minimum to maximum (including the minimum) interval. These numbers seem very Close to uniform distribution.

int irand(int min, int max) {
return ((double)rand() / ((double)RAND_MAX + 1.0) ) * (max-min + 1) + min;
}

And don’t forget to call srand before using it:

int occurences [8] = {0};

srand(time(0));
for (int i = 0; i <100000; ++i)
++occurences [irand(1,7)];

for (int i = 1; i <= 7; ++i)
printf("%d ", occurences[i]);

Yield: 14253 14481 14210 14029 14289 14503 14235

Also take a look:
Generate a random number within range?
Generate random numbers uniformly over an entire range
And find some time, at least watch the first 11 minutes of the above video

Other than this:

Use as already pointed out by Kerrek SB That way.

What is the best way to generate random numbers?

If and only if:

>You are not looking for “perfect uniformity” or
>you don’t have C 11 support , And even without TR1 (so you have no other choice)

Then you can consider using the following C-style solution, (for the reputation of this community ~ see rand() Considered Harmful) is written in perspective font :

This is a simple C-style function that generates random numbers from the minimum to the maximum (including the minimum) interval. These numbers seem to be very close to a uniform distribution.

int irand(int min, int max) {
return ((double)rand() / ((double)RAND_MAX + 1.0)) * (max-min + 1) + min;
}

And don’t forget to call srand before using it:

int occurences[8] = {0};

srand(time(0));
for (int i = 0; i <100000; ++i)
++occurences[irand(1,7)];

for (int i = 1; i <= 7; ++i)
printf("%d ", occurences[i]);

Yield: 14253 14481 14210 14029 14289 14503 14235

Also take a look:
Generate a random number within range?
Generate random numbers uniformly over an entire range
and find some time, at least before watching the above video 11 minutes

Other than this:

Use as already pointed out by Kerrek SB.

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 2212 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.