My random numbers aren't so random
by Daniel Buckmaster · in Torque Game Engine · 11/02/2007 (7:28 am) · 5 replies
I'm writing a method to make an AIPlayer fire a shot after a random interval of time. However, my random number always turns out to be the equivalent of about 4/10! Here's the method-
void AIPlayer::singleShot(int minTO,int maxTO)
{
srand(time(NULL));
S32 interval = abs(maxTO - minTO);
S32 time = rand() * interval / (RAND_MAX + 1);
time += minTO;
mFireCountdown = true;
mCountdownTime = time;
}If I put in 10 and 20, I get 14. 0 and 1000, I get 400. Am I right in thinking it might be a mistake to seed the generator every time?About the author
Studying mechatronic engineering and computer science at the University of Sydney. Game development is probably my most time-consuming hobby!
#2
11/02/2007 (12:57 pm)
When should I seed it then? AIPlayer::onAdd?
#3
11/02/2007 (1:23 pm)
I thought the "seed" generation is done on when the engine is started...
#4
and I dont think this line is quite right:
I'm not sure why you are adding 1 to RAND_MAX before dividing.
Should work just fine.
I.e. if interval is 10 then 0 *10 / RAND_MAX = 0 and 32767 * 10 / 32767 = 1
11/02/2007 (4:40 pm)
Looking at mathTypes.cc maybe you should use these functions instead:[b]S32 mRandI(S32 i1, S32 i2)[/b]
{
return gRandGen.randI(i1, i2);
}
[b]F32 mRandF(F32 f1, F32 f2)[/b]
{
return gRandGen.randF(f1, f2);
}
ConsoleFunction(getRandom, F32, 1, 3, "(int a=1, int b=0)"
"Get a random number between a and b.")
{
if (argc == 2)
return F32(gRandGen.randI(0,dAtoi(argv[1])));
else
{
if (argc == 3)
{
S32 min = dAtoi(argv[1]);
S32 max = dAtoi(argv[2]);
if (min > max)
{
S32 t = min;
min = max;
max = t;
}
return F32(gRandGen.randI(min,max));
}
}
return gRandGen.randF();
}and I dont think this line is quite right:
S32 time = rand() * interval / (RAND_MAX + 1);
I'm not sure why you are adding 1 to RAND_MAX before dividing.
S32 time = rand() * interval / RAND_MAX;
Should work just fine.
I.e. if interval is 10 then 0 *10 / RAND_MAX = 0 and 32767 * 10 / 32767 = 1
#5
About adding 1, I saw that in another forum thread on random numbers. Don't know where it came from...
EDIT: New method works perfectly. Thanks :)
11/03/2007 (2:56 am)
Ah. Thank you very much for that :)About adding 1, I saw that in another forum thread on random numbers. Don't know where it came from...
EDIT: New method works perfectly. Thanks :)
Associate Ross Pawley