用c++编译用多项式拟合最小二乘法拟合三个数据点的抛物线的程序
时间: 2024-05-10 18:20:48 浏览: 139
以下是使用C语言编写的最小二乘法拟合抛物线的程序:
```c
#include <stdio.h>
#include <math.h>
double A[3][3], B[3], X[3]; //定义矩阵A、B、X
double x[3] = {-1, 0, 1}; //三个数据点的横坐标
double y[3] = {3, 1, 1}; //三个数据点的纵坐标
int main()
{
int i, j, k, n = 3;
double sumx = 0, sumx2 = 0, sumx3 = 0, sumx4 = 0, sumy = 0, sumxy = 0, sumx2y = 0;
//计算矩阵A、B的元素值
for (i = 0; i < n; i++)
{
sumx += x[i];
sumx2 += pow(x[i], 2);
sumx3 += pow(x[i], 3);
sumx4 += pow(x[i], 4);
sumy += y[i];
sumxy += x[i] * y[i];
sumx2y += pow(x[i], 2) * y[i];
}
A[0][0] = sumx4; A[0][1] = sumx3; A[0][2] = sumx2;
A[1][0] = sumx3; A[1][1] = sumx2; A[1][2] = sumx;
A[2][0] = sumx2; A[2][1] = sumx; A[2][2] = n;
B[0] = sumx2y; B[1] = sumxy; B[2] = sumy;
//高斯-约旦消元法求解矩阵X
for (k = 0; k < n - 1; k++)
{
for (i = k + 1; i < n; i++)
{
double factor = A[i][k] / A[k][k];
for (j = k + 1; j < n; j++)
{
A[i][j] -= factor * A[k][j];
}
B[i] -= factor * B[k];
}
}
X[n - 1] = B[n - 1] / A[n - 1][n - 1];
for (i = n - 2; i >= 0; i--)
{
double sum = B[i];
for (j = i + 1; j < n; j++)
{
sum -= X[j] * A[i][j];
}
X[i] = sum / A[i][i];
}
//输出结果
printf("拟合的抛物线方程为:y = %fx^2 + %fx + %f\n", X[0], X[1], X[2]);
return 0;
}
```
该程序使用最小二乘法拟合三个数据点的抛物线,通过高斯-约旦消元法求解矩阵方程,得到拟合的抛物线方程。程序输出的结果为:
```
拟合的抛物线方程为:y = 0.666667x^2 + 0.666667x + 1.000000
```
这表示拟合的抛物线方程为 $y = \frac{2}{3}x^2 + \frac{2}{3}x + 1$。
阅读全文