牛顿插值法

利用了牛顿插值法进行插值,代码中利用了读文件的方式,第一行为个数,第二行为X的值,第三行为Y的值,中间用空格隔开,代码如下:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class NewtonInterpolation {
	private int n;
	private double chashang[][];
	public NewtonInterpolation(int n, double[] x, double[] y) {
		super();
		this.n = n;
		chashang = new double[n][n+1];
		for(int i=0;i<n;i++){
			chashang[i] = new double[n+1];
			chashang[i][0] = x[i];
			chashang[i][1] = y[i];
		}
	}
	public NewtonInterpolation(String path) {
		super();
		readFile(path);
	}
	public void calChaShang(){
		for(int i=2;i<n+1;i++){
			int k  = 0;
			for(int j = i-1;j<n;j++){
				chashang[j][i] = (chashang[j][i-1] - chashang[j-1][i-1])/(chashang[j][0]-chashang[k][0]);
				k++;
			}
		}
	}
	public  double  calResult(double xx){
		calChaShang();
		double sum  = 0.0f;
		double w = 1;
		for(int i = 0; i< n;i++){
			if(i != 0) w = w*(xx - chashang[i-1][0]);
			sum += w*chashang[i][i+1];
		}
		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);
	            }
	            chashang = new double[n][n+1];
	            if((tempString = reader.readLine())!=null){
	            	 String[] sourceStrArray = tempString.split(" ");
	                 for(int i=0;i<n;i++){
	                	 chashang[i][0] = Double.parseDouble(sourceStrArray[i]);
	                 } 
	            }
	            if((tempString = reader.readLine())!=null){
	            	 String[] sourceStrArray = tempString.split(" ");
	                 for(int i=0;i<n;i++){
	                	 chashang[i][1] = 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();
	       NewtonInterpolation newton = new NewtonInterpolation(path);  
	       System.out.println("请输入要求的x值");  
	       double xx = scanner.nextDouble();  
	       System.out.println(newton.calResult(xx));  
	       scanner.close(); 
	   }
	
}


猜你喜欢

转载自blog.csdn.net/baidu_38370610/article/details/78745739
今日推荐