Skip to main content
Participant
May 22, 2017
Answered

How to get distance between objects in XY plane.

  • May 22, 2017
  • 2 replies
  • 717 views

Hello,

Is there a quick way to find distance between two or more objects in XY plane, something like finding perimeter of a polygon.
Something like 'math.distance' in math.js.

I know there is this method
var dist = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) );

I just want to know if is there any quick method for this

Cheers.

This topic has been closed for replies.
Correct answer Colin Holgate

Using multiply is faster than using Power. Behind the scenes math.distance is most likely just doing the Pythagoras that ClayUUID and the rest of the world are filled with anticipation to learn about. For readability I tend to break out the steps instead of doing it all in one line. Plus, sometimes the individual values can be of other use.

Which ends up with this:

var dx = x2-x1;

var dy = y2-y1;

var dist = Math.sqrt(dx*dx+dy*dy);

2 replies

Colin Holgate
Colin HolgateCorrect answer
Inspiring
May 22, 2017

Using multiply is faster than using Power. Behind the scenes math.distance is most likely just doing the Pythagoras that ClayUUID and the rest of the world are filled with anticipation to learn about. For readability I tend to break out the steps instead of doing it all in one line. Plus, sometimes the individual values can be of other use.

Which ends up with this:

var dx = x2-x1;

var dy = y2-y1;

var dist = Math.sqrt(dx*dx+dy*dy);

Legend
May 22, 2017

It's true that multiplying is slightly faster than pow (in Firefox and Chrome; in IE the difference is actually pretty significant), but unless you're processing thousands of points the difference is negligible, so it really comes down to stylistic choice. Note that calculating the intermediate dx/dy variables actually slows things down a bit.

https://jsperf.com/pythagorean-distance-pow-vs-mult

Legend
May 22, 2017

So you're asking us to invent a new formula for calculating distance, hitherto unknown to all of mathematics.