fork download
  1. class NewtonRaphsonHorner {
  2.  
  3. // Evaluate f(x) using Horner's rule
  4. static double f(double[] coeffs, double x) { //ID=240242058 (MD Sakib)
  5.  
  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. // Evaluate derivative f'(x) using Horner's rule
  14. static double fPrime(double[] coeffs, double x) {
  15. int n = coeffs.length - 1;
  16. double result = coeffs[0] * n;
  17. for (int i = 1; i < n; i++) {
  18. result = result * x + coeffs[i] * (n - i);
  19. }
  20. return result;
  21. }
  22.  
  23. public static void main(String[] args) {
  24. // Example polynomial: f(x) = 2x^3 + 3x - 1 => coefficients {2,0,3,-1}
  25. double[] coeffs = {2, 0, 3, -1};
  26. double x0 = 0.5; // initial guess
  27. double E = 1e-8;
  28. double error = 1, x1 = x0;
  29. int i = 0;
  30.  
  31. System.out.printf("%-5s %-12s %-12s %-12s %-12s\n", "Iter", "x", "f(x)", "Error", "%Error");
  32.  
  33. while (error >= E) {
  34. double fx = f(coeffs, x0);
  35. double fpx = fPrime(coeffs, x0);
  36. x1 = x0 - fx / fpx;
  37. error = Math.abs(x1 - x0);
  38. double perError = (x0 == 0) ? 0 : (error / Math.abs(x1)) * 100;
  39.  
  40. i++;
  41. System.out.printf("%-5d %-12.8f %-12.8f %-12.8f %-12.8f\n", i, x1, fx, error, perError);
  42.  
  43. x0 = x1;
  44. }
  45.  
  46. System.out.println("\nApproximate root = " + x1);
  47. System.out.println("Total iterations = " + i);
  48. }
  49. }
  50.  
Success #stdin #stdout 0.17s 56404KB
stdin
Standard input is empty
stdout
Iter  x            f(x)         Error        %Error      
1     0.33333333   0.75000000   0.16666667   50.00000000 
2     0.31313131   0.07407407   0.02020202   6.45161290  
3     0.31290844   0.00079975   0.00022288   0.07122775  
4     0.31290841   0.00000009   0.00000003   0.00000831  
5     0.31290841   0.00000000   0.00000000   0.00000000  

Approximate root = 0.3129084094792334
Total iterations = 5