• Advertisement

Random numbers, different platforms

This topic is 4177 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello! Does anyone know of a simple random number generator (in C/C++), which have the following properties: - Always generating the same sequence of numbers, independent of the architecture it's running on. - Good randomness from a statistical point of view is not that important. It just has to generate numbers which are "kind of" random. As far as I know rand() is not guaranteed to work the same way on all platforms and architectures, not even the common ones (correct me if I'm wrong). I need it to generate levels for a cross-platform game, as you probably have guessed :) Thanks in advance! -Rasmus

Advertisement

Share this post

Share on other sites
If you don't want to include boost, and you don't care about statistical randomness, you can implement a linear congruential generator very easily.

namespace {   const uint32 kA = 1664525;   const uint32 kB = 1013904223;   uint32 gSeed;}void seedRand(uint32 seed) { gSeed = seed; }uint32 genRand() {  gSeed = kA * gSeed + kB;  return gSeed;}

Some values of kA and kB are better than others... Plenty of research out there. However, no LCG is going to be statistically good; you wouldn't want to use this for security reasons or gambling type stuff (where people are putting down \$).

Benefits of LCG: trivial and fast. And it'll be cross-platform, and repeatable if everyone uses the same initial seed.

Share this post

Share on other sites
If you use an LCG (which is reasonable), remember that the first few bits and the last few bits are the least random. So if you are ok with getting 16-bit random numbers, I would return (short int)(seed>>8), or something like that.

If you decide you need a better random generator, a Mersenne twister might be a good option.

Share this post

Share on other sites
Quote:
 Original post by alvaroIf you decide you need a better random generator, a Mersenne twister might be a good option.

Which happens to be one of the generators provided by boost::random. [wink]

Share this post

Share on other sites
Another kind of RNG (which can also easily be implemented in hardware) is an LFSR:
http://en.wikipedia.org/wiki/Linear_feedback_shift_register

Share this post

Share on other sites
Hey, thanks for all the responses! :)

I decided to implement a Mersenne twister from scratch as described in the article, and it works like a charm.

Maybe it would be smarter just to use the boost one, but I try to only add external library dependencies if it's absolutely necesary.

Thanks again!

-Rasmus

Share this post

Share on other sites

• Advertisement
• Advertisement
• Popular Tags

• Advertisement
• Popular Now

• 45
• 11
• 17
• 11
• 13
• Advertisement