Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # coding: utf-8
- # # Метод Ньютона
- # In[1]:
- def calc_f(x):
- return x**3-2.56*x**2-1.325*x+4.395
- def deriv_f(x):
- return 3*x**2 - 2.56*2*x -1.325
- def deriv2_f(x):
- return 3*2*x - 2.56*2
- # In[2]:
- def newtonsMethod(x0, eps):
- global n
- n = 0
- x1 = x0 - (calc_f(x0) / deriv_f(x0))
- while (abs(calc_f(x0)) > eps) :
- print ("x =", x0)
- print ("f(", x0, ") = ", calc_f(x0), "\n")
- print ("f1(", x0, ") = ", deriv_f(x0), "\n")
- print ("f2(", x0, ") = ", deriv2_f(x0), "\n")
- n = n + 1
- x1 = x0 - (calc_f(x0) / deriv_f(x0))
- x0 = x1
- return x1
- # In[3]:
- def iter_f (a, b, step, eps):
- global n
- n = 0
- while (a <= b):
- 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):
- if (calc_f(a)*deriv2_f(a) > 0):
- ans = newtonsMethod(a, eps)
- print ("x =", ans)
- print ("f(", ans, ") = ", calc_f(ans), "\n")
- print ("f1(", ans, ") = ", deriv_f(ans), "\n")
- print ("f2(", ans, ") = ", deriv2_f(ans), "\n")
- else:
- ans = newtonsMethod(a + step, eps)
- print("x=",ans)
- print ("f(", ans, ") = ", calc_f(ans), "\n")
- print ("f1(", ans, ") = ", deriv_f(ans), "\n")
- print ("f2(", ans, ") = ", deriv2_f(ans), "\n")
- a = a + step
- print("Количество итераций: ", n)
- # In[4]:
- def answer (a, eps):
- global n
- print("Введите: 1 - для вывода ответа на экран; 2 - для сохранения ответа в файл.")
- err = True
- while (err == True):
- kuda_write = input()
- if (kuda_write == '1' or kuda_write == '2'):
- err = False
- else:
- print(":(")
- if (kuda_write == '1'):
- x = newtonsMethod(a, eps)
- print (f'Начальное приближение = {a}, погрешность = {eps}\n\nОтвет:\nx = {x}\nf(x) = {calc_f(x)}\nКоличество итераций = {n}')## calc_f - надо или нет?
- return x
- if (kuda_write == '2'):
- out_file = open("answer_newton.txt", "w",encoding("utf-8"))
- x = newtonsMethod(a, eps)
- str_ans = "Мы попали в экстремум"
- out_file.write(str_ans)
- return x
- # # Ввод данных с файла
- #
- # В файле data_newton.txt должны находиться 2 значения в разных строках:
- #
- # 1. Начальное приближение
- # 2. Погрешность
- # In[ ]:
- # with open('data_newton.txt', 'r') as myfile:
- # content = myfile.readlines()
- # content = [x.strip() for x in content]
- # try:
- # a = float(content[0])
- # eps = float(content[1])
- # n = 0
- # if (answer(a, eps) is None):
- # raise Exception("")
- # except Exception:
- # ("Проверьте правильность данные в файле")
- # # Ввод данных с клавиатуры
- # In[ ]:
- err = True
- while (err == True):
- try:
- n = 0
- print ("Введите начальное приближение:")
- a = float(input())
- print ("Введите погрешность:")
- eps = float(input())
- newtonsMethod(a,eps)
- # calc_f(a)
- # deriv_f(a)
- # deriv2_f(a)
- answer(a, eps)
- err = False
- except:
- pass
- # # Поиск всех корней на промежутке [a, b]
- # In[ ]:
- # err = True
- # while (err == True):
- # try:
- # print ("Введите координату начала:")
- # a = float(input())
- # print ("Введите координату конца:")
- # b = float(input())
- # if (a > b):
- # print("Координата конца больше координаты начала? :С")
- # raise Exception("")
- # print ("Введите погрешность:")
- # eps = float(input())
- # err = False
- # except Exception:
- # print("Ошибка. Проверьте правильность введенных данных\n")
- # print ("\nОтвет:")
- # iter_f(a, b, 0.1, eps)
- # # График функции
- # In[ ]:
- # get_ipython().run_line_magic('matplotlib', 'inline')
- import numpy as np
- import matplotlib.pyplot as plt
- x = np.array(np.arange(-4.5, 2, step=0.1))
- y = calc_f(x)
- plt.figure(figsize=(12,6))
- plt.plot(x, y)
- plt.grid()
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment