Untitled

 avatar
unknown
plain_text
a year ago
1.4 kB
11
Indexable
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

// Function (a): f(x) = x - 2^(-x)
double f1(double x) {
    return x - pow(2.0, -x);
}

// Function (b): f(x) = e^x - x^2 + 3x - 2
double f2(double x) {
    return exp(x) - x*x + 3*x - 2;
}

// Secant Method implementation
double secant(double (*f)(double), double x0, double x1, double tol = 1e-4, int maxIter = 100) {
    double f0 = f(x0);
    double f1_ = f(x1);
    int iter = 0;

    while (fabs(x1 - x0) > tol && iter < maxIter) {
        double denom = (f1_ - f0);
        if (fabs(denom) < 1e-12) {  // Avoid division by zero
            cout << "Denominator too small, stopping.\n";
            break;
        }

        double x2 = x1 - f1_ * (x1 - x0) / denom;

        x0 = x1;
        f0 = f1_;
        x1 = x2;
        f1_ = f(x1);

        iter++;
    }

    cout << "Iterations: " << iter << endl;
    return x1;
}

int main() {
    cout << fixed << setprecision(6);

    cout << "Root of equation (a) f(x) = x - 2^(-x):" << endl;
    double root1 = secant(f1, 0.0, 1.0);
    cout << "Approximate root = " << root1 << endl << endl;

    cout << "Root of equation (b) f(x) = e^x - x^2 + 3x - 2:" << endl;
    double root2 = secant(f2, 0.0, 1.0);
    cout << "Approximate root = " << root2 << endl;

    return 0;
}
Editor is loading...
Leave a Comment