C++ random number generation

In summary, the program works as intended. The function coinToss() is a pseudo-random number generator that returns either 1 or 2, and the loop in the main function uses this function to simulate multiple coin tosses. The difference in behavior between placing the srand(seeder) statement inside or outside the function is due to the fact that srand() initializes a new sequence of pseudo-random numbers, and for the same seed value, it will always generate the same sequence of numbers. It is recommended to use proper random number generators, such as the Mersenne-Twister algorithm, for more accurate and reliable results.
  • #1
Lord Anoobis
131
22
Homework Statement
Write a function named coinToss that simulates the tossing of a coin and generates the number of tosses as input by the user.
Relevant Equations
None.
The program works as intended.
C++:
#include <iostream>
#include <ctime>
#include <cstdlib>

int coinToss ();int main ()
{
    int tosses, result;
    std::cout << "How many coin tosses? ";
    std::cin >> tosses;
    size_t seeder = time(0);
    srand(seeder);
    
    for (int i = 0; i < tosses; i++)
    {
        result = coinToss ();
        std::cout << result << "\n";
    }
    
    return 0;
}

int coinToss ()
{
    int toss;
    toss = rand() % 2 + 1;
    return toss;
}

What I would like to know is why when the randomization is placed within the function (which is what I had done first) does it spit out either all 1s or all 2s?
C++:
int coinToss ()
{
    int toss;
    size_t seeder = time(0);
    srand(seeder);
    toss = rand() % 2 + 1;
    return toss;
}
 
Physics news on Phys.org
  • #2
When you initialize the pseudo-random number generator with the srand(seeder) statement, this starts off a new sequence of pseudo-random numbers. For the same value of seeder, you will always get the same sequence of numbers. The loop runs so fast, that the value of time(0) is always the same each time through the loop. I think the value of time(0) is in milliseconds, but I'm not sure. So you always intialize with the same value of seeder, so the rand() statement always gives you the same number. Try printing out the value of time(0).

Edit: Actually the value of time(0) is in seconds since 00:00 hours, Jan 1, 1970 UTC, so the loop can run many,many times in 1 second.
 
Last edited:
  • #3
Tried that just now. The value of time(0) stays the same in both cases but with different results. As long as seeder and its accomplices are part of the function its always 1s or 2s. Weird.
 
  • #4
It's not weird, it's completely understandable. What part of my explanation didn't you get?
 
  • #5
phyzguy said:
It's not weird, it's completely understandable. What part of my explanation didn't you get?
I'm not quite sure why the two cases behave so differently if the value of time(0) does not change for each repetition of the loop in both cases.
 
  • #6
In the case where the srand(seeder) statement is outside the loop, you get:

Initialize pseudo-random number generator
Pseudo-random number 1
Pseudo-random number 2
Pseudo-random number 3
...

In the case where the srand(seeder) statement is inside the loop, you get:

Initialize pseudo-random number generator
Pseudo-random number 1
Initialize pseudo-random number generator
Pseudo-random number 1
Initialize pseudo-random number generator
Pseudo-random number 1
...
 
  • #7
I just had it generate randoms only. I was under the impression that in the case of it being in the loop it would generate a different number on each pass regardless.
 
  • #8
Lord Anoobis said:
I just had it generate randoms only. I was under the impression that in that case it would generate a different number on each pass regardless.
No! It's a pseudo-random number generator. You should read about how they work. It is deterministic. For the same seed value, it will always generate the same sequence of numbers.
 
  • #9
phyzguy said:
No! It's a pseudo-random number generator. You should read about how they work. It is deterministic. For the same seed value, it will always generate the same sequence of numbers.
Yeah, I can see now what you meant in the first post. Valuable lesson learned and thanks.
 
  • #10
On another note, when I was testing it earlier today multiple times, an even number of tosses always gave 2s and an uneven number 1s, from 1 all the way to 20 and on more than one attempt. It was only when I used say, 10, a number of times in succession that it eventually broke formation. If ever there was a case of coincidence further confounding the issue.
 
  • #11
Since you already start doubting your random number generation: I do not know about your specific observation, but rand() is generally not an appropriate way to generate random numbers. Not for scientific purposes. Absolutely not for cryptography. Probably not even for computer games with dice rolling.

Since version C++11, C++ features proper random number generators out of the box. I highly recommend using them for all cases (except cryptography - just don't do cryptography at all). The Mersenne-Twister algorithm is a good default. Here's your code using this RNG, instead:
C++:
#include <ctime>
#include <iostream>
#include <random>// Mersenne-Twister generator with current time as seed.
std::mt19937 randomNumberGenerator(time(0));

// Distribution represeting a coin: Gets 1 or 2,
// depending on the random number passed.
std::uniform_int_distribution<> coinDistribution(1, 2);int coinToss() {
    return coinDistribution(randomNumberGenerator);
}int main() {
    int tosses, result;
    std::cout << "How many coin tosses? ";
    std::cin >> tosses;

    for (int i = 0; i < tosses; i++) {
        result = coinToss();
        std::cout << result << "\n";
    }

    return 0;
}
 

1. How can I generate a random number in C++?

To generate a random number in C++, you can use the rand() function from the cstdlib library. This function generates a pseudo-random number between 0 and RAND_MAX. To get a random number within a specific range, you can use the modulus operator.

2. How can I ensure that the random numbers generated are truly random?

C++ does not have a built-in function for generating truly random numbers. However, you can use the random_device class from the random library to generate a seed for the random number generator. This will help generate more random numbers.

3. Can I generate random numbers with decimal values in C++?

Yes, you can generate random numbers with decimal values by using the float or double data types. You can also use the uniform_real_distribution class from the random library to specify a range for the random numbers to be generated within.

4. How can I generate a random number from a specific distribution in C++?

C++ offers various distribution classes in the random library to generate random numbers from different distributions such as uniform, normal, binomial, etc. You can use these classes along with the random_device class to generate random numbers from a specific distribution.

5. Can I generate the same set of random numbers every time I run my program?

By default, the rand() function uses the current time as a seed for the random number generator. This means that the same set of random numbers will not be generated every time you run your program. However, you can use the srand() function to set a specific seed for the random number generator, which will result in the same set of random numbers being generated every time.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
3
Views
758
  • Engineering and Comp Sci Homework Help
Replies
8
Views
844
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
15
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
24
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
7
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
Back
Top