Find the intersaction of two equations

Viewed 36

I would like to find the intersection between (eq1, eq2) and (eq1, eq3) and show that point with the dotted line on each axis. This code does not give me the exact point but just an approximation. I do not understand where am I doing mistake.

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 Answers

Several issues here:

  1. Firstly, your code is unnecessarily long. Make use of NumPy arrays to simplify things. Since NumPy is a dependency of matplotlib, you are not overkilling by importing NumPy.
  2. You need to make a very dense mesh of points between 0 and 25 to get more accurate intersection points. Use linspace with 1000 points for example.

As you can see, with arrays, you don't need to use for loop, neither you need to initialize empty lists and then append values one by one.

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

Related