Kosty_Fomin

Untitled

Nov 11th, 2018
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.67 KB | None | 0 0
  1.  
  2. # coding: utf-8
  3.  
  4. # # Метод Ньютона
  5.  
  6. # In[1]:
  7.  
  8.  
  9. def calc_f(x):
  10.     return x**3-2.56*x**2-1.325*x+4.395
  11.  
  12. def deriv_f(x):
  13.     return 3*x**2 - 2.56*2*x -1.325
  14.  
  15. def deriv2_f(x):
  16.     return 3*2*x - 2.56*2
  17.  
  18.  
  19. # In[2]:
  20.  
  21.  
  22. def newtonsMethod(x0, eps):
  23.     global n
  24.     x1 = x0 - (calc_f(x0) / deriv_f(x0))
  25.     while (abs(calc_f(x0)) > eps) :
  26.         print ("x =", x0)
  27.         print ("f(", x0, ") = ", calc_f(x0), "\n")
  28.         print ("f1(", x0, ") = ", deriv_f(x0), "\n")
  29.         print ("f2(", x0, ") = ", deriv2_f(x0), "\n")
  30.         n = n + 1
  31.         x1 = x0 - (calc_f(x0) / deriv_f(x0))
  32.         x0 = x1
  33.        
  34.        
  35.     return x1
  36.  
  37.  
  38. # In[3]:
  39.  
  40.  
  41. def iter_f (a, b, step, eps):
  42.     global n
  43.     n = 0
  44.     while (a <= b):
  45.         if (calc_f(a)*calc_f(a + step) <= 0 and deriv_f(a)*deriv_f(a + step) > 0 and deriv2_f(a)*deriv2_f(a + step) > 0 and abs(deriv_f(a)) > eps):
  46.             if (calc_f(a)*deriv2_f(a) > 0):
  47.                 ans = newtonsMethod(a, eps)
  48.                 print ("x =", ans)
  49.                 print ("f(", ans, ") = ", calc_f(ans), "\n")
  50.                 print ("f1(", ans, ") = ", deriv_f(ans), "\n")
  51.                 print ("f2(", ans, ") = ", deriv2_f(ans), "\n")
  52.                
  53.             else:
  54.                 ans = newtonsMethod(a + step, eps)
  55.                 print("x=",ans)
  56.                 print ("f(", ans, ") = ", calc_f(ans), "\n")
  57.                 print ("f1(", ans, ") = ", deriv_f(ans), "\n")
  58.                 print ("f2(", ans, ") = ", deriv2_f(ans), "\n")
  59.         a = a + step
  60.     print("Количество итераций: ", n)
  61.  
  62.  
  63. # In[4]:
  64.  
  65.  
  66. def answer (a, eps):
  67.     global n
  68.     print("Введите: 1 - для вывода ответа на экран; 2 - для сохранения ответа в файл.")
  69.    
  70.     err = True
  71.     while (err == True):
  72.         kuda_write = input()
  73.         if (kuda_write == '1' or kuda_write == '2'):
  74.             err = False
  75.         else:
  76.             print(":(")
  77.    
  78.     if (kuda_write == '1'):
  79.         x = newtonsMethod(a, eps)
  80.         print (f'Начальное приближение = {a}, погрешность = {eps}\n\nОтвет:\nx = {x}\nf(x) = {calc_f(x)}\nКоличество итераций = {n}')
  81.         return x
  82.    
  83.     if (kuda_write == '2'):
  84.         out_file = open("answer_newton.txt", "w",encoding("utf-8"))
  85.         x = newtonsMethod(a, eps)
  86.         str_ans = "Мы попали в экстремум"
  87.         out_file.write(str_ans)
  88.         return x
  89.  
  90.  
  91. # # Ввод данных с файла
  92. #
  93. # В файле data_newton.txt должны находиться 2 значения в разных строках:
  94. #
  95. # 1. Начальное приближение
  96. # 2. Погрешность
  97.  
  98. # In[ ]:
  99.  
  100.  
  101. with open('data_newton.txt', 'r') as myfile:
  102.     content = myfile.readlines()
  103.  
  104.    
  105. content = [x.strip() for x in content]
  106.  
  107. try:
  108.     a = float(content[0])
  109.     eps = float(content[1])
  110.     n = 0
  111.     if (answer(a, eps) is None):
  112.         raise Exception("")
  113. except Exception:
  114.     ("Проверьте правильность данные в файле")
  115.  
  116.  
  117. # # Ввод данных с клавиатуры
  118.  
  119. # In[ ]:
  120.  
  121.  
  122. err = True
  123.  
  124. while (err == True):
  125.     try:
  126.         n = 0
  127.         print ("Введите начальное приближение:")
  128.         a = float(input())
  129.         print ("Введите погрешность:")
  130.         eps = float(input())
  131.         print(newtonsMethod(a,eps))
  132.         print(calc_f(a))
  133.         print(deriv_f(a))
  134.         print(deriv2_f(a))
  135.         err = False
  136.     except:
  137.         pass
  138.  
  139.  
  140. # # Поиск всех корней на промежутке [a, b]
  141.  
  142. # In[ ]:
  143.  
  144.  
  145. # err = True
  146.  
  147. # while (err == True):
  148. #     try:
  149. #         print ("Введите координату начала:")
  150. #         a = float(input())
  151. #         print ("Введите координату конца:")
  152. #         b = float(input())
  153. #         if (a > b):
  154. #             print("Координата конца больше координаты начала? :С")
  155. #             raise Exception("")
  156. #         print ("Введите погрешность:")
  157. #         eps = float(input())
  158. #         err = False
  159. #     except Exception:
  160. #         print("Ошибка. Проверьте правильность введенных данных\n")
  161.  
  162. # print ("\nОтвет:")
  163. # iter_f(a, b, 0.1, eps)
  164.  
  165.  
  166. # # График функции
  167.  
  168. # In[ ]:
  169.  
  170.  
  171. # get_ipython().run_line_magic('matplotlib', 'inline')
  172.  
  173. import numpy as np
  174. import matplotlib.pyplot as plt
  175.  
  176. x = np.array(np.arange(-4.5, 2, step=0.1))
  177. y = calc_f(x)
  178. plt.figure(figsize=(12,6))
  179. plt.plot(x, y)
  180. plt.grid()
  181. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment