我一直在尝试将表单的一个函数与给出的数据相匹配:
160 0.277 0.006
170 0.2805 0.005
180 0.2825 0.007
190 0.276 0.012
200 0.2475 0.011
210 0.1645 0.009
220 0.1075 0.011
230 0.0785 0.009
240 0.0585 0.005
250 0.048 0.002
260 0.046 0.002
270 0.0485 0.001
280 0.0555 0.001
290 0.078 0.002
300 0.113 0.002
310 0.161 0.01
320 0.262 0.008
330 0.3035 0.005
340 0.326 0.004
350 0.3305 0.007
360 0.336 0.006
10 0.3275 0.005
20 0.3075 0.007
30 0.231 0.012
40 0.1625 0.005
50 0.1205 0.003
60 0.0905 0.003
70 0.0775 0.001
80 0.075 0.002
90 0.077 0.002
100 0.079 0.004
110 0.0965 0.003
120 0.124 0.002
130 0.1695 0.003
140 0.281 0.004
150 0.32 0.002这是我写的代码:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import special as sp
def strt(x, a, b):
"""definition of a straight line"""
return a*x+b
def trig(x, ang, I0, offset):
"""cos function to be fit"""
return offset+(I0*(sp.cosdg(x-ang)**2))
"""file handler block"""
f=open(r"C:\Users\lenovo\Desktop\trials.txt", "r")
raw=f.readlines()
data=np.loadtxt(raw)
data=np.transpose(data)
f.close()
"""fitting block"""
popt1, pcov1 = curve_fit(trig, data[0], data[1])
print(popt1)
#print(pcov1)
perr1 = np.sqrt(np.diag(pcov1))
print(perr1)
xerror=[1]*len(data[0])
"""plotting block"""
plt.figure('a')
plt.scatter(data[0], (data[1]), c='b', label="Data")
plt.plot(data[0], trig(data[0], *popt1), 'b-', label='fit: a=%5.3f, b=%5.3f c=%5.3f; sigma a=%5.3e, sigma b=%5.3e, sigma c=%5.3e' %tuple(list(popt1)+list(perr1)))
#plt.plot(data[0], trig(data[0], *popt1), 'b-', label='fit: a=%5.3f; sigma a=%5.3e' %tuple(list(popt1)+list(perr1)))
plt.xlabel('Angle (degrees)', fontsize=20)
plt.errorbar(data[0], data[1], fmt='none', xerr=xerror, yerr=data[2], ecolor='b', markersize=8, capsize=5)
#plt.xlim([-0.0075, 0.0075])
#plt.ylim([-3, 50])
plt.ylabel('Power ($\mu$W)', fontsize=20)
plt.legend(prop={"size":15}, loc='upper left')
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.grid(True, which='both')
plt.axhline(y=0, color='k')
plt.show('a')拟合看起来很好,但由于某些原因,图像有一条直线从曲线的一端延伸到另一端。我认为这意味着该函数为每个输入提供了两个输出。我想知道为什么会发生这种情况,以及我如何修改它。我试着只拟合一个cos函数,输出的图像仍然是一条从一端到另一端的直线。有人能帮帮忙吗?output image
发布于 2020-03-20 20:48:19
我解决了这个问题:数据应该以递增的顺序列出,上面的列表从中间开始。
https://stackoverflow.com/questions/60723093
复制相似问题