To generate Random float/double numbers in a given limit

Posted: October 9, 2009 in Applications, C, C++, Programming Tips, VC++, Visual Studio, Windows, XP
Tags: ,

Include these header files in you program and then use the given function.

#define _CRT_RAND_S
#include <stdio.h>
#include <stdlib.h>

If you need a random numbers in floating point then use this function

float RandF(float fMaxLimit)
{
 unsigned int    uiNumber;
 errno_t         err;

 err = rand_s( &uiNumber );
 if (err != 0)
 {
 return 0.0;
 }
 return ((float) uiNumber / (float) UINT_MAX * fMaxLimit);
}

If you need a random numbers in double then use this function

double RandDB(double dbMaxLimit)
{
 unsigned int    uiNumber;
 errno_t         err;

 err = rand_s( &uiNumber );
 if (err != 0)
 {
 return 0.0;
 }
 return ((double) uiNumber / (double) UINT_MAX * dbMaxLimit);
}

NB: The lower limit for the generated numbers is 0.0

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s