Advertisement
SenyaSych

Метод золотого сечения

Mar 23rd, 2018
2,480
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. #Подключение библиотек
  2. import math
  3. import pylab
  4. import matplotlib.pyplot as plt
  5. from matplotlib import mlab
  6.  
  7. #Определение переменных
  8. A = 1.5; B = 1; C = 3; D = 1.5; x_min = 2.2; x_max = 4.4
  9.  
  10. #Определение функции
  11. function_f = lambda x: D * math.sin(A * x**B + C)
  12.  
  13.  
  14. #Метод золотого сечения
  15. def Golden_Section_Method (x_min, x_max, eps):
  16.     iteration = 1.0
  17.     print((" {0:.8s} || {1:.5s}  || {2:.8s} || {3:.5s}  || {4:.8s}").format("Итерация", "x_min", "f(x_min)", "x_max", "f(x_max)"))
  18.     coefficient = (math.sqrt(5) - 1) / 2
  19.     d = x_min + (x_max - x_min) * coefficient
  20.     c = x_max - (x_max - x_min) * coefficient
  21.     sc = function_f(c)
  22.     sd = function_f(d)
  23.     while (x_max - x_min) > eps:
  24.         if (sd < sc):
  25.             x_max = d
  26.             d = c
  27.             c = x_max - (x_max - x_min) * coefficient
  28.             sd = sc
  29.             sc = function_f(c)
  30.         else:
  31.             x_min = c
  32.             c = d
  33.             d = x_min + (x_max - x_min) * coefficient
  34.             sc = sd
  35.             sd = function_f(d)
  36.         iteration += 1
  37.         print(("     {0:.0f}    || {1:.4f} || {2:.4f}   || {3:.4f} || {4:.4f}").format(iteration-1, x_min, function_f(x_min), x_max, function_f(x_max)))
  38.    
  39. Golden_Section_Method (x_min, x_max, 0.02)
  40.  
  41. # Шаг между точками
  42. dx = 0.1
  43.  
  44. # Создадим список координат по оси X на отрезке [-x_min; x_max], включая концы
  45. xlist = mlab.frange (x_min, x_max, dx)
  46.  
  47. # Вычислим значение функции в заданных точках
  48. ylist = [function_f(x) for x in xlist]
  49.  
  50. # Нарисуем одномерный график
  51. pylab.plot (xlist, ylist)
  52. plt.grid(True)
  53.  
  54. # Покажем окно с нарисованным графиком
  55. pylab.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement