fork download
  1. class Main {
  2. public static void main(String[] args) {
  3. double[] x = {0, 1, 2, 3};
  4. double[] y = {1, 2, 4, 8};
  5. double x0 = 1.5;
  6. double result = newtonForward(x, y, x0);
  7. System.out.printf("Interpolated value at x = %.2f is y = %.3f\n", x0, result);
  8. }
  9. static double newtonForward(double[] x, double[] y, double x0) {
  10. int n = x.length;
  11. double[][] diff = new double[n][n];
  12.  
  13. for (int i = 0; i < n; i++)
  14. diff[i][0] = y[i];
  15.  
  16. for (int j = 1; j < n; j++)
  17. for (int i = 0; i < n - j; i++)
  18. diff[i][j] = diff[i + 1][j - 1] - diff[i][j - 1];
  19.  
  20. double h = x[1] - x[0];
  21. double u = (x0 - x[0]) / h;
  22. double sum = diff[0][0];
  23. double term = 1;
  24. for (int i = 1; i < n; i++) {
  25. term *= (u - (i - 1));
  26. sum += term * diff[0][i] / fact(i);
  27. }
  28. return sum; }
  29. static int fact(int n) {
  30. int f = 1;
  31. for (int i = 1; i <= n; i++) f *= i;
  32. return f;
  33. }
  34. }
  35.  
Success #stdin #stdout 0.15s 56172KB
stdin
Standard input is empty
stdout
Interpolated value at x = 1.50 is y = 2.813