首页 > 解决方案 > 如何在Python的循环中找到所有图形的交点?

问题描述

我绘制了一组特定的圆圈,如下所示:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(1, figsize=(10,10))
numbers = [2,4,6]

for i in range(1,len(numbers)+1):
    for n in numbers:
        for j in range(1,4):

            x = np.linspace(-20, 25, 100)
            y = np.linspace(-20, 20, 100)

            X, Y = np.meshgrid(x,y)

            F = (X-i)**2 + Y**2 - (numbers[i-1]*j)**2

            ax = plt.gca()
            ax.set_aspect(1)
            plt.contour(X,Y,F,[0])

            plt.grid(linestyle='--')

plt.show()

我收到:

在此处输入图像描述

如何找到圆之间的所有交点?

标签: pythonpython-3.xnumpymatplotlib

解决方案


这是一些用于查找所有交叉点的 SymPy 代码。请注意,您的代码多次生成大量圆圈,因此我将它们放在一组中。(圆与自身的圆与圆相交当然是它自己,在这种情况下 intersect 不返回列表,而只是返回圆。)

from sympy import *
from sympy.geometry import *
import itertools

numbers = [2,4,6]
circles = set()

for i in range(1,len(numbers)+1):
    for n in numbers:
        for j in range(1,4):
            circles.add(Circle(Point(i, 0), numbers[i-1]*j))

all_intersections = []
for c1, c2 in itertools.combinations(circles, 2):
    all_intersections += c1.intersection(c2)

print(all_intersections)
all_intersections_as_tuple = [tuple(p.evalf()) for p in all_intersections]

哪个输出:

[Point2D(5/2, -5*sqrt(23)/2), Point2D(5/2, 5*sqrt(23)/2), Point2D(-3, 0), Point2D(3/2, -3*sqrt(7)/2), Point2D(3/2, 3*sqrt(7)/2), Point2D(2, sqrt(35)), Point2D(2, -sqrt(35))]

将它们添加到您的情节中:

plt.plot([x for x, y in all_intersections_as_tuple], [y for x, y in all_intersections_as_tuple], 'or', color='red')

添加到绘图的交叉点


推荐阅读