Advertisement
Guest User

Untitled

a guest
Nov 15th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. import numpy as np
  2. import numpy.linalg as la
  3. import matplotlib.pyplot as plt
  4. from scipy.optimize import minimize_scalar
  5.  
  6. def f(r):
  7. x, y = r
  8. return 3 +((x**2)/8) + ((y**2)/8) - np.sin(x)*np.cos((2**-0.5)*y)
  9.  
  10. def df(r):
  11. x, y = r
  12. return np.array([0.25 * x - np.cos(x)*np.cos((2**-0.5)*y), 0.25 * y + (2**-0.5) * np.sin(x)*np.sin((2**-0.5)*y),])
  13.  
  14. def h(r):
  15. x, y = r
  16. return np.array([[0.25 + np.sin(x)*np.cos((2**-0.5)*y), (2**-0.5)*np.cos(x)*np.sin((2**-0.5)*y)], [(2**-0.5)*np.cos(x)*np.sin((2**-0.5)*y), 0.25 + 0.5 * np.sin(x)*np.cos((2**-0.5)*y)]])
  17.  
  18. iteration_count_newton = 0
  19. newton_iter = []
  20. r_newton = np.copy(r_init)
  21. while True:
  22. newton_iter.append(r_newton)
  23. r_df = df(r_newton)
  24. r_h = h(r_newton)
  25. if la.norm(r_df, 2) < stop:
  26. break
  27. iteration_count_newton += 1
  28. r_newton = r_newton + np.matmul(la.inv(r_h), -r_df)
  29.  
  30. iteration_count_sd = 0
  31. sd_iter = []
  32. r_sd = np.copy(r_init)
  33. while True:
  34. sd_iter.append(r_sd)
  35. r_df = df(r_sd)
  36. if la.norm(r_df, 2) < stop:
  37. break
  38. iteration_count_sd += 1
  39. find_a = lambda a : f(r_sd - a * r_df)
  40. r_sd = r_sd - minimize_scalar(find_a).x * r_df
  41.  
  42. newton_error = [np.log(la.norm(newton_iter[i] - r_newton, 2)) for i in range(len(newton_iter))]
  43. sd_error = [np.log(la.norm(sd_iter[i] - r_sd, 2)) for i in range(len(sd_iter))]
  44. plt.plot(range(len(newton_iter)), newton_error, label="newton")
  45. plt.plot(range(len(sd_iter)), sd_error, label="sd")
  46. plt.xlabel("number of iterations")
  47. plt.ylabel("log of error")
  48. plt.title("Error as a function of num iter")
  49. plt.legend()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement