Advertisement
Guest User

Untitled

a guest
Apr 26th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. import math
  2. import sys
  3. from sympy import diff, symbols, sin
  4. import numpy
  5.  
  6. ideal = (1 + math.sqrt(5)) / 2
  7.  
  8.  
  9. def bisection(f, a, b, eps, i=0):
  10.     c = (a + b) / 2
  11.     dist = math.fabs(a - b)
  12.     i += 1
  13.     if dist < 2 * eps:
  14.         return c, i
  15.     elif f(c) < f(c + eps):
  16.         return bisection(f, a, c, eps, i)
  17.     else:
  18.         return bisection(f, c, b, eps, i)
  19.  
  20.  
  21. def helper(b, a):
  22.     global ideal
  23.     return (a - b) / ideal
  24.  
  25.  
  26. def golden(f, x0, x1, eps, i=0):
  27.     alpha = x1 - helper(x0, x1)
  28.     betha = x0 + helper(x0, x1)
  29.     i += 1
  30.     if math.fabs(x1 - x0) < eps:
  31.         return (x0 + x1) / 2, i
  32.     elif f(alpha) >= f(betha):
  33.         return golden(f, alpha, x1, eps, i)
  34.     else:
  35.         return golden(f, x0, betha, eps, i)
  36.  
  37.  
  38. def newton():
  39.     x, y = symbols('x y')
  40.     func = x ** 2 + 10 * (y - sin(x)) ** 2
  41.     f_x = diff(func, x)
  42.     f_y = diff(func, y)
  43.     f_xx = diff(func, x, x)
  44.     f_xy = diff(func, x, y)
  45.     f_yx = diff(func, y, x)
  46.     f_yy = diff(func, y, y)
  47.     val = [1, 1]
  48.  
  49.     def grad(a, b):
  50.         s = {x: a, y: b}
  51.         return numpy.array([f_x.evalf(subs=s), f_y.evalf(subs=s)], dtype=numpy.float64)
  52.  
  53.     def gesse(a, b):
  54.         s = {x: a, y: b}
  55.         return numpy.array([[f_xx.evalf(subs=s), f_xy.evalf(subs=s)],
  56.                             [f_yx.evalf(subs=s), f_yy.evalf(subs=s)]],
  57.                            dtype=numpy.float64)
  58.  
  59.     p = numpy.linalg.solve(gesse(1, 1), grad(1, 1))
  60.     next = val-(numpy.linalg.solve(gesse(1, 1), grad(1, 1)))
  61.  
  62.  
  63. print(newton())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement