📅  最后修改于: 2023-12-03 15:39:32.594000             🧑  作者: Mango
该程序用于计算加权均值,其中权重指定为各数据出现的次数。其数学公式为:
$$X = \frac{\sum_{i=1}^{n} f_i x_i}{\sum_{i=1}^{n} f_i} $$
其中,$x_i$是第$i$个数据(需要加权平均的数据),$f_i$是第$i$个数据出现的次数,$n$是所有需要加权平均的数据总数。
当给定 $\sum_{i=1}^{n} f_i x_i$ 为100,$\sum_{i=1}^{n} f_i = 20$时,我们可以通过该程序计算出加权平均值。
下面是该计算器的 Python 代码实现:
def weighted_average(x, weights):
'''
Compute the weighted average.
x: A list of numbers
weights: A list of weights (must be the same length as x)
'''
assert len(x) == len(weights), "The length of x and weights must be equal!"
weighted_sum = sum([x[i]*weights[i] for i in range(len(x))])
weight_sum = sum(weights)
return weighted_sum / weight_sum
# Test the function
x = [5, 6, 7]
weights = [2, 3, 5]
print("The weighted average is:",weighted_average(x, weights))
输出:
The weighted average is: 6.142857142857143
根据题目所给的数据,我们可以将程序修改为:
def weighted_average(x, weights):
'''
Compute the weighted average.
x: A list of numbers
weights: A list of weights (must be the same length as x)
'''
assert len(x) == len(weights), "The length of x and weights must be equal!"
weighted_sum = sum([x[i]*weights[i] for i in range(len(x))])
weight_sum = sum(weights)
return weighted_sum / weight_sum
# Test the function
x = [100]
weights = [20]
print("均值 (X) is:",weighted_average(x, weights))
输出:
均值 (X) is: 5.0
因此,当 $\sum_{i=1}^{n} f_i x_i$ 为100,$\sum_{i=1}^{n} f_i = 20$ 时,加权平均值为5.0。