1 样本的自协方差函数的通式如下:
2 其实,后面要计算的自相关函数也可以用自协方差来表示:
1 TimeSeries = [11.67602657, 5.637492979, 1.375516942, 0.618705492, -0.152047234, -0.508555434, -6.065288121, -9.417602801, 2 -10.47205437, -8.018063902, 0.523277554, 4.86893283, 4.23977562, -10.2344375, -3.463362573, 36.51326577, 3 -8.518370963, -15.37474905, -7.687911176, 4.818978874, 7.876681639, 1.763788865] 4 Zt = [] 5 LZt = [] 6 AutoCovariance = [] 7 # 自协方差存为列表形式,显示格式如下: 8 # [γ0,γ1,γ2,γ3,....] 9 # [γk,....] k = 0,1,2,3.... 10 total = 0 11 i = 1 12 while i < len(TimeSeries): 13 L = TimeSeries[i::] 14 LL = TimeSeries[:-i:] 15 total = total + TimeSeries[i - 1] 16 Zt.append(L) 17 LZt.append(LL) 18 i += 1 19 total = total + TimeSeries[-1] 20 avg = total / len(TimeSeries) 21 22 k = 0 23 result_temp0 = 0 24 # 首先求γ0的值 25 while k < len(TimeSeries): 26 result_temp0 = result_temp0 + pow((TimeSeries[k] - avg), 2) 27 k += 1 28 AutoCovariance.append(result_temp0) 29 print(AutoCovariance) 30 # 显示结果: 31 #[2418.4380925669107] 32 33 # 然后计算分子 34 p = 0 35 q = 0 36 while p < len(Zt): 37 q = 0 38 result_temp1 = 0 39 while q < len(Zt[p]): 40 result_temp1 = result_temp1 + (Zt[p][q] - avg) * (LZt[p][q] - avg) 41 q += 1 42 AutoCovariance.append(result_temp1) # 保留小数点后三位 43 p += 1 44 print(AutoCovariance) 45 print(len(AutoCovariance)) 46 # 显示结果: 47 # [2418.4380925669107, 154.73148259271665, -909.2825195711046, -216.01009095585525, 381.064309087456, 253.8899860047866, 48 # -455.76866093122146, -513.7425279639118, -234.77764765735802, 51.726042700512416, 266.05419016606146, 116.26795577123028, 49 # -76.63272849007276, -209.6990237967077, 78.50856193561651, 336.9664948029677, -195.8237009651655, -211.6227696432054, -50.67152070500246, 50 # 103.09738426011762, 101.91169142979405, 20.59404564489024]