This question already has answers here:
What does 'seeding' mean?
(4 answers)
Closed 6 years ago.
What is a seed in terms of generating a random number?
I need to generate hundreds to thousands of random numbers, I have read a lot about using a "seed". What is a seed? Is a seed where the random numbers start from? For example if I set my seed to be 5 will it generate numbers from 5 to whatever my limit is? So it will never give me 3 for example.
I am using C++, so if you provide any examples it'd be nice if it was in C++.
Thanks!
What is normally called a random number sequence in reality is a "pseudo-random" number sequence because the values are computed using a deterministic algorithm and probability plays no real role.
The "seed" is a starting point for the sequence and the guarantee is that if you start from the same seed you will get the same sequence of numbers. This is very useful for example for debugging (when you are looking for an error in a program you need to be able to reproduce the problem and study it, a non-deterministic program would be much harder to debug because every run would be different).
If you need just a random sequence of numbers and don't need to reproduce it then simply use current time as seed... for example with:
srand(time(NULL));
So, let's put it this way:
if you and your friend set the seed equals to the same number, by then you and your friend will get the same random numbers. So, if all of us write this simple program:
#include<iostream>
using namespace std;
void main () {
srand(0);
for (int i=0; i<3; i++){
int x = rand()%11; //range between 0 and 10
cout<<x<<endl;
}
}
We all will get the same random numbers which are (5, 8, 8).
And if you want to get different number each time, you can use srand(time())
Related
This question already has answers here:
Why does rand() yield the same sequence of numbers on every run?
(7 answers)
Closed 3 years ago.
So I am new to C++ and learning all alone... until now everything went fine, but i am learning how to use rand() and the result does bother me a little...
So my goal is to generate a random number for the HP of a player at the beginning of a game. To be fair, I set up a minimal HP of 50 points and I want to create a random number with 50 being the minimal and 200 the maximum.
int HP = 50 + rand() %200;
cout << HP;
Now, the problem is:
The program always give me the same int.
To check the result i created a new project and only displayed the rand() number with the same values, and I got the same result -> 91.
this mean, I would say int HP = 91; would be exactly the same.
Practice and trial being the key to learn (I think) I tried the same rand() values on 5 new projects, always the same number...
std::srand() seeds the pseudo-random number generator used by rand(). If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1).
Each time rand() is seeded with srand(), it must produce the same sequence of values on successive calls.
https://en.cppreference.com/w/cpp/numeric/random/rand
Therefore, what you're seeing is (awkardly) exactly what rand is supposed to do. The easy fix is to call std::srand(std::time(nullptr)); so that each time the program runs, it starts with a different seed.
The more advanced fix is to study The awesome C++ standard randum number library
std::default_random_engine e1(r());
std::uniform_int_distribution<int> uniform_dist(50, 250);
int HP = uniform_dist(e1);
rand() isn't really the best random number generator, but if you're going to use it you need to seed it with the srand function as follows:
srand(time(0));
This question already has answers here:
Why do I get the same sequence for every run with std::random_device with mingw gcc4.8.1?
(5 answers)
Closed 5 years ago.
//My trial program
#include<iostream>
#include<random>
using namespace std;
int main(){
//USed to initialize (seed) the random number generator
random_device sd{};
// The random number generator
mt19937 engine {sd()};
//Uniformly distribute random numbers in [1...10]
uniform_int_distribution <> dis{1, 50};
//Generate a random integer
int x {dis(engine)};
//Print it
cout<<x<<"\n";
return 0;
}
I have used the code above to a generate random number between 1 to 50. But whenever I run the program, the random number generated is the same. An online course that I am taking has this code and it works perfectly fine on the instructor's clang compiler. I am using gcc compiler. Can anyone tell me what needs to be done please? thank you!!
From std::random_device :
std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each std::random_device object may generate the same number sequence.
Although it's not ideal for it's users, an implementation is allowed to have the behavior you described.
The issue here is that std::random_device does not have to really be a random device. It can be a wrapper around an unseeded rand which would give you the same value every time you use it. This means your seed for engine would be the same which means the pseudo-random sequence it generates would be the same as well.
One way you could get around this is to use the current as a seed like
auto seed = std::chrono::system_clock::now().time_since_epoch().count();
mt19937 engine {seed};
But this can be manipulated via external processes and isn't very fined grained so multiple instances seeded at the same time could all make the same sequence.
I've been searching for a better solution than my own and I haven't really been able to find one that I understand or that works for me.
I have made the simple game where the computer randomly generates a number which you then guess a number and if it is higher the computer says higher and so on..
The problem is my randomly generated number, after looking up alot of information regarding the <random>, uniform_int_distribution and default_random_engine. I have found out that the computer generates a random number, but if you run the program again the same random number will be generated.
My solution:
uniform_int_distribution<unsigned> u(0,100); // code to randomly generate numbers between 0 and 100
default_random_engine e; // code to randomly generate numbers
size_t userInput; // User input to find out where to look in the vector
vector<int> randomNumbers; //vector to hold the random numbers
unsigned start = 0, ending = 101, cnt = 0; // used in the game not important right now
cout << "Please enter a number between 1 and 1000 for randomness" << endl;
cin >> userInput;
for(size_t i = 0; i < 1000; ++i){ //for loop to push numbers into the vector
randomNumbers.push_back(u(e));
}
unsigned guess = randomNumbers[userInput]; // finally the number that the user will have to guess in the game
My solution right now is to use a vector where I push alot of randomly generated numbers in then ask the user to type a number which then the computer uses for the game. But there should be a better way of doing this. And my question is therefore
Is there a better way to randomly generate numbers to use in the game?
Either use std::random_device in place of std::default_random_engine, or else think of a way to provide a different number to the engine each time it is run.
This number is called a "seed" and can be passed as an optional parameter to the constructor. Since std::default_random_engine is implementation-specific, and different engines do different things about seeding, you generally want to choose a specific engine if you're providing a seed. A deterministic pseudo-random number generator will produce the same sequence of outputs for any given seed, so you want to use a different seed each time.
For no-security uses like a guessing game, the most "obvious" thing to use as a seed is the current time. Generally speaking this is different each time the program is run, although obviously if you can run the program twice in less than the granularity of the clock then that's not the case. So using the time to seed your random engine is pretty limited but will do the job for a toy program.
That's because your random number is actually what we call a pseudorandom number generator
It's just a machine that given a starting number generates a large list of seemingly random numbers. As you don't provide a starting number, the generated list of random numbers is thus always the same. One easy way to fix this is to use the current time as a starting value or 'seed', which is an argument of the constructor of std::default_random_engine.
You can also use your machines real random number generator std::random_device as a replacement for std::default_random_engine
Why not simply:
#include <ctime> // for time()
#include <cstdlib> // for srand()
srand(time(NULL)); // Initializes the rand() function
int randomNumber = rand()%100; // Random number between 0 and 99.
What this does is the rand() seed is set at the current time, meaning that every execution of the program will have a different seed for rand().
Still just pseudo-random solution, though suitable for your purposes.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
rand function returns same values when called within a single function c++
I have a program which creates a new set of random numbers each mouse click. If I run the program without srand ( time(NULL) ); the numbers are the same each time. If I run the program WITH srand ( time(NULL) ); then it's possible for me to spam click and the numbers will repeat themselves. How can I get around this?
Your problem is about seeding the random number generator with the same value. The srand function is for initializing the so called "seed" for it. A seed can be used to generate the same random numbers in a sequence.
First you need to initialize the generator then just call the rand function without arguments, and it will generate random numbers. For example:
/* initialize random seed with actual date-time */
std::srand(std::time(NULL));
/* generate ten random number lower than 10 */
int random, times = 10;
while(times){
random = std::rand() % 10;
times--;
}
About the "spam click": std::time(NULL) has precision in seconds, so you're initializing the random seed with the same value if you click within the same second.
Here is an example on the official c++ reference site,
and another example on cplusplus.com too.
rand function is not very good at generating random numbers, take a look at boost::random. it is awesome and can create random and semi random numbers
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What’s the Right Way to use the rand() Function in C++?
When I run the below program I always get the same values each time. Is rand not a true random function?
int main()
{
while(1)
{
getch();
cout<<rand()<<endl;
}
}
In each run I am getting the below values.
41
18467
6334
26500
19169
15724
......
Yes and no. rand() is a pseudo random number generator that will always return the same sequence of numbers given the same seed value. Typically one 'seeds' the random number generator with some random data and then uses rand() to return a sequence of seemingly random numbers. If your random data isn't needed for something requiring 'true' randomness (such as cryptography based security) just using the current system time is sufficient. However, if you are using it for security purposes, look into obtaining more truly random data from entropy gathering utilities and use that to seed the random number generator.
As aa mentioned, the seed function is referenced here
What is a true random function? Last I checked, computers couldn't do that :)
As to why you are getting the same set of numbers each time, it's because you need to seed the built in number generator with some starting 'random' value. There are many places to get this, but some tend to look good, but turn out bad. In our games, we generally seed with tic time from game bootup until the first or second user input. User input will always vary across many tics and can therefore be used as a decent starting point.
If you are using a Microsoft compiler, you can use rand_s, which generates very good random numbers (as good as you can get with only a computer): http://msdn.microsoft.com/en-us/library/sxtz2fa8%28VS.80%29.aspx
You can also use /dev/urandom on Linux and CryptGenRandom() on Windows to get quality random numbers.
or put srand() at the beginning of the function.
Just to follow on from the disucussion on "True" random numbers. As already, stated any generator that has a seed has a predictable period - I believe it can be 2^48.
If that level of randomness you can use the following:
long randomLong(unsigned int x)
{
x ^= (x << 21); // x is a non zero seed value
x ^= (x >> 35);
x ^= (x << 4);
return x;
}
This is taken from the following paper:
http://www.jstatsoft.org/v08/i14/paper
Which is a really interesting paper describing some low cost random number generators