对于下面的python脚本,当我向curve_fit
函数添加边界时,得到的曲线拟合完全不同并且明显错误,即使为拟合调整的参数在之前和之前的范围内也是如此。将边界添加到代码后。为什么会这样?
这是指向数据的链接:https://drive.google.com/file/d/0Bwb0PrDn9o3KZ0lOa1FVZldjV0k/view?usp=sharing
import numpy as np
import matplotlib.pyplot as plt
from numpy import loadtxt, sqrt
from scipy.optimize import curve_fit #for least squares curve fit
from scipy import special #for erfc function
plt.rcParams.update({'font.family': "Times New Roman"})
plt.rcParams.update({'font.size': 12})
filename = 'Cr3.csv'
C_b = 17 #base concentration
t_hours = 451
t = t_hours * 3600 #451 hours = 1623600 seconds
data = loadtxt(filename, delimiter=',')
xdata = data[:, 0] #positions
ydata = data[:, 1] #concentration
corr = data[0, 2] #the correction value is manually measured in imagej
xdata = xdata - corr
def func(x, D):
return C_b/2 * special.erfc(x/(2 * sqrt(D * t))/1e6) #correction for um to m
fig = plt.figure()
plt.plot(xdata, ydata, 'b-', label='data')
popt, pcov = curve_fit(func, xdata, ydata, p0=1e-16)#, bounds=(0,1))
perr = np.sqrt(np.diag(pcov))
plt.plot(xdata, func(xdata, *popt), 'r-',
label='fit: D = %.2e' % tuple(popt))#, z = %5.3f
plt.xlabel('x (μm)')
plt.ylabel('Cr (wt%)')
plt.legend()
plt.show()