【问题标题】:How to find all intersection points of graphs in a loop in Python?如何在Python的循环中找到所有图形的交点?
【发布时间】:2019-11-24 11:27:58
【问题描述】:

我绘制了一组圆如下:

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()

我收到:

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

【问题讨论】:

  • 每个圈子得到 3 次,因为从未使用过 for n in numbers:n。可能你会想要for i, n in enumerate(numbers)F = (X-i-1)**2 + Y**2 - (n*j)**2 `

标签: python python-3.x numpy matplotlib


【解决方案1】:

这是一些用于查找所有交叉点的 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')

【讨论】:

  • 我可以在 Point() 函数的 sympy.geometry 中使用浮点值吗?
  • 是的,你可以,但你必须小心。正如 sympy 喜欢准确的那样,浮点错误可能会导致大问题。最好的方法是将您的浮点数转换为 sympy 分数(即 1.2345 为 S(12345) /10000)。参见例如stackoverflow.com/questions/21005132/…。仅在最后使用 evalf() 转换为浮点数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-24
  • 2012-05-18
  • 1970-01-01
  • 2020-11-18
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多