0

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?

3

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Your links really helped to understand the problem. So you will get the mark! I end up with a cast to float and back to double. That rounds my numbers in respect to the magnitude of the value with float precision. Do you have any idea how I can reach a higher precision (float < X < double) since float is still very inaccurate.
1

Use Double to calculate and Long to store.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.