Friday, July 28, 2017

HP Prime and TI-84 Plus CE: Cosine Regression

HP Prime and TI-84 Plus CE:  Cosine Regression

Introduction

The program COSREG attempts to fit data to the curve:

Y = A*cos(C*(X-D)) +B

The user will provide the x-data, y-data, and the period of the data.  Radians mode will be used. 

HP Prime Program: COSREG
Arguments  x list, y list, estimated period

EXPORT COSREG(L1,L2,P)
BEGIN
// EWS 2017-07-25
// x list, y list, period
// Estimated Cosine Regression
// Y = A*COS(C(X-D))+B
// Radians mode

HAngle:=0;

LOCAL C:=2*π/P;
LOCAL I:=POS(L2,MAX(L2));
LOCAL D:=L1(I);
LOCAL S:=SIZE(L1);
LOCAL L0:=MAKELIST(1,X,1,S);
L1:=COS(C*L1-D);


LOCAL M1,M2,M3;
M1:=list2mat(CONCAT(L0,L1),S);
M1:=TRN(M1);
M2:=list2mat(L2,S);
M2:=TRN(M2);
M3:=CAS.LSQ(M1,M2);
LOCAL A:=M3[2,1];
LOCAL B:=M3[1,1];

RETURN {"A*COS(C(X-D))+B",
A,C,D,B};

END;


TI-84 Plus CE Program:  COSREG

"EWS 2017-07-26"
Disp "COSINE FIT"
Disp "A*cos(C*(X-D))+B"
Radian
Input "X: ",L1
Input "Y: ",L2
Input "PERIOD: ",C
2π/C→C
0→K
Repeat L2(K)=max(L2)
K+1→K
End
L1(K)→D
cos(C*L1-D)→L1
LinReg(a+bx) L1,L2
Disp "{A,C,D,B}"
Pause {a,C,D,b}
Disp "r=",r

The coefficients are returned in a list.

Cosine Regression: Y = A * COS(C*(X – D)) + B

Example 1

X = {0, π/4, π/2, 3π/4 ,1}
Y = {5, 2, -1, 2, 5}
Period:  π

Results:

A = 3
C = 2
D = 0
B = 2
(TI-84 Plus CE:  r = 1)
(Y = 2 COS(2X) + 3 – exact match)


Example 2

X = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Y = {2.5, 4.2, 6.8, 4.4, 2.24, 4.35, 7, 4.41, 2.6, 4.2, 6.76, 4.48}
Period = 4


Results:

A = 4.495
C = 1.570796327
D = 7
B = -1.37970927
(TI-84 Plus CE:  r = -0.6213278417)
(An OK… fit)


Eddie


This blog is property of Edward Shore, 2017