问题描述
我编写了一个将圆“绘制”到坐标系(二维数组/列表)中的函数:
def drawCircle(x,y,r,steps,draw=True):
coords = []
for n in range(steps):
coords.append(((round(x + r * math.cos(2 * math.pi * (n / steps)))),round(y + r * math.sin(2 * math.pi * (n / steps)))))
if draw:
for n in range(len(coords)):
self.drawPixel(coords[n][0],coords[n][1])
return list(set(coords))
它返回实际可见的点数,因为它会覆盖一些点。
我的问题:
(如何)我可以从steps
中确定r
。这样可以使功能更有效。
如果我跑步
print(len(drawCircle(10,10,200)))
它给了我我要寻找的答案。
for r in range(5,30):
print(len(drawCircle(10,200)))
40
40
56
56
72
80
80
88
96
96
112
112
128
136
120
128
152
152
176
152
176
168
160
176
192
我看不到任何图案。的
drawPixel(x,y)
list[y][x] = "#"
解决方法
不要使用三角函数,而要利用有效的Bresenham circle drawing algorithm。
它仅产生不同的点。
,您可能会丢失函数返回的坐标/像素数取决于r
和step
变量的信息。如果steps
足够大,像素数将不会随着steps
的增加而增加。
考虑这一点:
for steps in range(200,5000,200):
print(len(drawCircle(10,10,40,steps,draw=False)))
Out [1]:
200
280
288
304
288
312
320
320
312
320
320
320
312
320
320
320
320
320
320
320
320
320
320
320
因此,您可能希望获得尽可能少的steps
,从而使尽可能多的坐标/像素。
这更具挑战性,我想不出一种非常简单的方法来计算这一点。一个“ bruteforce”解决方案可能就是这样
def drawCircle(x,y,r,draw=True):
steps = 500
n_pixels = 0
n_pixels_prev = -1
while n_pixels_prev < n_pixels:
coords = []
for n in range(steps):
x_pix = round( x + r * math.cos(2 * math.pi * (n / steps)) )
y_pix = round( y + r * math.sin(2 * math.pi * (n / steps)) )
coords.append( (x_pix,y_pix) )
n_pixels_prev = n_pixels
n_pixels = len(set(coords))
steps += 1000
if draw:
for n in range(len(coords)):
self.drawPixel(coords[n][0],coords[n][1])
return list(set(coords))
它的作用是为step
选择越来越大的值,直到像素数量不再增加为止。然后该函数返回这些坐标。但这不是您可以想象的理想。
我对此并不陌生,但是如果我理解正确, 这是您要找的
import sympy as sy # a symbolic math module in numpy stack
import sympy.geometry as gm # a geometry module in sympy
import numpy as np # you might know this
unit=3 # the units of your field
#List of circles from 5 to 30
circles=[gm.Circle(gm.Point(10,10),r) for r in range(5,30)]
# list of circle perimeters
perimeters=[i.circumference for i in circles]
#number of units for each radius step
num_of_units=[i//unit for i in perimeters]
print(num_of_units)