Monday, 26 August 2013

pseudo random integer number c++ perfect mapping

pseudo random integer number c++ perfect mapping

I looked for a good method to generate an integer inside a range of values.
I think using modulo is not a good method because the values are not
perfectly mapped in the range.
So I map the pseudo random generated number in the range by a double using
divisions.
What do you think about this method?
How would you improve it? (I used the Qt functions but you can easily
replace it by the std functions)
quint8 randquint8(quint8 low = 0, quint8 high = 0)
{
if (low == 0 && high == 0)
{
high = 0xff;
if (RAND_MAX > high)
{
return (qrand() & high);
}
}
else if (low > high)
{
qSwap(low, high);
}
const quint8 numberOfBits = bitCount(RAND_MAX);
quint8 myRand = 0;
int i = qCeil(8.0f / numberOfBits);
while (i--)
{
myRand += qrand();
if (i)
{
myRand <<= numberOfBits;
}
}
if (myRand == 0xff)
{
return high;
}
double factor = (double)0xff / (double)(high - low + 1);
double tmpRand = low + ((double)myRand / factor);
quint32 finalRand = qFloor(tmpRand);
return finalRand;
}

No comments:

Post a Comment