Python程式:計算多邊形面積


假設我們有一個有序點的列表,表示二維平面上的一個簡單多邊形的端點。我們需要找到這個多邊形的面積。

因此,如果輸入類似於 points = [(0, 0), (0,5), (3, 5), (3,0)],則輸出將為 15。

為了解決這個問題,我們將遵循以下步驟:

  • 定義一個函式 getInfo()。它將接收 x1、y1、x2、y2 作為引數。
  • 返回 x1*y2 - y1*x2
  • 在主方法中,執行以下操作:
  • N := points 的大小
  • (firstx, firsty) := points[0]
  • (prevx, prevy) := (firstx, firsty)
  • res := 0
  • 對於 i 從 1 到 N-1,執行以下操作:
    • (nextx, nexty) := points[i]
    • res := res + getInfo(prevx, prevy, nextx, nexty)
    • prevx := nextx
    • prevy := nexty
  • res := res + getInfo(prevx, prevy, firstx, firsty)
  • 返回 |res| / 2.0

示例

讓我們看看下面的實現來更好地理解:

def getInfo(x1, y1, x2, y2):
   return x1*y2 - y1*x2

def solve(points):
   N = len(points)
   firstx, firsty = points[0]
   prevx, prevy = firstx, firsty
   res = 0

   for i in range(1, N):
      nextx, nexty = points[i]
      res = res + getInfo(prevx,prevy,nextx,nexty)
      prevx = nextx
      prevy = nexty
   res = res + getInfo(prevx,prevy,firstx,firsty)
   return abs(res)/2.0

points = [(0, 0), (0,5), (3, 5), (3,0)]
print(solve(points))

輸入

[(0, 0), (0,5), (3, 5), (3,0)]

輸出

15.0

更新於: 2021年10月12日

2K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.