我正在尝试计算特定多边形的面积。
让我解释得更好。我正在尝试学习如何处理Python中的多边形。我知道有可用的软件包,例如 Shapely ,但是我想自己编写代码,使用更常见的软件包,例如 numpy , scipy 或数学。
我当前正在尝试此练习:给出一些顶点坐标和一个半径度量,计算您获得的多边形的面积。面积由以下部分形成:(在一个给定点上具有中心的圆的面积,并且给定了半径)-(在给定顶点上按顺时针方向形成的多边形的面积)。
让我们看一些示例:
我有一个圆,给定的顶点形成一个不与圆相交的多边形。所需区域就是圆的区域: area = areaCircle (简单的任务-完成)。
我有一个圆形,给定的顶点形成一个多边形,该多边形在某个点与该圆形相交。半径就像一根棍子(刚性,其尺寸不会随时间变化)。我应该计算 area = areaCircle-areaPolygon (中等任务)。
我有一个圆形,给定的顶点形成一个多边形,该多边形在某个点与该圆形相交。半径就像一根绳子(柔软的)。当两个多边形相交时,半径会变化(因此圆将不是完美的)。 如您所见,圆的中心为(5,5),半径为〜4。当半径绳索碰到(4,7)和(8,4)中的多边形时,它使圆变形。因此,我要获取的区域应该是: area = areaDeformedCircle-areaPolygon (困难任务)。
到目前为止,这是我的代码:
from math import pi
# parser for input
def parser():
while 1:
data = list(input().split(' '))
for number in data:
if len(number) > 0:
yield (number)
input_parser = parser()
def get_word():
global input_parser
return next(input_parser)
def get_number():
data = get_word()
try:
return int(data)
except ValueError:
return float(data)
# input data:
X,Y,L = map(int,input().split()) # circle data: X_coord_center, Y_coord_center, radius
N = get_number() # number of vertices of the polygon
vertexes = []
for i in range(N): #vertices of the polygon, given clockwise
xy = (get_number(), get_number())
vertexes.append(xy)
def circleArea(radius):
return pi * radius ** 2
# from question https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates
def polyArea(coords):
t=0
for count in range(len(coords)-1):
y = coords[count+1][1] + coords[count][1]
x = coords[count+1][0] - coords[count][0]
z = y * x
t += z
return abs(t/2.0)
# area polygon
print("area polygon: ", polyArea(vertexes))
# area circle
print("area circle: ", circleArea(L))
问题是,我只能在它们之间做点1)(计算圆的半径,没什么大不了的)。 实际上,有了这些输入示例,仅当多边形不与圆相交时,我才能计算出正确的面积。
example where the circle does not intersect the polygon (answerArea = 3.14159)
3 3 1
4
3 5
6 7
8 5
7 2
example where the circle intersects the polygon (answerArea = 36.71737) - it's the image's data
5 5 4
4
4 7
7 9
9 7
8 4
我应该如何修改我的代码(不使用Shapely )以计算另外两点之一?我没有老师,我一个人在学习,在线提示对我没有多大帮助。
感谢建议谁会为每个人提供帮助和快乐的编码:)