在Python中查找两个序列的组合均值和方差
假设我们有两个不同的序列A1和A2,大小分别为b和a。我们必须找到组合序列的均值和方差。
因此,如果输入类似于A1 = [24, 46, 35, 79, 13, 77, 35] 和 A2 = [66, 68, 35, 24, 46],则输出将是:均值 = [44.1429, 47.8],标准差 = [548.694, 294.56],组合均值 = 45.6667,d1_square = 2.322,d2_square = 4.5511,组合方差 = 446.056
为了解决这个问题,我们将遵循以下步骤:
定义一个函数 mean()。它将接收数组 arr
返回 arr 元素的平均值
定义一个函数 sd()。它将接收数组 arr 和 n
sum := 0;
对于 i 从 0 到 n,执行以下操作:
sum := sum +((arr[i] - mean(arr)) * (arr[i] - mean(arr)))
sdd := sum / n
返回 sdd
在主方法中,执行以下操作:
n := A1 的大小,m := A2 的大小
mean1 := mean(A1),mean2 := mean(A2)
显示 mean1 和 mean2
sd1 := sd(A1, n),sd2 := sd(A2, m)
显示 sd1 和 sd2
combinedMean :=(n * mean1 + m * mean2) /(n + m)
显示 combinedMean
d1_square :=(mean1 - combinedMean) *(mean1 - combinedMean)
d2_square :=(mean2 - combinedMean) *(mean2 - combinedMean)
显示 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