Subscribed unsubscribe Subscribe Subscribe

多角形の図心を求める(nspired lua)

図心の計算
function centroid(vertsList)
   local numVerts = #vertsList/2
   local points = vertsList
   table.insert(points, vertsList[1]); table.insert(points, vertsList[2])  
   local x, y = {}, {}
   for i = 1, #points/2 do
      x[i], y[i] = points[2*i-1], points[2*i]
   end
   local xc, yc, eachAreas = {}, {}, {}
   local totalArea, xgTemp, ygTemp = 0, 0, 0
   for i = 1, numVerts do
      xc[i], yc[i] = (x[i] + x[i+1])/3, (y[i] + y[i+1])/3
      eachAreas[i] = (x[i+1] * y[i] - y[i+1] * x[i])/2
      totalArea = totalArea + eachAreas[i]
      xgTemp, ygTemp = xgTemp + eachAreas[i] * xc[i], ygTemp + eachAreas[i] * yc[i]
   end
   return xgTemp/totalArea, ygTemp/totalArea
end
print(centroid({2, 3, 3, 2, 1, -2, -5, -1, -7, 1, -1, 4}))

f:id:ti-nspire:20160607090220j:plain

Remove all ads