Untitled

 avatar
unknown
plain_text
9 days ago
1.0 kB
5
Indexable
#include <iostream>
#include <cmath>
using namespace std;
double function(double x);
double derivative(double x);

int main() {
    double x0, epsilon;
    int maxIterations;

    cout << "Enter initial guess: ";
    cin >> x0;

    cout << "Enter tolerance: ";
    cin >> epsilon;

    cout << "Enter maximum number of iterations: ";
    cin >> maxIterations;

    double x1, fx, dfx;
    for (int i = 0; i < maxIterations; i++) {
        fx = function(x0);
        dfx = derivative(x0);

        if (dfx == 0.0) {
            cout << "Derivative is zero. No solution found.\n";
            return -1;
        }

        x1 = x0 - fx / dfx;

        if (fabs(x1 - x0) < epsilon) {
            cout << "Root found: " << x1 << "\n";
            return 0;
        }

        x0 = x1;
    }

    cout << "Maximum number of iterations reached. No solution found.\n";
    return -1;
}

double function(double x) {
    return x * x - 2;
}

double derivative(double x) {
    return 2 * x;
}
Leave a Comment