I have a problem with my code, which should give me the center of a square. The square is saved as it's corners in an double[][] array.
static double[] getMid(double[][] points){
double[] mid = new double[2];
double a = Math.sqrt( (points[0][0] - points[1][0]) * (points[0][0] - points[1][0])
+ (points[0][1] - points[1][1]) * (points[0][1] - points[1][1]) );
a/=2;
double c = a / Math.sin(Math.toRadians(45));
mid[0] = Math.sin(Math.toRadians(45)) * c + points[1][0];
mid[1] = Math.cos(Math.toRadians(45)) * c + points[1][1];
StdDraw.point(mid[0], mid[1]);
return mid;
}
My initial idea was to calculate the distance of the center and the corner and then calculate the centerpoint with the distance and the angle. This works fine when the square is in a normal position, but once it's rotated the center is way off.

The dots represent the calculated centers.
I think the code is much too complicate for what it does. If you know the figure is a square, all you need to do to find the centre is compute the midpoint between any two opposite corners.
mid[0] = (points[0][0] + points[2][0]) / 2;
mid[1] = (points[0][1] + points[2][1]) / 2;
Because it's a square, you can find the center by taking the average of the x coordinates of the corners, and then take the average of the y coordinates of the corners. This will give you the x and y coordinates of the center of the square. I believe this also works for rectangles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With