How to generate random double number in C/C++ in scope [min, max]

It seems that generation of random double number in scope is really easy in C/C++ – and  it is really easy! Assume that we want to generate 10 random numbers in scope [a, b]. TO do it use following code written in C:

#include <stdio.h> //for printf and scanf
#include <stdlib.h> //for RAND_MAX, srand, rand

int main(int argc, char ** argv)
{
double a, b, r;
int i;
srand((unsigned int)time(NULL));
printf(“Put two real numbers a i b (a < b)\n”);
scanf(“%lf %lf”, &a, &b);
printf(“10 random numbers in scope : %lf – %lf\n”, a, b);

for(i = 0; i < 10; i++){
r = a + (double)rand() / RAND_MAX * (b – a);
printf(“%lf “, r);
}
return 0;
}

This code also applies in C++ compilers.

Explanation of some lines:

srand((unsigned int)time(NULL)); – this function causing that program don’t return the same random numbers. If you pass as argument 1, then all ten numbers will be identical. This function set start point, which is used to generate set of integer pseudorandom numbers.

RAND_MAXmaximum number that is returned by the rand() function.

Piece of code responsible for returning random double number:

r = a + (double)rand() / RAND_MAX * (b – a);

Example of execution:

Put two real numbers a i b (a < b)
1.2
4.85
Random number in scope : 1.200000 – 4.850000
3.374051 4.748467 4.349848 3.396794 3.424234 3.976439 1.539638 1.869381 2.107359 1.650877

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s