最小二乘法拟合三角函数C语言
时间: 2023-10-17 15:06:49 浏览: 120
可以使用最小二乘法来拟合三角函数。以下是一个使用C语言实现最小二乘法拟合三角函数的示例代码:
```c
#include <stdio.h>
#include <math.h>
#define N 10 // 数据点个数
double func(double x) {
return sin(x); // 以sin函数为例
}
void leastSquaresFit(double x[], double y[], int n, double *a, double *b) {
double sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
// 计算各个累加和
for (int i = 0; i < n; i++) {
sumX += x[i];
sumY += y[i];
sumXY += x[i] * y[i];
sumX2 += x[i] * x[i];
}
// 计算拟合直线的系数
double denominator = n * sumX2 - sumX * sumX;
if (denominator == 0) {
printf("Error: denominator is zero!");
return;
}
*a = (n * sumXY - sumX * sumY) / denominator;
*b = (sumX2 * sumY - sumX * sumXY) / denominator;
}
int main() {
// 输入数据点的x和y值
double x[N] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
double y[N] = {0, 0.8415, 0.9093, 0.1411, -0.7568, -0.9589, -0.2794, 0.656, 0.989, 0.4121};
// 计算拟合直线的系数
double a, b;
leastSquaresFit(x, y, N, &a, &b);
printf("拟合直线的方程: y = %f * x + %f\n", a, b);
// 输出拟合结果
printf("实际值\t\t预测值\n");
for (int i = 0; i < N; i++) {
printf("%f\t%f\n", y[i], a * x[i] + b);
}
return 0;
}
```
阅读全文