Guest User

Untitled

a guest
Dec 11th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. def eval_func(x, basis_func, coef):
  2. n = len(coef)
  3. assert len(basis_func) == n
  4. p = 0.0
  5. for j in range(n):
  6. p += coef[j] * basis_func[j](x)
  7. return p
  8.  
  9. def best_fit(basis_func, xi, yi):
  10. m = len(basis_func); N = len(xi); assert len(yi) == N
  11. vdm = zeros((m,m), float)
  12. rhs = zeros((m,), float)
  13. for j in range(m):
  14. for k in range(m):
  15. for i in range(N):
  16. vdm[j,k] += basis_func[j](xi[i]) * basis_func[k](xi[i])
  17. for i in range(N):
  18. rhs[j] += yi[i] * basis_func[j](xi[i])
  19. return linalg.solve(vdm,rhs)
  20.  
  21. def least_squares(m, xi, yi):
  22. monomial_basis = [lambda x, k=j: x**k for j in range(m)]
  23. coef = best_fit(monomial_basis, xi, yi)
  24. x_plot = linspace(min(xi), max(xi), 100)
  25. y_plot = [eval_func(x, monomial_basis, coef) for x in x_plot]
  26. return x_plot, y_plot, coef
  27.  
  28. def lsplot(x, y, order):
  29. data = [[],[]]
  30. data[0], data[1], coef = least_squares(order, x, y)
  31. print "coefficients are", coef
  32. plot(x, y, 'o')
  33. plot(data[0], data[1], '-')
  34. show()
  35.  
  36. lsplot(t, Damped_Newton(x), 5)
Add Comment
Please, Sign In to add comment