0

I am looking for a way to project the intersection point of the graph using a vertical discontinuous line (style '--') on the x-axis and then write the x-coordinate on that axis.

Here's my attempt to find the intersection. For some reason, the point is not exactly on the intersection. It's strange.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

n = 256 
k = np.arange(0, 100) 
g = 1 - np.exp(-0.5 * k * (k - 1) / n)
plt.plot(g, '-')
plt.hlines(0.5, 0, 100, 'r')
idx = np.argwhere(np.diff(np.sign(g - 0.5)))
plt.plot(k[idx], g[idx], 'o')
plt.show()

enter image description here

LivBanana
  • 361
  • 2
  • 9
  • 2
    You might start with finding the intersection, like https://stackoverflow.com/questions/28766692/intersection-of-two-graphs-in-python-find-the-x-value, then think about drawing it. – tevemadar Dec 06 '20 at 20:36
  • I did it and edited my post. It looks strange. – LivBanana Dec 06 '20 at 20:46
  • 1
    For your particular equation, 100 data points isn't enough "resolution" to have an index where the value falls exactly on the intersection point. – AKX Dec 06 '20 at 20:52
  • [How to find the exact intersection of a curve (as np.array) with y==0?](https://stackoverflow.com/a/46911822/12046409) provides a way to find the exact intersection point using linear interpolation. You can call `find_roots(k, g-0,5)` using the function of the linked post. – JohanC Dec 06 '20 at 23:05

1 Answers1

1

As mentioned in the comment by tevemadar you need to find the intersection point by solving for k for g = 0.5 i.e where you've drawn your hline.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

n = 256
k = np.arange(0, 100)
f = 0.5
g = 1 - np.exp(-0.5 * k * (k - 1) / n)
plt.plot(g, '-')

hline_pos = 0.5
plt.hlines(hline_pos, 0, 100, 'r')
# inverse
# np.exp(-0.5 * k * (k - 1) / n) = 1 - g
# -0.5 * k * (k - 1) / n = np.log(1 - g)
# k^2 - k = np.log(1 - g) * (-n/0.5)
solve_for = hline_pos
constant = np.log(1 - solve_for) * (-n/0.5)
ks = np.roots([1, -1, -constant])
ks = np.sort(ks) # sort to get the positive root based on the domain boundaries

plt.scatter(ks[1], hline_pos)
plt.vlines(ks[1], 0, hline_pos, linestyles='--')

plt.show()

enter image description here

sai
  • 1,734
  • 1
  • 7
  • 13