Area of Triangles and Polygons (2D)

Area of Triangles and Polygons (2D)

Triangles

Ancient ways

S = b*h/2

   = abSin(θ)/2

   = sqrt[s(s-a)(s-b)(s-c)]

s = (a+b+c)/2

Modern ways

S = |(V1-V0)×(V2-V0)|/2

   = [(x1-x0)(y2-y0)-(x2-x0)(y1-y0)]/2

Polygons Area - 2D

let polygon(Ω) is defined by its vertices Vi=(xi,yi), with V0=Vn. Let P be any point, and for each edge ViVi+1of Ω, form the triangle i=△PViVi+1, then:

S(Ω) = sum{i=0:n-1 | S(i)} and △i=△PViVi+1      (1)

Notice that, for a counterclockwise oriented polygon, use the modern way to calculate the triangle △i area, △PV2V3 and △PVn-1Vn have positive value and △PV0V1 and △PV1V2 have negative value, so the above rule (1) is right.

Let P = (0,0), the area of polygon is:

2S(Ω) = sum{i=0:n-1 | (xiyi+1-xi+1yi)}

C++ Algorithms

point_position

    int point_position(line L, point P)

        // if P is in the left of L , return value > 0

        // if P is in the right of L, return value < 0

        // if P is on the L, reutrn value = 0

int point_position(line L, point P)
{
    return (int)((L.x2-L.x1)*(P.y-L.y1) - (P.x-L.x1)*(L.y2-L.y1));
}

area_triangle(point A, point B, point C)

        double area_triangle(point A, point B, point C)
        {
            return abs((B.x - A.x)*(C.y - A.y) - (C.x - A.x)*(B.y - A.y))/2.0;
        }

area_polygon(vector<point> Poly)

        double area_polygon(vector<point> Poly)
        {
            int i;
            double ret = 0;
            for(i=0;i<Poly.size()-1;i++){
                ret += Poly[i].x*Poly[i+1].y-Poly[i+1].x*Poly[i].y;
            }
            int n = Poly.size()-1;
            ret += Poly[n].x*Poly[0].y-Poly[0].x*Poly[n].y;
            return ret/2.0;
        }

你可能感兴趣的:(C++,c,each)