Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. y(x) = p[0]* x^7 + p[1]*x^6 + p[2]*x^5 + p[3]*x^4 + p[4]*x^3 + p[5]*x^2 + p[6]*x^1 + p[7]
  2.  
  3. x(y) = p[0]*y^n + p[1]*y^n-1 + .... + p[n]*y^0
  4.  
  5. import numpy as np
  6.  
  7. # generate a random coefficient vector a
  8. degree = 1
  9. a = 2 * np.random.random(degree+1) - 1
  10.  
  11. # an assumed true polynomial y(x)
  12. def y_of_x(x, coeff_vector):
  13. """
  14. Evaluate a polynomial with coeff_vector and degree len(coeff_vector)-1 using Horner's method.
  15. Coefficients are ordered by increasing degree, from the constant term at coeff_vector[0],
  16. to the linear term at coeff_vector[1], to the n-th degree term at coeff_vector[n]
  17. """
  18. coeff_rev = coeff_vector[::-1]
  19. b = 0
  20. for a in coeff_rev:
  21. b = b * x + a
  22. return b
  23.  
  24.  
  25. # generate some data
  26. my_x = np.arange(-1, 1, 0.01)
  27. my_y = y_of_x(my_x, a)
  28.  
  29.  
  30. # verify that polyfit in the "traditional" direction gives the correct result
  31. # [::-1] b/c polyfit returns coeffs in backwards order rel. to y_of_x()
  32. p_test = np.polyfit(my_x, my_y, deg=degree)[::-1]
  33.  
  34. print p_test, a
  35.  
  36. # fit the data using polyfit but with y as the independent var, x as the dependent var
  37. p = np.polyfit(my_y, my_x, deg=degree)[::-1]
  38.  
  39. # define x as a function of y
  40. def x_of_y(yy, a):
  41. return y_of_x(yy, a)
  42.  
  43.  
  44. # compare results
  45. import matplotlib.pyplot as plt
  46. %matplotlib inline
  47.  
  48. plt.plot(my_x, my_y, '-b', x_of_y(my_y, p), my_y, '-r')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement