Advertisement
Guest User

Untitled

a guest
Feb 26th, 2020
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3.  
  4. def function(point, a, b, c, d):
  5.     x, y = point
  6.  
  7.     return a*x + b*y + np.exp(c*x**2+d*y**2)
  8.  
  9. def derivative(point, a, b, c, d):
  10.     dx = a + np.exp(c*(point[0]**2)+d*(point[1]**2))*2*c*point[0]
  11.     dy = b + np.exp(c*(point[0]**2)+d*(point[1]**2))*2*d*point[1]
  12.  
  13.     return [dx, dy]
  14.  
  15. def grad(point, alpha, a, b, c, d):
  16.     new_point = [None, None]
  17.     der = derivative(point, a, b, c, d)
  18.     new_point[0] = point[0] - alpha*der[0]
  19.     new_point[1] = point[1] - alpha*der[1]
  20.  
  21.     return new_point
  22.  
  23. def criterion(point, a, b, c ,d):
  24.     der = derivative(point, a, b, c, d)
  25.     if np.sqrt(der[0]**2 + der[1]**2) < 0.0001:
  26.         return False
  27.     elif (np.abs(der[0]) < 0.0001/2) and (np.abs(der[1]) < 0.0001/2):
  28.         return False
  29.  
  30.     return True
  31.  
  32. point = [0, 0]
  33. alpha = 1
  34.  
  35. a, b, c, d = map(float, input("Введите a, b, c, d через пробел: ").split(" "))
  36.  
  37. while criterion(point, a, b, c, d):
  38.     new_point = grad(point, alpha, a, b, c, d)
  39.     if function(new_point, a, b, c, d) > function(point, a, b, c, d):
  40.         alpha/=2
  41.     elif function(new_point, a, b, c, d) < function(point, a, b, c, d):
  42.         point = new_point
  43.  
  44.     print(f'''
  45.         x:{point[0]}, y:{point[1]}
  46.         f(x):{function(point, a, b, c, d)}
  47.         grad(x):{new_point[0]}, grad(y):{new_point[1]}
  48.         alpha:{alpha}''')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement