where a, b, c, and d are constants.
#include <stdio.h>
#include <math.h>
#define EPSILON 0.000001 // defines the precision of the solution
double f(double x, double a, double b, double c, double d) {
return a * x * x * x + b * x * x + c * x + d;
}
double f_prime(double x, double a, double b, double c) {
return 3 * a * x * x + 2 * b * x + c;
}
double newtonRaphson(double a, double b, double c, double d, double start) {
double x = start; // Initial guess
double h = f(x, a, b, c, d) / f_prime(x, a, b, c);
while (fabs(h) >= EPSILON) {
h = f(x, a, b, c, d) / f_prime(x, a, b, c);
x = x - h; // Update x
}
return x;
}
int main() {
// Coefficients of the cubic equation: ax^3 + bx^2 + cx + d.
double a, b, c, d;
printf("Enter coefficients a, b, c, d of cubic function ax^3 + bx^2 + cx + d:\n");
scanf("%lf %lf %lf %lf", &a, &b, &c, &d);
// Initial guess - can be chosen randomly or based on prior knowledge
double initial_guess;
printf("Enter an initial guess:\n");
scanf("%lf", &initial_guess);
double root = newtonRaphson(a, b, c, d, initial_guess);
printf("An approximate root of the cubic function is: %lf\n", root);
return 0;
}
Please remember that the Newton-Raphson method requires a reasonable initial guess and it might not converge if the guess is too far from the root. Also, there is no guarantee that the method will find a real root if the function doesn't have any, or it may not find multiple roots without running the algorithm with different initial guesses. Additionally, if the derivative of the function is zero or very close to zero, the method can fail or converge very slowly.
The Newton-Raphson method is an example of a root-finding algorithm. Depending on the specific requirements of your problem, you may need to consider other methods such as the bisection method, secant method, or using analytical solutions for certain types of cubic equations.