The function below runs, but always returns the same numbers each time I run the program. Is there a way to generate random numbers that are different each time I run the program?
int getrand(int min,int max){
int rnum = rand()%(max-min)+min;
return rnum;
}
You might like to use the high-quality standard library random number generation facilities:
#include <random>
typedef std::mt19937 rng_type;
std::uniform_int_distribution<rng_type::result_type> udist(min, max);
rng_type rng;
int main()
{
// seed rng first:
rng_type::result_type const seedval = 4; // or implement a good get_seed()?
rng.seed(seedval);
rng_type::result_type random_number = udist(rng);
return random_number;
}
try with this:
/* initialize random seed: */
srand ( time(NULL) );
somewhere when your program start ( absolutely not in your getrand() function ). This will force the generator to start each time with a different seed.
Seems like you forgot to call srand.
Pseudo random number generators need to be "seeded" before you use them; the default seed is the same every time, so you get the same sequence.
Typically you use something like srand(time(NULL)), but this fails if you run the program again within a second.
It's also good to use up a random number or two after seeding, since the first few values are highly correlated with the seed itself.
a simple solution to randomize once would be:
int getrand(int min, int max) {
static bool init = false;
if (!init) {
srand(time(NULL));
init = true;
}
return rand()%(max-min)+min;
}
You need to initiate the seed. Check out srand. Also, try boost if you want:
boost::lagged_fibonacci607 base_prng(seed);
boost::variate_generator<boost::lagged_fibonacci607&,boost::uniform_smallint<> > prng(base_prng,boost::uniform_smallint<>(min,max))
Related
In this rather basic C++ code snippet involving random number generation:
include <iostream>
using namespace std;
int main() {
cout << (rand() % 100);
return 0;
}
Why am I always getting an output of 41? I'm trying to get it to output some random number between 0 and 100. Maybe I'm not understanding something about how the rand function works?
You need to change the seed.
int main() {
srand(time(NULL));
cout << (rand() % 101);
return 0;
}
This srand thing also works for C.
See also:
http://xkcd.com/221/
For what its worth you are also only generating numbers between 0 and 99 (inclusive). If you wanted to generate values between 0 and 100 you would need.
rand() % 101
in addition to calling srand() as mentioned by others.
srand() seeds the random number generator. Without a seed, the generator is unable to generate the numbers you are looking for. As long as one's need for random numbers is not security-critical (e.g. any sort of cryptography), common practice is to use the system time as a seed by using the time() function from the <ctime> library as such: srand(time(0)). This will seed the random number generator with the system time expressed as a Unix timestamp (i.e. the number of seconds since the date 1/1/1970). You can then use rand() to generate a pseudo-random number.
Here is a quote from a duplicate question:
The reason is that a random number generated from the rand() function isn't
actually random. It simply is a transformation. Wikipedia gives a better
explanation of the meaning of pseudorandom number generator: deterministic
random bit generator. Every time you call rand() it takes the seed and/or the
last random number(s) generated (the C standard doesn't specify the algorithm
used, though C++11 has facilities for specifying some popular algorithms), runs
a mathematical operation on those numbers, and returns the result. So if the
seed state is the same each time (as it is if you don't call srand with a truly
random number), then you will always get the same 'random' numbers out.
If you want to know more, you can read the following:
http://www.dreamincode.net/forums/topic/24225-random-number-generation-102/
http://www.dreamincode.net/forums/topic/29294-making-pseudo-random-number-generators-more-random/
You are not seeding the number.
Use This:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
cout << (rand() % 100) << endl;
return 0;
}
You only need to seed it once though. Basically don't seed it every random number.
random functions like borland complier
using namespace std;
int sys_random(int min, int max) {
return (rand() % (max - min+1) + min);
}
void sys_randomize() {
srand(time(0));
}
"srand(time(NULL));" as 1st line at "main()" won't help you if you're using "rand()" at static init. somewhere. You better create "struct rnd_init { rnd_init() { srand (time (nullptr)); } }" named whatever suits you, as a static var at the scope where "rand()" is being used: at some constructor, or whatever.
I like to learn by screwing around with code, recently I copied and pasted a random number generator code. Then I removed all the lines of code that were not "necessary" to make the executable work to generate a random number. The final straw was me deleting "time" from srand.
srand((unsigned) time(0));
What is the point of "time(0)" here?
Does it use the time that the program is opened to generate the seed for the random number? Is that why removing it (time) makes it not work? Because then it doesn't have a seed?
Also...
include <stdlib.h>
include <stdio.h>
include <time.h>
int main()
{
srand((unsigned) time(0));
printf("Your dice has been rolled! You got:");
int result = 1 + (rand() % 20);
printf("%d", result);
}
that's the whole code and I noticed it used the "rand" result for output. Does the "rand" pull the seed from "srand"?
If you don’t “seed” the random number generator (or if you use the same seed value), you’ll get the same set of pseudorandom numbers.
Using the current time is an easy way to get a different seed every time.
The effect of srand cannot cross threads, so the random number seed should be set once on each thread. #Buddy said that using time(0) is the most convenient way to do this, and each call will get a different seed.Of course you can use an atomic variable .
std::atomic<int> seek(2374213); //init whatever you like
void thread1fun()
{
srand(++seek);
//...
int rand_num = rand();
}
void thread2fun()
{
srand(++seek);
//...
int rand_num = rand();
}
I was using rand() to produce some random numbers inside a function to populate some arrays but when I ran the program I noticed it was giving always the same row of generated numbers. The arrays were filled with the same row of generated numbers, it could be all 0 or a row with different numbers, but this pattern of numbers were the same in every array.
So I used debug to run the program step by step and it worked, rand() were generating different numbers to every array..
After this I decided to try another method to generate random numbers. I found a way to do this using Boost library.
This is the code I'm using now:
int main(){
typedef boost::mt19937 RNGType;
RNGType rng( (unsigned int)time(NULL));
boost::uniform_int<> one_to_six( 1, 6);
boost::variate_generator< RNGType, boost::uniform_int<> >
dice(rng, one_to_six);
for(int i=0;i<10;i++){
std::cout<<dice()<<std::endl;
}
}
If I use this code on main() function, everything goes well and it gives me 10 random numbers.
But if I put this code in a function to call it whenever I want it returns me the same number. Always 55555555, or 0000000..
Fun fact is, if I use debug and make a breakpoint at that function and run it step by step, it works again giving me always different numbers.
So I don't know what I'm missing here..
edit: When I used rand() I was using srand((unsigned int)time(NULL));
update 1:
int random(int begin,int end){
typedef boost::mt19937 RNGType;
RNGType rng( (unsigned int)time(NULL));
boost::uniform_int<> one_to_six( begin , end );
boost::variate_generator< RNGType, boost::uniform_int<> >
dice(rng, one_to_six);
return dice();
}
int main() {
for(int i=0; i<10; i++)
cout<<random(0,6)<<endl;
}
If I use this method it will give me the same sequence. If I run it step by step with debug it will work and give me different numbers.
You seed the rng in every function call, therefore you always get a random sequence (of length 1) starting from a seed. Since you use time(NULL) as the seed, all calls within a second will get the same seed and therefore the same sequence.
Since you don't want to have the same sequence repeatedly, you should not seed the rng between calls to random but instead continue the sequence from previous call, just like you do in the version that is entirely inside main. That requires you to maintain the state of the generator object between the calls instead of constructing a new one every time.
Found another way, and it's working now.
I'll let the code here if someone needs
boost::random::mt19937 gen;
int random(int begin, int end)
{
boost::random::uniform_int_distribution<> dist(begin, end);
return dist(gen);
}
int main(){
for(int i=0;i<10;i++)
std::cout << random(0,20) << std::endl;
}
Im trying to shuffle a deck of cards but random_shuffle produces the same result every time
void
Deck::shuffle() {
cout << "SHUFFLING CARDS!!!\n\n";
srand(time(0));
random_shuffle(cards.begin(), cards.end());
displayCards();
}
That's because you seed pseudo-random number generator to the same value each time:
srand(time(0));
The granularity of time are seconds, if I'm not mistaken. If you pause the execution for some time between calls to Deck::shuffle() you should see different results.
Remove that line from the function and call it once at the start of your program.
I think that the problem is because you are putting srand(...) inside of your function.
Try to move it outside (so that it will be executed only once)
You are reseeding the random number generator each time you call shuffle.
You should only seed the random number generator once per application (typically in your application initialization):
int main()
{
// other initialization
srand(time(NULL)); // seed the number generator
// ...
}
It is important to know that to be able to receive a "random" number you have to seed the generator. Also it should be seeded outside the function.
srand(time(NULL));
The use of the time function will help ensure that you will receive a random number.
time.h does need to be included for it to work. For more reference on srand, click here.
I'm not familiar with random_shuffle, but here's a function that does a perfect shuffle - in other words, each 52! permutations of the deck has to be equally likely.
This is from Gayle Laakmann's Cracking the Coding Interview (Question 20.2)
void Deck::shuffle() {
int temp, index;
for (int i = 0; i < cards.size(); i++){
index = (int) (rand() %(cards.size() - i)) + i;
temp = cards[i];
cards[i] = cards[index];
cards[index] = temp;
}
}
I'm in need of a C++ (pseudo, i don't care) random number generator that can get me different numbers every time I call the function. This could be simply the way I seed it, maybe there's a better method, but every random generator I've got doesn't generate a new number every time it's called. I've got a need to get several random numbers per second on occasion, and any RNG i plug in tends to get the same number several times in a row.
Of course, I know why, because it's seeded by the second, so it only generates a new number every second, but I need to, somehow, get a new number on every call. Can anyone point me in the right direction?
Sounds like you do it like this:
int get_rand() {
srand(time(0));
return rand();
}
Which would explain why you get the same number within one second. But you have to do it like this:
int get_rand() {
return rand();
}
And call srand once at program startup.
You only need to seed the generator once with srand() when you start, after that just call the rand() function. If you seed the generator twice with the same seed, you'll get the same value back each time.
You should only seed the PRNG once.
Boost.Random has a variety of pretty good random number generators.
If you're generating a large number of random numbers, you could try an XORShift generator. For longs (8 bit):
// initial setup
unsigned long x = ... init from time etc ...
// each time we want a random number in 'x':
x ^= x << 21;
x ^= x >> 35;
x ^= x << 4;
This code generates a unique random number only once.
#include <ctime>
# include <iostream>
using namespace std;
int main()
{
int size=100;
int random_once[100];
srand(time(0));
for (int i=0;i<size;i++) // generate unique random number only once
{
random_once[i]=rand() % size;
for(int j=0;j<i;j++) if (random_once[j]==random_once[i]) i--;
}
for ( i=0;i<size;i++) cout<<" "<<random_once[i]<<"\t";
return 0;