Skip to content

Instantly share code, notes, and snippets.

@aurbano
Last active January 14, 2020 10:54
Show Gist options
  • Save aurbano/4693462 to your computer and use it in GitHub Desktop.
Save aurbano/4693462 to your computer and use it in GitHub Desktop.
JavaScript 2D distance in the usual way and a faster approximation
// Usual function
function distance(p1,p2){
var dx = p2.x-p1.x;
var dy = p2.y-p1.y;
return Math.sqrt(dx*dx + dy*dy);
}
// Faster approximation
function distanceApprox(p1,p2){
// Approximation by using octagons approach
var x = p2.x-p1.x;
var y = p2.y-p1.y;
return 1.426776695*Math.min(0.7071067812*(Math.abs(x)+Math.abs(y)), Math.max (Math.abs(x), Math.abs(y)));
}
@aurbano
Copy link
Author

aurbano commented Jan 14, 2020

Update: The "faster" approximation is actually slower: https://jsperf.com/js-distance/

I'll investigate and write a blog post on this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment