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?
srand()
is OK up until you want to be able to repeat a previous run - but that's a wholly separate problem from the 'persistent 8'. Maybe you should temporarily track the return values fromrand()
- perhaps with a wrapper function. And I'd be worried about the repetition of the algorithm; use a function 'int randominteger(int min, int max)' to avoid it. (Note that seeding with time is not good for cryptographic randomness - it is rather predictable.) – Cyruscystsizeof(time_t)
on your system? What'ssizeof(unsigned)
? Does(unsigned)time(NULL)
return the same value repeatedly? (Does the value get truncated wierdly?) – Scyphussrand(time(NULL))
will implicitly convert thetime_t
result oftime(NULL)
to theunsigned
argument type required bysrand
. – Montrealsrand
andrand
and displays the results. If it produces the same anomaly, that will make it easier to track down. If it doesn't, perhaps there's something wrong in the implementation of yourVector
class. Some implementations ofrand()
are better behaved than others. What OS and runtime library are you using? – Montrealsrand
you forgot about somewhere. – Object