In my 2D physics simulation (Java) I calculate the center of a convex polygon as follows, where the parameter area is the enclosed area of the polygon calculated before.
private Vector2d calculateCenterOfMass(double area) {
Vector2d center = new Vector2d(0, 0);
for (int i = 0; i < vertices.length; i++) {
int j = (i + 1) % vertices.length;
double factor = (vertices[i].x * vertices[j].y
- vertices[j].x * vertices[i].y);
center.x += (vertices[i].x + vertices[j].x) * factor;
center.y += (vertices[i].y + vertices[j].y) * factor;
}
center.scale(1 / (area * 6));
return center;
}
I further have a polygon with the following points I use the function to calculate the center of mass of:
Vector2d [x=325.20399446366355, y=400.0, length=515.5168649182318]
Vector2d [x=375.20399446366355, y=400.0, length=548.4323453822622]
Vector2d [x=375.20399446366355, y=450.0, length=585.8993407245727]
Vector2d [x=325.20399446366355, y=450.0, length=555.2095442399406]
As you can see just by looking at the y values the center must be at y=425.0. Due to floating point magic the y value becomes 425.00000000000017 instead. The area given as parameter has the exact value 2500.0.
How can I avoid this and get my expected 425.0?