# random number generation in C++

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

## Recommended Posts

I'm trying to create my own random number generator, and I've found several sources which give me code on how to do it, but none of them really explain to me how it works. I know you need to call srand() to "seed" the random numbers generator, but I have no idea what that means, or what different seed values will do, or how determine what an acceptable seed value would be for your needs. Can anyone help, or point me somewhere that explains it clearly? Thanks in advance, LilMonk001

##### Share on other sites
I dont know the theory behind the number generation but I still may say something usefull.

Boost Has a random number generator that may be of use to you because it fixes the problem of several repeated numbers in a row. Think about a tetris game where you could get 7 of the same type of bricks in a row, boost random can fix this so I hear.

Stuff like a random number generator should be left to a standard libary and only implemented for academic purposes or well I cant think of any others right now :).

##### Share on other sites
Quote:
 Original post by LilMonk001I'm trying to create my own random number generator...
That's a huge topic, and your further comments suggest that is not what you are trying to do.

C includes a pseudorandom number generator in its standard library. Random numbers are obtained through subsequent invocations of rand(). The RNG (random number generator) can be seeded, resulting in the same sequence of numbers for the same number of invocations. Seeding is performed using the srand() function.

#include <cstdlib>#include <iostream>using namespace std;int main(int argc, char *argv[]){  srand(123456789);  for(int i = 0; i < 10; ++i)  {    cout << rand() << ", ";  }  cout << '\n' << endl;  srand(123456789);  for(int i = 0; i < 10; ++i)  {    cout << rand() << ", ";  }  cout << endl;  return 0;}

The output is 10 sequences of the same random numbers. This means that you can generate the same sequence of random numbers by seeding the RNG with the same value, a technique that is useful in, for instance, replay systems.

##### Share on other sites
You can use Mersenne twister generator. It's pretty good and fast. It has some nice properties and is simple to use (at least my modified version).

##### Share on other sites
If you aren't looking for pre-built solutions, Numerical Recipes has a good chapter on random number generation. It explains things fairly well, and leaves you in a state where you can create several different algorithms depending on your specific needs.

CM

1. 1
Rutin
29
2. 2
3. 3
4. 4
5. 5

• 13
• 13
• 11
• 10
• 13
• ### Forum Statistics

• Total Topics
632959
• Total Posts
3009461
• ### Who's Online (See full list)

There are no registered users currently online

×