目的:求圆和线段的交点 网上搜出的代码大多千篇一律,都是这样: 千篇一律,或许根本运都没运行就发出来了;
源代码
def line_intersect_circle(p, lsp, esp):
x0, y0, r0 = p
x1, y1 = lsp
x2, y2 = esp
if r0 == 0:
return [[x1, y1]]
if x1 == x2:
if abs(r0) >= abs(x1 - x0):
p1 = x1, round(y0 - math.sqrt(r0 ** 2 - (x1 - x0) ** 2), 5)
p2 = x1, round(y0 + math.sqrt(r0 ** 2 - (x1 - x0) ** 2), 5)
inp = [p1, p2]
inp = [p for p in inp if p[0] >= min(x1, x2) and p[0] <= max(x1, x2)]
else:
inp = []
else:
k = (y1 - y2) / (x1 - x2)
b0 = y1 - k * x1
a = k ** 2 + 1
b = 2 * k * (b0 - y0) - 2 * x0
c = (b0 - y0) ** 2 + x0 ** 2 - r0 ** 2
delta = b ** 2 - 4 * a * c
if delta >= 0:
p1x = round((-b - math.sqrt(delta)) / (2 * a), 5)
p2x = round((-b + math.sqrt(delta)) / (2 * a), 5)
p1y = round(k * x1 + b0, 5)
p2y = round(k * x2 + b0, 5)
inp = [[p1x, p1y], [p2x, p2y]]
inp = [p for p in inp if p[0] >= min(x1, x2) and p[0] <= max(x1, x2)]
else:
inp = []
return inp if inp != [] else [[x1, y1]]
出现的问题
我输入,求 圆心为(0,0),半径为1的圆 与 线段(0.5,-0.5)(1.5,-1)的交点:
print(line_intersect_circle((0, 0, 1), (0.5, -0.5), (1.5, -1)))
结果输出: [[0.77178, -1.0]]
一般一眼就能看出结果 x 没问题,但是 y 错了; x应该在0.5 和 1.5 之间,且还没到1,y应该在-0.5到-1之间;
错误代码
倒数第八行:
p1y = round(k * x1 + b0, 5)
p2y = round(k * x2 + b0, 5)
很明显这里的 p1y 和 p2y 还是用的函数一开始传进去的 原始x坐标,而没有用解方程得到的 交点x坐标,交点x坐标分别是p1x和p2x; 所以,这里改为:
p1y = round(k * p1x + b0, 5)
p2y = round(k * p2x + b0, 5)
得到正确结果:[[0.77178, -0.63589]]
正确代码
def line_intersect_circle(p, lsp, esp):
x0, y0, r0 = p
x1, y1 = lsp
x2, y2 = esp
if r0 == 0:
return [[x1, y1]]
if x1 == x2:
if abs(r0) >= abs(x1 - x0):
p1 = x1, round(y0 - math.sqrt(r0 ** 2 - (x1 - x0) ** 2), 5)
p2 = x1, round(y0 + math.sqrt(r0 ** 2 - (x1 - x0) ** 2), 5)
inp = [p1, p2]
inp = [p for p in inp if p[0] >= min(x1, x2) and p[0] <= max(x1, x2)]
else:
inp = []
else:
k = (y1 - y2) / (x1 - x2)
b0 = y1 - k * x1
a = k ** 2 + 1
b = 2 * k * (b0 - y0) - 2 * x0
c = (b0 - y0) ** 2 + x0 ** 2 - r0 ** 2
delta = b ** 2 - 4 * a * c
if delta >= 0:
p1x = round((-b - math.sqrt(delta)) / (2 * a), 5)
p2x = round((-b + math.sqrt(delta)) / (2 * a), 5)
p1y = round(k * p1x + b0, 5)
p2y = round(k * p2x + b0, 5)
inp = [[p1x, p1y], [p2x, p2y]]
inp = [p for p in inp if p[0] >= min(x1, x2) and p[0] <= max(x1, x2)]
else:
inp = []
return inp if inp != [] else [[x1, y1]]
|