最小二乘法拟合圆c++
时间: 2023-06-18 20:07:27 浏览: 252
最小二乘法拟合圆是一种常见的数据拟合方法,可以用于圆形数据的拟合。下面是一个用 C++ 实现最小二乘法拟合圆的示例代码:
```c++
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
// 定义一个二维向量点结构体
struct Point {
double x;
double y;
};
// 最小二乘法拟合圆函数
bool leastSquareCircle(const vector<Point>& points, Point& center, double& radius) {
int n = points.size();
// 计算x、y、x^2、y^2、x*y的和
double sum_x = 0.0;
double sum_y = 0.0;
double sum_x2 = 0.0;
double sum_y2 = 0.0;
double sum_xy = 0.0;
for (int i = 0; i < n; i++) {
sum_x += points[i].x;
sum_y += points[i].y;
sum_x2 += points[i].x * points[i].x;
sum_y2 += points[i].y * points[i].y;
sum_xy += points[i].x * points[i].y;
}
// 计算a、b、c的值
double a = n * sum_x2 - sum_x * sum_x;
double b = n * sum_xy - sum_x * sum_y;
double c = n * sum_y2 - sum_y * sum_y;
// 判断是否为圆
double delta = a * c - b * b;
if (delta <= 0) {
return false;
}
// 计算圆心坐标和半径
center.x = (c * sum_x - b * sum_y) / delta / 2.0;
center.y = (a * sum_y - b * sum_x) / delta / 2.0;
radius = sqrt((a + c) / 2.0 + sqrt(delta) / 2.0);
return true;
}
int main() {
// 构造测试数据
vector<Point> points;
points.push_back(Point{1, 2});
points.push_back(Point{3, 4});
points.push_back(Point{5, 6});
points.push_back(Point{7, 8});
// 进行拟合
Point center;
double radius;
bool ret = leastSquareCircle(points, center, radius);
if (ret) {
cout << "圆心坐标为(" << center.x << ", " << center.y << ")" << endl;
cout << "半径为" << radius << endl;
} else {
cout << "无法拟合圆" << endl;
}
return 0;
}
```
上述代码实现了一个最小二乘法拟合圆的函数,接受一个二维向量点的数组作为输入,并返回拟合出的圆的圆心和半径。在主函数中构造了一个测试数据,并调用最小二乘法拟合圆函数进行拟合,输出拟合结果。
阅读全文