using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Hippo;
namespace LeastSquareSolution
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string[] figures;
private void Form1_Load(object sender, EventArgs e)
{
draw();
}
private void draw()
{
SeriesList sList = new SeriesList();
sList.ChartType = ChartType.Scatter;
Random r = new Random();
for (int i = 0; i < 1; i++)
{
Series sr = new Series();
sr.Points.Width = 4;
sr.Points.PointType = PointType.FillCircle;
for (int x = 0; x < 150; x++)
{
SeriesItem item = new SeriesItem();
item.XValue = x;
item.YValue = r.Next(500) * x + 13;
sr.items.Add(item);
}
sList.SeriesCollection.Add(sr);
}
sList.SeriesCollection.Add(this.GetTrendSeries(sList));
this.hHippoChart1.LegendBox.Visible = false;
this.hHippoChart1.Titles.Label.ForeColor = Color.SteelBlue;
this.hHippoChart1.DesignType = ChartDesignType.Simple;
this.hHippoChart1.SeriesListDictionary.Add(sList);
this.hHippoChart1.DrawChart();
}
private void button1_Click(object sender, EventArgs e)
{
this.hHippoChart1.SeriesListDictionary.Clear();
draw();
}
private Series GetTrendSeries(SeriesList sList)
{
Series TrSr = new Series();
TrSr.SeriesColor = Color.Blue;
TrSr.ChartType = ChartType.Line;
double a = 0;
double b = 0;
double[,] MatrixL = new double[2, 2];
double[,] InverseMatrixL = new double[2, 2];
double[] MatrixR = new double[2];
int totalcount = 0;
foreach (Series sr in sList.SeriesCollection)
{
foreach (SeriesItem item in sr.items)
{
MatrixL[0, 0] = MatrixL[0, 0] + 1;
MatrixL[1, 0] += item.XValue * 1;
MatrixL[0, 1] += item.XValue * 1;
MatrixL[1, 1] += item.XValue * item.XValue;
MatrixR[0] += item.YValue * 1;
MatrixR[1] += item.YValue * item.XValue;
totalcount++;
}
}
// 역행렬을 만드는 공식에서 ad - bc 체크
double adMinusbc = MatrixL[0, 0] * MatrixL[1, 1] - MatrixL[1, 0] * MatrixL[0, 1];
if (adMinusbc != 0)
{
InverseMatrixL[0, 0] = MatrixL[1, 1] / adMinusbc;
InverseMatrixL[1, 0] = (MatrixL[1, 0] * (-1)) / adMinusbc;
InverseMatrixL[0, 1] = (MatrixL[0, 1] * (-1)) / adMinusbc;
InverseMatrixL[1, 1] = MatrixL[0, 0] / adMinusbc;
a = (InverseMatrixL[0, 0] * MatrixR[0] + InverseMatrixL[1, 0] * MatrixR[1]);
b = (InverseMatrixL[0, 1] * MatrixR[0] + InverseMatrixL[1, 1] * MatrixR[1]);
// 해당 시리즈 만들기
for (int i = 0; i < totalcount; i++)
{
SeriesItem tritem = new SeriesItem();
tritem.XValue = i;
tritem.YValue = (float)(b * i + a);
TrSr.items.Add(tritem);
}
}
else // 나누는 분모가 0이 되므로 불능
{
// 해당 시리즈 만들기
for (int i = 0; i < totalcount; i++)
{
SeriesItem tritem = new SeriesItem();
tritem.XValue = i;
tritem.YValue = 0;
TrSr.items.Add(tritem);
}
}
return TrSr;
}
}
}
|