【发布时间】:2019-09-12 23:23:28
【问题描述】:
我试图在 Python 中找到两个圆之间的交点(使用 Matplotlib),但无法取回任何值。
我通过为每个单独的圆创建 X 和 Y 列表来做到这一点(Matplotlib 在绘制圆时将第一个参数作为 X 值,将第二个参数作为 Y 值),然后相应地与列表相交(例如, circle1 x 值和 circle2 x 值)。
import numpy
import math
import matplotlib.pyplot as plt
import random
def origin_circle():
global x_points
global y_points
global r
global n
r=1
n=2**16
x_points=[(r*math.cos(t)) for t in numpy.linspace(0, 2*numpy.pi*r, n+1)]
y_points=[(r*math.sin(t)) for t in numpy.linspace(0, 2*numpy.pi*r, n+1)]
def new_circle(x_offset, y_offset):
global x_points1
global y_points1
x_points1=[x_offset+(r*math.cos(t)) for t in numpy.linspace(0, 2*numpy.pi*r, n+1)]
y_points1=[y_offset+(r*math.sin(t)) for t in numpy.linspace(0, 2*numpy.pi*r, n+1)]
origin_circle()
new_center= random.randint(0, len(x_points))
x_offset = x_points[new_center]
y_offset = y_points[new_center]
new_circle(x_offset, y_offset)
print(set(x_points1).intersection(set(x_points)))
print(set(y_points1).intersection(set(y_points)))
我希望返回值,但返回的集合是空的。
【问题讨论】:
-
如果您希望能够在函数之外使用该数据,则每个函数都应返回其 x 和 y 点。 docs.python.org/3/tutorial/controlflow.html#defining-functions
-
既然你的圆圈是由有限数量的点组成的,你确定它们有共同点吗?它们可能仅在连续极限中具有共同点。
-
有计算两个圆的交点(如果有的话)的公式,给定中心和半径,不涉及枚举圆周上的任何点。
-
这里的这条线
(set(x_points1).intersection(set(x_points)))实际上永远不会找到这两个集合之间的交集,只是恰好存在于两个集合中的点。由于您在每个圆的外部生成点,因此这些点中的两个在不同的圆上完全相同是极不可能的,即使被0.00000000001关闭也将确保您的交点什么也找不到。您需要一种更好的方法来找到交叉点。