fast random numbers

Started by
18 comments, last by Rasta 24 years ago
JD and Mossmoss, thanks for correcting me!!!

Jaap Suter
____________________________Mmmm, I''ll have to think of one.
Advertisement
Ok, I made a little test program that uses (rand()%99)+1 to make a random number between 1 and 100, loops it a couple of million times and then calculates the average... it's VERY close to 50... (wich it should be) so i dont understand whats wrong w/ using the mod...

heres the source:


#include
#include


int main()
{
time_t t;
int i,j;
unsigned long temp=0;
float final[10], abs_final;


srand((unsigned int) (time(&t)));
clrscr();
for(i=0; i<10; i++)
{
for(j=0; j<10000000; j++)
temp+=(rand()%99)+1;
final =(float)temp/10000000;
printf("%d. %f\n",i,final);
temp=0;
}

abs_final= (final[0]+final[1]+
final[2]+final[3]+
final[4]+final[5]+
final[6]+final[7]+
final[8]+final[9])/10;

printf("\n\nAbsoulte final number iiiiis.... %f\n",abs_final);
printf("(btw. your computer has just completed 100000000 rand calls...)\n");
}


plz. compile it and try it urselfs!
(select 'edit message' to get the src w/ all chars...)



========================
Game project(s):
www.fiend.cjb.net

Edited by - JonatanHedborg on 4/16/00 5:53:02 PM
=======================Game project(s):www.fiend.cjb.net
quote:Original post by mossmoss

Original post by Gladiator
if you want to do

randnum = rand()%256; // since 256 = 2^8

you ccan use the following instead, which is a hell of a lot faster

randnum = rand()&255;



Actually, if you have a modern compiler (and probably even with plenty of non-modern compilers), you don''t gain anything by doing this. In fact, the compiler will be smart enough to do exactly this on its own.

You are usually better off writing your code so that it is readable, understandable, and logical rather than trying to come up with little tricks. Odds are that the compiler knows all those tricks, and trying to implement them yourself might actually make things worse (the compiler knows many more optimizations that you do, and by trying to do its work, you may "confuse" it).




—- — – -
Blue programmer needs food badly. Blue programmer is about to die!


Not so!!

You should never trust the compiler. You''ll be better off implementing it yourself, then thinking that the compiler will parse it correcly and everything… If you don''t know how toprogram well, you''ll be beter off staying with simpe instructions not optimizing anything until you''re good enough to understand your own code, and all the little tiddy bits out there that make your code run faster. The fact, is that a compiler can NEVER be compared to the human brain, and you''ll be always better of writing the exact code that you want to be executed.. that''s why there''s assemly and all those optimizing tricks…

btw, kill , please stop!!, i would guess you have never written a single game in your life and don''t know how things work. You might be happy with your 5 FPS pong game, but other people might not be…

..-=ViKtOr=-..
Gladiator''s right in this case (though still has a lot to learn about tact, and probably isn''t right for the right reasons) assuming we''re talking about the rand() function declared in ANSI C.

rand() % 256 won''t be optimized to rand() & 255 because the ANSI C declaration of rand has it returning a signed int, and % 256 and & 255 have different results when performed on negative numbers. (-4 % 256 = -4, -4 & 255 = 252)
However, if rand() is cast to unsigned int, then the compiler will optimize to & 255. i.e. ((unsigned int)rand()) % 256.

But quite frankly this is the matter of about 2 clock cycles per rand() call. Given that a rand() is an expensive operation (unless you are using a completely moronic generator) is it really worth obfuscating your code with bit operators? Especially in this case, where a simple cast will clear things up.

And further more I''d like to add saying that you should never trust the compiler is much like saying that your time is worth nothing. Even if the compiler can''t optimize as well as the human brain, it still performs it''s optimizations on several orders of magnitude fater than a human can.
quote:Original post by JonatanHedborg

Ok, I made a little test program that uses (rand()%99)+1 to make a random number between 1 and 100, loops it a couple of million times and then calculates the average... it''s VERY close to 50... (wich it should be) so i dont understand whats wrong w/ using the mod...


In practice, the ''bias'' is so small as to be hardly noticeable. I think people are arguing the technicality here Imagine that rand() returned an unsigned char, 0 to 255. Therefore, if you used rand()%100 you''d have more ways of getting a number from 0 to 55 (eg 10, 110, 210 would all return 10) than 56-99 (only 60 and 160 could return 60 - there is no 260 between 0 and 255). So if it was a char, you could have as much as a 50% bias on a simple percentage towards lower numbers. Now, since rand() uses an int (usually 32 bits) then rand()%100 is hardly ever going to look wrong. It''s when your desired random-number range starts approaching the maximum range that can be returned from rand() that you should be concerned about bias. (eg. rand() % (MAX_INT/2.5) would be very badly weighted towards lower numbers.)
Everyone,

I apologize for my post that previously occupied this space. It was inappropriate for these forums, and I should have used better judgement before posting.

---- --- -- -
Blue programmer needs food badly. Blue programmer is about to die!

Edited by - mossmoss on 4/17/00 10:06:06 AM
SiCrane, Im sure ur right, why dont u try it? i posted the (very simple) code...

========================
Game project(s):
www.fiend.cjb.net
=======================Game project(s):www.fiend.cjb.net
quote:Original post by Kylotan
In practice, the ''bias'' is so small as to be hardly noticeable. I think people are arguing the technicality here Imagine that rand() returned an unsigned char, 0 to 255. Therefore, if you used rand()%100 you''d have more ways of getting a number from 0 to 55 (eg 10, 110, 210 would all return 10) than 56-99 (only 60 and 160 could return 60 - there is no 260 between 0 and 255). So if it was a char, you could have as much as a 50% bias on a simple percentage towards lower numbers. Now, since rand() uses an int (usually 32 bits) then rand()%100 is hardly ever going to look wrong. It''s when your desired random-number range starts approaching the maximum range that can be returned from rand() that you should be concerned about bias. (eg. rand() % (MAX_INT/2.5) would be very badly weighted towards lower numbers.)



I agree, Kylotan, and should have suggested as such in my earlier postings.

One area, though, where even this little bias may make a difference is in some Monte Carlo methods, where you may generate several million random numbers. I was hit by this problem in school where my final results were off by a slight bit (although I may have been using 16-bit numbers, which would increase the bias slightly).



---- --- -- -
Blue programmer needs food badly. Blue programmer is about to die!
this is what i''d do for a number from 1 to 10:
int n = 10 * (double)rand() / RAND_MAX + 1;

As far as I can tell it works great. If you''re doing encryption or something you might wanna do more research, but for any game application i can think of, it works peachy. kill''s right, worry about your drawing code. I''m making a cute little asteroids game in DDraw. I was getting 75fps. I added a page and a half of collision detection and resolution code, and all of the physics code, to be processed every frame. It called plenty of trig functions and used mod several times every pass. After that, I was getting about 74.4 fps.

-J
I''m fluent in C++ and Java, know something of Perl, HTML, DirectDraw.CSE student at the University of California San Diego.
quote:Original post by JonatanHedborg
SiCrane, Im sure ur right, why dont u try it? i posted the (very simple) code...

Huh, I''m not quite sure I understand the context of your post. I was simply refering to the & 255 vs % 256 optimization. Your code seems to be with regards to the mod bias.

(Btw, shouldn''t you be modding against 100, not 99? Just a thought.)

This topic is closed to new replies.

Advertisement