Print the Approximate Root
In this step, we will enhance our Newton's method implementation to provide more detailed output about the root approximation.
Open the previous newton_method.c
file:
cd ~/project
nano newton_method.c
Update the code to improve root approximation output:
#include <stdio.h>
#include <math.h>
// Previous function and method definitions remain the same
double f(double x) {
return x * x - 4;
}
double f_derivative(double x) {
return 2 * x;
}
double newton_method(double initial_guess, int max_iterations, double tolerance) {
double x = initial_guess;
printf("Newton's Method Root Approximation\n");
printf("-----------------------------------\n");
printf("Initial Guess: %f\n", x);
printf("Tolerance: %e\n", tolerance);
printf("Max Iterations: %d\n\n", max_iterations);
for (int i = 0; i < max_iterations; i++) {
double fx = f(x);
double fpx = f_derivative(x);
if (fabs(fpx) < tolerance) {
printf("Error: Derivative too close to zero.\n");
return x;
}
double x_next = x - fx / fpx;
printf("Iteration %d:\n", i + 1);
printf(" Current x: %f\n", x_next);
printf(" f(x): %f\n", f(x_next));
printf(" |x_next - x|: %e\n\n", fabs(x_next - x));
if (fabs(x_next - x) < tolerance) {
printf("Convergence achieved!\n");
return x_next;
}
x = x_next;
}
printf("Maximum iterations reached.\n");
return x;
}
int main() {
double initial_guess = 1.0;
int max_iterations = 10;
double tolerance = 1e-6;
double root = newton_method(initial_guess, max_iterations, tolerance);
printf("Final Results:\n");
printf("-------------\n");
printf("Approximate Root: %f\n", root);
printf("f(root): %f\n", f(root));
printf("Absolute Error: %e\n", fabs(f(root)));
return 0;
}
Compile and run the code:
gcc -o newton_method newton_method.c -lm
./newton_method
Example output:
Newton's Method Root Approximation
-----------------------------------
Initial Guess: 1.000000
Tolerance: 1.000000e-06
Max Iterations: 10
Iteration 1:
Current x: 2.500000
f(x): 2.250000
|x_next - x|: 1.500000e+00
Iteration 2:
Current x: 2.050000
f(x): 0.202500
|x_next - x|: 4.500000e-01
... (more iterations)
Convergence achieved!
Final Results:
-------------
Approximate Root: 2.000000
f(root): 0.000000
Absolute Error: 0.000000e+00
Key improvements:
- Added detailed iteration information
- Displayed initial parameters
- Showed convergence progress
- Printed final results with absolute error