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

Iteration   x1		 x2		 x3		 f(x1)		 f(x2)
-------------
1          4.000000  2.000000  3.222222  14.000000  -22.000000
2          2.000000  3.222222  4.031927  -22.000000  -8.766804
3          3.222222  4.031927  3.518089  -8.766804  15.225491
4          4.031927  3.518089  3.567991  15.225491  -1.637678
5          3.518089  3.567991  3.577296  -1.637678  -0.257395
6          3.567991  3.577296  3.577089  -0.257395  0.005875
7          3.577296  3.577089  3.577089  0.005875  -0.000020

Approximate root = 3.5770894450806314