python - 如何在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()
我收到:
如何找到圆之间的所有交点?
解决方案
这是一些用于查找所有交叉点的 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')
推荐阅读
- javascript - 使用 map 函数在 React 中传递道具
- python - 在 __init__ 函数中处理多个参数的优雅方式
- python - try/except 不会在 Python 中捕获 TypeError
- node.js - ReactJS Express 服务器端不接收主路由
- php - 使用 WordPress 文本编辑器发布内容
- java - 如何创建公共类的新对象
- python - 如何使用 PyQt5 将动画应用于 matplotlib 图
- javascript - 如何在 JavaScript 中创建实时更改
- ubuntu - Octopus 部署和 Ubuntu 权限
- c++ - 如何在 C++ 中向字符串中添加字符?