fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3. #define EPSILON 0.0001
  4. #define MAX_ITERATIONS 50
  5. // Function to calculate the equation: log(x) - cos(x)
  6. double equation(double x) {
  7. return log(x) - cos(x);
  8. }
  9. // Derivative of the equation: 1/x + sin(x)
  10. double derivative(double x) {
  11. return 1.0 / x + sin(x);
  12. }
  13. // Newton-Raphson method
  14. double newtonRaphson(double x0, int* iterations) {
  15. double x1, f0, f1;
  16. printf("%-10s%-12s%-12s%-12s%-12s\n", "Iteration", "x0", "f(x0)", "f'(x0)",
  17. "x1");
  18. for (*iterations = 1; *iterations <= MAX_ITERATIONS; ++(*iterations)) {
  19. f0 = equation(x0);
  20. if (fabs(f0) < EPSILON)
  21. break;
  22. f1 = derivative(x0);
  23. x1 = x0 - f0 / f1;
  24. printf("%-10d%-12.4lf%-12.4lf%-12.4lf%-12.4lf\n",
  25. *iterations, x0, f0, f1, x1);
  26. x0 = x1;
  27. }
  28. return x1;
  29. }
  30. int main() {
  31. double x0 = 2.0; // Initial guess for Newton-Raphson method
  32. double root_newton;
  33. int iterations;
  34. // Newton-Raphson method
  35. root_newton = newtonRaphson(x0, &iterations);
  36. printf("\nRoot (Newton-Raphson Method): %.4lf\n", root_newton);
  37. printf("Number of iterations: %d\n", iterations);
  38. return 0;
  39. }
Success #stdin #stdout 0.01s 5316KB
stdin
45
stdout
Iteration x0          f(x0)       f'(x0)      x1          
1         2.0000      1.1093      1.4093      1.2129      
2         1.2129      -0.1573     1.7611      1.3022      
3         1.3022      -0.0013     1.7321      1.3030      

Root (Newton-Raphson Method): 1.3030
Number of iterations: 4