Find longest distance from a certain point (java, 2d diagram)

1.9k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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:

double distanceSquared = Math.pow(coordsX[A] - coordsX(B), 2) + Math.pow(coordsY[A] - coordsY(B), 2);

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.

double longestDistanceSquared = 0;
int mostDistantPointIndex = -1;
for (int k = 0; k < coordsX.length; k++){
    double distanceSquared = Math.pow(coordsX[k] - x_coord, 2) + Math.pow(coordsY[k] - y_coord, 2);
    if (distanceSquared > longestDistanceSquared){
        longestDistanceSquared = distanceSquared;
        mostDistantPointIndex = k;
    }
}
0
On

The first thing that jumps out of the code to me is that you are casting the result of the sqrt() call to an int. That seems like it's going to cause problems.