Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

коды / 7

.py
Скачиваний:
12
Добавлен:
20.06.2023
Размер:
1 Кб
Скачать
import numpy as np
import matplotlib.pyplot as plt

eps = 0.01
def f(x):return x**5+2*x**4-5*x**2-7*x-3
def fp(x):return 5*x**4+8*x**3-10*x-7
def bisect(a, b):
    c=(a+b)/2;fc=f(c)
    while abs(fc)>eps:
        if f(a)*fc<0:b=c
        else:a=c
        c=(a+b)/2;fc=f(c)
    return c,fc
def fixiter(x):
    l=(-2*eps)/(f(x-eps)-f(x+eps));fx=f(x)
    while abs(fx)>eps:x=x-l*fx;fx=f(x)
    return x,fx
def newton(x):
    fx=f(x)
    while abs(fx)>eps:x=x-fx/fp(x);fx=f(x)
    return x,fx
def create_plot(ax,x,y,title):
    ax.plot(xs,ys);ax.set_xticks(np.arange(-5,6))
    ax.set_title(title);ax.grid(True);ax.scatter(x,y)
def on_click(event):
    if event.inaxes is None:return
    index=np.where(axs==event.inaxes)[0][0];plt.figure()
    create_plot(plt.gca(),[x,x2,x3][index],[y,y2,y3][index],
    ['Метод половинного деления','Метод простой итерации','Метод Ньютона'][index])
    plt.show()
    
x,y=bisect(-5,5);x2,y2=fixiter(3);x3,y3=newton(3)
print(x,y),print(x2,y2),print(x3,y3)

xs=np.linspace(-5,5,100);ys=xs**5+2*xs**4-5*xs**2-7*xs-3
fig, axs = plt.subplots(3,1,figsize=(4,8))
for i, ax in enumerate(axs):create_plot(ax,[x,x2,x3][i],[y,y2,y3][i],
    ['Метод половинного деления','Метод простой итерации','Метод Ньютона'][i])
fig.canvas.mpl_connect('button_press_event',on_click);plt.tight_layout();plt.show()
Соседние файлы в папке коды