Skip to content

Instantly share code, notes, and snippets.

@arguiot
Last active May 1, 2017 08:57
Show Gist options
  • Save arguiot/25052fd6d1d555433ab55f4da42a5351 to your computer and use it in GitHub Desktop.
Save arguiot/25052fd6d1d555433ab55f4da42a5351 to your computer and use it in GitHub Desktop.
This will give you the distance between 2 or 3 (depends how many axis you have) points on a cartesian plane
// This will give you the distance between 2 or 3 (depends how many axis you have) points on a cartesian plane
// © Arthur Guiot 2017
// Sqare Root algorithm based on babylonian method
// @param n - the number to compute the square root of
// @param g - the best guess so far (can omit from initial call)
const squareroot = (n, g) => {
if (!g) {
// Take an initial guess at the square root
g = n / 2.0;
}
const d = n / g; // Divide our guess into the number
const ng = (d + g) / 2.0; // Use average of g and d as our new guess
if (g == ng) {
// The new guess is the same as the old guess; further guesses
// can get no more accurate so we return this guess
return g;
}
// Recursively solve for closer and closer approximations of the square root
return squareroot(n, ng);
};
// The actual function
Math.dist = (x1, y1, x2, y2, z1, z2) => {
if(!x2) x2=0;
if(!y2) y2=0;
if(!z1) z1=0;
if(!z2) z2=0;
return squareroot((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1));
}
Math.dist(0,0,1,1,0,0);
// 1.41421356237
Math.dist(0,0,1,1);
// 1.41421356237
// Try it out!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment