Is it possible to use the loop to calculation of geometric area?
Re: Is it possible to use the loop to calculation of geometric area?
Yes. What sort of data are you working on?
If you have an array of 2d points that define your shape then you can use this: (C# code by the way)
Code:
int GetPolyArea(Point[] pts)
{
//C#
uint i, j; //uints loop faster than ints
int area = 0;
int upper = pts.Length;
for (i = 0 ; i < upper ; i++)
{
j = (i + 1) % upper;
area += (pts[i].X * pts[j].Y) - (pts[i].Y * pts[j].X);
}
area >>= 1;
return(area < 0 ? -area : area);
}
The polygon must not be tangled up (ie, none of its lines cross eachother) like a figure 8 for instance.
That's about as fast as it gets.
Re: Is it possible to use the loop to calculation of geometric area?
Nice formula, I've never seen it :)
My way is much simpler to visualize. You can consider it as the integration between points i and j. The needed division by two (average Y value) is done later as well.
area += (pts[j].X - pts[i].X) * (pts[i].Y + pts[j].Y);
For the rest, it's the same as Wossname's.
This way should be a tad faster theoretically, because there's a multiplication less and a subtraction more.
If you don't make the area positive (see the return statement), then you can derive the direction of the points (vertexes) which enclose the area. If the area is negative, then the vertexes run counter clockwise, and if the area is positive, then the vertexes run clockwise. I'm not sure if this is also true for Wossname's way.