代码C语言 数组X{1,2,3,4,5,6,7,8,9},Y{2,3,4,5,6,7,8,9,10} 用移动最小二乘法做曲线拟合 当X=2.5和6.8时,求Y的值
时间: 2024-03-05 19:45:04 浏览: 63
以下是使用移动最小二乘法进行曲线拟合的C语言代码:
```c
#include <stdio.h>
// 定义数组X和Y
int X[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int Y[] = {2, 3, 4, 5, 6, 7, 8, 9, 10};
// 定义移动最小二乘法函数
float moving_least_squares(int n, int m, float x, int k) {
float sum_x = 0, sum_y = 0, sum_xy = 0, sum_xx = 0; float a, b;
// 计算相关的和
for (int i = k; i < k + m; i++) {
sum_x += X[i];
sum_y += Y[i];
sum_xy += X[i] * Y[i];
sum_xx += X[i] * X[i];
}
// 计算斜率和截距
a = (m * sum_xy - sum_x * sum_y) / (m * sum_xx - sum_x * sum_x);
b = (sum_y - a * sum_x) / m;
// 计算预测值
float y = a * x + b;
return y;
}
int main() {
// 定义需要预测的X值
float x1 = 2.5;
float x2 = 6.8;
// 定义移动窗口的大小
int m = 3;
// 定义移动窗口的起始位置
int k1 = 0;
int k2 = 4;
// 使用移动最小二乘法进行曲线拟合并输出结果
float y1 = moving_least_squares(sizeof(X) / sizeof(X[0]), m, x1, k1);
float y2 = moving_least_squares(sizeof(X) / sizeof(X[0]), m, x2, k2);
printf("当X=%.1f时,Y的值为:%.2f\n", x1, y1);
printf("当X=%.1f时,Y的值为:%.2f\n", x2, y2);
return 0;
}
```
运行以上代码,将会得到以下输出结果:
```
当X=2.5时,Y的值为:3.50
当X=6.8时,Y的值为:7.80
```
阅读全文