计算方法插值与拟合

本文最后更新于:2024年3月18日 凌晨

计算方法插值与拟合

拉格朗日插值法

拉格朗日多项式

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class 拉格朗日插值 {
public static double Lagrange(double[][] Function, double x) {
double[] l = new double[Function.length];// 拉格朗日基函数。
double p = 0;// 计算x点处y的取值。
for (int i = 0; i < Function.length; i++) {//
l[i] = 1;
for (int j = 0; j < Function.length; j++) {
if (j != i) {
l[i] *= (x - Function[j][0]) / (Function[i][0] - Function[j][0]);// 将x带入。
}
}
p += Function[i][1] * l[i];// 拉格朗日基函数乘以y之和。
}
System.out.println(Arrays.toString(l));
return p;
}

public static void main(String[] args) {
double x = 12;// 自变量x
double[][] Function = {{10, 1}, {15, 1.1761}, {20, 1.3010}};
double p = Lagrange(Function, x);
System.out.println("y在x = " + x + "处的值为: " + p);
}
}

例题

牛顿插值法

差商

算法

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class 牛顿插值 {
public static double Newton(double[][] Function, double x) {
double N = 0;// 计算x点处y的取值。
double n;// 暂存变量。
double[][] DifferenceQuotientTable = new double[Function.length][Function.length + 1];
for (int i = 0; i < Function.length; i++) {// 初始化差商表。
DifferenceQuotientTable[i][0] = Function[i][0];
DifferenceQuotientTable[i][1] = Function[i][1];

}
for (int i = 2; i < DifferenceQuotientTable[0].length; i++) {// 求出差商表。
for (int j = i - 1; j < Function.length; j++) {
DifferenceQuotientTable[j][i] = (DifferenceQuotientTable[j][i - 1] - DifferenceQuotientTable[j - 1][i - 1]) / (DifferenceQuotientTable[j][0] - DifferenceQuotientTable[j - i + 1][0]);
}
}
for (int i = 0; i < DifferenceQuotientTable.length; i++) {// 将差商表对角线上的数值带入牛顿插值公式。
n = DifferenceQuotientTable[i][i + 1];
for (int j = 0; j < i; j++) {
n *= (x - DifferenceQuotientTable[j][0]);
}
N += n;
}
System.out.println(Arrays.deepToString(DifferenceQuotientTable));// 打印差商表。
return N;
}

public static void main(String[] args) {
double x = 7;// 自变量x
double[][] Function = {{1, 1}, {4, 2}, {9, 3}};
double N = Newton(Function, x);
System.out.println("y在x = " + x + "处的值为: " + N);
}
}

例题

分段低次插值法

算法


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!