牛顿插值法求近似值

牛顿插值法求近似值_第1张图片牛顿插值法求近似值_第2张图片
牛顿插值法求近似值_第3张图片

import java.util.Scanner;

public class Newton_interpolation {
    static int num;//x和f(x)数量
    final static int MAXN = 20;
    static double b[][] = new double[MAXN][MAXN];//记录f(x)$差商
    static double a[] = new double[MAXN];//记录x
    static double x;//待求值对应的x值
    static double y=0;//保存估计值

    static void scanf() {//输入x&f(x)
        Scanner scanner = new Scanner(System.in);
        for (int i = 0; i < num; i++) {

            a[i] = scanner.nextDouble();
            b[i][0] = scanner.nextDouble();
        }
    }

    static void deal() {//插值
        for (int i = 1; i < num; i++) {
            for (int j = i; j < num; j++) {
                if (i == 1) {
                    b[j][i] = (b[j][i - 1] - b[j - 1][i - 1]) / (a[j] - a[j - 1]);
                } else {
                    b[j][i] = (b[j][i - 1] - b[j - 1][i - 1]) / (a[j] - a[j - i]);
                }
            }

        }
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("输入共有几对x和f(x):");
        num = sc.nextInt();

        System.out.println("依次输入x&f(x):");
        scanf();
        deal();
        print();

        System.out.println("输入待求近似值的x:");
        x = sc.nextDouble();
        calculate();
        System.out.println("近似值为:"+y);
    }
    static  void calculate(){
        y+=b[0][0];
        for (int i = 1; i < num; i++) {

            double temp=1;
            for (int j = 0; j < i; j++) {
                temp*=(x-a[j]);
            }
            temp*=b[i][i];
            y+=temp;
        }
    }
    static void print() {//打印插值多项式

        System.out.println("牛顿插值多项式为:N(x)="+b[0][0] + "+");
        for (int i = 1; i < num; i++) {
            System.out.print(Math.abs(b[i][i]) + "*");
            for (int j = 0; j < i; j++) {
                if (a[j] > 0) {
                    System.out.print("(" + "x-" + a[j] + ")");
                } else {
                    System.out.print("(" + "x+" + Math.abs(a[j]) + ")");
                }
            }
            if (i != (num - 1)) if (b[i + 1][i + 1] > 0) System.out.println("+");
            else System.out.println("-");
        }
        System.out.println();
    }
}

牛顿插值法求近似值_第4张图片

你可能感兴趣的:(数值计算方法)