title: Avoid floating-point precision error in algorithm
body: <p>In my 2D physics simulation (Java) I calculate the center of a convex polygon as follows, where the parameter <em>area</em> is the enclosed area of the polygon calculated before.</p>
  
  <pre class="lang-java prettyprint-override"><code>private Vector2d calculateCenterOfMass(double area) {
      Vector2d center = new Vector2d(0, 0);
  
      for (int i = 0; i &lt; 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;
  }
  </code></pre>
  
  <p>I further have a polygon with the following points I use the function to calculate the center of mass of:</p>
  
  <pre><code>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]
  </code></pre>
  
  <p>As you can see just by looking at the <strong>y</strong> values the center must be at <strong>y=425.0</strong>. Due to floating point magic the y value becomes <strong>425.00000000000017</strong> instead. The area given as parameter has the exact value <strong>2500.0</strong>.</p>
  
  <p><strong>How can I avoid this and get my expected 425.0?</strong></p>