将圆周等分并返回坐标
Dividing circumference into equal parts and returning coordinates
我使用 Python 创建了几个不同来源的圆圈,我正在尝试实现一个函数,将每个圆圈沿圆周分成 n
个相等的部分。我正在尝试填充一个数组,其中包含圆周上每个部分的起始 [x,y]
坐标。
我的代码如下:
def fnCalculateArcCoordinates(self,intButtonCount,radius,center):
lstButtonCoord = []
#for degrees in range(0,360,intAngle):
for arc in range(1,intButtonCount + 1):
degrees = arc * 360 / intButtonCount
xDegreesCoord = int(center[0] + radius * math.cos(math.radians(degrees)))
yDegreesCoord = int(center[1] + radius * math.sin(math.radians(degrees)))
lstButtonCoord.append([xDegreesCoord,yDegreesCoord])
return lstButtonCoord
当我运行 3 个部分的代码时,返回的一组坐标的示例是:
[[157, 214], [157, 85], [270, 149]]
这意味着段的大小不同。有人可以帮我确定我的错误在哪里吗?
这种三角函数计算的精确结果很少是精确的整数。当然,通过将它们设为 int
,您会损失一些精度。近似(毕达哥拉斯)距离检查表明您的数学是正确的:
(270-157)**2 + (149-85)**2
# 16865
(270-157)**2 + (214-149)**2
# 16994
(157-157)**2 + (214-85)**2
# 16641
此外,您还可以使用内置的 complex
数字类型和 cmath
模块。特别是 cmath.rect
将极坐标(半径和角度)转换为直角坐标:
import cmath
def calc(count, radius, center):
x, y = center
for i in range(count):
r = cmath.rect(radius, (2*cmath.pi)*(i/count))
yield [round(x+r.real, 2), round(y+r.imag, 2)]
list(calc(4, 2, [0, 0]))
# [[2.0, 0.0], [0.0, 2.0], [-2.0, 0.0], [-0.0, -2.0]]
list(calc(6, 1, [0, 0]))
# [[1.0, 0.0], [0.5, 0.87], [-0.5, 0.87], [-1.0, 0.0], [-0.5, -0.87], [0.5, -0.87]]
您想根据需要更改舍入。
我使用 Python 创建了几个不同来源的圆圈,我正在尝试实现一个函数,将每个圆圈沿圆周分成 n
个相等的部分。我正在尝试填充一个数组,其中包含圆周上每个部分的起始 [x,y]
坐标。
我的代码如下:
def fnCalculateArcCoordinates(self,intButtonCount,radius,center):
lstButtonCoord = []
#for degrees in range(0,360,intAngle):
for arc in range(1,intButtonCount + 1):
degrees = arc * 360 / intButtonCount
xDegreesCoord = int(center[0] + radius * math.cos(math.radians(degrees)))
yDegreesCoord = int(center[1] + radius * math.sin(math.radians(degrees)))
lstButtonCoord.append([xDegreesCoord,yDegreesCoord])
return lstButtonCoord
当我运行 3 个部分的代码时,返回的一组坐标的示例是:
[[157, 214], [157, 85], [270, 149]]
这意味着段的大小不同。有人可以帮我确定我的错误在哪里吗?
这种三角函数计算的精确结果很少是精确的整数。当然,通过将它们设为 int
,您会损失一些精度。近似(毕达哥拉斯)距离检查表明您的数学是正确的:
(270-157)**2 + (149-85)**2
# 16865
(270-157)**2 + (214-149)**2
# 16994
(157-157)**2 + (214-85)**2
# 16641
此外,您还可以使用内置的 complex
数字类型和 cmath
模块。特别是 cmath.rect
将极坐标(半径和角度)转换为直角坐标:
import cmath
def calc(count, radius, center):
x, y = center
for i in range(count):
r = cmath.rect(radius, (2*cmath.pi)*(i/count))
yield [round(x+r.real, 2), round(y+r.imag, 2)]
list(calc(4, 2, [0, 0]))
# [[2.0, 0.0], [0.0, 2.0], [-2.0, 0.0], [-0.0, -2.0]]
list(calc(6, 1, [0, 0]))
# [[1.0, 0.0], [0.5, 0.87], [-0.5, 0.87], [-1.0, 0.0], [-0.5, -0.87], [0.5, -0.87]]
您想根据需要更改舍入。