Advertisement
Guest User

1

a guest
Dec 12th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3.  
  4.  
  5. def f(x):
  6.     return (x - 3) / (x ** 2 + 5) ** 0.5
  7.  
  8.  
  9. def search_method(a, b, e=0.01):
  10.     d = (b - a) / 4
  11.     x0 = a
  12.     while True:
  13.         x1 = x0 + d
  14.         if f(x0) > f(x1):
  15.             x0 = x1
  16.             if a <= x0 <= b:
  17.                 continue
  18.             else:
  19.                 if abs(d) <= e:
  20.                     return x0
  21.                 else:
  22.                     x0 = x1
  23.                     d = -d / 4
  24.         else:
  25.             if abs(d) <= e:
  26.                 return x0
  27.             else:
  28.                 x0 = x1
  29.                 d = -d / 4
  30.  
  31.  
  32. f_min = search_method(-3, -1)
  33. print('Метод поразрядного поиска')
  34. print('x =', f_min)
  35. print('f(x) =', f(f_min))
  36. print()
  37.  
  38.  
  39. def dichotomy_method(a, b, e=0.01):
  40.     c = 0.002
  41.     while True:
  42.         x1 = (b + a - c) / 2
  43.         x2 = (b + a + c) / 2
  44.         if f(x1) <= f(x2):
  45.             b = x2
  46.         else:
  47.             a = x1
  48.         e_n = (b - a) / 2
  49.         if e_n > e:
  50.             continue
  51.         else:
  52.             return (a + b) / 2
  53.  
  54. f_min = dichotomy_method(-3, -1)
  55. print('Метод дихотомии')
  56. print('x =', f_min)
  57. print('f(x) =', f(f_min))
  58. print()
  59.  
  60.  
  61. def golden_section_method(a, b, e=0.01):
  62.     while True:
  63.         c = a + (3 - 5**0.5) / 2 * (b - a)
  64.         d = a + (5**0.5 - 1) / 2 * (b - a)
  65.         if f(d) > f(c):
  66.             b = d
  67.         else:
  68.             a = c
  69.         if (b - a) > e:
  70.             continue
  71.         else:
  72.             return min(d, c)
  73.  
  74.  
  75. f_min = golden_section_method(-3, -1)
  76. print('Метод золотого сечения')
  77. print('x =', f_min)
  78. print('f(x) =', f(f_min))
  79. print()
  80.  
  81. x = np.arange(-3, -1, 0.01)
  82. y = list(map(f, x))
  83.  
  84. plt.plot(x, y)
  85. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement