簡體   English   中英

使用 numpy 和 matplot 查找根

[英]Finding roots using numpy and matplot

我想使用 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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM