To get random numbers (truly random and uniformly distributed over a given range) you'll probably need more than 3-4 lines of code...
Use a seeding function that hashes the output of time like this:
Code:
unsigned time_seed( time_t* T ){
time_t now = time( T );
unsigned char *p = ( unsigned char* )&now;
unsigned seed = 0;
size_t i;
for( i = 0; i < sizeof now; i++ )
seed = seed * ( UCHAR_MAX + 2U ) + p[i];
return seed;
}
then uniformly deviate your random pool over your range like this:
Code:
double uniformly_deviate( int seed ){
static const double R_MAX = RAND_MAX + 1.0;
return seed * ( 1.0 / ( R_MAX ) );
}
and write a function to obtain your random number like so:
Code:
// For an int..
int get_rand( ){
static const double R_MAX = RAND_MAX + 1.0;
return static_cast<int>( uniformly_deviate( rand() ) * R_MAX );
}
// For a double...
double get_rand_double( double LOWER_BOUND, double UPPER_BOUND ){
return ( LOWER_BOUND + uniformly_deviate( rand() ) * ( UPPER_BOUND - LOWER_BOUND ) );
}