I'm working on a clustering program in Java. I'm trying to find the point that has the longest distance from another point in an 2-dimentional diagram with x and y axis. I though I could use pytagoras: Where the square of the Y-axis of the starting point + the square of the X-axis of the of the other points will determine the distance between them.
What my code does is for this certain point, check all other points to see if it finds a point with a higher distance. The code I have at the moment is the following:
// The points to find longest distance from
x_coord = 2;
y_coord = 4;
// Need to find right size
double var1 = Math.pow(y_coord, 2); // square of Y
double var2 = 0;
double var3 = 0;
int sum = 0;
/* For all coords ( of the cluster clusters)
* coordsX is an array that holds all the X coordinates
* of all other points
*/
for (int k = 0; k < coordsX.length; k++){
// Check which is furthest away from
var2 = Math.pow(coordsX[k], 2); // square of X
var3 = var1 + var2; // Sum of var1 and var2
sum = (int)Math.sqrt(var3); // Square root to find distance
if (sum > longestDistance){
longestDistance = sum;
}
}
Does anyone have any suggestions what might be wrong? Or is this an unsuited method to calculate distances?
So, to find the distance between two points, say A and B located on a xy plane, where A and B are indices, here is what you need to do:
And if you just want to find the most distant point, there is no need to take a square root, because it is a monotonic function, so it does not change the result of comparison at all.
Simply compare the distance squares
EDIT: code for you.