Ideally, you could do something like:
#define RANGE_MIN (-5)
#define RANGE_MAX (+5)
#define RESOLUTION (1.1055228575200001e-012)
#define NUM_OF_VALUES ((int)((RANGE_MAX-RANGE_MIN)/RESOLUTION))
double GetRandVal()
{
return rand()%NUM_OF_VALUES*RESOLUTION+RANGE_MIN;
}
Unfortunately, the maximum return-value of rand()
is typically 32767, while the specified range and resolution in your example yield 9045493661191 values. So you will have to use rand()
several times:
#define RANGE_MIN (-5)
#define RANGE_MAX (+5)
#define RESOLUTION (1.1055228575200001e-012)
#define NUM_OF_VALUES ((unsigned long long)((RANGE_MAX-RANGE_MIN)/RESOLUTION))
int GetNumOfBits(unsigned long long val)
{
int numOfBits = 0;
while (val > 0)
{
numOfBits++;
val >>= 1;
}
return numOfBits;
}
static int numOfBitsInRandMax = GetNumOfBits(RAND_MAX);
static int numOfBitsInNumVals = GetNumOfBits(NUM_OF_VALUES);
static int quotient = numOfBitsInNumVals/numOfBitsInRandMax;
static int remainder = numOfBitsInNumVals%numOfBitsInRandMax;
double GetRandVal()
{
unsigned long long randVal = 0;
for (int i=0; i<quotient; i++)
randVal = (randVal<<numOfBitsInRandMax)|rand();
randVal = (randVal<<remainder)|(rand()&((1<<remainder)-1));
return randVal%NUM_OF_VALUES*RESOLUTION+RANGE_MIN;
}
Please note however, that on the theoretical aspect, it reduces the level of true randomness.
And BTW, don't forget to seed the RNG using srand((unsigned int)time(NULL))
...