• support@answerspoint.com

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:




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.

  • answered 7 years ago
  • G John


The interpretation of

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


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

The division operator and the multiplication operator have the same operator precedence, and they group left-to-right. Thus your expression is effectively

force.length = this.gravity * pa.mass * pb.mass;

I think perhaps your expectations of how the simulation should work may be off.

  • answered 7 years ago
  • B Butts

Your Answer

    Facebook Share        
  • asked 7 years ago
  • viewed 1563 times
  • active 7 years ago

Best Rated Questions