python-3.x - 找到两个方程的交集

标签 python-3.x matplotlib plot intersection

我想找到 (eq1, eq2) 和 (eq1, eq3) 之间的交点,并在每个轴上用虚线显示该点。这段代码没有给我确切的点,而只是一个近似值。我不明白我哪里做错了。

import matplotlib.pyplot as plt
import numpy as np

f = []
h = []
j = []
point = []

for x in range(25):
    eq1 = x * 185 * 3
    eq2 = 11930 - (12502 / 6) + (x * 185) / 6
    eq3 = 11930 - (12502 / 3) + (x * 185) / 6
    point.append(x)
    f.append(eq1)
    h.append(eq2)
    j.append(eq3)


plt.plot(point, f)
plt.plot(point, h)
plt.plot(point, j)
plt.legend(loc='lower right', fontsize=10)

idx1 = np.argwhere(np.diff(np.sign(np.array(f) - np.array(h)))).flatten()
idx2 = idx = np.argwhere(np.diff(np.sign(np.array(f) - np.array(j)))).flatten()
plt.plot(np.array(point)[idx1+1], np.array(h)[idx1+1], 'ro')
plt.plot(np.array(point)[idx2+1], np.array(j)[idx2+1], 'ro')
plt.show()

最佳答案

这里有几个问题:

  1. 首先,您的代码过长。使用 NumPy 数组来简化事情。由于 NumPy 是 matplotlib 的依赖项,因此导入 NumPy 并不过分。
  2. 您需要制作一个由 0 到 25 之间的点组成的非常密集的网格,以获得更准确的交点。以linspace为例,1000点。

如您所见,对于数组,您不需要使用 for 循环,也不需要初始化空列表然后一个一个地追加值。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 25, 1000)

f = x * 185 * 3
h = 11930 - (12502 / 6) + (x * 185) / 6
j = 11930 - (12502 / 3) + (x * 185) / 6

plt.plot(x, f, label='f')
plt.plot(x, h, label='h')
plt.plot(x, j, label='j')
plt.legend(loc='lower right', fontsize=12)

idx1 = np.argwhere(np.diff(np.sign(np.array(f) - np.array(h)))).flatten()
idx2 = idx = np.argwhere(np.diff(np.sign(np.array(f) - np.array(j)))).flatten()
plt.plot(x[idx1+1], h[idx1+1], 'ro')
plt.plot(x[idx2+1], j[idx2+1], 'ro')

plt.vlines(x[idx1+1], 0, h[idx1+1], linestyle='--')
plt.vlines(x[idx2+1], 0, j[idx2+1], linestyle='--')

plt.hlines(h[idx1+1], 0, x[idx1+1], linestyle='--')
plt.hlines(j[idx2+1], 0, x[idx2+1], linestyle='--')

plt.xlim(0, None)
plt.ylim(0, None)

plt.show()

enter image description here

关于python-3.x - 找到两个方程的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62182904/

相关文章:

python-3.x - ImportError : libnvidia-fatbinaryloader. so.384.90:无法打开共享对象文件:没有这样的文件或目录

python - Python 中的字典,保留最后 x 个访问的键

python - 如何更改 matplotlib 中多个绘图的默认颜色?

r - R 中的 corrplot.mixed - 使对角线中的标签更小

r - 在实现这个图之前我应该​​如何格式化我的数据?

python - 在打印 Python 期间换行文本

Python 3 : Programmatically converting list of hex numbers to binary

python 2.7 : cannot pip on windows "bash: pip: command not found"

python - 在更大的图中嵌入 matplotlib 图

python - 如何在 matplotlib 中将次轴图安排在主轴图下方?