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