1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace AdmStat
{
// http://biblioxtrn.uqar.qc.ca/stat/Fichesstat/multivariable/quanti/regression.htm
// http://www.codeproject.com/KB/recipes/LinReg.aspx
static class C_Regression
{
public static SizeF DoReg(List<C_DayVal> lDv)
{
if (lDv.Count < 2)
{
return new SizeF(0, 0);
}
double xAvg = 0;
double yAvg = 0;
DateTime BaseDate = lDv[0].Date.AddDays(-1);
for (int i = 0; i < lDv.Count; i++)
{
C_DayVal DV = lDv[i];
int x = (DV.Date - BaseDate).Days;
xAvg += x;
yAvg += DV.Val;
}
xAvg = xAvg / lDv.Count;
yAvg = yAvg / lDv.Count;
double v1 = 0;
double v2 = 0;
for (int i = 0; i < lDv.Count; i++)
{
C_DayVal DV = lDv[i];
int x = (DV.Date - BaseDate).Days;
v1 += (x - xAvg) * (DV.Val - yAvg);
v2 += Math.Pow(x - xAvg, 2);
}
double a = v1 / v2;
double b = yAvg - a * xAvg;
return new SizeF((float)a, (float)b);
}
// *****************************************************************************************
static void DoRegOrg(List<C_DayVal> lDv)
{
double[] values = { 4.8, 4.8, 4.5, 3.9, 4.4, 3.6, 3.6, 2.9, 3.5, 3.0, 2.5, 2.2, 2.6, 2.1, 2.2 };
double xAvg = 0;
double yAvg = 0;
for (int x = 0; x < values.Length; x++)
{
xAvg += x;
yAvg += values[x];
}
xAvg = xAvg / values.Length;
yAvg = yAvg / values.Length;
double v1 = 0;
double v2 = 0;
for (int x = 0; x < values.Length; x++)
{
v1 += (x - xAvg) * (values[x] - yAvg);
v2 += Math.Pow(x - xAvg, 2);
}
double a = v1 / v2;
double b = yAvg - a * xAvg;
Console.WriteLine("y = ax + b");
Console.WriteLine("a = {0}, the slope of the trend line.", Math.Round(a, 2));
Console.WriteLine("b = {0}, the intercept of the trend line.", Math.Round(b, 2));
Console.ReadLine();
}
// *****************************************************************************************
}
} |
Partager