Last active
January 14, 2020 10:54
-
-
Save aurbano/4693462 to your computer and use it in GitHub Desktop.
JavaScript 2D distance in the usual way and a faster approximation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update: The "faster" approximation is actually slower: https://jsperf.com/js-distance/
I'll investigate and write a blog post on this.