• support@answerspoint.com

Universal law of gravitation - order of operations

1770

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/ca5868f80d0b0cd5791ehttp://bl.ocks.org/arctwelve/ca5868f80d0b0cd5791e

2Answer


0

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 8 years ago
  • G John

0

The interpretation of

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

is

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 8 years ago
  • B Butts

Your Answer

    Facebook Share        
       
  • asked 8 years ago
  • viewed 1770 times
  • active 8 years ago

Best Rated Questions