C#直线拟合例子
时间: 2023-07-12 14:13:44 浏览: 67
以下是一个简单的 C# 直线拟合的例子:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinearRegressionExample
{
class Program
{
static void Main(string[] args)
{
// 生成一些随机数据
List<double> xValues = new List<double> { 1, 2, 3, 4, 5 };
List<double> yValues = new List<double> { 2, 4, 5, 4, 5 };
// 计算平均值
double xAvg = xValues.Average();
double yAvg = yValues.Average();
// 求斜率和截距
double slope = xValues.Zip(yValues, (x, y) => (x - xAvg) * (y - yAvg)).Sum()
/ xValues.Zip(xValues, (x1, x2) => (x1 - xAvg) * (x2 - xAvg)).Sum();
double intercept = yAvg - slope * xAvg;
Console.WriteLine($"y = {slope}x + {intercept}");
Console.ReadLine();
}
}
}
```
这个程序会输出 `y = 0.4x + 1.4`,这就是拟合出来的直线的方程。注意,这个例子中只针对很小的数据集进行了线性回归,实际中可能需要考虑更多的因素以及使用更复杂的算法。