1

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?

4

1 回答 1

7

数组“v”在第一次迭代后将保持相同的值。您应该在每个循环中重新初始化它。

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);
}
于 2013-06-13T15:34:26.750 回答