<jupyter_start><jupyter_text>Импорт всех необходимых модулей<jupyter_code>import pandas as pd
import math
import plotly.express as px
import numpy as np
import pylab as pl
import plotly
import plotly.graph_objs as go
import plotly.express as px
from plotly.subplots import make_subplots
import docx<jupyter_output><empty_output><jupyter_text>Задаем константы. Промежуток для которого ищем корень, и требуемые точности.<jupyter_code>START_X = -math.pi/2
FINISH_X = 0.0001
EPS = [0.01, 0.001, 0.0001]<jupyter_output><empty_output><jupyter_text>Реализуем саму функцию корень которой требуется найти<jupyter_code>def func(x):
    return (4.0 * math.cos(x) - x - (1.0/float(math.pow(x, 2))))<jupyter_output><empty_output><jupyter_text>Метод нахождения корня путем бисекции<jupyter_code>def bisection_method(func, df, x0, x1, eps=0.0001):
    delx = x1-x0
    f0 = func(x0)
    f1 = func(x1+eps)
    while delx > eps:
        xm = 0.5*(x0+x1)
        try:
            fm = func(xm)
        except:
            fm = float("inf")
        delx = math.fabs(x1-x0)
        if f0*fm > 0:
            x0 = xm
            f0 = fm
        else:
            x1 = xm
            f1 = fm
        df.loc[len(df)] = [x0, f0, x1, f1, delx]

    return df<jupyter_output><empty_output><jupyter_text>Поиск корня при каждом требуемом уровне точности, а также вывод полученных результатов в текстовом формате<jupyter_code>for eps in EPS:
    df = pd.DataFrame(columns=['Xleft', 'f(Xleft)',
                               'Xright', 'f(Xright)', 'delta'])
    df = bisection_method(func, df, START_X, FINISH_X, eps)
    print(f"Finding root at [{START_X}; {FINISH_X}] with eps = {eps}")
    print(df)
    print(
        f"Root is {(df[-1:]['Xleft'].values[0]+df[-1:]['Xright'].values[0])/2}")
    print("_______________________________________________________________")
def draw_func(func, start, finish, step):
    df = pd.DataFrame(columns=['x', 'y'])
    for x in np.arange(start, finish, step):
        try:
            y = func(x)
        except:
            y = float('inf')
        df.loc[len(df)] = [x, y]
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=df['x'], y=df['y'], name="4cos(x) - x - 1/x^2"))
    fig.show()
draw_func(func, -10, -0.2, 0.01)
def doctable(data, tabletitle, pathfile):
    from docx import Document
    import pandas as pd
    document = Document()
    data = pd.DataFrame(data)  # My input data is in the 2D list form
    document.add_heading(tabletitle)
    # First row are table headers!
    table = document.add_table(rows=(data.shape[0]), cols=data.shape[1])
    for i, column in enumerate(data):
        for row in range(data.shape[0]):
            table.cell(row, i).text = str(data[column][row])
    document.save(pathfile)
doctable(df, "bisection", "text.docx")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13701067615658363, 'fraction_numerical': 0.025266903914590747, 'mean_word_length': 3.1644444444444444, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '269890', 'license': 'MIT', 'n_tokens_mistral': 1107, 'n_tokens_neox': 1105, 'n_words': 242, 'path': '.ipynb_checkpoints/bisection_method-checkpoint.ipynb', 'repo_name': 'teslaistra/Numerical-Methods-MISiS', 'size': '2810'}