Python - How To Find The Exact Intersection of A Curve (As NP - Array) With y 0 - Stack Overflow
Python - How To Find The Exact Intersection of A Curve (As NP - Array) With y 0 - Stack Overflow
How can I get from a plot in Python an exact value on y - axis? I have two arrays
vertical_data and gradient(temperature_data) and I plotted them as:
7
plt.plot(gradient(temperature_data),vertical_data)
plt.show()
I need the zero value but it is not exactly zero, it's a float.
Your Share
privacyImprove this question edited Feb 26, 2020 at 22:54 asked Oct 24, 2017 at 11:28
By clicking
Follow“Accept all cookies”, you agree Stack Exchange
JohanCcan store cookies on your device
Arcturus
and disclose
information in accordance with our Cookie Policy. 59.3k 8 19 45 73 1 3
Sorted by:
1 Answer
Highest score (default)
I did not find a good answer to the question of how to find the roots or zeros of a numpy
array, so here is a solution, using simple linear interpolation.
16
import numpy as np
N = 750
x = .4+np.sort(np.random.rand(N))*3.5
y = (x-4)*np.cos(x*9.)*np.cos(x*6+0.05)+0.1
def find_roots(x,y):
s = np.abs(np.diff(np.sign(y))).astype(bool)
z = find_roots(x,y)
plt.plot(x,y)
plt.show()
plt.plot(y,x)
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose
information in accordance with our Cookie Policy.
y0 = 1.4
z = find_roots(x,y-y0)
# ...
plt.plot(z, np.zeros(len(z))+y0)
People were also asking how to get the intersection between two curves. In that case it's again
about finding the roots of the difference between the two, e.g.
x = .4 + np.sort(np.random.rand(N)) * 3.5
z = find_roots(x,y2-y1)
plt.plot(x,y1)
plt.plot(x,y2, color="C2")
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose
information in accordance with our Cookie Policy.
1 Hey, just wanted to say that's a neat idea to turn places where the sign of the function changes sign
into indices like this. Thanks!
– Dominik Stańczak
Oct 24, 2017 at 16:14
@JohanC For regularly spaced data one could replace np.diff(x)[s] by (x[1]-x[0]) . That would
give a very small performance gain, if that's what you mean.
– ImportanceOfBeingErnest
Feb 26, 2020 at
23:32
@ImportanceOfBeingErnest Brilliant and elegant! Do you have a ref for the equation used / LaTeX
version? :)
– jtlz2
Apr 7 at 11:34
Also, not that it probably matters, but how (i) expensive and (ii) accurate (as in second-order residuals)
is this compared to other methods? Thanks again! :)
– jtlz2
Apr 7 at 11:35
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose
information in accordance with our Cookie Policy.