public class LagrangeInterpolation {
public static void main(String... args) {
int n_points = 4;
double p = 20.; // x-value for f(p)
double ans=0.;
double L_bunshi1;
double L_bunbo1;
double L_bunshi2;
double L_bunbo2;
double lj;
double[] x = new double[n_points];
double[] f = new double[n_points];
//double[] l = new double[n_points];
x[0]=19.9466;
f[0]=2.712;
x[1]=19.9907;
f[1]=2.714;
x[2]=20.0349;
f[2]=2.716;
x[3]=20.0793;
f[3]=2.718;
for (int j = 0; j < n_points; j++) {
L_bunshi1=1.;
L_bunbo1=1.;
L_bunshi2=1.;
L_bunbo2=1.;
for (int jj = 0; jj <= j - 1; jj++) {
L_bunshi1=L_bunshi1*(p-x[jj]);
L_bunbo1=L_bunbo1*(x[j]-x[jj]);
}
for (int jj = j+1; jj < n_points; jj++) {
L_bunshi2=L_bunshi2*(p-x[jj]);
L_bunbo2=L_bunbo2*(x[j]-x[jj]);
}
lj=(L_bunshi1*L_bunshi2)/(L_bunbo1*L_bunbo2);
ans=ans+f[j]*lj;
}
System.out.printf("x = %8.6f, f(x) = %11.9f" , p,ans); //True f(20) = 2.7144176
}
}