vendredi 4 décembre 2015

Program ignoring condition?

In my code, I'm trying to prevent circles from overlapping so I specified it as a condition on the distance between the centres of the circles but it seems to not work all the time

as you can see :

enter image description here

could it be some kind of numerical precision rounding problem ?

Here is the relevant code (I can post the whole code if needed):

const double win_size = 800;
const double L = 50e-9; //box size (m)
const double k = 1.38e-23; // Boltzmann constant = 1.38e-23 J/K
const double R = 1.6e-10*30;  //N2 radius = 1.6e-10 m 
const double m = 4.65e-26; //N2 mass = 4.65e-26 kg

struct parameters{
    double x;
    double y;
    double v_x;
    double v_y;
};

bool empty_space(double x, double y, struct parameters gas[], int N, int i){
    if (i == 0) return true;
    for (int i = 0; i<N; i++){
        if (pow(x-gas[i].x,2) + pow(y-gas[i].y,2) <= 4*R*R){
            cout << gas[i].x << " " << gas[i].y << endl;
            return false;
        }
    }
    return true;
}

void initialize(struct parameters gas[], int N, double T){    // Sets initial conditions (velocity depends on temperature)
    int tries = 0;
    double x, y;
    for (int i=0; i<N; i++){
        if (tries == 10000){
            cout << "Couldn't fit " << N << " molecules in the box, aborting simulation... " << endl;
            exit(1);
        }
        x = R + (L - 2*R)*rand()/RAND_MAX;
        y = R + (L - 2*R)*rand()/RAND_MAX;
        if (empty_space(x,y,gas,N,i)){
            gas[i].x = x;
            gas[i].y = y;
        }
        else {
            i--;
            tries++;
        }
        gas[i].v_x = sqrt(2*k*T/m)*(1-2.0*rand()/RAND_MAX);
        gas[i].v_y = (2*(rand()%2) - 1)*sqrt(2*k*T/m - pow(gas[i].v_x, 2));
    }
}

void draw(int window, struct parameters gas[], int N, int automatic){
    g2_pen(window,g2_ink(window,0.8,0.3,0.4));
    for (int i=0; i<N; i++){
        g2_circle(window,gas[i].x*win_size/L,gas[i].y*win_size/L,R*win_size/L);
    }
    g2_flush(window);
    usleep(10000);
    g2_pen(window,0);
    g2_filled_rectangle(window,0,0,win_size,win_size);
    if (!automatic) getchar();
}

Aucun commentaire:

Enregistrer un commentaire