Advertisement
Guest User

Untitled

a guest
Sep 19th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. import numpy as np
  2. from scipy import optimize
  3. import random
  4.  
  5. def f( x, p0, p1, p2):
  6. return p0*x + 0.4*np.sin(p1*x) + p2
  7.  
  8. def ff(x, p):
  9. return f(x, *p)
  10.  
  11. # These are the true parameters
  12. p0 = 1.0
  13. p1 = 40
  14. p2 = 2.0
  15.  
  16. # These are initial guesses for fits:
  17. pstart = [
  18. p0 + random.random(),
  19. p1 + 5.*random.random(),
  20. p2 + random.random()
  21. ]
  22.  
  23. %matplotlib inline
  24. import matplotlib.pyplot as plt
  25. xvals = np.linspace(0., 1, 120)
  26. yvals = f(xvals, p0, p1, p2)
  27.  
  28. xdata = np.array(xvals)
  29. np.random.seed(42)
  30. err_stdev = 0.2
  31. yvals_err = np.random.normal(0., err_stdev, len(xdata))
  32. ydata = f(xdata, p0, p1, p2) + yvals_err
  33.  
  34. def fit_curvefit(p0, datax, datay, function, yerr=err_stdev, **kwargs):
  35.  
  36. pfit, pcov = \
  37. optimize.curve_fit(f,datax,datay,p0=p0,\
  38. sigma=yerr, epsfcn=0.0001, **kwargs)
  39. error = []
  40. for i in range(len(pfit)):
  41. try:
  42. error.append(np.absolute(pcov[i][i])**0.5)
  43. except:
  44. error.append( 0.00 )
  45. pfit_curvefit = pfit
  46. perr_curvefit = np.array(error)
  47. return pfit_curvefit, perr_curvefit
  48.  
  49. pfit, perr = fit_curvefit(pstart, xdata, ydata, ff)
  50.  
  51. print("\n# Fit parameters and parameter errors from curve_fit method :")
  52. print("pfit = ", pfit)
  53. print("perr = ", perr)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement