gpt4 book ai didi

c# - 散点图 'best-fit' 线的算法

转载 作者:太空狗 更新时间:2023-10-29 18:22:44 25 4
gpt4 key购买 nike

我正在用 C# 编写一个小型应用程序,使用 MSChart 控件来绘制 X 和 Y 数据点集的散点图。其中一些可能相当大(数百个数据点)。

想问一下是否有一个“标准”算法来绘制跨点的最佳拟合线。我正在考虑将 X 数据点划分为预定义数量的集合,比如 10 或 20,并且对于每个集合取相应的 Y 值和中间 X 值的平均值,依此类推来创建线。这是正确的做法吗?

我搜索了现有线程,但它们似乎都是关于使用现有应用程序(如 Matlab)实现相同目标的。

谢谢,

最佳答案

使用线性最小二乘算法

public class XYPoint
{
public int X;
public double Y;
}

class Program
{
public static List<XYPoint> GenerateLinearBestFit(List<XYPoint> points, out double a, out double b)
{
int numPoints = points.Count;
double meanX = points.Average(point => point.X);
double meanY = points.Average(point => point.Y);

double sumXSquared = points.Sum(point => point.X * point.X);
double sumXY = points.Sum(point => point.X * point.Y);

a = (sumXY / numPoints - meanX * meanY) / (sumXSquared / numPoints - meanX * meanX);
b = (a * meanX - meanY);

double a1 = a;
double b1 = b;

return points.Select(point => new XYPoint() { X = point.X, Y = a1 * point.X - b1 }).ToList();
}

static void Main(string[] args)
{
List<XYPoint> points = new List<XYPoint>()
{
new XYPoint() {X = 1, Y = 12},
new XYPoint() {X = 2, Y = 16},
new XYPoint() {X = 3, Y = 34},
new XYPoint() {X = 4, Y = 45},
new XYPoint() {X = 5, Y = 47}
};

double a, b;

List<XYPoint> bestFit = GenerateLinearBestFit(points, out a, out b);

Console.WriteLine("y = {0:#.####}x {1:+#.####;-#.####}", a, -b);

for(int index = 0; index < points.Count; index++)
{
Console.WriteLine("X = {0}, Y = {1}, Fit = {2:#.###}", points[index].X, points[index].Y, bestFit[index].Y);
}
}
}

关于c# - 散点图 'best-fit' 线的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12946341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com