Given a set of n particles in two-dimensional space, where each particle experiences an attractive force with respect to all other particles in the set, proportional to the inverse square of the distances between them, can you imagine any clever methods for calculating the net force experienced by each particle without performing distance computations n ^ 2?
From the Particle class of my program:
public void calculateAttractions(List<Particle> entities) { foreach (Particle p in entities) { if (!p.Equals(this)) { Vector2 dx = this.Position - p.Position; this.ApplyForce(-dx / dx.LengthSquared()); } } }
The brute force method can only simulate ~ 150 particles in my program (using the XNA infrastructure and the Farseer physics engine) before running into performance issues.
If there is no other way, how can I optimize this code, or how can I cheat? I tried to randomize the call to compute Attractions () based on particles with particles, so that at any given time, only about 1/3 of the particles are actually updated. This led to some performance improvements, but of course, at the cost of accuracy.
What I'm trying to do is like calculating the gravitational force. Someone from this topic suggested working with complex numbers and using the equation:
(z-z')/abs(z-z')**3
However, I do not know what z refers to, and I cannot find a link to this equation anywhere else.
EDIT: although I accepted the answer below, I ended up using a solution that no one mentioned: lookup table. In principle, I pre-calculate the force acting on one particle by another particle at all distances (with a resolution of 1 pixel) up to 2000 pixels in any direction. The forces can then be determined without any calculation of the distance at run time. Although this is not an exact solution, the distortion is not perceived, and this allowed me to increase the number of simulation particles by a factor of three (until the moment when the number is now limited by the physical engine, and not by the n-body problem.)