利用了拉格朗日插值法进行插值,代码中利用了读文件的方式,第一行为个数,第二行为X的值,第三行为Y的值,中间用空格隔开,代码如下:
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; public class LagrangeInterpolation { private int n; private double x[]; private double y[]; private double l[]; private double sum; public LagrangeInterpolation(int n,double[] x, double[] y) { super(); this.n = n; this.x = x; this.y = y; l = new double[n]; } public LagrangeInterpolation(String path) { super(); readFile(path); } double cal(double xx){ for(int i = 0;i<n;i++){ double ll = 1; for(int j = 0;j<n;j++){ if(i!=j){ ll *= ((xx-x[j])/(x[i]-x[j])); } } l[i] = ll*y[i]; } double sum = 0; for(int i = 0;i<n;i++){ sum += l[i]; } return sum; } void readFile(String fileName){ File file = new File(fileName); BufferedReader reader = null; try { System.out.println("以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); String tempString = null; // 一次读入一行,直到读入null为文件结束 if((tempString = reader.readLine())!=null){ n = Integer.parseInt(tempString); } x = new double[n]; y = new double[n]; l = new double[n]; if((tempString = reader.readLine())!=null){ String[] sourceStrArray = tempString.split(" "); for(int i=0;i<n;i++){ x[i] = Double.parseDouble(sourceStrArray[i]); } } if((tempString = reader.readLine())!=null){ String[] sourceStrArray = tempString.split(" "); for(int i=0;i<n;i++){ y[i] = Double.parseDouble(sourceStrArray[i]); } } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } public static void main(String [] args){ System.out.println("请输入文件 路径"); Scanner scanner = new Scanner(System.in); String path = scanner.next(); LagrangeInterpolation la = new LagrangeInterpolation(path); System.out.println("请输入要求的x值"); double xx = scanner.nextDouble(); System.out.println(la.cal(xx)); scanner.close(); } }