满足条件的坐标超预期:计分黑点超出10分圆圈左侧问题排查
问题描述
我编写了一段代码用于计算并可视化获得10分及以上的概率,使用的计分板包含一个居中的10分圆圈。但运行后发现,部分代表计分的黑点轻微超出了10分圆圈的左侧区域。
我的代码如下:
from PIL import Image, ImageDraw import random, math img = Image.open("ScoreBoard.png") img = img.convert("RGB") pixels = img.load() width, height = img.size radius = 3/10 * width total_area = width * height def circle(x, r): return math.sqrt(r**2 - x**2) N = 5000 black_pix_count = 0 for _ in range(N): # Randomly select a number within the range of the width of the image. rand_x = random.randint(0, width-1) rand_y = random.randint(0, height-1) if 2 * width/10 <= rand_x <= 8 * width/10: rise = circle(width/2 - rand_x, radius) if height/2 - rise <= rand_y <= height/2 + rise: pixels[rand_x,rand_y] = (0,0,0) black_pix_count += 1 scoring_area_ratio = black_pix_count / N print(scoring_area_ratio) img.show()
运行后,部分黑点超出了10分圆圈的左侧区域,请问我哪里出错了?
问题分析与解决
你代码的问题出在圆内点的判断逻辑上,用分段判断x范围再计算y范围的方式,很容易在边界处出现误差,具体原因和修正方法如下:
错误原因
- 你先限定
rand_x在20%width到80%width之间,这对应圆的x方向理论边界,但接下来用width/2 - rand_x代入圆方程计算y范围时,浮点运算的精度问题加上整数像素坐标的取整,会导致部分靠近左边界的点被误判为在圆内。 - 这种分段判断的方式本身就容易出现边界逻辑漏洞,不如直接用点到圆心的距离判断来得准确。
修正后的代码
from PIL import Image, ImageDraw import random, math img = Image.open("ScoreBoard.png") img = img.convert("RGB") pixels = img.load() width, height = img.size radius = 3/10 * width # 定义圆心坐标 center_x = width / 2 center_y = height / 2 N = 5000 black_pix_count = 0 for _ in range(N): rand_x = random.randint(0, width-1) rand_y = random.randint(0, height-1) # 计算点到圆心的距离平方(避免开根号,提升效率同时减少精度损失) dist_sq = (rand_x - center_x)**2 + (rand_y - center_y)**2 # 比较距离平方和半径平方,判断是否在圆内 if dist_sq <= radius**2: pixels[rand_x, rand_y] = (0, 0, 0) black_pix_count += 1 scoring_area_ratio = black_pix_count / N print(scoring_area_ratio) img.show()
修正说明
- 采用点到圆心的距离平方与半径平方比较的方式,是判断点是否在圆内的标准方法,逻辑准确且能完全避免边界误判。
- 省去了多余的x范围判断,距离计算会自动筛选出所有圆内的点。
- 用距离平方代替开根号后的距离,既提升了运算效率,也减少了浮点运算带来的精度误差。
修改后,黑点就会严格落在10分圆圈范围内,不会再出现超出左侧区域的问题。
内容的提问来源于stack exchange,提问作者Nemo
相关产品推荐
相关产品推荐

