Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ generating random numbers

  1. May 9, 2015 #1

    ChrisVer

    User Avatar
    Gold Member

    Hi. I am trying to create a program that I will give the maximum range (1,...,max) from which to generate random numbers, and make it generate N=maxgen random numbers (which later I can use for example in another program). Below you can see the code I wrote:
    Code (C):

    #include <iostream>
    #include <ctime>
    #include <cstdlib>
    #include <cmath>
    #include <vector>

    using namespace std;

    int main(){

        int max,maxgen;
        cout<< "Please give the number of maximum = " ;   //max for the range of generated numbers (1,...,max)
        cin >> max ;
        cout << endl << "Please give the number of generated numbers = " ;
        cin >> maxgen;
        cout << endl;

        vector<int> random_no; //an empty vector to take in its elements the random numbers
        for(int j=0; j<= maxgen; ++j){ // to print the generated numbers
                  for(int a=0; a<=max; ++a){ //to generate at each element the random numbers
                           srand(time(0));
                           random_no.push_back((rand () % max) + 1);
                  }
                  cout << random_no.at(j) << endl;
        }

        system("pause");
        return 0;
    }
    Mod note: I formatted the code above using [ code ] tags.


    My problem is that the program doesn't generated N=maxgen random numbers, but it generates only 1 number for maxgen times (so I think something is wrong with my second for loop). Any idea?

    For eg max=5 and maxgen=10 , I get 10 times the number 4. Whereas my idea is to get something like: 1,5,4,3,5,2,4,1,4,2 (ten random numbers from 1 to 5).
     
    Last edited by a moderator: May 9, 2015
  2. jcsd
  3. May 9, 2015 #2

    ChrisVer

    User Avatar
    Gold Member

    Sorry for the bad appearence, it didn't accept my "tabs" :/
     
  4. May 9, 2015 #3

    Mark44

    Staff: Mentor

    Use code tags to preserve your indentation. Put a [ code=c ] tag at the top, and a [ /code ] tag at the bottom (without the spaces I showed). You don't need all of the [ color ] tags you used. The software we're using will color your source code very nicely without any extra effort.
     
  5. May 9, 2015 #4

    Mark44

    Staff: Mentor

    You should "seed" your random number only once, not each iteration of the inner loop. I would move the call to srand() outside both loops; i.e., just above the outer loop.
     
  6. May 9, 2015 #5

    ChrisVer

    User Avatar
    Gold Member

    Yes I was able to do it :) Thank you... Although I don't understand quiet well what "seeding" does.
    It's really amazing how this small problem, after solved, led me in creating a Hit or Miss Monte Carlo method for calculating pi!!
     
  7. May 9, 2015 #6

    Mark44

    Staff: Mentor

    srand() initializes the random number generator. You need to do this only once in your program.
     
  8. May 9, 2015 #7

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    You don't need to do it at all. The standard says that in a program that calls rand() prior to calling srand() (or simply omits the call to srand()), rand() must behave as if the program had called srand(1) prior to the first call to rand().

    rand() is a pseudo-random number generator. For any pseudo-random number generator (PRNG for short), there exists a cyclical sequence of numbers that the PRNG will generate. Seeding the generator changes where the PRNG starts in that sequence.

    In a good PRNG, the sequence is fairly long, and a subset of the sequence looks somewhat "random". In a very good PRNG, the sequence is extremely long, and a subset looks very "random", by every test of what that word "random" means. That's not good enough for keeping your credit card number and bank account number safe from random hackers. That mandates a cryptographically secure PRNG. Cryptographically secure PRNGs are beyond my area of expertise.

    The standard random number generator supplied with C is well with my area of expertise. In many implementations, it doesn't even qualify as "good". There are a lot of very good PRNGs, and with C++11, they are part of the language. The Mersenne Twister PRNG that comes built-in with C++11 is very good, and it's typically faster than rand().
     
  9. May 9, 2015 #8

    FactChecker

    User Avatar
    Science Advisor
    Gold Member

    The seed gives a starting point for a pseudo-random series. That is good if you want to compare two options A, B with exactly the same random series. Then you only have to save the seed, not the entire series. And that is why resetting the random series at the same seed always gave you the same first random number.
     
  10. May 9, 2015 #9

    FactChecker

    User Avatar
    Science Advisor
    Gold Member

    I would say it is good enough for most physics and engineering simulations. But if a person apples advanced time series analysis, it's flaws become apparent.
     
  11. May 9, 2015 #10

    wle

    User Avatar

    Some questions/comments about the code:
    1. What's the inner loop for(int a=0; a<=max; ++a){ ... } for?
    2. The outer loop for(int j=0; j<= maxgen; ++j){ ... } will iterate maxgen + 1 times.
    3. If this program's sole purpose is to print the random numbers, why are they being stored in a vector before being printed?
    4. This might not make a big difference in practice, but even if rand() produces a "good" uniform distribution of numbers, strictly speaking, (rand () % max) + 1 won't be uniform unless max happens to exactly divide RAND_MAX + 1.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: C++ generating random numbers
Loading...