shoelace formula
Summary
Area of polygon
Sum of triangle areas
C++ implementation
cpp
#include <vector>
#include <cmath>
#include <utility>
double shoelaceArea(const std::vector<std::pair<double, double>>& pts) {
size_t n = pts.size();
if (n < 3) return 0.0;
double signedArea = 0.0;
for (size_t i = 0; i < n; ++i) {
const auto& [x_i, y_i] = pts[i];
const auto& [x_ip1, y_ip1] = pts[(i + 1) % n]; // wraps last -> first
signedArea += x_i * y_ip1 - x_ip1 * y_i; // this is 2 * triangle_{i,i+1}
}
signedArea *= 0.5;
return std::fabs(signedArea); // drop fabs() to keep the signed area (winding direction)
}
// usage
#include <iostream>
int main() {
std::vector<std::pair<double, double>> square = {
{0, 0}, {4, 0}, {4, 4}, {0, 4}
};
std::cout << shoelaceArea(square) << "\n"; // 16
}
Concept
Triangle at origin and 2 points
- using the area analogy of determinants
Negative triangle
- negative determinant implies a flip in the new axes defined by the matrix
- clockwise points vs anticlockwise
anti-clockwise is +ve, clockwise is negative