# Random numbers, different platforms

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

## 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

##### 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 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 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 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 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

1. 1
Rutin
42
2. 2
3. 3
4. 4
5. 5

• 9
• 27
• 20
• 14
• 14
• ### Forum Statistics

• Total Topics
633387
• Total Posts
3011607
• ### Who's Online (See full list)

There are no registered users currently online

×