javascriptsimulationphysicsverlet-integration

Universal law of gravitation - order of operations


I'm working on a little N-Body Simulation in JavaScript. It's running as I expected, but I noticed something odd. The simulation uses a verlet integrator and the function that accumulates the forces has the line:

force.length = (this.gravity * pa.mass * pb.mass) / dist * dist;

As I said, the simulation works as expected, but shouldn't the code actually read:

force.length = (this.gravity * pa.mass * pb.mass) / (dist * dist);

where the order of operations is correct for the square of the distance? When I have it that way the simulation blows up. Kind of an odd thing, the wrong way works correctly, or seems to. Anyone have an idea of what the issue is? Complete code and running example here:

https://gist.github.com/arctwelve/ca5868f80d0b0cd5791e http://bl.ocks.org/arctwelve/ca5868f80d0b0cd5791e

TIA


Solution

  • In your code, var dist = vect.x * vect.x + vect.y * vect.y; is actually setting dist to the square of the distance, so force.length = (this.gravity * pa.mass * pb.mass) / dist; should give you the correct result.