0

So I'm making a Graphical Calculator, which shows an intersection between graphs and axes. I found the method from Intersection of two graphs in Python, find the x value to work most of the time, however trying to plot the x-axis intersection of x**2 as such

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-5, 5, 0.01)
g = (x) ** 2

plt.plot(x, g, '-')

idx = np.argwhere(np.diff(np.sign(g))).flatten()
plt.plot(x[idx], g[idx], 'ro')
plt.show()

doesn't put the dot at (0,0) point. I assumed it has something to do with the fact that 0 is not in g, so the grpah it doesn't actually pass through the point exactly and instead gets really close to it. So I experimented with changing idx to

epsilon = 0.0001
# or another real small number
idx = g < epsilon

Unfortunately, that only seemed to make a lot of points near the actual x-intercept, instead of just one.

Hgorski6
  • 3
  • 1

1 Answers1

1

You are close, instead, I just search for where the absolute value of the derivative is at a minimum such that

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-5, 5, 0.01)
g = x**2


plt.plot(np.abs(np.diff(g)))
plt.show()

which shows that the minimum should be at index 500:

result

Then all you need to do is return the index of the minimum value with argmin and plot that point

idx = np.argmin(np.abs(np.diff(g)))
plt.plot(x, g, '-')
plt.scatter(x[idx],g[idx])
plt.show()

result2

You'll need to modify the idx variable to return multiple roots, but for the question you posted, this should be sufficient.

t.o.
  • 832
  • 6
  • 20
  • I was asking for more general solution. setting g to something like (x-1)^2*x*(x+1)^2 exposes the flaws of this method. – Hgorski6 Oct 13 '22 at 12:54
  • As I had stated, you'll have to play around with the algorithm to be valid for multiple roots. Root-finding packages exist in the [`scipy.optimize`](https://docs.scipy.org/doc/scipy/tutorial/optimize.html#root-finding) module, so that may be a good place to start. As far as the question you had asked goes, my answer was meant to address it. You may want to open a second question asking for a generalized solution. – t.o. Oct 14 '22 at 23:26
  • Maybe also take a look at [this](https://stackoverflow.com/questions/28724070/finding-all-roots-of-an-equation-in-python) for an explanation why the generalized question you are asking is nontrivial. – t.o. Oct 14 '22 at 23:29