Adrian
Adrian

Reputation: 2365

C++ random numbers the same when called in a while loop

I'm creating vectors of different length and direction and there's some behaviour I can't explain.

I start with a random seed and declare a vector:

srand(time(NULL));
std::vector<Particle> psystem;

The following code then creates demonstrably "random" vectors:

float v[3] = {0};
for(int i = 0; i < vectors; ++i) {
    v[0] = float(rand() % 200 - 100) / 3000;
    v[1] = float(rand() % 200 - 100) / 3000;
    v[2] = float(rand() % 200 - 100) / 3000;
    Particle p(0, 0, 0, v[0], v[1], v[2]);
    psystem.push_back(p);
}

An added while-loop causes all elements in psystem to have the same exact values (e.g all have [0.00345, -0.234, 0.00701]):

const float min_length = 0.0174;

float v[3] = {0};
for(int i = 0; i < vectors; ++i) {
    while(sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) < min_length) {
        v[0] = float(rand() % 200 - 100) / 3000;
        v[1] = float(rand() % 200 - 100) / 3000;
        v[2] = float(rand() % 200 - 100) / 3000;
    }
    Particle p(0, 0, 0, v[0], v[1], v[2]);
    psystem.push_back(p);
}

This runs very fast, so I don't mind it looping a bit until a random v[0+1+2] combination fulfills the while condition. However I'm Somehow killing the random assignment along the way. What am I missing?

Upvotes: 1

Views: 532

Answers (1)

Matzi
Matzi

Reputation: 13925

The array 'v' will hold the same values after the first iteration. You should reinitialize it in each loop.

float v[3] = {0, 0, 0};
for(int i = 0; i < vectors; ++i) {
    v[0] = 0;
    v[1] = 0;
    v[2] = 0;
    while(sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) < min_length) {
        v[0] = float(rand() % 200 - 100) / 3000;
        v[1] = float(rand() % 200 - 100) / 3000;
        v[2] = float(rand() % 200 - 100) / 3000;
    }
    Particle p(0, 0, 0, v[0], v[1], v[2]);
    psystem.push_back(p);
}

Upvotes: 7

Related Questions