Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- from scipy import optimize
- import random
- def f( x, p0, p1, p2):
- return p0*x + 0.4*np.sin(p1*x) + p2
- def ff(x, p):
- return f(x, *p)
- # These are the true parameters
- p0 = 1.0
- p1 = 40
- p2 = 2.0
- # These are initial guesses for fits:
- pstart = [
- p0 + random.random(),
- p1 + 5.*random.random(),
- p2 + random.random()
- ]
- %matplotlib inline
- import matplotlib.pyplot as plt
- xvals = np.linspace(0., 1, 120)
- yvals = f(xvals, p0, p1, p2)
- xdata = np.array(xvals)
- np.random.seed(42)
- err_stdev = 0.2
- yvals_err = np.random.normal(0., err_stdev, len(xdata))
- ydata = f(xdata, p0, p1, p2) + yvals_err
- def fit_curvefit(p0, datax, datay, function, yerr=err_stdev, **kwargs):
- pfit, pcov = \
- optimize.curve_fit(f,datax,datay,p0=p0,\
- sigma=yerr, epsfcn=0.0001, **kwargs)
- error = []
- for i in range(len(pfit)):
- try:
- error.append(np.absolute(pcov[i][i])**0.5)
- except:
- error.append( 0.00 )
- pfit_curvefit = pfit
- perr_curvefit = np.array(error)
- return pfit_curvefit, perr_curvefit
- pfit, perr = fit_curvefit(pstart, xdata, ydata, ff)
- print("\n# Fit parameters and parameter errors from curve_fit method :")
- print("pfit = ", pfit)
- print("perr = ", perr)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement