Basically I need to do a loop that has a big number of iterations so I am trying to make the code as fast as possible.
these are my initializations
eps = 8.85*10^(-12);
q = 80;
m = 50;
L = 2;
nparticles = 5000;
ngrid = 500;
vth = 2;
u = 1;
dx = L/ngrid;
dist = ProbabilityDistribution[
1./(2.*Pi*Power[vth, 2.])^(0.5)*Exp[-(v - u)^2./(2.*vth^2.)] +
1./(2.*Pi*Power[vth, 2])^(0.5)*
Exp[-(v + u)^2./(2. vth^2)], {v, -Infinity, Infinity},
Method -> "Normalize"];
And this For loop is one of the places in the code that I would like to improve. (I tried ParallelDo and it takes much longer)
\[Rho] = Table[q*nparticles/(dx*ngrid), ngrid + 1]; // AbsoluteTiming
\[Rho][[ngrid + 1]] = 0;
v = RandomVariate[dist, nparticles];
x = RandomVariate[UniformDistribution[{0, L}], nparticles];
r = 0;
xgrid = Range[0, L, dx] // N;
For[i = 1, i <= nparticles, i++,
Do[If[Abs[x[[i]] - xgrid[[j]]] <=
dx, \[Rho][[j]] = \[Rho][[j]] -
q*(1 - (Abs[x[[i]] - xgrid[[j]]])/dx)/dx; r += 1, 0] , {j,
ngrid + 1}]]; // AbsoluteTiming
\[Rho][[1]] = \[Rho][[1]] + \[Rho][[ngrid + 1]];
Is there some way to make this faster?
as I side note I would really apreciate if somebody can explain to me why I need to restart the kernel each time I run the dist function