多项式最小二乘插值法 c++
时间: 2023-09-04 07:15:56 浏览: 184
这是一个多项式最小二乘插值法的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_N 100
#define MAX_M 10
double x[MAX_N], y[MAX_N];
double a[MAX_M], b[MAX_M], c[MAX_M];
int main()
{
int n, m, i, j, k;
double sum, t;
printf("Please input the number of points n (1 <= n <= %d): ", MAX_N);
scanf("%d", &n);
printf("Please input the points x and y:\n");
for (i = 0; i < n; i++)
scanf("%lf%lf", &x[i], &y[i]);
printf("Please input the degree of the polynomial m (1 <= m <= %d): ", MAX_M - 1);
scanf("%d", &m);
for (i = 0; i <= m; i++) {
sum = 0.0;
for (j = 0; j < n; j++)
sum += pow(x[j], i) * y[j];
a[i] = sum;
for (j = 0; j <= m; j++) {
sum = 0.0;
for (k = 0; k < n; k++)
sum += pow(x[k], i + j);
b[i * (m + 1) + j] = sum;
}
}
for (i = 0; i <= m; i++) {
for (j = i; j <= m; j++) {
sum = 0.0;
for (k = 0; k < n; k++)
sum += pow(x[k], i + j);
c[i * (m + 1) + j] = sum;
c[j * (m + 1) + i] = sum;
}
}
for (i = 0; i <= m; i++) {
for (j = i + 1; j <= m; j++) {
t = c[j * (m + 1) + i] / c[i * (m + 1) + i];
for (k = i; k <= m + 1; k++)
c[j * (m + 1) + k] -= t * c[i * (m + 1) + k];
b[j * (m + 1) + m + 1] -= t * b[i * (m + 1) + m + 1];
}
}
for (i = m; i >= 0; i--) {
sum = 0.0;
for (j = i + 1; j <= m; j++)
sum += a[j] * c[i * (m + 1) + j];
a[i] = (b[i * (m + 1) + m + 1] - sum) / c[i * (m + 1) + i];
}
printf("The coefficients of the polynomial are:\n");
for (i = 0; i <= m; i++)
printf("a%d = %lf\n", i, a[i]);
return 0;
}
```
代码中使用了一个二维数组c来存储矩阵,并使用了高斯-约旦消元法求解线性方程组。输入时需要先输入点的个数和坐标,再输入多项式的阶数。输出时将多项式的系数输出即可。
阅读全文