Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. import sympy as s
  2.  
  3.  
  4. def sub_x(f_, val):
  5.     return f_.subs(x, val)
  6.  
  7.  
  8. def sub_y(f_, val):
  9.     return f_.subs(y, val)
  10.  
  11.  
  12. def sub_h(f_, val):
  13.     return f_.subs(h, val)
  14.  
  15.  
  16. def sub(f_, val_x, val_y):
  17.     return sub_y(sub_x(f_, val_x), val_y)
  18.  
  19.  
  20. x, y, h = s.symbols('x y h')
  21.  
  22. f = (x - 3)**2 + (y - 2)**2
  23. # f = 2*x*y + 2*x - x**2 - 2*y**2
  24.  
  25. f_x = s.diff(f, x)
  26.  
  27. f_y = s.diff(f, y)
  28.  
  29.  
  30. def steepest(x_initial, y_initial, max_error, iterations):
  31.     x0, y0 = x_initial, y_initial
  32.     ite = 0
  33.     error = 1
  34.  
  35.     while error > max_error and ite < iterations:
  36.         ite += 1
  37.  
  38.         X = x0 + sub(f_x, x0, y0) * h
  39.         Y = y0 + sub(f_y, x0, y0) * h
  40.  
  41.         if not(h in X.free_symbols) and not(h in Y.free_symbols):
  42.             break
  43.  
  44.         g = sub(f, X, Y)
  45.         g_h = s.diff(g, h)
  46.  
  47.         h_root = s.solve(g_h)[0]
  48.  
  49.         x_root = sub_h(X, h_root)
  50.         y_root = sub_h(Y, h_root)
  51.  
  52.         error_x = abs(x_root - x0) / x_root
  53.         error_y = abs(y_root - y0) / y_root
  54.  
  55.         error = max(error_x, error_y)
  56.  
  57.         x0, y0 = x_root, y_root
  58.  
  59.     return [float(x0), float(y0), float(sub(f, x0, y0)), error, ite]
  60.  
  61.  
  62. res = steepest(1, 1, 1e-2, 100)
  63.  
  64. print('The optimum of f(x) is', res[2], 'at x =', res[0], 'and y =', res[1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement