Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- class Vector(object):
- def __init__(self, x, y):
- """ создаём вектор """
- self.x = x
- self.y = y
- def __repr__(self):
- return "({0}, {1})".format(self.x, self.y)
- def __add__(self, other):
- x = self.x + other.x
- y = self.y + other.y
- return Vector(x, y)
- def __sub__(self, other):
- x = self.x - other.x
- y = self.y - other.y
- return Vector(x, y)
- def __rmul__(self, other):
- x = self.x * other
- y = self.y * other
- return Vector(x, y)
- def __truediv__(self, other):
- x = self.x / other
- y = self.y / other
- return Vector(x, y)
- def c(self):
- return (self.x, self.y)
- def f(z):
- x, y = z
- # функция по варианту
- # return -(2 / (1 + ((x - 1) / 2) ** 2 + (y - 1) ** 2)) - (3 / (1 + ((x - 2) / 3) ** 2 + ((y - 3) / 2) ** 2))
- # функция из методы min(1,1)
- # return 100*(y - x) ** 2 + (1 - x) ** 2
- # функция Розенброка min(1,1)
- return 100 * (y - x ** 2) ** 2 + (1 - x) ** 2
- def nelder_mead(alpha=1, beta=0.5, gamma=2, i=10):
- v1 = Vector(0, 1)
- v2 = Vector(1, 0)
- v3 = Vector(1, 1)
- for i in range(i):
- adict = {v1: f(v1.c()), v2: f(v2.c()), v3: f(v3.c())}
- points = sorted(adict.items(), key=lambda p: p[1])
- b = points[0][0]
- g = points[1][0]
- w = points[2][0]
- mid = (g + b) / 2
- # отражение
- xr = mid + alpha * (mid - w)
- if f(xr.c()) < f(g.c()):
- w = xr
- else:
- if f(xr.c()) < f(w.c()):
- w = xr
- c = (w + mid) / 2
- if f(c.c()) < f(w.c()):
- w = c
- if f(xr.c()) < f(b.c()):
- # растяжение
- xe = mid + gamma * (xr - mid)
- if f(xe.c()) < f(xr.c()):
- w = xe
- else:
- w = xr
- if f(xr.c()) > f(g.c()):
- # сжатие
- xc = mid + beta * (w - mid)
- if f(xc.c()) < f(w.c()):
- w = xc
- # переобозначим точки: b = best, g = good, w = worst — соответственно.
- v1 = w
- v2 = g
- v3 = b
- return b
- res = nelder_mead()
- print("Лучшее решение: %s" % (res))
- print("Значение функции в точке экстремума: %s" % f(res.c()))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement