如何找到y == 0的曲线的精确交点(如np.array)? [英] How to find the exact intersection of a curve (as np.array) with y==0?

查看:105
本文介绍了如何找到y == 0的曲线的精确交点(如np.array)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从Python中的图获得 y 轴上的确切值?我有两个数组vertical_datagradient(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()

当然,您可以将xy的角色反转以获得

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")

这篇关于如何找到y == 0的曲线的精确交点(如np.array)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆