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.
So you're asking us to invent a new formula for calculating distance, hitherto unknown to all of mathematics.
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);
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.