|
!'最小2乗法により一次関数(多変数)を求める(重回帰)
!' A + X*B + Y*C + Z*D + W*E = F(X,Y,Z,W)
!'Σ1*1 ΣX*1 ΣY*1 ΣZ*1 ΣW*1 ΣF(X,Y,Z,W)*1
!'Σ1*X ΣX*X ΣY*X ΣZ*X ΣW*X ΣF(X,Y,Z,W)*X
!'Σ1*Y ΣX*Y ΣY*Y ΣZ*Y ΣW*Y ΣF(X,Y,Z,W)*Y
!'Σ1*Z ΣX*Z ΣY*Z ΣZ*Z ΣW*Z ΣF(X,Y,Z,W)*Z
!'Σ1*W ΣX*W ΣY*W ΣZ*W ΣW*W ΣF(X,Y,Z,W)*W
LET N = 10 !'データ数
RANDOMIZE
DIM X(N),Y(N),Z(N),W(N),F(N)
FOR I = 1 TO N
LET X(I) = INT(RND*20)
LET Y(I) = INT(RND*20)
LET Z(I) = INT(RND*20)
LET F(I) = INT(RND*20)
NEXT I
LET M=INT(RND*2)+2
SELECT CASE M
CASE 2
FOR I=1 TO N
PRINT "X=";X(I);"Y=";Y(I);"F(X,Y)=";F(I);"^F(X,Y)=";FORECAST2(N,X,Y,F,X(I),Y(I))
NEXT I
CASE 3
FOR I=1 TO N
PRINT "X=";X(I);"Y=";Y(I);"Z=";Z(I);"F(X,Y,Z)=";F(I);"^F(X,Y,Z)=";FORECAST3(N,X,Y,Z,F,X(I),Y(I),Z(I))
NEXT I
END SELECT
END
EXTERNAL FUNCTION FORECAST2(N,X(),Y(),F(),XA,YA)
!'F(X,Y)=A+B*X+C*Y
DIM XX(3,3),YY(3),WW(3)
FOR I=1 TO N
LET XX(1,1)=XX(1,1)+1
LET XX(2,1)=XX(2,1)+X(I)
LET XX(3,1)=XX(3,1)+Y(I)
LET XX(1,2)=XX(1,2)+X(I)
LET XX(2,2)=XX(2,2)+X(I)*X(I)
LET XX(3,2)=XX(3,2)+X(I)*Y(I)
LET XX(1,3)=XX(1,3)+Y(I)
LET XX(2,3)=XX(2,3)+Y(I)*X(I)
LET XX(3,3)=XX(3,3)+Y(I)*Y(I)
LET YY(1)=YY(1)+F(I)
LET YY(2)=YY(2)+F(I)*X(I)
LET YY(3)=YY(3)+F(I)*Y(I)
NEXT I
CALL CRAMER(3,XX,YY,WW)
LET AA=WW(1)
LET BB=WW(2)
LET CC=WW(3)
LET FORECAST2 = AA+BB*XA+CC*YA
END FUNCTION
EXTERNAL FUNCTION FORECAST3(N,X(),Y(),Z(),F(),XA,YA,ZA)
!'F(X,Y,Z)=A+B*X+C*Y+D*Z
DIM XX(4,4),YY(4),WW(4)
FOR I=1 TO N
LET XX(1,1)=XX(1,1)+1
LET XX(2,1)=XX(2,1)+X(I)
LET XX(3,1)=XX(3,1)+Y(I)
LET XX(4,1)=XX(4,1)+Z(I)
LET XX(1,2)=XX(1,2)+X(I)
LET XX(2,2)=XX(2,2)+X(I)*X(I)
LET XX(3,2)=XX(3,2)+X(I)*Y(I)
LET XX(4,2)=XX(4,2)+X(I)*Z(I)
LET XX(1,3)=XX(1,3)+Y(I)
LET XX(2,3)=XX(2,3)+Y(I)*X(I)
LET XX(3,3)=XX(3,3)+Y(I)*Y(I)
LET XX(4,3)=XX(4,3)+Y(I)*Z(I)
LET XX(1,4)=XX(1,4)+Z(I)
LET XX(2,4)=XX(2,4)+Z(I)*X(I)
LET XX(3,4)=XX(3,4)+Z(I)*Y(I)
LET XX(4,4)=XX(4,4)+Z(I)*Z(I)
LET YY(1)=YY(1)+F(I)
LET YY(2)=YY(2)+F(I)*X(I)
LET YY(3)=YY(3)+F(I)*Y(I)
LET YY(4)=YY(4)+F(I)*Z(I)
NEXT I
CALL CRAMER(4,XX,YY,WW)
LET AA=WW(1)
LET BB=WW(2)
LET CC=WW(3)
LET DD=WW(4)
LET FORECAST3 = AA+BB*XA+CC*YA+DD*ZA
END FUNCTION
EXTERNAL SUB CRAMER (N, X(,), Y(), D()) !'クラーメル法
DIM A(N, N)
FOR I=1 TO N
FOR J=1 TO N
LET A(I,J)=X(I,J)
NEXT J
NEXT I
LET DD = DET(A)
IF DD = 0 THEN STOP !'ERROR
FOR K = 1 TO N
FOR I = 1 TO N
FOR J = 1 TO N
IF J = K THEN LET A(I, J) = Y(I) ELSE LET A(I, J) = X(I, J)
NEXT J
NEXT I
LET D(K) = DET(A) / DD
NEXT K
END SUB
|
|