c语言 多项式拟合函数
时间: 2024-01-20 22:03:19 浏览: 217
多项式拟合函数polyfit之C语言的源码
4星 · 用户满意度95%
多项式拟合函数可以使用最小二乘法进行求解。以下是一个简单的 C 语言多项式拟合函数的示例代码,其中假设要拟合的多项式为二次函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void polyfit(double x[], double y[], int n, int degree, double coeff[]);
double evaluate(double x, double coeff[], int degree);
int main()
{
int n = 5; // 数据点数目
double x[] = {1.0, 2.0, 3.0, 4.0, 5.0}; // X 值
double y[] = {1.0, 4.0, 9.0, 16.0, 25.0}; // Y 值
int degree = 2; // 多项式次数
double coeff[degree + 1]; // 存储拟合系数
polyfit(x, y, n, degree, coeff);
printf("拟合的二次函数为:y = %.2fx^2 + %.2fx + %.2f\n", coeff[2], coeff[1], coeff[0]);
double x_test = 6.0; // 预测值
double y_test = evaluate(x_test, coeff, degree);
printf("当 x = %.2f 时,预测的 y 值为:%.2f\n", x_test, y_test);
return 0;
}
void polyfit(double x[], double y[], int n, int degree, double coeff[])
{
int i, j, k;
double X[2 * degree + 1];
double B[degree + 1][degree + 2];
double Y[degree + 1];
for (i = 0; i < 2 * degree + 1; i++)
{
X[i] = 0;
for (j = 0; j < n; j++)
{
X[i] = X[i] + pow(x[j], i);
}
}
for (i = 0; i <= degree; i++)
{
for (j = 0; j <= degree; j++)
{
B[i][j] = X[i + j];
}
Y[i] = 0;
for (j = 0; j < n; j++)
{
Y[i] = Y[i] + pow(x[j], i) * y[j];
}
}
int m = degree + 1;
int p = 2 * m - 1;
double A[m][m + 1];
for (i = 0; i < m; i++)
{
for (j = 0; j < m; j++)
{
A[i][j] = B[i][j];
}
A[i][p] = Y[i];
}
for (k = 0; k < m; k++)
{
for (i = 0; i < m; i++)
{
if (i != k)
{
double c = A[i][k] / A[k][k];
for (j = 0; j <= p; j++)
{
A[i][j] = A[i][j] - c * A[k][j];
}
}
}
}
for (i = 0; i < m; i++)
{
coeff[i] = A[i][p] / A[i][i];
}
}
double evaluate(double x, double coeff[], int degree)
{
double y = 0;
for (int i = 0; i <= degree; i++)
{
y = y + coeff[i] * pow(x, i);
}
return y;
}
```
代码中 `polyfit()` 函数使用最小二乘法求解多项式拟合系数,`evaluate()` 函数用于计算预测的 y 值。在主函数中,我们传入了五个数据点,拟合一个二次函数,并计算了当 x 等于 6 时的预测值。
阅读全文