C++ | Generating a pseudo number between 10-20

The stdlib random number generator would be an okay place to start:

#include <stdlib.h>
#include <time.h>

srand(time(NULL)); // initialize the RNG
int poll = rand() % 20; // random number between 0 and 19 inclusive

Eventually, you'll want to start using a more random RNG. Game Coding Complete has a pretty decent one to get you started.


A good choice would be std::random, the random number generator that’s built-in to C++.

If you don’t have C++11 support yet, use boost::random. The new std::random is based on boost::random, so it’s basically the same thing. The documentation has several examples, including Generating integers in a range.

One of the options offered is the Mersenne Twister (mt19937), which is a good general-purpose pseudo-random number generator.

Like most of the other suggestions, this is pseudo-random. To get true randomness is more difficult—but you don’t need that for an RPG, right? (For cryptographically-strong random numbers, consider OpenSSL or, on Windows, CryptoAPI.)


You should omit the word "truly" from the title, because you probably don't mean it. You probably just want a pseudorandom number. True randomness is virtually impossible to achieve with a personal computer. The following snippet will give you a pseudorandom number in the range 10..19 inclusive:

#include<cstdlib>
#include<ctime>

// ...
srand(time(0));
int r = rand() % (20 - 10) + 10;

If you want to include 20 in the range then this is a range of 11 numbers:

int r = rand() % (21 - 10) + 10

As others said, maybe rand() will be really sufficient for you. What is important is the seed used to initialise the pseudo random number generator ( the call to srand() is the seed)

But beware, True Chaos doesnt mean that you have exactly the same chance to generate any possible random output.

Ten years ago I have played with stochastic sound generation. I needed several sources of chaos.

I just let you know those which I had kept and found useful. of course since they need a seed, they are pseudo chaos.

1/for chaotic float number between -1 and 1: compute the function f(x) = cos(exp(x)). exp() grows so fast, that after really few iteration, what goes out from cos() is chaos.

2/the baker transform: chaotic number between 0 and 1: take a number, multiply it by two, and again, when it is superior to 1, substract something so as it goes back betwen 0 and 1. A much more precise explanation The Baker Transform.

But I think rand() and srand() will satisfy you.

For applying to your range 10-20, of course you stretch/scale the chaotic range (0;1) or (-1;1) by multiplying and offsetting so as the ouput fits your need. ;-)

Tags:

C++

Random