简体   繁体   English

查找最接近 0 的值的索引时出错

[英]Error with finding the index of value closest to 0

I have an issue with my code.我的代码有问题。 I am trying to find the x value for which my y is equal (or close) to 0, for the first time.我试图第一次找到我的 y 等于(或接近)0 的 x 值。

The following code computes the values of x and y for different parameters.以下代码计算不同参数的 x 和 y 值。 What I don't understand is that when I try the code line by line, I obtain a min-value for my val array, but using np.where doesn't work as it can't find this value it just obtained.. I thought it was maybe related to how the min_value is stored and that it somehow rounds it up, making it not equal to what it previously was.我不明白的是,当我逐行尝试代码时,我为我的 val 数组获得了一个最小值,但是使用 np.where 不起作用,因为它找不到它刚刚获得的这个值。我认为这可能与 min_value 的存储方式有关,并且它以某种方式将其四舍五入,使其不等于以前的值。 I tried using `idx = np.where(np.isclose(val,0)) instead but I couldn't make it work.我尝试使用 `idx = np.where(np.isclose(val,0)) 代替,但我无法使其工作。 How can I solve this problem?我怎么解决这个问题?

D = np.logspace(21,27,7)
x = np.logspace(0,7,500)
V0 = 1.17e+13
alpha = ((4*D)/((3300-1000)*9.81))**(1/4)


fig, axs = plt.subplots(2,4, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)

axs = axs.ravel()

for i in range(0,len(D)):
  val = np.zeros((len(x)))

  val = -(V0*(alpha[i]**3))/(8*D[i]) * np.exp(-x/alpha[i]) * (np.cos(x/alpha[i]) + np.sin(x/alpha[i]))

  # Find the index for which val crosses the x axis for the first time
  min_val = np.min(np.abs(val))
  idx = np.where(val == min_val)
  idx_first = idx[0][0]
  pos = x[idx_first]

It's because your minimum value is negative, so when you take这是因为你的最小值是负数,所以当你取

min_val = np.min(np.abs(val))

min_val isn't a member of your array. min_val 不是您的数组的成员。 But it is a member of np.abs(val) so I'd recommend:但它是np.abs(val)的成员,所以我建议:

idx = np.where(np.abs(val) == min_val)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM