Python 使用numpy和matplot查找根

Python 使用numpy和matplot查找根,python,numpy,matplotlib,math,Python,Numpy,Matplotlib,Math,我想用numpy绘制两条线的交点。介绍给我的链接说明了如何到达十字路口,但我得到了一个新的错误 TypeError: only integer scalar arrays can be converted to a scalar index 根据我的数据集更正的代码如下: import numpy as np import matplotlib.pyplot as plt with open('configuration_300.out', 'r') as f: lines = f.r

我想用numpy绘制两条线的交点。介绍给我的链接说明了如何到达十字路口,但我得到了一个新的错误

TypeError: only integer scalar arrays can be converted to a scalar index
根据我的数据集更正的代码如下:

import numpy as np
import matplotlib.pyplot as plt

with open('configuration_300.out', 'r') as f:
   lines = f.readlines()
   x_1 = [float(line.split()[0]) for line in lines]
   y_1 = [float(line.split()[1]) for line in lines]

   g = [x_1, y_1]

## size of x_1 and y_1 is 1696
x_2 = np.zeros(1696)
y_2 = np.ones(1696)

h = [x_2,y_2]

def find_roots(g,h):
   s = np.abs(np.diff(np.sign(h))).astype(float)
   return g[:-1][s] + np.diff(g)[s]/(np.abs(h[1:][s]/g[:-1][s])+1)

z = find_roots(g,h)

import matplotlib.pyplot as plt

plt.plot(g,h)
plt.plot((z, np.zeros(len(z))), marker="o", ls="", ms=4)

plt.show()
运行之后,我得到了前面提到的错误


所有的帮助都将被感激

为了解决这个问题,我使用了这种方法,它足够好和快速

import numpy as np
import matplotlib.pyplot as plt
%matplotlib qt

with open('file_300.out', 'r') as f:
    lines = f.readlines()
    x = [float(line.split()[0]) for line in lines]
    y = [float(line.split()[1]) for line in lines]

xx = []
for i in range(1,len(x)):
    if (y[i] > 1 and y[i-1] < 1) or (y[i] < 1 and y[i-1] > 1):
        xx.append((x[i]+x[i-1])/2)

yx = [0 for _ in range(len(xx))]


plt.axhline(y=1, color='g', linestyle='-') 
plt.plot(x,y)
plt.plot(xx,yx, color="C2", marker="o", ls="", ms=5)
plt.axis('equal')
将numpy导入为np
将matplotlib.pyplot作为plt导入
%matplotlib qt
以open('file_300.out','r')作为f:
行=f.读行()
x=[float(line.split()[0])表示行中的行]
y=[float(line.split()[1])表示行中的行]
xx=[]
对于范围(1,len(x))中的i:
如果(y[i]>1和y[i-1]<1)或(y[i]<1和y[i-1]>1):
xx.追加((x[i]+x[i-1])/2)
yx=[0表示范围内的uu(len(xx))]
plt.axhline(y=1,color='g',linestyle='-')
平面图(x,y)
plt.绘图(xx,yx,color=“C2”,marker=“o”,ls=”,ms=5)
plt.轴(“相等”)

您能发布几行数据和预期的绘图结果吗?这可能就是问题所在,s=np.abs(np.diff(np.sign(h)).astype(float)。使用s作为索引时,与将
.astype(bool)
更改为
.astype(float)
相比,它应该是int而不是float。这毫无意义。恢复原始状态。@ImportanceOfBeingErnest即使不更改为float并保持bool,也不会发生任何事情。与非零根相同,我试图得到结果,但仍然得到相同的错误。\n请尝试理解原始答案。它接受一个x数组和一个y数组作为输入。这里你放了一些完全不同的东西。