假设我们有两个大小分别为b和a的不同系列A1和A2。我们必须找到组合级数的均值和方差。
因此,如果输入像A1 = [24,46,35,79,13,77,35]并且A2 = [66,68,35,24,46],那么输出将是Mean = [44.1429,47.8 ],sd = [548.694,294.56],组合均值= 45.6667,d1_square = 2.322,d2_square = 4.5511,combined_var = 446.056
为了解决这个问题,我们将遵循以下步骤-
定义一个函数mean()。这将需要
返回arr元素的平均值
定义一个函数sd()。这将花费arr,n
sum:= 0;
对于0到n范围内的i,执行
sum:= sum +((arr [i]-平均值(arr))*(arr [i]-平均值(arr)))
sdd:= sum / n
返回sdd
从主要方法中,执行以下操作-
n:= A1的大小,m:= A2的大小
均值1:=均值(A1),均值2:=均值(A2)
显示均值1和均值2
sd1:= sd(A1,n),sd2:= sd(A2,m)
显示sd1和sd2
CombinedMean:=(n *平均值1 + m *平均值2)/(n + m)
显示组合平均值
d1_square:=(平均值1-组合均值)*(平均值1-组合均值)
d2_square:=(平均值2-组合均值)*(平均值2-组合均值)
显示d1_square,d2_square
comb_var:=(n *(sd1 + d1_square)+ m *(sd2 + d2_square))/(n + m)
显示comb_var
让我们看下面的实现以更好地理解-
def mean(arr): return sum(arr)/len(arr) def sd(arr, n): sum = 0; for i in range(n): sum = sum + ((arr[i] - mean(arr)) * (arr[i] - mean(arr))) sdd = sum / n return sdd def combinedVariance(A1, A2): n = len(A1) m = len(A2) mean1 = mean(A1) mean2 = mean(A2) print("mean_1: ", round(mean1, 2), " mean_2: ", round(mean2, 2)) sd1 = sd(A1, n) sd2 = sd(A2, m) print("sd_1: ", round(sd1, 2)," sd_2: ", round(sd2, 2)) combinedMean = (n * mean1 + m * mean2) / (n + m) print("Combined Mean: ", round(combinedMean, 2)) d1_square = ((mean1 - combinedMean) * (mean1 - combinedMean)) d2_square = ((mean2 - combinedMean) * (mean2 - combinedMean)) print("d1_square: ", round(d1_square, 2), " d2_square: ", round(d2_square, 2)) comb_var = (n * (sd1 + d1_square) + m * (sd2 + d2_square)) / (n + m) print("Combined Variance: ", round(comb_var, 2)) A1 = [24, 46, 35, 79, 13, 77, 35 ] A2 = [66, 68, 35, 24, 46 ] n = len(A1) m = len(A2) combinedVariance(A1, A2)
[24, 46, 35, 79, 13, 77, 35 ],[66, 68, 35, 24, 46 ]
输出结果
mean_1: 44.14 mean_2: 47.8 sd_1: 548.69 sd_2: 294.56 Combined Mean: 45.67 d1_square: 2.32 d2_square: 4.55 Combined Variance: 446.06