In [1]:
from scipy.optimize import minimize, differential_evolution
from matplotlib import pylab as plt
from math import sin, exp

Задача 1. Минимизация гладкой функции


In [2]:
def f(x):
    return sin(x / 5.0) * exp(x / 10.0) + 5.0 * exp(-x / 2.0)

res_1 = minimize(f, 2.0,  method='BFGS')
res_2 = minimize(f, 30.0, method='BFGS')

with open('submission-1.txt', 'w') as file_obj:
    ans_1 = format(res_1.fun, '.2f')
    ans_2 = format(res_2.fun, '.2f')
    file_obj.write(str(ans_1) + ' ' + str(ans_2))

Testing.


In [3]:
x = plt.frange(1.0, 30.0, 0.1)
y = map(f, x)

plt.plot(x, y)
plt.plot(res_1.x, res_1.fun, 'rx')
plt.plot(res_2.x, res_2.fun, 'gx')
plt.show()


Задача 2. Глобальная оптимизация


In [4]:
def f(x):
    return sin(x / 5.0) * exp(x / 10.0) + 5.0 * exp(-x / 2.0)

x0 = [(1.0, 30.0)]

res = differential_evolution(f, x0)

with open('submission-2.txt', 'w') as file_obj:
    file_obj.write(format(res.fun, '.2f'))

Testing.


In [5]:
x = plt.frange(1.0, 30.0, 0.1)
y = map(f, x)

plt.plot(x, y)
plt.plot(res.x, res.fun, 'rx')
plt.show()


Задача 3. Минимизация негладкой функции


In [6]:
def h(x):
    return int(sin(x / 5.0) * exp(x / 10.0) + 5.0 * exp(-x / 2.0))

res_1 = minimize(h, 30.0,  method='BFGS')
res_2 = differential_evolution (h, [(1.0, 30.0)])

with open('submission-3.txt', 'w') as file_obj:
    ans_1 = format(res_1.fun, '.2f')
    ans_2 = format(res_2.fun, '.2f')
    file_obj.write(str(ans_1) + ' ' + str(ans_2))

Testing.


In [7]:
x = plt.frange(1.0, 30.0, 0.1)
y = map(h, x)

plt.plot(x, y)
plt.plot(res_1.x, res_1.fun, 'rx')
plt.plot(res_2.x, res_2.fun, 'gx')
plt.show()