Public Const MAX_X = 300
Public Const MAX_Y = 300
Public Const MIN_X = 0
Public Const MIN_Y = 0
Public Const PLOT_COUNT = 30
Public Const PLOT_CIRCLE_RADIUS = 2
Public Const PLOT_CIRCLE_COLOR = &HFF0000
Public Type POINT
x As Long
y As Long
End Type
Public plot_data(PLOT_COUNT - 1) As POINT
'プロットデータを作成する
'ここでは、y=xの近似直線を引くようにする
Public Sub SetPlotData(ByVal sList As Object, _
ByVal sPic As Object)
Dim i As Long, t As Long
sList.Clear
sPic.Cls
Randomize
sPic.Scale (MIN_X, MAX_Y)-(MAX_X, MIN_Y)
For i = 0 To PLOT_COUNT - 1
plot_data(i).x = Int(Rnd * MAX_X)
plot_data(i).y = plot_data(i).x + (Int(Rnd * MAX_Y - MAX_Y \ 2)) \ 3
sList.AddItem plot_data(i).x & "," & plot_data(i).y
sPic.Circle (plot_data(i).x, plot_data(i).y), _
PLOT_CIRCLE_RADIUS, PLOT_CIRCLE_COLOR
Next i
End Sub
'xの総和を求める
Public Function GetSumX() As Double
Dim SumValue As Double
Dim i As Integer
SumValue = 0#
For i = 0 To PLOT_COUNT - 1
SumValue = SumValue + plot_data(i).x
Next i
GetSumX = SumValue
End Function
'yの総和を求める
Public Function GetSumY() As Double
Dim SumValue As Double
Dim i As Integer
SumValue = 0#
For i = 0 To PLOT_COUNT - 1
SumValue = SumValue + plot_data(i).y
Next i
GetSumY = SumValue
End Function
'xを2乗した値の総和を求める
Public Function GetSumSpaX() As Double
Dim SumSpaValue As Double
Dim i As Integer
SumSpaValue = 0#
For i = 0 To PLOT_COUNT - 1
SumSpaValue = SumSpaValue + plot_data(i).x ^ 2#
Next i
GetSumSpaX = SumSpaValue
End Function
'yを2乗した値の総和を求める
Public Function GetSumSpaY() As Double
Dim SumSpaValue As Double
Dim i As Integer
SumSpaValue = 0#
For i = 0 To PLOT_COUNT - 1
SumSpaValue = SumSpaValue + plot_data(i).y ^ 2#
Next i
GetSumSpaY = SumSpaValue
End Function
'xとyの積和を求める
Public Function GetSumMul() As Double
Dim i As Long
Dim SumMulValue As Double
SumMulValue = 0#
For i = 0& To PLOT_COUNT - 1&
SumMulValue = SumMulValue + plot_data(i).x * plot_data(i).y
Next i
GetSumMul = SumMulValue
End Function
'回帰直線を描画し、相関係数を戻り値として返す
Public Function DrawLinearFit(ByVal sPic As Object) As Double
Dim sx As Double, sy As Double, sm As Double
Dim sxp As Double, syp As Double
Dim a As Double, b As Double
sx = GetSumX
sy = GetSumY
sxp = GetSumSpaX
syp = GetSumSpaY
sm = GetSumMul
a = (sm - sx * sy / PLOT_COUNT) / _
(sxp - sx * sx / PLOT_COUNT)
b = (sy - a * sx) / PLOT_COUNT
sPic.Line (MIN_X, MIN_X * a + b)-(MAX_X, MAX_X * a + b)
DrawLinearFit = (sm - sx * sy / PLOT_COUNT) / _
Sqr(sxp - sx * sx / PLOT_COUNT) / _
Sqr(syp - sy * sy / PLOT_COUNT)
End Function
|