Kosty_Fomin

Untitled

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