Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
0
Добавлен:
09.09.2026
Размер:
3 Кб
Скачать
#include <iostream>
#include <bits/stdc++.h>
#include <cmath>
#include <vector>
#define Error 1e-10
#define Step 0.01
using namespace std;


vector<double> bis_res;
vector<double> new_res;


double df(double x) {
    return 5 * pow(x, 4) + 1;
}


double f(double x, double a) {
    return pow(x, 5) + x + a;
}


void find_section(double &x1, double &x2, double a) {
    double i = 0, y1 = f(0, a), y2;
    if (a <= 0) {
        while (true) {
            y2 = f(i + Step, a);
            if (y1 <= 0 && y2 > 0) {
                x1 = i;
                x2 = i + Step;
                break;
            }
            y1 = y2;
            i += Step;
        }
    } else {
        while (true) {
            y2 = f(i - Step, a);
            if (y1 >= 0 && y2 < 0) {
                x1 = i - Step;
                x2 = i;
                break;
            }
            y1 = y2;
            i -= Step;
        }
    }
}


void bisection_method(double x1, double x2, double a) {
    if (f(x1, a) * f(x2, a) > 0) {
        cout << "The root does not lie in this interval\n";
        return;
    }
    double c = x1;
    while ((x2 - x1) >= Error) {
        c = (x1 + x2) / 2;
        if (f(c, a) == 0.0)
            break;
        else if (f(c, a) * f(x1, a) <= 0)
            x2 = c;
        else
            x1 = c;
        bis_res.push_back(c);
    }
}


void newton_method(double x1, double x2, double a){
    double x_i = x1 + fabs((x2 - x1) / 2), x_ii, sub;
    int iter = 0;
    do {
        x_ii = x_i - (f(x_i, a) / df(x_i));
        new_res.push_back(x_ii);
        sub = x_ii - x_i;
        x_i = x_ii;
        iter ++;
    } while (fabs(sub) > Error && iter < 20000);
}


int main() {
    double x1, x2, a = 100;

    if (a == 0) {
        cout << "Root is 0" << endl;
        return 0;
    }

    find_section(x1, x2, a);
    bisection_method(x1, x2, a);
    newton_method(x1, x2, a);

    std::cout << std::fixed;
    std::cout << std::setprecision(17);
    int m = min(bis_res.size(), new_res.size());
    for (int i = 0; i < m; i++)
        cout << bis_res[i] << " " << new_res[i] << endl;
    if (m == new_res.size()) {
        for (int i = m; i < bis_res.size(); i++)
            cout << bis_res[i] << endl;
    } else {
        for (int i = m; i < new_res.size(); i++)
            cout << "                     "<< new_res[i] << endl;
    }

    cout << "\nRoot lie in [" << x1 << ", " << x2 << "]\n";
    cout << "The bisection's root is : " << bis_res.back() << endl;
    cout << "The Newton's root is :    " << new_res.back() << endl;
    return 0;
}
Соседние файлы в папке ИДЗ по ВычМат 2024