fork download
  1. import java.util.Scanner;
  2.  
  3. class SecantHorner {
  4. //id=240242058 "(sakib)"
  5. static double f(double[] coeffs, double x) {
  6. double result = coeffs[0];
  7. for (int i = 1; i < coeffs.length; i++) {
  8. result = result * x + coeffs[i];
  9. }
  10. return result;
  11. }
  12.  
  13. public static void main(String[] args) {
  14. Scanner sc = new Scanner(System.in);
  15.  
  16. double[] coeffs = {1, 0, 0, -4}; // f(x) = x^3 - 4
  17.  
  18. System.out.print("Enter first initial guess x1: ");
  19. double x1 = sc.nextDouble();
  20. System.out.print("Enter second initial guess x2: ");
  21. double x2 = sc.nextDouble();
  22. System.out.print("Enter tolerance: ");
  23. double tol = sc.nextDouble();
  24.  
  25. double f1 = f(coeffs, x1);
  26. double f2 = f(coeffs, x2);
  27. double x3 = 0, prev = x2, error;
  28. int i = 0;
  29.  
  30. System.out.printf("%-5s %-12s %-12s %-12s %-12s\n", "Iter", "x3", "f(x3)", "Error", "%Error");
  31.  
  32. while (true) {
  33. x3 = (f2*x1 - f1*x2) / (f2 - f1);
  34. double f3 = f(coeffs, x3);
  35. i++;
  36.  
  37. error = Math.abs(x3 - prev);
  38. double perError = (x3 != 0) ? (error / Math.abs(x3)) * 100 : 0;
  39.  
  40. System.out.printf("%-5d %-12.8f %-12.8f %-12.8f %-12.8f\n", i, x3, f3, error, perError);
  41.  
  42. if (Math.abs(f3) < tol) break;
  43.  
  44. x1 = x2; f1 = f2;
  45. x2 = x3; f2 = f3;
  46. prev = x3;
  47. }
  48.  
  49. System.out.println("\nApproximate root = " + x3);
  50. System.out.println("Total iterations = " + i);
  51. }
  52. }
  53.  
Success #stdin #stdout 0.22s 61320KB
stdin
1
3
1e-8
stdout
Enter first initial guess x1: Enter second initial guess x2: Enter tolerance: Iter  x3           f(x3)        Error        %Error      
1     1.23076923   -2.13563951  1.76923077   143.75000000
2     1.38109121   -1.36568876  0.15032198   10.88429062 
3     1.64772260   0.47355002   0.26663139   16.18181302 
4     1.57907284   -0.06262759  0.06864976   4.34747263  
5     1.58709140   -0.00234039  0.00801855   0.50523580  
6     1.58740268   0.00001233   0.00031129   0.01960975  
7     1.58740105   -0.00000000  0.00000163   0.00010273  

Approximate root = 1.5874010516500963
Total iterations = 7