fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. double f(double x) {
  5. return 2 * x * x * x + 3 * x - 1;
  6. }
  7.  
  8. double df(double x) {
  9. return 6 * x * x + 3;
  10. }
  11.  
  12. int main() {
  13. double x0, x1, f0, df0, E = 1e-8;
  14. int i = 0;
  15. printf("Enter initial guess: ");
  16. scanf("%lf", &x0);
  17. printf("Iter\t x0\t\t f(x0)\t\t f'(x0)\t\t x1\n");
  18. do {
  19. f0 = f(x0);
  20. df0 = df(x0);
  21. if (df0 == 0) {
  22. printf("Derivative is zero. Cannot continue.\n");
  23. return 0;
  24. }
  25. x1 = x0 - f0 / df0;
  26. printf("%d\t%.6lf\t%.6lf\t%.6lf\t%.6lf\n", ++i, x0, f0, df0, x1);
  27. if (fabs(x1 - x0) < E)
  28. break;
  29. x0 = x1;
  30. } while (1);
  31. printf("\nApproximate root = %.8lf\n", x1);
  32. return 0;
  33. }
  34.  
Success #stdin #stdout 0s 5324KB
stdin
Standard input is empty
stdout
Enter initial guess: Iter	 x0		 f(x0)		 f'(x0)		 x1
1	0.000000	-1.000000	3.000000	0.333333
2	0.333333	0.074074	3.666667	0.313131
3	0.313131	0.000800	3.588307	0.312908
4	0.312908	0.000000	3.587470	0.312908
5	0.312908	0.000000	3.587470	0.312908

Approximate root = 0.31290841