Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
1.2 kB
1
Indexable
Never
#include <stdio.h>
#include <math.h>

#define EPSILON 0.000001 // Error tolerance

// Function representing the cubic equation: f(x) = a2*x^3 + a1*x^2 + a0
double cubicEquation(double x, double a2, double a1, double a0) {
    return a2 * x * x * x + a1 * x * x + a0;
}

// Secant method function to find root of the cubic equation
double secantMethod(double a2, double a1, double a0) {
    double x0 = 0.0, x1 = 1.0; // Initial guesses
    double fx0, fx1, x2;

    do {
        fx0 = cubicEquation(x0, a2, a1, a0);
        fx1 = cubicEquation(x1, a2, a1, a0);

        // Secant formula to find the next approximation
        x2 = x1 - ((fx1 * (x1 - x0)) / (fx1 - fx0));

        x0 = x1;
        x1 = x2;
    } while (fabs(x1 - x0) >= EPSILON);

    return x1;
}

int main() {
    double a2, a1, a0;

    printf("Enter the coefficients of the cubic equation (a2*x^3 + a1*x^2 + a0): \n");
    printf("Enter a2: ");
    scanf("%lf", &a2);
    printf("Enter a1: ");
    scanf("%lf", &a1);
    printf("Enter a0: ");
    scanf("%lf", &a0);

    double root = secantMethod(a2, a1, a0);

    printf("Root of the equation: %lf\n", root);

    return 0;
}


Leave a Comment