2017年3月13日月曜日

回帰直線のメモ

using System;
using System.Collections.Generic;

namespace WindowsFormsApplication1
{
    public class RegressionLine
    {
        public RegressionLine(Listdata)
        {
            this.Data = data;

            this.CalcSlopeIntercept();
        }

        private List Data { get; set; }

        public double Slope { get; private set; }

        public double Intercept { get; private set; }

        private void CalcSlopeIntercept()
        {
            double sumXY = 0;
            double sumX = 0;
            double sumY = 0;
            double sumX2 = 0;

            for (int i = 0; i < this.Data.Count; i++)
            {
                sumXY += Data[i].X * this.Data[i].Y;
                sumX += Data[i].X;
                sumY += this.Data[i].Y;
                sumX2 += Math.Pow(Data[i].X, 2);
            }

            this.Slope = (this.Data.Count * sumXY - sumX * sumY) / (this.Data.Count * sumX2 - Math.Pow(sumX, 2));
            this.Intercept = (sumX2 * sumY - sumXY * sumX) / (this.Data.Count * sumX2 - Math.Pow(sumX, 2));
        }

        public double GetExpectancyX(double y)
        {
            return (y - this.Intercept) / this.Slope;
        }

        public double GetExpectancyY(double x)
        {
            return this.Slope * x + this.Intercept;
        }
    }
}

0 件のコメント:

コメントを投稿