如何计算半径为r的圆在坐标系中占多少个域

How to calculate how many fields a circle with radius r will take up in a coordinate system

我编写了一个将圆“绘制”到坐标系(2d array/list)的函数:

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))

它returns实际上有多少点是可见的,因为它透支了一些点。 我的问题: (如何)我可以从 r 确定 steps。这将使该功能更有效率。

如果我运行

print(len(drawCircle(10, 10, r, 200)))

它给了我正在寻找的答案。

for r in range(5,30):
    print(len(drawCircle(10, 10, r, 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

它只产生不同的点。

您可能错过了 coordinates/pixels 函数的数量 returns 取决于 rstep 变量。如果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,从而获得尽可能多的 coorditates/pixels。

这有点更具挑战性,我想不出一种非常直接的方法来计算它。一个“暴力”解决方案可能是这个

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 选择越来越大的值,直到像素数不再增加为止。然后函数 returns 那些坐标。但这并不像你想象的那样理想。

我是新手,但如果我理解正确的话, 这是你要找的吗

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)