多角形の面積、多角形の重心

どちらも、自己交差をもつ多角形ではバグる。

多角形の面積

//aに面積が求まる

double[] x = {4,4,2,2};
double[] y = {2,4,4,2};
double a = 0;
for (int i = x.length,u = 0; i-->0;u=i)
	a += (x[i]-x[u])*(y[i]+y[u]);
a = Math.abs(0.5*a);

多角形の重心

//aに面積,cx,cyに重心座標が求まる

double[] x = {4,4,2,2};
double[] y = {2,4,4,2};
double a = 0, cx = 0, cy = 0;
for (int i = x.length,u = 0; i-->0;u=i) {
	double k = x[i]*y[u] - x[u]*y[i];
	a += k;
	cx += k*(x[u]+x[i]);
	cy += k*(y[u]+y[i]);
}
cx /= 3.0*a;
cy /= 3.0*a;
a = Math.abs(0.5*a);

参考:

inserted by FC2 system