I have only learnt python for for few months and totally a newb in C, I got a C code from the web, and I am dying to study it. But i only understand python language, so would someone can help to translate the following code to python would be great. Thanks in advance!
for(i=0; i<n; i++) { /* Foreach particle "i" ... */
ax=0.0;
ay=0.0;
az=0.0;
for(j=0; j<n; j++) { /* Loop over all particles "j" */
dx=x[j]-x[i];
dy=y[j]-y[i];
dz=yz[j]-z[i];
invr = 1.0/sqrt(dx*dx + dy*dy + dz*dz + eps);
invr3 = invr*invr*invr;
f=m[j]*invr3;
ax += f*dx; /* accumulate the acceleration from gravitational attraction */
ay += f*dy;
az += f*dx;
}
xnew[i] = x[i] + dt*vx[i] + 0.5*dt*dt*ax; /* update position of particle "i" */
ynew[i] = y[i] + dt*vy[i] + 0.5*dt*dt*ay;
znew[i] = z[i] + dt*vz[i] + 0.5*dt*dt*az;
vx[i] += dt*ax; /* update velocity of particle "i" */
vy[i] += dt*ay;
vz[i] += dt*az;
}
Thanks again!
Here’s a literal translation
(Edit: was a literal translation but there are some anomalies in the original C code which @hughdbrown pointed out in comments — looks like you’re trying to study this subject from code so utterly broken it wouldn’t even compile, which seems very unwise on your part, so, anyway, I’m taking the liberty of fixing the apparent errors and absurdities of the original C code in this Python “almost”-literal translation…):
Of course it assumes lists x, y, z, … vx, vy, vz are all pre-existing and of the same length
n, just like the C code snippet assumes for the same-named arrays.