Generating Random Numbers in C++ for Scientific Applications

  • Context: C/C++ 
  • Thread starter Thread starter ChrisVer
  • Start date Start date
  • Tags Tags
    C++ Numbers Random
Click For Summary

Discussion Overview

The discussion revolves around generating random numbers in C++ for scientific applications, specifically focusing on the implementation of a program that generates a specified number of random integers within a defined range. Participants explore issues related to code functionality, random number generation techniques, and the implications of using different random number generators.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant describes their code and identifies a problem where the program generates only one random number repeatedly instead of multiple unique numbers.
  • Another participant suggests moving the call to srand() outside of the loops to properly seed the random number generator only once.
  • A participant expresses gratitude for the solution but admits to not fully understanding the concept of "seeding" in random number generation.
  • Discussion includes explanations about how seeding affects the starting point of a pseudo-random number generator (PRNG) and the importance of using a good PRNG for scientific applications.
  • Concerns are raised about the quality of the standard rand() function, with some participants noting that it may not be suitable for all applications, especially in advanced analyses.
  • Questions are posed regarding the structure of the code, including the purpose of nested loops and the storage of random numbers in a vector before printing.
  • Participants discuss the uniformity of the distribution of generated numbers and the implications of using modulo operations with rand().

Areas of Agreement / Disagreement

Participants generally agree on the need to seed the random number generator only once, but there is disagreement regarding the effectiveness of the standard rand() function and its suitability for various applications. The discussion remains unresolved on the best practices for random number generation in C++.

Contextual Notes

Some participants note that the inner loop in the provided code may not serve a clear purpose, and the outer loop iterates one extra time than intended. Additionally, the uniformity of the random number distribution is questioned based on the relationship between max and RAND_MAX.

ChrisVer
Science Advisor
Messages
3,372
Reaction score
465
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:
C:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <vector>

using namespace std;

int main(){

    int max,maxgen;
    count<< "Please give the number of maximum = " ;   //max for the range of generated numbers (1,...,max)
    cin >> max ;
    count << endl << "Please give the number of generated numbers = " ;
    cin >> maxgen;
    count << 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);
              }
              count << 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:
Technology news on Phys.org
Sorry for the bad appearence, it didn't accept my "tabs" :/
 
ChrisVer said:
Sorry for the bad appearence, it didn't accept my "tabs" :/
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.
 
  • Like
Likes   Reactions: ChrisVer
ChrisVer said:
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:
C:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <vector>

using namespace std;

int main(){

    int max,maxgen;
    count<< "Please give the number of maximum = " ;   //max for the range of generated numbers (1,...,max)
    cin >> max ;
    count << endl << "Please give the number of generated numbers = " ;
    cin >> maxgen;
    count << 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);
              }
              count << 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).
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.
 
  • Like
Likes   Reactions: ChrisVer
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!
 
ChrisVer said:
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!
srand() initializes the random number generator. You need to do this only once in your program.
 
Mark44 said:
You need to do this only once in your program.
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().
 
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.
 
jk22 said:
In many implementations, [rand] doesn't even qualify as "good"..
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.
 
  • #10
Some questions/comments about the code:
  1. What's the inner loop for(int a=0; a<=max; ++a){ ... } for?
    [*] The outer loop for(int j=0; j<= maxgen; ++j){ ... } will iterate maxgen + 1 times.
    [*] If this program's sole purpose is to print the random numbers, why are they being stored in a vector before being printed?
    [*] 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.
 

Similar threads

  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 15 ·
Replies
15
Views
4K
Replies
11
Views
2K
  • · Replies 6 ·
Replies
6
Views
12K
  • · Replies 2 ·
Replies
2
Views
4K
Replies
22
Views
5K
Replies
12
Views
2K
Replies
12
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K