如何找到曲线(如 np.array)与 y==0 的确切交点? [英] How to find the exact intersection of a curve (as np.array) with y==0?
问题描述
如何从 Python 中的绘图中获得 y 轴上的精确值?我有两个数组 vertical_data
和 gradient(temperature_data)
并将它们绘制为:
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:
plt.plot(gradient(temperature_data),vertical_data)
plt.show()
此处显示的图:
我需要零值,但它不完全为零,它是一个浮点数.
I need the zero value but it is not exactly zero, it's a float.
推荐答案
对于如何找到 numpy 数组的根或零的问题,我没有找到好的答案,所以这里有一个解决方案,使用简单的线性插值.
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.
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)
return x[:-1][s] + np.diff(x)[s]/(np.abs(y[1:][s]/y[:-1][s])+1)
z = find_roots(x,y)
import matplotlib.pyplot as plt
plt.plot(x,y)
plt.plot(z, np.zeros(len(z)), marker="o", ls="", ms=4)
plt.show()
当然你可以把x
和y
的角色颠倒得到
Of course you can invert the roles of x
and y
to get
plt.plot(y,x)
plt.plot(np.zeros(len(z)),z, marker="o", ls="", ms=4)
<小时>因为人们询问如何在非零值 y0
处获得截距,请注意,人们可能会简单地找到 y-y0
的零点.
Because people where asking how to get the intercepts at non-zero values
y0
, note that one may simply find the zeros of y-y0
then.
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
y1 = (x - 4) * np.cos(x * 9.) * np.cos(x * 6 + 0.05) + 0.1
y2 = (x - 2) * np.cos(x * 8.) * np.cos(x * 5 + 0.03) + 0.3
z = find_roots(x,y2-y1)
plt.plot(x,y1)
plt.plot(x,y2, color="C2")
plt.plot(z, np.interp(z, x, y1), marker="o", ls="", ms=4, color="C1")
这篇关于如何找到曲线(如 np.array)与 y==0 的确切交点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!