使用csharp 实现最小二乘法法拟合椭圆的代码
时间: 2023-09-01 08:13:01 浏览: 344
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
namespace EllipseFitting
{
class Program
{
static void Main(string[] args)
{
List<double> x = new List<double>() { 1, 2, 3, 4, 5 };
List<double> y = new List<double>() { 2, 3, 4, 5, 6 };
Tuple<double, double, double> ellipse = FitEllipse(x, y);
Console.WriteLine($"Semi-major axis: {ellipse.Item1}");
Console.WriteLine($"Semi-minor axis: {ellipse.Item2}");
Console.WriteLine($"Orientation angle: {ellipse.Item3}");
}
static Tuple<double, double, double> FitEllipse(List<double> x, List<double> y)
{
// Compute the centroid of the points
double xMean = x.Average();
double yMean = y.Average();
// Compute the covariance matrix of the points
double covXX = x.Select(xi => (xi - xMean) * (xi - xMean)).Sum() / x.Count;
double covYY = y.Select(yi => (yi - yMean) * (yi - yMean)).Sum() / y.Count;
double covXY = x.Zip(y, (xi, yi) => (xi - xMean) * (yi - yMean)).Sum() / x.Count;
double covYX = covXY;
// Compute the eigenvalues and eigenvectors of the covariance matrix
double lambda1 = (covXX + covYY + Math.Sqrt((covXX - covYY) * (covXX - covYY) + 4 * covXY * covYX)) / 2;
double lambda2 = (covXX + covYY - Math.Sqrt((covXX - covYY) * (covXX - covYY) + 4 * covXY * covYX)) / 2;
double angle = Math.Atan2(covXY, lambda1 - covXX);
// Compute the semi-major and semi-minor axes
double a = Math.Sqrt(lambda1);
double b = Math.Sqrt(lambda2);
return Tuple.Create(a, b, angle);
}
}
}
```
阅读全文