I am trying to write a PHP function that will calculate the center of gravity of a polygon.
I\'ve looked at the other similar questions but I can\'t seem to find a s
Here is my implementation in Python, based off the C++ implementation from Joseph. I think it is clearer than the other python answer.
def find_centroid(polygon):
""" Computes the centroid (a.k.a. center of gravity) for a non-self-intersecting polygon.
Parameters
----------
polygon : list of two-dimensional points (points are array-like with two elements)
Non-self-intersecting polygon (orientation does not matter).
Returns
-------
center_of_gravity : list with 2 elements
Coordinates (or vector) to the centroid of the polygon.
"""
offset = polygon[0]
center_of_gravity = [0.0, 0.0]
double_area = 0.0
for ii in range(len(polygon)):
p1 = polygon[ii]
p2 = polygon[ii-1]
f = (p1[0]-offset[0])*(p2[1]-offset[1]) - (p2[0]-offset[0])*(p1[1]-offset[1])
double_area += f
center_of_gravity[0] += (p1[0] + p2[0] - 2*offset[0]) * f
center_of_gravity[1] += (p1[1] + p2[1] - 2*offset[1]) * f
center_of_gravity[0] = center_of_gravity[0] / (3*double_area) + offset[0]
center_of_gravity[1] = center_of_gravity[1] / (3*double_area) + offset[1]
return center_of_gravity
# If you want to return both the CoG and the area, comment the return above
return center_of_gravity, abs(double_area/2)