Generating Random Numbers in C++ for Scientific Applications

In summary: I am not sure if this is the best way to do it or not.In summary, the code does not generate the desired number of random numbers.
  • #1
ChrisVer
Gold Member
3,378
464
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;
    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:
Technology news on Phys.org
  • #2
Sorry for the bad appearence, it didn't accept my "tabs" :/
 
  • #3
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 ChrisVer
  • #4
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;
    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).
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 ChrisVer
  • #5
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!
 
  • #6
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.
 
  • #7
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().
 
  • #8
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.
 
  • #9
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?
  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.
 

1. How can I generate random numbers in C++?

C++ has a built-in library function called rand() that can be used to generate random numbers. This function returns a pseudo-random integer between 0 and RAND_MAX. To use this function, you need to include the cstdlib header file in your code.

2. How can I generate a random number within a specific range in C++?

To generate a random number within a specific range, you can use the formula rand() % (max - min + 1) + min. This will generate a random number between min and max, inclusive. For example, if you want to generate a random number between 1 and 10, you can use rand() % 10 + 1.

3. How can I set a seed for the random number generator in C++?

To set a seed for the random number generator, you can use the srand() function. This function takes an integer as its argument and sets it as the seed for the random number generator. It is recommended to use a variable that changes frequently, such as the current time, as the seed to generate more unpredictable random numbers.

4. Can I generate random floating-point numbers in C++?

Yes, you can use the static_cast function to convert the random integer generated by rand() into a floating-point number. For example, if you want to generate a random floating-point number between 0 and 1, you can use static_cast(rand()) / RAND_MAX.

5. Is the rand() function truly random in C++?

No, the rand() function is a pseudo-random number generator, which means it generates a sequence of numbers that appear to be random but are actually determined by an initial value called the seed. This means that the same seed will result in the same sequence of numbers being generated. To generate truly random numbers, you can use external sources such as hardware-based random number generators.

Similar threads

  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
15
Views
2K
  • Programming and Computer Science
Replies
22
Views
3K
  • Programming and Computer Science
Replies
6
Views
8K
  • Programming and Computer Science
Replies
12
Views
1K
  • Programming and Computer Science
2
Replies
66
Views
4K
  • Programming and Computer Science
Replies
11
Views
1K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
23
Views
2K
Back
Top