Last active
May 1, 2017 08:57
-
-
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 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
// 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)); | |
} |
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
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