#269 Fitting noisy data with a linear equation using python
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def func(x,a,b): return a*x+b x=np.linspace(0,10,100) y=func(x,1,2) # Adding noise to the data yn=y+0.9*np.random.normal(size=len(x)) popt,pcov=curve_fit(func,x,yn) fig,ax = plt.subplots() ax.plot(x,y,'b-',label='data') ax.plot(x,yn,'.',c='red',label='data with noise') ax.plot(x, func(x, *popt),'g--',label='fit: a=%5.3f, b=%5.3f' % tuple(popt)) plt.xlabel('x') plt.xlabel('y') plt.legend() plt.savefig('ex269.png', dpi=90) plt.show()
Recent Comments