fork download
  1. public class Main {
  2.  
  3. static double f(double x) {
  4. return 2*x*x*x + 3*x - 1;
  5. }
  6.  
  7. public static void main(String[] args) {
  8.  
  9. double x0 = -1; // starting value
  10. double x1 = 2; // starting value
  11. double eps = 1e-6;
  12. double x2, f0, f1, f2;
  13. int iter = 1;
  14.  
  15. System.out.println("Enter the value of x0: -1");
  16. System.out.println("Enter the value of x1: 2\n");
  17.  
  18. System.out.println("Iteration x0\t\t x1\t\t x2\t\t f0\t\t f1\t\t f2");
  19. System.out.println("--------------------------------------------------------------------------------");
  20.  
  21. while (Math.abs(x1 - x0) > eps) {
  22.  
  23. x2 = (x0 + x1) / 2;
  24. f0 = f(x0);
  25. f1 = f(x1);
  26. f2 = f(x2);
  27.  
  28. System.out.printf("%-10d %.6f %.6f %.6f %.6f %.6f %.6f\n",
  29. iter, x0, x1, x2, f0, f1, f2);
  30.  
  31. if (f0 * f2 < 0)
  32. x1 = x2;
  33. else
  34. x0 = x2;
  35.  
  36. iter++;
  37. }
  38.  
  39. System.out.println("\nApproximate root = " + (x0 + x1) / 2);
  40. }
  41. }
  42.  
Success #stdin #stdout 0.21s 58336KB
stdin
Standard input is empty
stdout
Enter the value of x0: -1
Enter the value of x1:  2

Iteration   x0		  x1		  x2		   f0		   f1		   f2
--------------------------------------------------------------------------------
1          -1.000000  2.000000  0.500000  -6.000000  21.000000  0.750000
2          -1.000000  0.500000  -0.250000  -6.000000  0.750000  -1.781250
3          -0.250000  0.500000  0.125000  -1.781250  0.750000  -0.621094
4          0.125000  0.500000  0.312500  -0.621094  0.750000  -0.001465
5          0.312500  0.500000  0.406250  -0.001465  0.750000  0.352844
6          0.312500  0.406250  0.359375  -0.001465  0.352844  0.170952
7          0.312500  0.359375  0.335938  -0.001465  0.170952  0.083636
8          0.312500  0.335938  0.324219  -0.001465  0.083636  0.040819
9          0.312500  0.324219  0.318359  -0.001465  0.040819  0.019611
10         0.312500  0.318359  0.315430  -0.001465  0.019611  0.009057
11         0.312500  0.315430  0.313965  -0.001465  0.009057  0.003792
12         0.312500  0.313965  0.313232  -0.001465  0.003792  0.001163
13         0.312500  0.313232  0.312866  -0.001465  0.001163  -0.000151
14         0.312866  0.313232  0.313049  -0.000151  0.001163  0.000506
15         0.312866  0.313049  0.312958  -0.000151  0.000506  0.000177
16         0.312866  0.312958  0.312912  -0.000151  0.000177  0.000013
17         0.312866  0.312912  0.312889  -0.000151  0.000013  -0.000069
18         0.312889  0.312912  0.312901  -0.000069  0.000013  -0.000028
19         0.312901  0.312912  0.312906  -0.000028  0.000013  -0.000008
20         0.312906  0.312912  0.312909  -0.000008  0.000013  0.000003
21         0.312906  0.312909  0.312908  -0.000008  0.000003  -0.000003
22         0.312908  0.312909  0.312908  -0.000003  0.000003  0.000000

Approximate root = 0.3129080533981323