Group Abstract Group Abstract

Message Boards Message Boards

0
|
7.9K Views
|
8 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Speeding up a loop?

Posted 3 years ago
POSTED BY: Diogo Carvalho
8 Replies
Posted 3 years ago
POSTED BY: Eric Rimbey
Posted 3 years ago

Another thing you might try is Nearest.

Nearest[deltaSequence -> {"Index", "Distance"}, particleValues, {All, deltaParam}]

I renamed some variables because I was having trouble keeping track, but I think it would be this with your original variables:

Nearest[xg -> {"Index", "Distance"}, xp, {All, dx}]

I included my renamed version so that if I messed it up, you can hopefully correct it.

Anyway, what this will give you is something like the following:

{{{6, 0.0122529}, {7, 0.0877471}}, {{18, 0.00370914}, {17, 
   0.0962909}}, {{18, 0.0247811}, {17, 0.0752189}}, {{4, 
   0.0364263}, {5, 0.0635737}}, {{8, 0.0122352}, {7, 0.0877648}}, <...etc...>}

You should be able to write a function that uses this data to do your update to your rho table. I haven't done a performance comparison.

POSTED BY: Eric Rimbey

Diogo,

I am confused. so you are saying my code should be something like this?

Almost. However, Do[] loops are generally not recommended in Mathematica. Also, the FractionalPart is always positive so the Abs is not necessary. I would use Map or MapThread instead of the loop.

For example, your posted code takes 0.2 seconds to run compiled. This code gets the same result but takes only 0.007 seconds on my M1 machine without compilation:

AbsoluteTiming[rr = Table[q*nparticles/(dx*ngrid), n];
 rr[[ngrid + 1]] = 0;
 MapThread[(rr[[#1]] = rr[[#1]] - q*(1 - (#2))/dx) &, {pos, frac}];
 MapThread[(rr[[#1]] = rr[[#1]] - q*((#2))/dx) &, {pos + 1, frac}];
 rr[[1]] = rr[[1]] + rr[[ngrid + 1]];]

Regards,

Neil

POSTED BY: Neil Singer
Posted 3 years ago

Related question on MSE.

POSTED BY: Rohit Namjoshi
POSTED BY: Neil Singer
Posted 3 years ago

I am confused. so you are saying my code should be something like this?

Do[pos=Floor[x[[i]]/dx];rho[[pos]]=q/dx * Abs[FractionalPart[x[[i]]/dx], {i,nparticles}];
 Do[pos=Ceiling[x[[i]]/dx];\[rho][[pos]]=q/dx * Abs[FractionalPart[x[[i]]/dx], {i,nparticles}];

Because the particles influence the point of the grid before and after them.

POSTED BY: Diogo Carvalho
Posted 3 years ago

Just a clarification... Is it expected that each position of \[Rho] can get updated multiple times during each inner loop?

POSTED BY: Eric Rimbey
Posted 3 years ago

Yes. ρ is calculated at each point xg[[j]]. The number of times ρ is updated depends on the number of particles that has a position between xg[[j]] + or - dx.

POSTED BY: Diogo Carvalho
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard