Calculating the coefficients:
static public double[] newtonPolCoef(double[] x, double[] y) {
int n = x.length - 1;
double dd[][] = new double[n][];
double[] a = new double[n + 1];
for (int i = 0; i < n; i++) {
dd[i] = new double[n - i];
}
for (int j = 0; j < n; j++) {
dd[0][j] = (y[j + 1] - y[j]) / (x[j + 1] - x[j]);
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < n - i; j++) {
dd[i][j] = (dd[i - 1][j + 1] - dd[i - 1][j]) / (x[j + i + 1] - x[j]);
}
}
a[0] = y[0];
for (int i = 1; i < n + 1; i++) {
a[i] = dd[i - 1][0];
}
return a;
}Approximating the value based on the coefficients:
static public double newtonPolVal(double[] coef, double[] x, double val) {
double r = coef[0];
double mul = 1;
for (int i = 1; i < x.length; i++) {
mul *= (val - x[i - 1]);
r += coef[i] * mul;
}
return r;
}This is part of the Function Approximations project.
No comments:
Post a Comment