Untitled
unknown
plain_text
a year ago
1.2 kB
2
Indexable
Never
#include <stdio.h> #include <math.h> // Define the function and its derivative double f(double x) { return x * x * x - 5 * x + 3; } double df(double x) { return 3 * x * x - 5; } // Newton-Raphson using divided differences formula double newtonRaphson(double x0, double tolerance, int maxIterations) { double x = x0; int iterations = 0; while (iterations < maxIterations) { double fValue = f(x); double dfValue = df(x); double h = fValue / dfValue; double h2 = h * h; double h3 = h * h2; x -= h - 0.5 * h2 + h3 / 6; if (fabs(h) < tolerance) { printf("Converged to root after %d iterations.\n", iterations); return x; } iterations++; } printf("Failed to converge after %d iterations.\n", maxIterations); return x; } int main() { double initialGuess = 1.0; double tolerance = 1e-6; int maxIterations = 1000; double root = newtonRaphson(initialGuess, tolerance, maxIterations); printf("Approximate root: %lf\n", root); return 0; }