Advertisement
lightningleaf

Polynomial curve fitting in Python

Jul 5th, 2016
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. import numpy as np
  2. # Solutions to a system of polynomial coefficients Xa = f
  3.  
  4. # the x-coordinates of the points we know
  5. x = np.array([0, 1, 2, 3, 4, 5, 6, 6.7, 7.5])
  6.  
  7. # plugs x into f(x) = Σa_i*x^i and represents it as a vector for each value of x, creating a matrix
  8. # when multiplied by the appropriate coefficient vector a, we get a vector of f(x)
  9. to_poly = lambda x : np.array([x ** (i) for i in range(len(x))]).T
  10. X = to_poly(x)
  11.  
  12. # the f(x) values corresponding to the x-coordinates
  13. f = np.array([0, 1.1, 1.5, 1.6, 1.55, 1.4, 1, 0.5, 0])
  14.  
  15. # solves the system
  16. a = (np.linalg.solve(X, f))
  17.  
  18. # formatting mumbo-jumbo; the '10' specifies 10 decimal places
  19. print('[%s]' % ', '.join(map(str, ['%.10f' % r for r in a])))
  20.  
  21. # creates the polynomial in Python (numpy)
  22. p = np.poly1d(a[::-1])
  23.  
  24. # check if (x, f(x)) is correct
  25. for r in x:
  26.     print('p(', r, ')', '=', p(r), end= ', ', sep='')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement