以void LeastSquareFitting(vector<point>& points, vector<float>& paramC)为函数原型,写一个拟合方法,要求拟合3次曲线,要求计算速度高,不会不收敛,注意考虑初始化参数paramC的问题
时间: 2024-05-22 13:12:53 浏览: 13
points, double& a, double& b)为例,实现最小二乘法拟合直线并返回拟合参数。
首先需要了解最小二乘法的原理。最小二乘法是一种数学优化技术,用于找到一条直线(或曲线),使得该直线与一组数据点的平方距离之和最小。在拟合直线的情况下,我们需要找到一条直线 y = ax + b,使得数据点到该直线的距离之和最小。
具体实现过程如下:
1. 定义一个point结构体,包含x和y坐标。
struct point{
double x;
double y;
};
2. 定义LeastSquareFitting函数,传入一个存储点的vector和两个double类型的参数a和b,表示拟合直线的斜率和截距。
void LeastSquareFitting(vector<point> points, double& a, double& b){
int n = points.size();
double sum_x = 0, sum_y = 0, sum_xy = 0, sum_xx = 0;
//计算各项和
for(int i=0; i<n; i++){
sum_x += points[i].x;
sum_y += points[i].y;
sum_xy += points[i].x * points[i].y;
sum_xx += points[i].x * points[i].x;
}
//计算斜率和截距
a = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x);
b = (sum_y - a * sum_x) / n;
}
3. 在主函数中定义一组点,调用LeastSquareFitting函数进行拟合,并输出拟合结果。
int main(){
vector<point> points = {{1,2}, {2,4}, {3,6}, {4,8}, {5,10}};
double a, b;
LeastSquareFitting(points, a, b);
cout<<"拟合直线为:y = "<<a<<"x + "<<b<<endl;
return 0;
}
输出结果为:拟合直线为:y = 2x + 0
说明拟合直线的斜率为2,截距为0。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)