Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better random algorithm?

I'm making a game in C++ and it involves filling tiles with random booleans (either yes or no) whether it is yes or no is decided by rand() % 1. It doesn't feel very random.

I'm using srand with ctime at startup, but it seems like the same patterns are coming up.

Are there any algorithms that will create very random numbers? Or any suggestions on how I could improve rand()?

like image 353
jmasterx Avatar asked Dec 16 '09 04:12

jmasterx


People also ask

What is TRNG and PRNG?

The difference between PRNG and TRNG is deterministic, PRNG is a deterministic random number generator, and TRNG is a non-deterministic random number generator. PRNG generates a long-length random number using algo- rithms based on a short initial value.

What is a PCG code?

A permuted congruential generator (PCG) is a pseudorandom number generation algorithm developed in 2014 which applies an output permutation function to improve the statistical properties of a modulo-2n linear congruential generator.

What's the difference between random and pseudorandom number?

So, the distinction between random and pseudorandom. If it's statistically random, then it's pseudorandom for the purposes for which we're using the term. Pseudorandom means it's produced by an algorithm that generates a series of bits that appear unpredictable, but in fact are computed from an algorithm.


1 Answers

True randomness often doesn't seem very random. Do expect to see odd runs.

But at least one immediate thing you can do to help is to avoid using just the lowest-order bit. To quote Numerical Recipes in C:

If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in
j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
and never by anything resembling
j = 1 + (rand() % 10);
(which uses lower-order bits).

Also, you might consider using a different RNG with better properties instead. The Xorshift algorithm is a nice alternative. It's speedy and compact at just a few lines of C, and should be good enough statistically for nearly any game.

like image 55
Boojum Avatar answered Sep 29 '22 03:09

Boojum