Flask接口签名sign原理与实例代码浅析
290
2022-09-03
python求圆和线段/直线的交点,纠正网上有问题的代码
目的:求圆和线段的交点
网上搜出的代码大多千篇一律,都是这样:
千篇一律,或许根本运都没运行就发出来了;
源代码
# 计算圆 与 直接相交的点def line_intersect_circle(p, lsp, esp): # p is the circle parameter, lsp and lep is the two end of the line 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] # select the points lie on the line segment 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]] # select the points lie on the line segment 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): # p is the circle parameter, lsp and lep is the two end of the line 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] # select the points lie on the line segment 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]] # select the points lie on the line segment 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]]
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~