Accepted Answer This is because MATLAB's random number generator is initialized to the same state each time MATLAB starts up. If you wish to generate different random values in each MATLAB session, you can use the system clock to initialize the random number generator once at the beginning of each MATLAB session.
The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1) were called at the program start. Any other value for seed sets the generator to a different starting point.
In the C programming language, the rand() function is a library function that generates the random number in the range [0, RAND_MAX]. When we use the rand() function in a program, we need to implement the stdlib. h header file because rand() function is defined in the stdlib header file.
In order to allow for different values, a different seed is used in each run. One thing that changes between runs and can easily be used is the start time of the program. Show activity on this post. If you do not add srand(), each time you run your program, rand will generate the same random numbers.
So, I'm trying to create a random vector (think geometry, not an expandable array), and every time I call my random vector function I get the same x value, though y and z are different.
int main () {
srand ( (unsigned)time(NULL));
Vector<double> a;
a.randvec();
cout << a << endl;
return 0;
}
using the function
//random Vector
template <class T>
void Vector<T>::randvec()
{
const int min=-10, max=10;
int randx, randy, randz;
const int bucket_size = RAND_MAX/(max-min);
do randx = (rand()/bucket_size)+min;
while (randx <= min && randx >= max);
x = randx;
do randy = (rand()/bucket_size)+min;
while (randy <= min && randy >= max);
y = randy;
do randz = (rand()/bucket_size)+min;
while (randz <= min && randz >= max);
z = randz;
}
For some reason, randx will consistently return 8, whereas the other numbers seem to be following the (pseudo) randomness perfectly. However, if I put the call to define, say, randy before randx, randy will always return 8.
Why is my first random number always 8? Am I seeding incorrectly?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With