I'm having some trouble with this code:
for (long long int loop = 0; loop < 50000000; loop++)
{
srand( (unsigned)time(NULL) ); // set the seed
int r = abs(rand()); // stores the random seed for this loop
int res = loop + r - r * r / r; // random operations with the loop number and the random seed.
cout << "Loop number: " << loop << ". " << "Result: ";
cout << res << endl;
}//this was missing
If you run that code, you can see, very clearly in the console, that the output of it is only doing the calculations once every few seconds. What's going on? The number should be completely different for each loop, because it's doing calculations with random numbers. Instead, the number changes every x loops ran, and then it only seems to increase between these times it actually does the math.
Do I need to specify I want the loop to wait until everything is complete before moving on?
Because you're doing srand in the loop with time seed. time()'s granularity is in seconds so until one second has passed it will return the same seed and therefore the same random number. Do srand outside the loop.
The point of seeding the rand function with srand is that the sequence of generated random numbers is different with each program run. You need only one srand in your program.
And by the way, rand() always returns a non-negative number, so abs is useless. Be careful though that r can be 0, and you do divide by r, which potentially has undefined behavior. do r = rand()+1 to be safe.
Your seed is the same for the same second, so the random numbers with that seed will be the same. You could try taking out the srand.
srand( (unsigned)time(NULL) ); // set the seed
for (long long int loop = 0; loop < 50000000; loop++)
{
int r = abs(rand()); // stores the random seed for this loop
int res = loop + r - r * r / r; // random operations with the loop number and the random seed.
cout << "Loop number: " << loop << ". " << "Result: ";
cout << res << endl;
}
Cheers
Related
I am trying to create a slot machine where I have to generate 3 random numbers from 2 - 7 and then use that output to give different outcomes. For example if the output is 777 and then your bet gets multiplied by 10, if it's 222 then it gets multiplied by 5. I can't seem to get the output of the rand function into a variable to use it and its not calculating properly.
Code:
This is not the full code
if (bet <= 2000)
{
std::cout << endl;
int game_num = 0;
srand (0);
for (int i = 0; i < 3; i++)
std::cout << (rand() % 1) + 2;
std::cout << endl;
if (game_num == 777)
{
bet = bet * 10;
std::cout << "You Won: " << bet << endl;
return 0;
}
else if (game_num == 222 || 333 || 444 || 555 || 666)
{
bet = bet * 5;
std::cout << "You Won: " << bet << endl;
return 0;
}
The issue is that you aren’t seeding the random number generator properly in this situation.
This will always return the same sequence of random numbers every time the program runs.
srand(0)
You want to seed the random number generator with a new value each time the program is run.
Using the timestamp at runtime will enable that behavior.
srand(time(0))
Dan's answer is correct, you're using the same seed every time, so every sequence of numbers is identical. You need to seed with a random value. Time as source of randomness isn't great in terms of being random, but it's working unless you run twice in the same second (due to time() only counting seconds, and seconds being ... long for modern computers, unlike 1970's computers, when that way of seeding was invented).
So, instead, honestly, don't use srand or rand at all. They're really bad random number generators to begin with, and their dependence on "hidden" state makes them a nightmare to deal with. Simply. Ignore their existence!
C++ brings its own random facilities:
You want a uniform integer distribution, so use uniform_int_distribution. Seed with an actual random value from actual randomness-generating events.
#include <random>
// …
// Somewhen before you need the random numbers, not every time:
// Will be used to obtain a seed for the random number engine
std::random_device real_random;
// Set up the generator for random bits, seed it from the actual random
std::mt19937 gen(real_random());
// Use that to generate random numbers in [2,7]
std::uniform_int_distribution<> distrib(2, 7);
// Where you need the randomness:
for (int i = 0; i < 3; i++)
std::cout << distrib(gen) << "\n";
I'm trying to create a program using Merge Sort for an assignment, using rand and srand to place random numbers in the array. The goal is to sort a large number of values entered manually by the user and count how long it takes the program in seconds to process it.
Everything works so far, but the one problem I'm getting is that a random value is only being assigned to the first position and the rest are given 0
This is the body of my merge function (main program) where I suspect the issue might be:
//Function that begins the Merge Sort option and acts as int main()
void mergeSortAlg(){
srand(time(NULL));
int n= 0;
cout << "\n\nPlease make a selection by typing one of the following:\n";
cout << "1000 \n10000 \n50000 \n\n";
cin >> n;
cout << "You have selected: " << n << "\n";
cout << "Stopwatch has started...\n\n";
//statement that begins counting the execution time for the program
auto start = chrono::steady_clock::now();
int arr[n]= {rand() % 100}; //generating random values between 1-99 in the array
int arr_size= sizeof(arr) / sizeof(arr[0]);
cout << "The array list before sorting is: \n";
displayMergeArray(arr, arr_size);
mergeSorting(arr, 0, arr_size-1);
cout << "\n\n\nThe array list after sorting is: \n";
displayMergeArray(arr, arr_size);
auto end = chrono::steady_clock::now(); //stopping the timer at the end of the merge sort
//printing the amount of time (in seconds) the program took to sort the values
cout << "\n\n\nTotal processing time elapsed:\n" << chrono::duration_cast<chrono::seconds>(end - start).count() << " seconds\n\n\n";
}
Note that the mergeSortAlg() function just acts as int main() since the main program currently is being used to call a menu function for 3 sorting options
Still kind of new to merging and C++ in general, so I'm not sure how to use rand to assign the number of random values needed based on how many positions are entered by the user.
You expect array initialization to work in a way it does not work. This
int arr[n]= {rand() % 100};
Initializes the first element with rand()%100 and the remaining elements are zero-initialized.
Moreover int arr[n] is not valid c++. See here: Why aren't variable-length arrays part of the C++ standard?.
You can use a std::vector when the size is only known at runtime and you can use a loop to roll n random numbers instead of just one:
std::vector<int> arr(n);
for (auto& e : arr) e = rand() % 100;
PS: Note that rand() is not the best way to generate random numbers. rand() is only loosely specificed and implementations are known to have issues. And on top of that rand() % N is not uniformly distributed (only if RAND_MAX % N == 0). You can find better random generators in <random>.
This question already has answers here:
rand() returns same values when called within a single function
(5 answers)
Closed 3 years ago.
I am calling to a random number generator function twice and theoretically should be getting 2 random numbers each time but instead I am being given the same number both times.
I have tried calling to the function in different way and replaced the integer in srand to 0 and null but still receive the same answer
int randomNUM()
{
srand(time(NULL));
int RL = rand() % 100;
return RL;
RL = 0;
}
int main()
{
int RL = randomNUM();
int RL2 = randomNUM();
cout << "RL: " << RL << endl;
cout << "RL2: " <<RL2 << endl;
}
I expect the results for RL and RL2 to be completely randomized numbers between 1-99 but instead get the same number for each of them.
You should only call srand() once, right at the beginning of your program. Once you call srand() the string of random numbers is reset.
Do something like
int randomNUM()
{
int RL = rand() % 100;
return RL;
RL = 0;
}
int main()
{
srand(time(NULL));
int RL = randomNUM();
int RL2 = randomNUM();
cout << "RL: " << RL << endl;
cout << "RL2: " <<RL2 << endl;
}
srand sets the seed. You should do it once in main, not every time you want a random number. So instead, you should have
int randomNUM()
{
// removed srand(time(NULL));
int RL = rand() % 100;
return RL;
RL = 0;
}
int main()
{
srand(time(NULL));
int RL = randomNUM();
int RL2 = randomNUM();
cout << "RL: " << RL << endl;
cout << "RL2: " <<RL2 << endl;
}
You are reseeding the random number generator each time you call randomNUM(). Since it doesn't take much time between calls to randomNUM(), then the value that time() returns is the same both times. As a result, the random number generator restarts the random number sequence at the same beginning point. There are two ways you can solve the problem:
Move the call to srand() to be before all calls to randomNUM()
Have a static boolean value that you initialize to false and then set to true the first time you call srand(). You can then check what the value of this variable is to determine whether you should call srand().
I am trying to generate a file of 10000 integers between 0 and 100 000 so I can do a MergeSort on them later.
When I generate the file using fstream, I never get an integer over 32760.
The following method generates the file and then reads it back and checks for any integer over 32750. I usually get between 3-5 integers between 32750 and 32760. Why does this happen and how can I fix it? Is it a seed problem or the actual use of the Random function?
// sizeOfArray = 10000
void generateFile() {
ofstream fout("unsorted.txt");
srand(time(NULL));
// Generating the file
int num;
for(int i = 0; i < sizeOfArray; i++) {
num = rand() % 100000;
if(i < sizeOfArray-1)
//fout << i+1 << ": " << num << endl;
fout << num << endl;
else
//fout << i+1 << ": " << num;
fout << num;
}
// Reading the File Back
ifstream fin("unsorted.txt");
for(int i = 0; i < sizeOfArray; i++) {
fin >> num;
if(num > 32750)
cout << num << endl;
}
cin.get();
}
SOLVED
Using the answer provided below I generated the file 500 times
and the highest Integer I received was 99931.
The highest random value that you can get from rand() is RAND_MAX, a library-dependent constant. In your case, it appears to be set to 2^15-1, the highest positive number that fits in a signed 16-bit integer.
When you need to generate numbers that are larger than RAND_MAX, call rand() several times, each time multiplying by RAND_MAX. For example, in your case the following code should work (I am assuming that your int has 32 bits):
num = rand();
num *= RAND_MAX;
num += rand();
num %= 100000;
Note that merely adding three random numbers together to get the desired range will not produce the same random distribution as multiply and add approach.
You can use one of the new random number generators introduced with C++11 to get a larger range: http://en.cppreference.com/w/cpp/numeric/random
If you don't have C++11 you can also get it from Boost: http://www.boost.org/doc/libs/1_53_0/doc/html/boost_random.html
Depends on what you are using: http://www.cplusplus.com/reference/cstdlib/RAND_MAX/
I need a value between 0.0 and 1.0. So I seed the random number generator using time. Then I get a value between 0 and 10 using the rand function. After that I take that value and divide it by 10 to get my decimal value. My issues is that the program will randomly crash when I try and print out the value generated by (dRandNum % 10). Also of note is that it is not crashing in the middle of the for loop. It's always right at the beginning on the first attempt to print out. I'm honestly thinking that there's just something really strange with the compiler and was wondering if anyone could direct me otherwise.
double dRandNum = 0;
int tempRand = 0;
/* initialize random seed: */
srand ( (unsigned)time(0) );
for(int i = 0; i < 40; i++)
{
tempRand = rand();
cout << "tempRand= " << tempRand << endl;
dRandNum = tempRand % 10;// + 1;
// Crashes here for some reason. If I don't try and print the value it's fine
cout << "Random Num Before " << i << ": " << dRandNum << endl;
dRandNum = dRandNum / 10;
cout << "Random Num After " << i << ": " << dRandNum << endl;
weights[i] = dRandNum;
}
OK, I'm going to take a random stab here and ask you to show us the declaration of the weights[] array.
And I'll even wager the traditional virtual jelly doughnut that weights[] is not declared to hold 40 elements.
For the sake of the program one can assume the function is wholly independent
That's a big mistake, it never is. This has heap corruption written all over it. Which rarely causes a crash at the line of the code that corrupts the heap. Always later, sometimes much later.