Greetings,
in a Monte Carlo simulation of N hard spheres, radius R>0, I randomly choose a sphere and propose a new position for this particle in the direct vicinity of its original position.
Then I need to check wether the particle, at its proposed new position, overlaps with any other sphere.
Usually, one would write a simple loop that iterates through all the other spheres and checks wether the 'chosen' particle overlaps with any of them.
However, since I know that the new position of my particle is in the direct vicinity of its original position, I thought I could somehow use this to my advantage by only considering other spheres that are close to my particle's original position.
But then I would have to iterate through all spheres as well in order to figure out what spheres fit in that category, so the problem was just shifted.
Here is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <cmath>
#include <vector>
using namespace std;
struct particle{
double x;
double y;
double z;
};
//this function checks wether a chosen sphere u overlaps with any other sphere
bool overlap(vector<particle> pos, size_t u, const double R, double L){
double rx, ry, rz;
for(size_t j=0; j<pos.size(); j++){
if(u==j) continue;
//calculate shortest distance between spheres (periodic boundaries!)
rx=abs(pos.at(u).x-pos.at(j).x);
ry=abs(pos.at(u).y-pos.at(j).y);
rz=abs(pos.at(u).z-pos.at(j).z);
if(rx>0.5) rx=1-rx; //periodic boundaries
if(ry>0.5) ry=1-ry;
if(rz>0.5) rz=1-rz;
if(rx*rx+ry*ry+rz*rz < 4*(R/L)*(R/L)){
return true;
}
}
return false;
}
|
pos-vector stores the positions of all the particles (the chosen particle is already on its proposed new position), size_t u is the vector index of the chosen particle. I am in relative coordinates here, which is why the overlap condition
if(rx*rx+ry*ry+rz*rz < 4*(R/L)*(R/L))
looks like this (L=system length).
Under the condition that the new position of particle u, that I check for overlaps, is chosen randomly from within a small box of length a around particle u's original position:
Are there any ways to reduce computational effort here?
Regards!