Advertisement
SenyaSych

Метод Фибоначчи

Mar 23rd, 2018
1,064
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.14 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. #Определение функции
  12. function_f = lambda x: D * math.sin(A * x**B + C)
  13.  
  14. number_of_iterations = int(input(" Введите количество итераций: "))
  15.  
  16. #Число Фибоначчи
  17. def Fibonacci (n):
  18.    return int(((1 + math.sqrt(5))**n - (1 - math.sqrt(5))**n) / (2**n * math.sqrt (5)))
  19.  
  20. print((" {0:.8s} || {1:.5s}  || {2:.8s} || {3:.5s}  || {4:.8s}").format("Итерация", "x_min", "f(x_min)", "x_max", "f(x_max)"))
  21.  
  22. #Метод Фибоначчи
  23. def Fibonacci_Method(x_min, x_max, iteration = 0):
  24.     if (iteration == number_of_iterations): return
  25.     x_lhs = x_min + (((x_max - x_min) * Fibonacci(number_of_iterations - iteration - 1)) / Fibonacci (number_of_iterations - iteration + 1))
  26.     x_rhs = x_min + (((x_max - x_min) * Fibonacci(number_of_iterations - iteration)) / Fibonacci (number_of_iterations - iteration + 1))
  27.     if (function_f(x_lhs) < function_f(x_rhs)):
  28.         print(("     {0:.0f}    || {1:.4f} || {2:.4f}   || {3:.4f} || {4:.4f}").format(iteration+1, x_lhs, function_f(x_min), x_rhs, function_f(x_max)))
  29.         Fibonacci_Method(x_lhs, x_max, iteration + 1)
  30.     else:
  31.         print(("     {0:.0f}    || {1:.4f} || {2:.4f}   || {3:.4f} || {4:.4f}").format(iteration+1, x_lhs, function_f(x_min), x_rhs, function_f(x_max)))
  32.         Fibonacci_Method(x_min, x_rhs, iteration + 1)
  33.  
  34. Fibonacci_Method (x_min, x_max)
  35.  
  36. # Шаг между точками
  37. increment = 0.01
  38.  
  39. # Создадим список координат по оси X на отрезке [-xmin; xmax], включая концы
  40. xlist = mlab.frange (x_min, x_max, increment)
  41.  
  42. # Вычислим значение функции в заданных точках
  43. ylist = [function_f(x) for x in xlist]
  44.  
  45. # Нарисуем одномерный график
  46. pylab.plot (xlist, ylist)
  47. plt.grid(True)
  48.  
  49. # Покажем окно с нарисованным графиком
  50. pylab.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement