Question

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?

Was it helpful?

Solution

BigDecimal could help, but I would suggest reading the whole answer.

Floating point errors are 'normal' in a sense, that you cannot store every floating point number exact within a variable. There are many resources out there how to deal with this problem, a few links here:

  1. If you do not know what the actual problem is check this out.
  2. What Every Computer Scientist Should Know About Floating-Poit Arithmetic
  3. IEEE floating point
  4. To give you an idead how to work: Quantity Pattern

OTHER TIPS

Use Double to calculate and Long to store.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top