fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. double f(double x) {
  5. return x * x * x - 4;
  6. }
  7.  
  8. int main() {
  9. double x1 = 1, x2 = 3, x0, f1, f2, f0, E = 1e-8;
  10. int i;
  11. f1 = f(x1);
  12. f2 = f(x2);
  13. printf("Iter\t x1\t\t x2\t\t x0\t\t f1\t\t f2\t\t f0\n");
  14. for (i = 1; i <= 3; i++) {
  15. x0 = x1 - (f1 * (x2 - x1)) / (f2 - f1);
  16. f0 = f(x0);
  17. printf("%d\t%.6lf\t%.6lf\t%.6lf\t%.6lf\t%.6lf\t%.6lf\n", i, x1, x2, x0, f1, f2, f0);
  18. if (f1 * f0 < 0)
  19. x2 = x0;
  20. else
  21. x1 = x0;
  22. f1 = f(x1);
  23. f2 = f(x2);
  24. }
  25. return 0;
  26. }
  27.  
Success #stdin #stdout 0.01s 5292KB
stdin
-3
4
stdout
Iter	 x1		 x2		 x0		 f1		 f2		 f0
1	1.000000	3.000000	1.230769	-3.000000	23.000000	-2.135640
2	1.230769	3.000000	1.381091	-2.135640	23.000000	-1.365689
3	1.381091	3.000000	1.471831	-1.365689	23.000000	-0.811596