C++ Random?

Started by
31 comments, last by mpfeif101 20 years ago
The unrandomness of a simple modulus becomes glaringly obvious in a game or other program where you're invoking random numbers continuously and doing stuff based on them.

And please, read the thread first.

[edited by - Promit on April 14, 2004 7:13:13 PM]
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.
Advertisement
I havn't read the other posts but this is how I use random-numbers in C++

#define RANDOMIZE()			(srand(static_cast<unsigned int>(time(0))))#define RANDOM_INT(MIN, MAX)	(MIN + rand() % (MAX - MIN + 1))#define RANDOM_FLOAT(MIN, MAX)	(MIN + (static_cast<float>(rand())) / 0x7fff * (MAX - MIN))


// Last Attacker \\---=( LA )=---// LA Extreme \\

ICQ Number : 120585863

E-mail:

laextr@icqmail.com

[edited by - Last Attacker on April 15, 2004 3:53:31 AM]
"Take delight in the Lord and He will give you your heart's desires" - Psalm 37:4My Blog
quote:Original post by Last Attacker
I havn''t read the other posts but this is how I use random-numbers in C++

Your code has macro creation mistakes that are almost textbook example worthy.

quote:
#define RANDOM_INT(MIN, MAX) (MIN + rand() % (MAX - MIN + 1))

Here is the classic insufficient number of parethesis error. A call to RANDOM_INT(2 + 1, 2 + 6) will give strange results. In particular it would give results in the range of 3 to 10 instead of the expected 3 to 8 range. Also, it suffers from symbol duplication on the MIN parameter.

quote:
#define RANDOM_FLOAT(MIN, MAX) (MIN + (static_cast<float>(rand())) / 0x7fff * (MAX - MIN))

Again, symbol repeat issue on the MIN parameter, and the insufficient parenthesis error. Also add in the fact that you''re dividing by 0x7fff which makes your code non-portable. A implmentation of rand() returns numbers in the range 0 to RAND_MAX, where RAND_MAX is at least 0x7fff, but may be more. If you brought your code to a different compiler your random floats may suddenly be whole orders of magnitude greater than your MAX value.

You''re obviously using C++, so why not switch over to inline functions?

This topic is closed to new replies.

Advertisement