一组点拟合直线 C++
时间: 2023-07-29 14:14:43 浏览: 54
可以使用最小二乘法来拟合一组点到直线上,以下是C++代码示例:
```c++
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
struct Point {
double x, y;
};
struct Line {
double k, b;
};
Line fitLine(vector<Point> points) {
int n = points.size();
double sumx = 0, sumy = 0, sumxy = 0, sumxx = 0;
for (int i = 0; i < n; i++) {
sumx += points[i].x;
sumy += points[i].y;
sumxy += points[i].x * points[i].y;
sumxx += points[i].x * points[i].x;
}
double xmean = sumx / n;
double ymean = sumy / n;
double xxmean = sumxx / n;
double xymeans = sumxy / n;
double k = (xymeans - xmean * ymean) / (xxmean - xmean * xmean);
double b = ymean - k * xmean;
return {k, b};
}
int main() {
vector<Point> points = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
Line line = fitLine(points);
cout << "The fitted line is: y = " << line.k << "x + " << line.b << endl;
return 0;
}
```
该代码使用了最小二乘法来拟合一组点到直线上,其中 `fitLine` 函数接受一个 `vector` 类型的点集作为参数,返回一个 `Line` 结构体,包含拟合出的直线的斜率和截距。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)