User:Sdikiy/sandbox/PoligonCentroid

Centroid of polygon.(Centroid)
The centroid of a non-self-intersecting closed polygon defined by n vertices (x0,y0), (x1,y1), ..., (xn&minus;1,yn&minus;1) is the point (Cx, Cy), where


 * $$(1) \ C_{\mathrm x} = \frac{1}{6A}\sum_{i=0}^{n-1}(x_i+x_{i+1})(x_i\ y_{i+1} - x_{i+1}\ y_i)$$


 * $$(2) \ C_{\mathrm y} = \frac{1}{6A}\sum_{i=0}^{n-1}(y_i+y_{i+1})(x_i\ y_{i+1} - x_{i+1}\ y_i)$$

and where A is the polygon's signed area,


 * $$(3) \ A = \frac{1}{2}\sum_{i=0}^{n-1} (x_i\ y_{i+1} - x_{i+1}\ y_i)\;$$

In these formulas, the vertices are assumed to be numbered in order of their occurrence along the polygon's perimeter, and the vertex ( xn, yn ) is assumed to be the same as ( x0, y0 ). Note that if the points are numbered in clockwise order the area A, computed as above, will have a negative sign; but the centroid coordinates will be correct even in this case.

Software Implementation
Present xi and yi as


 * $$(4) \ x_i = X + \delta x_i ;\ y_i = Y + \delta y_i\;$$

where X and Y centroid coordinates.


 * $$(5) \ A = \frac{1}{2}\sum_{i=0}^{n-1} ((X + \delta x_i)\ (Y + \delta y_{i+1}) - (X + \delta x_{i+1})\ (Y + \delta y_i))\;$$


 * $$(6) \ A = \frac{1}{2}\sum_{i=0}^{n-1} ((X Y + X \delta y_{i+1} + Y \delta x_i + \delta x_i \delta y_{i+1}) - (X Y + X \delta y_i + Y \delta x_{i+1} + \delta x_{i+1} \delta y_i))\;$$

In real computer world we use Double-precision floating-point format. With the 52 bits of the fraction significand appearing in the memory format (approximately 16 decimal digits).

If X, Y > 108 and δxi, δyi < 1, we can neglect the term $$\delta x_i \delta y_{i+1}$$, $$\delta x_{i+1} \delta y_i$$


 * $$(7) \ A = \frac{1}{2}\sum_{i=0}^{n-1} ((X Y + X \delta y_{i+1} + Y \delta x_i + \cancel{\delta x_i \delta y_{i+1}}) - (X Y + X \delta y_i + Y \delta x_{i+1} + \cancel{\delta x_{i+1} \delta y_i}))\;$$


 * $$(8) \ A = \frac{1}{2}\sum_{i=0}^{n-1} ((X Y + X \delta y_{i+1} + Y \delta x_i) - (X Y + X \delta y_i + Y \delta x_{i+1}))\;$$


 * $$(9) \ A = \frac{1}{2} (X (\sum_{i=0}^{n-1} \delta y_{i+1} - \sum_{i=0}^{n-1} \delta y_i) + Y (\sum_{i=0}^{n-1} \delta x_i - \sum_{i=0}^{n-1} \delta x_{i+1}))\;$$


 * $$(10) \ A = \frac{1}{2} (X (\delta y_n - \delta y_0) + Y (\delta x_0 - \delta x_n)) = 0\;$$

Сonclusions.
The algorithm is extremely simple to understand and implement, but is not optimized for immediate implementation.

For example, if you want to calculate the result up to 16 digits all the internal variables must be calculated with a precision of 32 digits.