Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. from scipy.integrate import trapz
  2.  
  3. def osc(q, t, w, coefs):
  4. fu = np.poly1d(coefs)
  5. x, y = q
  6. dqdt = [y, fu(x) - w*x]
  7. return dqdt
  8.  
  9. f = open('homework3_dataFinal.txt', 'r')
  10. t = f.readline().rstrip().split()
  11. t = list(map(float,t))
  12. real = f.readline().rstrip().split()
  13. real = list(map(float,real))
  14. real = np.array(real)
  15. q0 = [2,1]
  16. coefs = [-0.01001609,-0.0101361,-0.01107698, -0.01775297, -0.02, -0.02]
  17. w = 0
  18.  
  19. def bound(q, tt, w, coefs):
  20. x, y = q
  21. fu = np.poly1d(coefs)
  22. fp = np.polyder(fu)
  23. dqdt = [y, -w * x + x * fp(x)]
  24. return dqdt
  25.  
  26. lq0 = [0, -2*(real[49] - odeint(osc, q0, t, args=(w, coefs), full_output = 0)[49,0])]
  27.  
  28. lambd = odeint(bound, lq0, list(reversed(t)), args=(w, coefs), full_output = 0)[:,0]
  29.  
  30. product = [np.flipud(lambd) * (odeint(osc,q0,t, args=(w, coefs))[:,0] ** i) for i in range(len(coefs))]
  31.  
  32. res = trapz(product, t)
  33.  
  34.  
  35.  
  36. Cal
  37. def gradi(coefs):
  38. lq0 = [0, -2*(real[49] - odeint(osc, q0, t, args=(w, coefs), full_output = 0)[49,0])]
  39.  
  40. lambd = odeint(bound, lq0, list(reversed(t)), args=(w, coefs), full_output = 0)[:,0]
  41.  
  42. product = [np.flipud(lambd) * (odeint(osc,q0,t, args=(w, coefs))[:,0] ** i) for i in range(len(coefs))]
  43.  
  44. res = trapz(product, t)
  45. return np.flipud((-1 * res))
  46. def mine(coefs):
  47. return (np.sum(np.abs(real - odeint(osc, q0, t, args=(w, coefs), full_output = 0)[:,0])))
  48.  
  49. def dx(f, x):
  50. return abs(0-f(x))
  51.  
  52. def newtons_method(f, df, x0):
  53. a = np.ones(len(x0))
  54. delta = dx(f, x0)
  55. oldf = delta
  56. i = 0
  57. oldx = 0
  58. while delta > 40:
  59. oldx = x0
  60. x0 = x0 - ((f(x0))/(a * df(x0)))
  61. if (f(x0) > oldf):
  62. x0 = oldx
  63. a[i % len(x0)] *= 100
  64. i+=1
  65. if i % 100 == 0:
  66. print ("hi",f(x0))
  67. print ("hey",f(oldx))
  68. else:
  69. print ("here")
  70. print (f(x0))
  71. print (x0)
  72. print (gradi(x0))
  73. oldf = f(x0)
  74. a = np.ones(len(x0))
  75. i = 0
  76. delta = dx(f, x0)
  77. print ('Root is at: ', x0)
  78. print ('f(x) at root is: ', f(x0))
  79.  
  80. newtons_method(mine,gradi,[0, -66.90116106, -393.85982963, -1183.98710777, 223.52126842])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement