Добавил:
egrpleh
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:
import numpy as np
import math as m
from matplotlib import pyplot as plt
def f(x):
return -x**2- 10*x + 5
eps = 2 ** (-15)
a = -6.6
b = -4
eps0 = [[], [], [], []]
res = []
# Алгоритм равномерного поиска
r = 1
a1 = a
b1 = b
n = 50
iterations = [0] * 4
while abs(b1 - a1) > eps:
x = np.arange(a1, b1, (b1 - a1) / n)
vals = [f(i) for i in x[0:-1]]
ch = vals.index(min(vals))
a1, b1 = x[ch - 1], x[ch + 1]
iterations[0] += 1
eps0[0].append(b1 - a1)
res.append([a1, b1, iterations[0]])
print(res)
# Алгоритм дихтомии(алгоритм деления пополам)
a1, b1 = a, b
while abs(b1 - a1) > eps:
n = (a1 + b1) / 2
x = [(a1 + n) / 2, (b1 + n) / 2]
vals = [f(i) for i in x]
if vals[0] < vals[1]:
b1 = n
else:
a1 = n
iterations[1] += 1
eps0[1].append(b1 - a1)
res.append([a1, b1, iterations[1]])
# print(eps0)
# print(res)
# Метод золотого сечения
a1, b1 = a, b
while abs(b1 - a1) > eps:
x = [b1 - (b1 - a1) * 0.618, a1 + (b1 - a1) * 0.618]
vals = [f(i) for i in x]
if vals[0] < vals[1]:
b1 = x[1]
else:
a1 = x[0]
iterations[2] += 1
eps0[2].append(b1 - a1)
res.append([a1, b1, iterations[2]])
# Метод Фибоначчи
iterations[3] = 1
a1, b1 = a, b
fib = [1, 1]
while (b1 - a1) / fib[-1] > eps:
fib.append(fib[-2] + fib[-1])
while abs(b1 - a1) > eps:
x = [a1 + (b1 - a1) * (fib[len(fib) - 1 - iterations[3]] / fib[len(fib) - iterations[3]]),
a1 + (b1 - a1) * (fib[len(fib) - 1 - iterations[3]] / fib[len(fib) - iterations[3]])]
if x[0] == x[1]:
x[1] = x[0] + (b1 - a1) / 10
vals = [f(i) for i in x]
if vals[1] < vals[0]:
a1 = x[0]
else:
b1 = x[1]
iterations[3] += 1
eps0[3].append(b1 - a1)
iterations[3] -= 1
res.append([a1, b1, iterations[3]])
lbls = ['Алгоритм равномерного поиска', 'Метод дихтомии', 'Метод золотого сечения',
'Метод Фибоначчи']
[print(lbls[i], '\n', res[i]) for i in range(len(res))]
plt.plot(eps0[0], range(iterations[0]), label=lbls[0])
plt.plot(eps0[1], range(iterations[1]), label=lbls[1])
plt.plot(eps0[2], range(iterations[2]), label=lbls[2])
plt.plot(eps0[3], range(iterations[3]), label=lbls[3])
plt.legend()
plt.show()
f_ax = []
x_ax = np.arange(a, b, 0.01)
for j in x_ax:
f_ax.append(f(j))
print(f_ax)
Соседние файлы в папке ЛР2