也就是说,下面两种算法是等价的,我们不需要遍历两遍:
// 预先累加权重和
function blend(samples: ReadonlyArray<readonly [value: number, weight: number]>) {
let result = 0.0;
let sumWeights = 0.0;
for (const [v, w] of samples) {
sumWeights += w;
}
if (sumWeights) {
for (const [v, w] of samples) {
result += (v * (w / sumWeights));
}
}
return result;
}
// 逐步累加权重和
function blend(samples: ReadonlyArray<readonly [value: number, weight: number]>) {
let result = 0.0;
let sumWeights = 0.0;
for (const [v, w] of samples) {
const newSum = sumWeights + w;
sumWeights = newSum;
if (!newSum) {
continue;
}
const t = w / newSum;
result = result * (1 - t) + v * t;
}
return result;
}