Advertisement
Misipuk

lab2

Mar 9th, 2020
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. import numpy as np
  2. import math
  3. import pandas as pd
  4.  
  5. eps=0.1
  6. h=0.001
  7.  
  8. def f(x,y):
  9.     return x**2+8*x*y+0.001*x*y-x-y
  10.  
  11. def dFx(x,y):
  12.     return (f(x+h,y)-f(x-h,y))/(2*h)
  13.  
  14. def dFy(x,y):
  15.     return (f(x,y+h)-f(x,y-h))/(2*h)
  16.  
  17. def d2Fx(x,y):
  18.     return (f(x+h,y)-2*f(x,y)+f(x-h,y))/(h**2)
  19.  
  20. def d2Fy(x,y):
  21.     return (f(x,y+h)-2*f(x,y)+f(x,y-h))/(h**2)
  22.  
  23. def d2Fxy(x,y):
  24.     return (f(x+h,y+h)-f(x+h, y-h)-f(x-h, y+h)-f(x-h,y-h))/(4*(h**2))
  25.  
  26. def gradF(x,y):
  27.     return np.array([dFx(x,y), dFy(x,y)], float)
  28.  
  29. def sdevF(x,y):
  30.     return  np.array([[d2Fx(x,y), d2Fxy(x,y)],[d2Fxy(x,y),d2Fy(x,y)]], float)
  31.  
  32. def Newton(x,y):
  33.     xy = np.array([x,y], float)
  34.     alpha = 1.0
  35.     while True:
  36.         hh = (-1) * np.dot(np.linalg.inv(sdevF(x,y)), gradF(x,y))
  37.         xyk = xy + alpha*hh
  38.         if f(x,y)-f(xyk[0],xyk[1]) <= eps * alpha * np.dot(gradF(xyk[0],xyk[1]),hh):
  39.             break
  40.         else:
  41.             alpha = alpha * 0.5
  42.             xy = np.copy(xyk)
  43.     return  xyk
  44.  
  45. Newton(0,0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement