我正在尝试使用曲线拟合来拟合将频率数组作为x值的函数。我不断收到此错误,并尝试重塑形状并使我的y值浮动。由于我不断收到错误消息,因此我不确定自己从哪里去。
r_0 = (n_0 - n_1)/(n_0 + n_1)
r_1 = (n_1 - n_0)/(n_1+ n_0)
t_1 = 1 + r_1
t_0 = 1 + r_0
freq_values = np.linspace(108,200,1000)
#function to fit to
def T(freq,ghz=[]):
Transmittance = []
for ghz in freq_values:
X_01 = np.exp((2j*np.pi*0.004724*1.528*ghz*10**9)/(3*10**8))
H_1 = X_01 + r_0*r_1*(X_01)**-1
T = (t_0*t_1)/(H_1)
hola = list(T.flat)
Transmittance.append(hola*np.conj(hola))
return Transmittance
x = freq_values
y = T(freq_values)
yy= np.reshape(y, len(y))
yyy= np.array(yy.real, dtype=float)
plt.plot(x,y, 'r', label = 'calculated')
#fit function, want to match/find optimized n value
def TT(freq,n,ghz=[]):
Transmittance = []
for ghz in freq_values:
X_01 = np.exp((2j*np.pi*0.004724*n*ghz*10**9)/(3*10**8))
H_1 = X_01 + r_0*r_1*(X_01)**-1
T = (t_0*t_1)/(H_1)
hola = list(T.flat)
Transmittance.append(hola*np.conj(hola))
return Transmittance
popt, pcov = curve_fit(TT, x, yyy) #ydata = power (transmission) data
plt.plot(x, TT(x, *popt), 'b', label = 'fit')
plt.legend(loc='upper right')
我希望代码或拟合结果能够与原始图匹配,但在curve_fit(TT,x,yyy)中仍会出现yyy错误
答案 0 :(得分:0)
相关代码块已修改为可以在下面工作。注意函数返回之间的区别。另外,我怀疑您需要为拟合度提供一个很好的初步猜测。
def TT(freq,n,ghz=[]):
Transmittance = []
for ghz in freq_values:
X_01 = np.exp((2j*np.pi*0.004724*n*ghz*10**9)/(3*10**8))
H_1 = X_01 + r_0*r_1*(X_01)**-1
T = (t_0*t_1)/(H_1)
hola = list(T.flat)
Transmittance.append(hola*np.conj(hola))
return np.real(np.array(Transmittance)[:,0])