public class Test {
static double[][] format;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.print("输入插入总点数:");
int n=in.nextInt();//插入点总数
double[][] xy=new double[2][n];//二维数组来存储x和y
for(int j=0;j<n;j++) {
System.out.print("输入第"+(j+1)+"个点的x:");
xy[0][j]=in.nextDouble();//第0行放各点的x值
System.out.print("输入第"+(j+1)+"个点的y:");
xy[1][j]=in.nextDouble();//第1行放各点的y值
}
creatformat(xy, n);
System.out.println("输入计算几个点:");
int v=in.nextInt();//所求点的总数
for(int i=0;i<v;i++) {
System.out.println("输入x= ");
double x=in.nextDouble();
System.out.print("f("+x+")≈"+"Nn("+x+")"+"=");
System.out.printf("%.5f", Nn(xy, n, x));
System.out.println();
}
}
static void creatformat(double[][] xy,int n) {
format=new double[n-1][n-1];
for(int i=0;i<n-1;i++) {
for(int j=0;j<n-1-i;j++) {
if(i==0) {
format[i][j]=(xy[1][j]-xy[1][j+1])/(xy[0][j]-xy[0][j+1]);
}
else{
format[i][j]=(format[i-1][j]-format[i-1][j+1])/(xy[0][j]-xy[0][j+i+1]);
}
}
}
}
static double Nn(double[][] xy,int n,double x) {
//牛顿插值公式
double sum=xy[1][0];//求和的初始值为f(X0)
for(int i=0;i<n-1;i++) {
double c=1;
for(int j=0;j<i+1;j++) {
c=(x-xy[0][j])*c;
}
sum=sum+format[i][0]*c;
}
return sum;
}
}
运行结果得: