This question already has answers here:
using rand to generate a random numbers
(6 answers)
Closed 8 years ago.
I am currently using these functions in C++ to find a number and a suit for a card.
int getnumber () {
srand(time(0));
int number ;
number = rand()% 13 + 1;
return number;
};
int getsuitn () {
srand(time(0));
int suitn;
suitn = rand() % 4 + 1;
return suitn;
}
the output is always just the default constructor for the class, I have all the libraries needed to make this work, what am I doing wrong?
With the same seed the same sequence will be generated every time. Since you seed with the current time in seconds, every call you make in the same second will get the same first number from the sequence. Your whole program probably runs in under a second, so they all get the same result.
Seed the random number generator once at the start of your program.
Question: are you using c++11?
You should use <random> header. These functions will be mostly deprecated in C++14. An example of how to use <random>:
cppreference example
Related
This question already has answers here:
srand(time(NULL)) generating similar results [duplicate]
(8 answers)
Closed 4 years ago.
I am using the rand() function in c++ yet i am getting very close numbers every time here is my code`
int pickrandom(){
time_t t;
time(&t);
srand (t);
return rand();
}
I get numbers like : 13809 13812 13812 13817
You are seeding the random generator on every pickrandom call, which defeats the purpose of seeding. Also, rand is a low-quality generator that has been superseded by the C++11 <random> library – you should use that instead.
This question already has an answer here:
std::random_shuffle produce the same result even though srand(time(0)) called once
(1 answer)
Closed 7 years ago.
I am writing a program that uses random numbers extensively in different ways and I am getting the same random numbers each time. I know to put srand(time(NULL));at the beginning of the program to seed the random number generator and so I have that, but it isn't working. Perhaps it has something to do with XCode or the Mac or something else? I can't find a similar problem online that I has a solution I haven't already tried. Some ways I'm using the random numbers are:
for (int i=0; i<num; i++)
{
chrom_arr[i] = i;
}
random_shuffle(&chrom_arr[0], &chrom_arr[num-1]);
(to get an array with a series of random ints between 0 and num-1)
int crossover = rand() % num;
and other simple things like that. Even though I have srand(time(NULL)); at the beginning, it still doesn't work. I've also tried srand(time(0)); and also putting it in different parts of the program, but I have since learned that's not right.
Alex, can you please post a small but complete program that fails to generate different random numbers every time you run it? I'd be interested to see it...
Here's one that (of course) does yield different numbers every time it is run on my Mac:
#include <iostream>
#include <ctime>
#include <cstdlib>
int main()
{
srand(time(NULL));
for (int i = 0; i < 10; ++i)
std::cout << rand() % 10 << std::endl;
return 0;
}
What does it do if you compile and run it several times on your computer?
UPDATE:
I thought you meant srand() + rand() also produced identical numbers every time. That is not true. However, you are right about the behaviour of srand() + random_shuffle(): it may indeed produce the same numbers every time, depending on your compiler. It does on my compiler (clang on Mac) too.
This is explained here.
You should try somethig like this:
srand(static_cast<unsigned int>(time(0)));
std::shuffle(chrom_arr.begin(), chrom_arr.end(), default_random_engine(rand()));
This will work as long as chrom_arr is a std::vector. Once you are using C++, I presume this is what you are trying to do.
This question already has answers here:
Generating a random integer from a range
(14 answers)
rand() function not generating enough random
(2 answers)
Closed 8 years ago.
I use this function to generate random integer.
int rnd(int min, int max)
{
static int srand(time(0));
return min + rand() % max;
}
Is it right? May be better to move srand(time(0)); to the main function? Like this:
int rnd(int min, int max){
return min + rand() % max;
}
int main(){
srand(time(0));
..............
}
Your first version does not do what you intend:
int rnd(int min, int max)
{
static int srand(time(0));
return min + rand() % max;
}
This does not call the function srand. It declares a static variable of type int and assigns it the value of time(0). Like int a(42); (or in C++11 int a{42};) declares an integer and sets it to 42.
Definitely use the second variant. It also makes live much easier, if you want to have another function for creating random values in a different way.
Additionally I strongly recommend to use std::random (or boost::random if you are not allowed to use C++11 for some obscure reason).
Definitely. You are now not calling the function but creating an integer variable named srand instead which shadows the global srand().
It does not help to re-seed the random generator each time -- it would even return always the same value if called during the same second! Calling it just once in main() would be better.
Also it should probably be min + rand() % (max - min + 1).
In general you only need to initialize the pseudorandom number generator once, so in the main function is a good idea.
I believe Netscape once had a bug due to seeding the random number generator too often, which caused its SSL implementation to be more easily cracked.
Is it right?
If by that you mean "is it generating a random number?", the answer is yes.
If you mean "is it optimal?" then the answer is no. You only need to initialize the sequence of random number once.
May be better to move srand(time(0)); to the main function
Maybe ... (you know what you need better than us).
What are you trying to achieve (that is, what are you using this random generator for)? If it is anything with financial data, online gambling application (or anything that takes/manages/costs money) it is not ok (nor is it to use srand and rand - you need something stronger).
This question already has answers here:
function with rand initializes matrix always the same way
(2 answers)
Seeding a random number generator C++ [duplicate]
(4 answers)
Closed 8 years ago.
I'm making a small "dungeons and dragons" type of program to help demonstrate rand() command to me. It's working just fine, except it always picks 2. Never 1. Help?
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
cout << "welcome to T's version of dungeons and dragons! \n Scenario:";
int Scenario1 = rand() % 2 + 1;
if(Scenario1==1){
cout << "you come across a sleeping traveler, Do you ignore him, or steal his loot?";
}
else {
cout << "you find an old bandit hideout in a cave. Do you ignore, or enter?";
}
}
rand() will essentially generate the same series of numbers every time if you don't seed it.
The seed determines how the rand function generates numbers. For better 'randomness', call the following once at the beginning of the program, for example as the first statement inside main:
srand(time(NULL));
This seeds the random number generator with the value of the current UNIX timestamp, which should be unique enough to guarantee a better illusion of randomness.
More information on srand here:
http://www.cplusplus.com/reference/cstdlib/srand/
Edit
As others have mentioned, it's better to use the functionality found in the <random> header, as this is a more modern approach that avoids many of the pitfalls of the srand/rand paradigm.
rand() will always generate the number in same sequence.
To generate totally random number you can use srand(time(0)); time() is available in header file called #include <ctime>
Fore more detail please have a look :: https://www.youtube.com/watch?v=naXUIEAIt4U
This question already has answers here:
How to generate a random number in C++?
(14 answers)
Closed 5 years ago.
I have two questions.
What other ways are there to seed a psuedo-random number generator in C++ without using srand(time(NULL))?
The reason I asked the first question. I'm currently using time as my seed for my generator, but the number that the generator returns is always the same. I'm pretty sure the reason is because the variable that stores time is being truncated to some degree. (I have a warning message saying, "Implicit conversion loses integer precision: 'time_t' (aka 'long') to 'unsigned int') I'm guessing that this is telling me that in essence my seed will not change until next year occurs. For my purposes, using time as my seed would work just fine, but I don't know how to get rid of this warning.
I have never gotten that error message before, so I assume it has something to do with my Mac. It's 64-bit OS X v10.8. I'm also using Xcode to write and compile, but I had no problems on other computers with Xcode.
Edit:
After toying and researching this more, I discovered a bug that 64-bit Macs have. (Please correct me if I am mistaken.) If you try to have your mac select a random number between 1 and 7 using time(NULL) as the seed, you will always get the number four. Always. I ended up using mach_absolute_time() to seed my randomizer. Obviously this eliminates all portability from my program... but I'm just a hobbyist.
Edit2:
Source code:
#include <iostream>
#include <time.h>
using namespace std;
int main(int argc, const char * argv[]) {
srand(time(NULL));
cout << rand() % 7 + 1;
return 0;
}
I ran this code again to test it. Now it's only returning 3. This must be something to do with my computer and not the C++ itself.
Tl;dr but, most likely, you're doing it wrong. You're only supposed to set the seed once, whereas you might have something like:
for ( ... )
{
srand(time(NULL));
whatever = rand();
}
when it should be
srand(time(NULL));
for ( ... )
{
whatever = rand();
}
1.Not really. You can ask user to input random seed, for example. Or use some other system parameters, but this won't make a difference.
2.To rid of this warning you have to do explicit conversion. Like:
unsigned int time_ui = unsigned int( time(NULL) );
srand( time_ui );
or
unsigned int time_ui = static_cast<unsigned int>( time(NULL) );
or
unsigned int time_ui = static_cast<unsigned int>( time(NULL)%1000 );
to check whether this is really conversion problem you can simply output your time on the screen and see yourself
std::cout << time(NULL);
You should see random once at the begining of you program:
int main()
{
// When testing you probably want your code to be deterministic
// Thus don't see random and you will get the same set of results each time
// This will allow you to use unit tests on code that use rand().
#if !defined(TESTING)
srand(time(NULL)); // Never call again
#endif
// Your code here.
}
For x86, direct call to the CPU time stamp counter rdtsc, instead of a library function TIME(NULL), could be used. Below 1) reads timestamp 2) seed RAND in assembly:
rdtsc
mov edi, eax
call srand
For C++, the following would do the job with g++ compiler.
asm("rdtsc\n"
"mov edi, eax\n"
"call srand");
NOTE: But may not be recommended if code is running in virtual machine.