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