fork download
  1. class FalsePosition {
  2. static double f(double x) {
  3. return x*x*x - 4; // f(x) = x^3 - 4 //Name= MD Sakib
  4. //ID = 240242058
  5. }
  6.  
  7. public static void main(String[] args) {
  8. double x1 = 1, x2 = 3, x0 = 0;
  9. double f1 = f(x1), f2 = f(x2);
  10. double prev = 0, error = 0;
  11. int iterations = 3;
  12.  
  13. System.out.printf("%-5s %-12s %-12s %-12s %-12s %-12s\n",
  14. "Iter", "x0", "Error", "%Error", "x1", "x2");
  15.  
  16. for(int i = 1; i <= iterations; i++) {
  17. x0 = x1 - (f1 * (x2 - x1)) / (f2 - f1);
  18. double f0 = f(x0);
  19.  
  20. if(i == 1) error = 0;
  21. else error = Math.abs(x0 - prev);
  22.  
  23. double perError = (i==1) ? 0 : (error/Math.abs(x0))*100;
  24.  
  25. System.out.printf("%-5d %-12.8f %-12.8f %-12.8f %-12.8f %-12.8f\n",
  26. i, x0, error, perError, x1, x2);
  27.  
  28. if(f1 * f0 < 0) {
  29. x2 = x0;
  30. f2 = f(x2);
  31. } else {
  32. x1 = x0;
  33. f1 = f(x1);
  34. }
  35.  
  36. prev = x0;
  37. }
  38. }
  39. }
  40.  
Success #stdin #stdout 0.11s 56240KB
stdin
Standard input is empty
stdout
Iter  x0           Error        %Error       x1           x2          
1     1.23076923   0.00000000   0.00000000   1.00000000   3.00000000  
2     1.38109121   0.15032198   10.88429062  1.23076923   3.00000000  
3     1.47183051   0.09073930   6.16506444   1.38109121   3.00000000