I have found this tutorial on topcoder Geometry Concept part 1.
In the last section of the tutorial it discusses about area of a polygon. I have took the code and ran it in my IDE but it seems that it give me area = 0 for this coordinates p = {{-1, -1}, {1, 1}, {1, -1}, {-1, 1}}.
What am I missing?
full code
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<vector<double>> p = {{-1, -1}, {1, 1}, {1, -1}, {-1, 1}};
double area = 0;
int N = p.size();
//We will triangulate the polygon
//into triangles with points p[0],p[i],p[i+1]
for (int i = 1; i + 1 < N; i++) {
double x1 = p[i][0] - p[0][0];
double y1 = p[i][1] - p[0][1];
double x2 = p[i + 1][0] - p[0][0];
double y2 = p[i + 1][1] - p[0][1];
double cross = x1 * y2 - x2 * y1;
area += cross;
}
cout << abs(area / 2.0) << endl;
return 0;
}
the coordinates should be ordered clockwise or counter-clockwise, I suppose
Thanks for the reply. I think this method is for Simple Polygon. But my input was a self-intersecting polygon. That's why it didn't work.