查找两个方程的相互作用项

问题描述 投票:0回答:1

我想找到(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()
python-3.x matplotlib plot intersection
1个回答
0
投票

这里有几个问题:

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.