fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. double f(double x) {
  5. return x * x * x - 2 * x - 5;
  6. }
  7.  
  8. void secant_method(double x0, double x1, double tol, int max_iter) {
  9. double x_next, fx0, fx1;
  10. int iter = 0;
  11.  
  12. printf("Iteration\t x0\t\t x1\t\t x_next\t\t f(x_next)\n");
  13.  
  14. do {
  15. fx0 = f(x0);
  16. fx1 = f(x1);
  17.  
  18. if (fx1 - fx0 == 0) {
  19. printf("Mathematical Error! Division by zero occurred.\n");
  20. return;
  21. }
  22.  
  23. x_next = x1 - (fx1 * (x1 - x0)) / (fx1 - fx0);
  24.  
  25. printf("%d\t\t %lf\t %lf\t %lf\t %lf\n", iter + 1, x0, x1, x_next, f(x_next));
  26.  
  27. x0 = x1;
  28. x1 = x_next;
  29. iter++;
  30.  
  31. } while (fabs(f(x_next)) > tol && iter < max_iter);
  32.  
  33. if (iter == max_iter) {
  34. printf("\nMethod did not converge within %d iterations.\n", max_iter);
  35. } else {
  36. printf("\nThe root of the equation is: %lf\n", x_next);
  37. }
  38. }
  39.  
  40. int main() {
  41. double x0, x1, tol;
  42. int max_iter;
  43.  
  44. printf("Enter two initial guesses (x0 and x1): ");
  45. scanf("%lf %lf", &x0, &x1);
  46.  
  47. printf("Enter the desired tolerance: ");
  48. scanf("%lf", &tol);
  49.  
  50. printf("Enter the maximum number of iterations: ");
  51. scanf("%d", &max_iter);
  52.  
  53. secant_method(x0, x1, tol, max_iter);
  54.  
  55. return 0;
  56. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Enter two initial guesses (x0 and x1): Enter the desired tolerance: Enter the maximum number of iterations: Iteration	 x0		 x1		 x_next		 f(x_next)
Mathematical Error! Division by zero occurred.