正常的Linest很简单,但我不知道如何将" b设置为等于0并且调整m值以适合y = mx。"
static class Program
{
static void Main(string[] args)
{
var yValues = new double[] { 1, 9, 5, 7 };
var xValues = new double[] { 0, 4, 2, 3 };
var noConst = Linest(yValues, xValues);
Console.WriteLine("m = {0}, b = {1}", noConst.Slope, noConst.Intercept);
}
public static LineSpec Linest(IList<double> yValues, IList<double> xValues)
{
var yAvg = yValues.Sum() / yValues.Count;
var xAvg = xValues.Sum() / xValues.Count;
double upperSum = 0;
double lowerSum = 0;
for (var i = 0; i < yValues.Count; i++)
{
upperSum += (xValues[i] - xAvg) * (yValues[i] - yAvg);
lowerSum += (xValues[i] - xAvg) * (xValues[i] - xAvg);
}
var m = upperSum / lowerSum;
var b = yAvg - m * xAvg;
return new LineSpec() { Slope = m, Intercept = b };
}
}
struct LineSpec
{
public double Slope { get; set; }
public double Intercept { get; set; }
}
答案 0 :(得分:-1)
这是一个数学问题,而不是编码问题。 Use linear regression without the intercept term.
public static LineSpec LinestConst(IList<double> yValues, IList<double> xValues)
{
var yAvg = yValues.Sum() / yValues.Count;
var xAvg = xValues.Sum() / xValues.Count;
double upperSum = 0;
double lowerSum = 0;
for (var i = 0; i < yValues.Count; i++)
{
upperSum += (xValues[i] * yValues[i] );
lowerSum += (xValues[i] * xValues[i] );
}
var m = upperSum / lowerSum;
var b = 0;
return new LineSpec() { Slope = m, Intercept = b };
}