本文共 1640 字,大约阅读时间需要 5 分钟。
本人是个新手,写下博客用于自我复习、自我总结。 如有错误之处,请各位大佬指出。
import java.util.Scanner;public class Interpolation{ public static void main(String args[]){ System.out.println("您想计算几次插值?"); Scanner reader = new Scanner(System.in); int n=reader.nextInt(); //n是插值的次数 double x[]=new double[n+1]; double y[]=new double[n+1]; System.out.println("请输入用于计算的坐标点:(提供的坐标数不要小于插值次数+1)"); try{ System.out.println("x:"); //输入x坐标 for(int b=0;b<=n;b++){ double x_in=reader.nextDouble(); x[b]=x_in; } System.out.println("y:"); //输入y坐标 for(int c=0;c<=n;c++){ double y_in=reader.nextDouble(); y[c]=y_in; } System.out.println("您想计算的x坐标是?"); double m=reader.nextDouble(); langrange(n,m,x,y); //调用langrange方法 newton(n,m,x,y); //调用newton方法 }catch(Exception e){ System.out.println("数据有误"); } } //实现langrange插值的方法,实行n次插值,计算输入为m时的近似值 public static void langrange(int n,double m,double x[],double y[]){ double value=0; //记录最终结果 double contain=1; //记录一个中间结果 for(int a=0;a<=n;a++){ for(int b=0;b<=n;b++){ if(b!=a){ contain=((m-x[b])/(x[a]-x[b]))*contain; //公式 } else continue; } value=value+contain*y[a]; //公式 contain=1; //每次循环结束重置contain } System.out.println(n+"次插值,langrange的y("+m+")的近似值是:"+value); } //实现newton插值的方法,实行n次插值,计算输入为m时的近似值 public static void newton(int n,double m,double x[],double y[]){ double value=0; //记录最终结果 double contain=1; //记录一个中间值 for(int a=0;a<=n;a++) { double x0[]=new double[a+1]; double y0[]=new double[a+1]; if(a==0) { value=value+y[a]; } else { for(int b=0;b
转载地址:http://cxyki.baihongyu.com/