【问题标题】:Find the intersaction of two equations找到两个方程的交点
【发布时间】:2020-09-22 17:53:38
【问题描述】:

我想找到 (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()

【问题讨论】:

  • 这是MCVE 的完美示例。非常好的问题。继续加油!

标签: python-3.x matplotlib plot intersection


【解决方案1】:

这里有几个问题:

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

【讨论】:

  • 非常感谢您的提示。所以,我的问题的第二部分是如何通过点线显示每个轴上该点的 x 和 y 值?我希望我问清楚。
  • @fsrfyama 我会将其添加到我的答案中
  • @fsrfyama 很高兴为您提供帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 2013-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多